Merge trunk version 194076 into gupc branch.
[official-gcc.git] / gcc / tree-sra.c
blob3328f4eb69cb996c998b6ffe0b556b742090959f
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, 2012 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. */
228 unsigned grp_to_be_replaced : 1;
230 /* Set when we want a replacement for the sole purpose of having it in
231 generated debug statements. */
232 unsigned grp_to_be_debug_replaced : 1;
234 /* Should TREE_NO_WARNING of a replacement be set? */
235 unsigned grp_no_warning : 1;
237 /* Is it possible that the group refers to data which might be (directly or
238 otherwise) modified? */
239 unsigned grp_maybe_modified : 1;
241 /* Set when this is a representative of a pointer to scalar (i.e. by
242 reference) parameter which we consider for turning into a plain scalar
243 (i.e. a by value parameter). */
244 unsigned grp_scalar_ptr : 1;
246 /* Set when we discover that this pointer is not safe to dereference in the
247 caller. */
248 unsigned grp_not_necessarilly_dereferenced : 1;
251 typedef struct access *access_p;
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> *) map. */
270 static struct pointer_map_t *base_access_vec;
272 /* Set of candidates. */
273 static bitmap candidate_bitmap;
274 static htab_t candidates;
276 /* For a candidate UID return the candidates decl. */
278 static inline tree
279 candidate (unsigned uid)
281 struct tree_decl_minimal t;
282 t.uid = uid;
283 return (tree) htab_find_with_hash (candidates, &t, uid);
286 /* Bitmap of candidates which we should try to entirely scalarize away and
287 those which cannot be (because they are and need be used as a whole). */
288 static bitmap should_scalarize_away_bitmap, cannot_scalarize_away_bitmap;
290 /* Obstack for creation of fancy names. */
291 static struct obstack name_obstack;
293 /* Head of a linked list of accesses that need to have its subaccesses
294 propagated to their assignment counterparts. */
295 static struct access *work_queue_head;
297 /* Number of parameters of the analyzed function when doing early ipa SRA. */
298 static int func_param_count;
300 /* scan_function sets the following to true if it encounters a call to
301 __builtin_apply_args. */
302 static bool encountered_apply_args;
304 /* Set by scan_function when it finds a recursive call. */
305 static bool encountered_recursive_call;
307 /* Set by scan_function when it finds a recursive call with less actual
308 arguments than formal parameters.. */
309 static bool encountered_unchangable_recursive_call;
311 /* This is a table in which for each basic block and parameter there is a
312 distance (offset + size) in that parameter which is dereferenced and
313 accessed in that BB. */
314 static HOST_WIDE_INT *bb_dereferences;
315 /* Bitmap of BBs that can cause the function to "stop" progressing by
316 returning, throwing externally, looping infinitely or calling a function
317 which might abort etc.. */
318 static bitmap final_bbs;
320 /* Representative of no accesses at all. */
321 static struct access no_accesses_representant;
323 /* Predicate to test the special value. */
325 static inline bool
326 no_accesses_p (struct access *access)
328 return access == &no_accesses_representant;
331 /* Dump contents of ACCESS to file F in a human friendly way. If GRP is true,
332 representative fields are dumped, otherwise those which only describe the
333 individual access are. */
335 static struct
337 /* Number of processed aggregates is readily available in
338 analyze_all_variable_accesses and so is not stored here. */
340 /* Number of created scalar replacements. */
341 int replacements;
343 /* Number of times sra_modify_expr or sra_modify_assign themselves changed an
344 expression. */
345 int exprs;
347 /* Number of statements created by generate_subtree_copies. */
348 int subtree_copies;
350 /* Number of statements created by load_assign_lhs_subreplacements. */
351 int subreplacements;
353 /* Number of times sra_modify_assign has deleted a statement. */
354 int deleted;
356 /* Number of times sra_modify_assign has to deal with subaccesses of LHS and
357 RHS reparately due to type conversions or nonexistent matching
358 references. */
359 int separate_lhs_rhs_handling;
361 /* Number of parameters that were removed because they were unused. */
362 int deleted_unused_parameters;
364 /* Number of scalars passed as parameters by reference that have been
365 converted to be passed by value. */
366 int scalar_by_ref_to_by_val;
368 /* Number of aggregate parameters that were replaced by one or more of their
369 components. */
370 int aggregate_params_reduced;
372 /* Numbber of components created when splitting aggregate parameters. */
373 int param_reductions_created;
374 } sra_stats;
376 static void
377 dump_access (FILE *f, struct access *access, bool grp)
379 fprintf (f, "access { ");
380 fprintf (f, "base = (%d)'", DECL_UID (access->base));
381 print_generic_expr (f, access->base, 0);
382 fprintf (f, "', offset = " HOST_WIDE_INT_PRINT_DEC, access->offset);
383 fprintf (f, ", size = " HOST_WIDE_INT_PRINT_DEC, access->size);
384 fprintf (f, ", expr = ");
385 print_generic_expr (f, access->expr, 0);
386 fprintf (f, ", type = ");
387 print_generic_expr (f, access->type, 0);
388 if (grp)
389 fprintf (f, ", grp_read = %d, grp_write = %d, grp_assignment_read = %d, "
390 "grp_assignment_write = %d, grp_scalar_read = %d, "
391 "grp_scalar_write = %d, grp_total_scalarization = %d, "
392 "grp_hint = %d, grp_covered = %d, "
393 "grp_unscalarizable_region = %d, grp_unscalarized_data = %d, "
394 "grp_partial_lhs = %d, grp_to_be_replaced = %d, "
395 "grp_to_be_debug_replaced = %d, grp_maybe_modified = %d, "
396 "grp_not_necessarilly_dereferenced = %d\n",
397 access->grp_read, access->grp_write, access->grp_assignment_read,
398 access->grp_assignment_write, access->grp_scalar_read,
399 access->grp_scalar_write, access->grp_total_scalarization,
400 access->grp_hint, access->grp_covered,
401 access->grp_unscalarizable_region, access->grp_unscalarized_data,
402 access->grp_partial_lhs, access->grp_to_be_replaced,
403 access->grp_to_be_debug_replaced, access->grp_maybe_modified,
404 access->grp_not_necessarilly_dereferenced);
405 else
406 fprintf (f, ", write = %d, grp_total_scalarization = %d, "
407 "grp_partial_lhs = %d\n",
408 access->write, access->grp_total_scalarization,
409 access->grp_partial_lhs);
412 /* Dump a subtree rooted in ACCESS to file F, indent by LEVEL. */
414 static void
415 dump_access_tree_1 (FILE *f, struct access *access, int level)
419 int i;
421 for (i = 0; i < level; i++)
422 fputs ("* ", dump_file);
424 dump_access (f, access, true);
426 if (access->first_child)
427 dump_access_tree_1 (f, access->first_child, level + 1);
429 access = access->next_sibling;
431 while (access);
434 /* Dump all access trees for a variable, given the pointer to the first root in
435 ACCESS. */
437 static void
438 dump_access_tree (FILE *f, struct access *access)
440 for (; access; access = access->next_grp)
441 dump_access_tree_1 (f, access, 0);
444 /* Return true iff ACC is non-NULL and has subaccesses. */
446 static inline bool
447 access_has_children_p (struct access *acc)
449 return acc && acc->first_child;
452 /* Return true iff ACC is (partly) covered by at least one replacement. */
454 static bool
455 access_has_replacements_p (struct access *acc)
457 struct access *child;
458 if (acc->grp_to_be_replaced)
459 return true;
460 for (child = acc->first_child; child; child = child->next_sibling)
461 if (access_has_replacements_p (child))
462 return true;
463 return false;
466 /* Return a vector of pointers to accesses for the variable given in BASE or
467 NULL if there is none. */
469 static vec<access_p> *
470 get_base_access_vector (tree base)
472 void **slot;
474 slot = pointer_map_contains (base_access_vec, base);
475 if (!slot)
476 return NULL;
477 else
478 return *(vec<access_p> **) slot;
481 /* Find an access with required OFFSET and SIZE in a subtree of accesses rooted
482 in ACCESS. Return NULL if it cannot be found. */
484 static struct access *
485 find_access_in_subtree (struct access *access, HOST_WIDE_INT offset,
486 HOST_WIDE_INT size)
488 while (access && (access->offset != offset || access->size != size))
490 struct access *child = access->first_child;
492 while (child && (child->offset + child->size <= offset))
493 child = child->next_sibling;
494 access = child;
497 return access;
500 /* Return the first group representative for DECL or NULL if none exists. */
502 static struct access *
503 get_first_repr_for_decl (tree base)
505 vec<access_p> *access_vec;
507 access_vec = get_base_access_vector (base);
508 if (!access_vec)
509 return NULL;
511 return (*access_vec)[0];
514 /* Find an access representative for the variable BASE and given OFFSET and
515 SIZE. Requires that access trees have already been built. Return NULL if
516 it cannot be found. */
518 static struct access *
519 get_var_base_offset_size_access (tree base, HOST_WIDE_INT offset,
520 HOST_WIDE_INT size)
522 struct access *access;
524 access = get_first_repr_for_decl (base);
525 while (access && (access->offset + access->size <= offset))
526 access = access->next_grp;
527 if (!access)
528 return NULL;
530 return find_access_in_subtree (access, offset, size);
533 /* Add LINK to the linked list of assign links of RACC. */
534 static void
535 add_link_to_rhs (struct access *racc, struct assign_link *link)
537 gcc_assert (link->racc == racc);
539 if (!racc->first_link)
541 gcc_assert (!racc->last_link);
542 racc->first_link = link;
544 else
545 racc->last_link->next = link;
547 racc->last_link = link;
548 link->next = NULL;
551 /* Move all link structures in their linked list in OLD_RACC to the linked list
552 in NEW_RACC. */
553 static void
554 relink_to_new_repr (struct access *new_racc, struct access *old_racc)
556 if (!old_racc->first_link)
558 gcc_assert (!old_racc->last_link);
559 return;
562 if (new_racc->first_link)
564 gcc_assert (!new_racc->last_link->next);
565 gcc_assert (!old_racc->last_link || !old_racc->last_link->next);
567 new_racc->last_link->next = old_racc->first_link;
568 new_racc->last_link = old_racc->last_link;
570 else
572 gcc_assert (!new_racc->last_link);
574 new_racc->first_link = old_racc->first_link;
575 new_racc->last_link = old_racc->last_link;
577 old_racc->first_link = old_racc->last_link = NULL;
580 /* Add ACCESS to the work queue (which is actually a stack). */
582 static void
583 add_access_to_work_queue (struct access *access)
585 if (!access->grp_queued)
587 gcc_assert (!access->next_queued);
588 access->next_queued = work_queue_head;
589 access->grp_queued = 1;
590 work_queue_head = access;
594 /* Pop an access from the work queue, and return it, assuming there is one. */
596 static struct access *
597 pop_access_from_work_queue (void)
599 struct access *access = work_queue_head;
601 work_queue_head = access->next_queued;
602 access->next_queued = NULL;
603 access->grp_queued = 0;
604 return access;
608 /* Allocate necessary structures. */
610 static void
611 sra_initialize (void)
613 candidate_bitmap = BITMAP_ALLOC (NULL);
614 candidates = htab_create (vec_safe_length (cfun->local_decls) / 2,
615 uid_decl_map_hash, uid_decl_map_eq, NULL);
616 should_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
617 cannot_scalarize_away_bitmap = BITMAP_ALLOC (NULL);
618 gcc_obstack_init (&name_obstack);
619 access_pool = create_alloc_pool ("SRA accesses", sizeof (struct access), 16);
620 link_pool = create_alloc_pool ("SRA links", sizeof (struct assign_link), 16);
621 base_access_vec = pointer_map_create ();
622 memset (&sra_stats, 0, sizeof (sra_stats));
623 encountered_apply_args = false;
624 encountered_recursive_call = false;
625 encountered_unchangable_recursive_call = false;
628 /* Hook fed to pointer_map_traverse, deallocate stored vectors. */
630 static bool
631 delete_base_accesses (const void *key ATTRIBUTE_UNUSED, void **value,
632 void *data ATTRIBUTE_UNUSED)
634 vec<access_p> *access_vec = (vec<access_p> *) *value;
635 vec_free (access_vec);
636 return true;
639 /* Deallocate all general structures. */
641 static void
642 sra_deinitialize (void)
644 BITMAP_FREE (candidate_bitmap);
645 htab_delete (candidates);
646 BITMAP_FREE (should_scalarize_away_bitmap);
647 BITMAP_FREE (cannot_scalarize_away_bitmap);
648 free_alloc_pool (access_pool);
649 free_alloc_pool (link_pool);
650 obstack_free (&name_obstack, NULL);
652 pointer_map_traverse (base_access_vec, delete_base_accesses, NULL);
653 pointer_map_destroy (base_access_vec);
656 /* Remove DECL from candidates for SRA and write REASON to the dump file if
657 there is one. */
658 static void
659 disqualify_candidate (tree decl, const char *reason)
661 if (bitmap_clear_bit (candidate_bitmap, DECL_UID (decl)))
662 htab_clear_slot (candidates,
663 htab_find_slot_with_hash (candidates, decl,
664 DECL_UID (decl), NO_INSERT));
666 if (dump_file && (dump_flags & TDF_DETAILS))
668 fprintf (dump_file, "! Disqualifying ");
669 print_generic_expr (dump_file, decl, 0);
670 fprintf (dump_file, " - %s\n", reason);
674 /* Return true iff the type contains a field or an element which does not allow
675 scalarization. */
677 static bool
678 type_internals_preclude_sra_p (tree type, const char **msg)
680 tree fld;
681 tree et;
683 switch (TREE_CODE (type))
685 case RECORD_TYPE:
686 case UNION_TYPE:
687 case QUAL_UNION_TYPE:
688 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
689 if (TREE_CODE (fld) == FIELD_DECL)
691 tree ft = TREE_TYPE (fld);
693 if (TREE_THIS_VOLATILE (fld))
695 *msg = "volatile structure field";
696 return true;
698 if (!DECL_FIELD_OFFSET (fld))
700 *msg = "no structure field offset";
701 return true;
703 if (!DECL_SIZE (fld))
705 *msg = "zero structure field size";
706 return true;
708 if (!host_integerp (DECL_FIELD_OFFSET (fld), 1))
710 *msg = "structure field offset not fixed";
711 return true;
713 if (!host_integerp (DECL_SIZE (fld), 1))
715 *msg = "structure field size not fixed";
716 return true;
718 if (AGGREGATE_TYPE_P (ft)
719 && int_bit_position (fld) % BITS_PER_UNIT != 0)
721 *msg = "structure field is bit field";
722 return true;
725 if (AGGREGATE_TYPE_P (ft) && type_internals_preclude_sra_p (ft, msg))
726 return true;
729 return false;
731 case ARRAY_TYPE:
732 et = TREE_TYPE (type);
734 if (TYPE_VOLATILE (et))
736 *msg = "element type is volatile";
737 return true;
740 if (AGGREGATE_TYPE_P (et) && type_internals_preclude_sra_p (et, msg))
741 return true;
743 return false;
745 default:
746 return false;
750 /* If T is an SSA_NAME, return NULL if it is not a default def or return its
751 base variable if it is. Return T if it is not an SSA_NAME. */
753 static tree
754 get_ssa_base_param (tree t)
756 if (TREE_CODE (t) == SSA_NAME)
758 if (SSA_NAME_IS_DEFAULT_DEF (t))
759 return SSA_NAME_VAR (t);
760 else
761 return NULL_TREE;
763 return t;
766 /* Mark a dereference of BASE of distance DIST in a basic block tht STMT
767 belongs to, unless the BB has already been marked as a potentially
768 final. */
770 static void
771 mark_parm_dereference (tree base, HOST_WIDE_INT dist, gimple stmt)
773 basic_block bb = gimple_bb (stmt);
774 int idx, parm_index = 0;
775 tree parm;
777 if (bitmap_bit_p (final_bbs, bb->index))
778 return;
780 for (parm = DECL_ARGUMENTS (current_function_decl);
781 parm && parm != base;
782 parm = DECL_CHAIN (parm))
783 parm_index++;
785 gcc_assert (parm_index < func_param_count);
787 idx = bb->index * func_param_count + parm_index;
788 if (bb_dereferences[idx] < dist)
789 bb_dereferences[idx] = dist;
792 /* Allocate an access structure for BASE, OFFSET and SIZE, clear it, fill in
793 the three fields. Also add it to the vector of accesses corresponding to
794 the base. Finally, return the new access. */
796 static struct access *
797 create_access_1 (tree base, HOST_WIDE_INT offset, HOST_WIDE_INT size)
799 vec<access_p> *v;
800 struct access *access;
801 void **slot;
803 access = (struct access *) pool_alloc (access_pool);
804 memset (access, 0, sizeof (struct access));
805 access->base = base;
806 access->offset = offset;
807 access->size = size;
809 slot = pointer_map_contains (base_access_vec, base);
810 if (slot)
811 v = (vec<access_p> *) *slot;
812 else
813 vec_alloc (v, 32);
815 v->safe_push (access);
817 *((vec<access_p> **)
818 pointer_map_insert (base_access_vec, base)) = v;
820 return access;
823 /* Create and insert access for EXPR. Return created access, or NULL if it is
824 not possible. */
826 static struct access *
827 create_access (tree expr, gimple stmt, bool write)
829 struct access *access;
830 HOST_WIDE_INT offset, size, max_size;
831 tree base = expr;
832 bool ptr, unscalarizable_region = false;
834 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
836 if (sra_mode == SRA_MODE_EARLY_IPA
837 && TREE_CODE (base) == MEM_REF)
839 base = get_ssa_base_param (TREE_OPERAND (base, 0));
840 if (!base)
841 return NULL;
842 ptr = true;
844 else
845 ptr = false;
847 if (!DECL_P (base) || !bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
848 return NULL;
850 if (sra_mode == SRA_MODE_EARLY_IPA)
852 if (size < 0 || size != max_size)
854 disqualify_candidate (base, "Encountered a variable sized access.");
855 return NULL;
857 if (TREE_CODE (expr) == COMPONENT_REF
858 && DECL_BIT_FIELD (TREE_OPERAND (expr, 1)))
860 disqualify_candidate (base, "Encountered a bit-field access.");
861 return NULL;
863 gcc_checking_assert ((offset % BITS_PER_UNIT) == 0);
865 if (ptr)
866 mark_parm_dereference (base, offset + size, stmt);
868 else
870 if (size != max_size)
872 size = max_size;
873 unscalarizable_region = true;
875 if (size < 0)
877 disqualify_candidate (base, "Encountered an unconstrained access.");
878 return NULL;
882 access = create_access_1 (base, offset, size);
883 access->expr = expr;
884 access->type = TREE_TYPE (expr);
885 access->write = write;
886 access->grp_unscalarizable_region = unscalarizable_region;
887 access->stmt = stmt;
889 if (TREE_CODE (expr) == COMPONENT_REF
890 && DECL_NONADDRESSABLE_P (TREE_OPERAND (expr, 1)))
891 access->non_addressable = 1;
893 return access;
897 /* Return true iff TYPE is a RECORD_TYPE with fields that are either of gimple
898 register types or (recursively) records with only these two kinds of fields.
899 It also returns false if any of these records contains a bit-field. */
901 static bool
902 type_consists_of_records_p (tree type)
904 tree fld;
906 if (TREE_CODE (type) != RECORD_TYPE)
907 return false;
909 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
910 if (TREE_CODE (fld) == FIELD_DECL)
912 tree ft = TREE_TYPE (fld);
914 if (DECL_BIT_FIELD (fld))
915 return false;
917 if (!is_gimple_reg_type (ft)
918 && !type_consists_of_records_p (ft))
919 return false;
922 return true;
925 /* Create total_scalarization accesses for all scalar type fields in DECL that
926 must be of a RECORD_TYPE conforming to type_consists_of_records_p. BASE
927 must be the top-most VAR_DECL representing the variable, OFFSET must be the
928 offset of DECL within BASE. REF must be the memory reference expression for
929 the given decl. */
931 static void
932 completely_scalarize_record (tree base, tree decl, HOST_WIDE_INT offset,
933 tree ref)
935 tree fld, decl_type = TREE_TYPE (decl);
937 for (fld = TYPE_FIELDS (decl_type); fld; fld = DECL_CHAIN (fld))
938 if (TREE_CODE (fld) == FIELD_DECL)
940 HOST_WIDE_INT pos = offset + int_bit_position (fld);
941 tree ft = TREE_TYPE (fld);
942 tree nref = build3 (COMPONENT_REF, TREE_TYPE (fld), ref, fld,
943 NULL_TREE);
945 if (is_gimple_reg_type (ft))
947 struct access *access;
948 HOST_WIDE_INT size;
950 size = tree_low_cst (DECL_SIZE (fld), 1);
951 access = create_access_1 (base, pos, size);
952 access->expr = nref;
953 access->type = ft;
954 access->grp_total_scalarization = 1;
955 /* Accesses for intraprocedural SRA can have their stmt NULL. */
957 else
958 completely_scalarize_record (base, fld, pos, nref);
962 /* Create total_scalarization accesses for all scalar type fields in VAR and
963 for VAR a a whole. VAR must be of a RECORD_TYPE conforming to
964 type_consists_of_records_p. */
966 static void
967 completely_scalarize_var (tree var)
969 HOST_WIDE_INT size = tree_low_cst (DECL_SIZE (var), 1);
970 struct access *access;
972 access = create_access_1 (var, 0, size);
973 access->expr = var;
974 access->type = TREE_TYPE (var);
975 access->grp_total_scalarization = 1;
977 completely_scalarize_record (var, var, 0, var);
980 /* Search the given tree for a declaration by skipping handled components and
981 exclude it from the candidates. */
983 static void
984 disqualify_base_of_expr (tree t, const char *reason)
986 t = get_base_address (t);
987 if (sra_mode == SRA_MODE_EARLY_IPA
988 && TREE_CODE (t) == MEM_REF)
989 t = get_ssa_base_param (TREE_OPERAND (t, 0));
991 if (t && DECL_P (t))
992 disqualify_candidate (t, reason);
995 /* Scan expression EXPR and create access structures for all accesses to
996 candidates for scalarization. Return the created access or NULL if none is
997 created. */
999 static struct access *
1000 build_access_from_expr_1 (tree expr, gimple stmt, bool write)
1002 struct access *ret = NULL;
1003 bool partial_ref;
1005 if (TREE_CODE (expr) == BIT_FIELD_REF
1006 || TREE_CODE (expr) == IMAGPART_EXPR
1007 || TREE_CODE (expr) == REALPART_EXPR)
1009 expr = TREE_OPERAND (expr, 0);
1010 partial_ref = true;
1012 else
1013 partial_ref = false;
1015 /* We need to dive through V_C_Es in order to get the size of its parameter
1016 and not the result type. Ada produces such statements. We are also
1017 capable of handling the topmost V_C_E but not any of those buried in other
1018 handled components. */
1019 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
1020 expr = TREE_OPERAND (expr, 0);
1022 if (contains_view_convert_expr_p (expr))
1024 disqualify_base_of_expr (expr, "V_C_E under a different handled "
1025 "component.");
1026 return NULL;
1029 switch (TREE_CODE (expr))
1031 case MEM_REF:
1032 if (TREE_CODE (TREE_OPERAND (expr, 0)) != ADDR_EXPR
1033 && sra_mode != SRA_MODE_EARLY_IPA)
1034 return NULL;
1035 /* fall through */
1036 case VAR_DECL:
1037 case PARM_DECL:
1038 case RESULT_DECL:
1039 case COMPONENT_REF:
1040 case ARRAY_REF:
1041 case ARRAY_RANGE_REF:
1042 ret = create_access (expr, stmt, write);
1043 break;
1045 default:
1046 break;
1049 if (write && partial_ref && ret)
1050 ret->grp_partial_lhs = 1;
1052 return ret;
1055 /* Scan expression EXPR and create access structures for all accesses to
1056 candidates for scalarization. Return true if any access has been inserted.
1057 STMT must be the statement from which the expression is taken, WRITE must be
1058 true if the expression is a store and false otherwise. */
1060 static bool
1061 build_access_from_expr (tree expr, gimple stmt, bool write)
1063 struct access *access;
1065 access = build_access_from_expr_1 (expr, stmt, write);
1066 if (access)
1068 /* This means the aggregate is accesses as a whole in a way other than an
1069 assign statement and thus cannot be removed even if we had a scalar
1070 replacement for everything. */
1071 if (cannot_scalarize_away_bitmap)
1072 bitmap_set_bit (cannot_scalarize_away_bitmap, DECL_UID (access->base));
1073 return true;
1075 return false;
1078 /* Disqualify LHS and RHS for scalarization if STMT must end its basic block in
1079 modes in which it matters, return true iff they have been disqualified. RHS
1080 may be NULL, in that case ignore it. If we scalarize an aggregate in
1081 intra-SRA we may need to add statements after each statement. This is not
1082 possible if a statement unconditionally has to end the basic block. */
1083 static bool
1084 disqualify_ops_if_throwing_stmt (gimple stmt, tree lhs, tree rhs)
1086 if ((sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1087 && (stmt_can_throw_internal (stmt) || stmt_ends_bb_p (stmt)))
1089 disqualify_base_of_expr (lhs, "LHS of a throwing stmt.");
1090 if (rhs)
1091 disqualify_base_of_expr (rhs, "RHS of a throwing stmt.");
1092 return true;
1094 return false;
1097 /* Scan expressions occurring in STMT, create access structures for all accesses
1098 to candidates for scalarization and remove those candidates which occur in
1099 statements or expressions that prevent them from being split apart. Return
1100 true if any access has been inserted. */
1102 static bool
1103 build_accesses_from_assign (gimple stmt)
1105 tree lhs, rhs;
1106 struct access *lacc, *racc;
1108 if (!gimple_assign_single_p (stmt)
1109 /* Scope clobbers don't influence scalarization. */
1110 || gimple_clobber_p (stmt))
1111 return false;
1113 lhs = gimple_assign_lhs (stmt);
1114 rhs = gimple_assign_rhs1 (stmt);
1116 if (disqualify_ops_if_throwing_stmt (stmt, lhs, rhs))
1117 return false;
1119 racc = build_access_from_expr_1 (rhs, stmt, false);
1120 lacc = build_access_from_expr_1 (lhs, stmt, true);
1122 if (lacc)
1123 lacc->grp_assignment_write = 1;
1125 if (racc)
1127 racc->grp_assignment_read = 1;
1128 if (should_scalarize_away_bitmap && !gimple_has_volatile_ops (stmt)
1129 && !is_gimple_reg_type (racc->type))
1130 bitmap_set_bit (should_scalarize_away_bitmap, DECL_UID (racc->base));
1133 if (lacc && racc
1134 && (sra_mode == SRA_MODE_EARLY_INTRA || sra_mode == SRA_MODE_INTRA)
1135 && !lacc->grp_unscalarizable_region
1136 && !racc->grp_unscalarizable_region
1137 && AGGREGATE_TYPE_P (TREE_TYPE (lhs))
1138 && lacc->size == racc->size
1139 && useless_type_conversion_p (lacc->type, racc->type))
1141 struct assign_link *link;
1143 link = (struct assign_link *) pool_alloc (link_pool);
1144 memset (link, 0, sizeof (struct assign_link));
1146 link->lacc = lacc;
1147 link->racc = racc;
1149 add_link_to_rhs (racc, link);
1152 return lacc || racc;
1155 /* Callback of walk_stmt_load_store_addr_ops visit_addr used to determine
1156 GIMPLE_ASM operands with memory constrains which cannot be scalarized. */
1158 static bool
1159 asm_visit_addr (gimple stmt ATTRIBUTE_UNUSED, tree op,
1160 void *data ATTRIBUTE_UNUSED)
1162 op = get_base_address (op);
1163 if (op
1164 && DECL_P (op))
1165 disqualify_candidate (op, "Non-scalarizable GIMPLE_ASM operand.");
1167 return false;
1170 /* Return true iff callsite CALL has at least as many actual arguments as there
1171 are formal parameters of the function currently processed by IPA-SRA. */
1173 static inline bool
1174 callsite_has_enough_arguments_p (gimple call)
1176 return gimple_call_num_args (call) >= (unsigned) func_param_count;
1179 /* Scan function and look for interesting expressions and create access
1180 structures for them. Return true iff any access is created. */
1182 static bool
1183 scan_function (void)
1185 basic_block bb;
1186 bool ret = false;
1188 FOR_EACH_BB (bb)
1190 gimple_stmt_iterator gsi;
1191 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1193 gimple stmt = gsi_stmt (gsi);
1194 tree t;
1195 unsigned i;
1197 if (final_bbs && stmt_can_throw_external (stmt))
1198 bitmap_set_bit (final_bbs, bb->index);
1199 switch (gimple_code (stmt))
1201 case GIMPLE_RETURN:
1202 t = gimple_return_retval (stmt);
1203 if (t != NULL_TREE)
1204 ret |= build_access_from_expr (t, stmt, false);
1205 if (final_bbs)
1206 bitmap_set_bit (final_bbs, bb->index);
1207 break;
1209 case GIMPLE_ASSIGN:
1210 ret |= build_accesses_from_assign (stmt);
1211 break;
1213 case GIMPLE_CALL:
1214 for (i = 0; i < gimple_call_num_args (stmt); i++)
1215 ret |= build_access_from_expr (gimple_call_arg (stmt, i),
1216 stmt, false);
1218 if (sra_mode == SRA_MODE_EARLY_IPA)
1220 tree dest = gimple_call_fndecl (stmt);
1221 int flags = gimple_call_flags (stmt);
1223 if (dest)
1225 if (DECL_BUILT_IN_CLASS (dest) == BUILT_IN_NORMAL
1226 && DECL_FUNCTION_CODE (dest) == BUILT_IN_APPLY_ARGS)
1227 encountered_apply_args = true;
1228 if (cgraph_get_node (dest)
1229 == cgraph_get_node (current_function_decl))
1231 encountered_recursive_call = true;
1232 if (!callsite_has_enough_arguments_p (stmt))
1233 encountered_unchangable_recursive_call = true;
1237 if (final_bbs
1238 && (flags & (ECF_CONST | ECF_PURE)) == 0)
1239 bitmap_set_bit (final_bbs, bb->index);
1242 t = gimple_call_lhs (stmt);
1243 if (t && !disqualify_ops_if_throwing_stmt (stmt, t, NULL))
1244 ret |= build_access_from_expr (t, stmt, true);
1245 break;
1247 case GIMPLE_ASM:
1248 walk_stmt_load_store_addr_ops (stmt, NULL, NULL, NULL,
1249 asm_visit_addr);
1250 if (final_bbs)
1251 bitmap_set_bit (final_bbs, bb->index);
1253 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
1255 t = TREE_VALUE (gimple_asm_input_op (stmt, i));
1256 ret |= build_access_from_expr (t, stmt, false);
1258 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
1260 t = TREE_VALUE (gimple_asm_output_op (stmt, i));
1261 ret |= build_access_from_expr (t, stmt, true);
1263 break;
1265 default:
1266 break;
1271 return ret;
1274 /* Helper of QSORT function. There are pointers to accesses in the array. An
1275 access is considered smaller than another if it has smaller offset or if the
1276 offsets are the same but is size is bigger. */
1278 static int
1279 compare_access_positions (const void *a, const void *b)
1281 const access_p *fp1 = (const access_p *) a;
1282 const access_p *fp2 = (const access_p *) b;
1283 const access_p f1 = *fp1;
1284 const access_p f2 = *fp2;
1286 if (f1->offset != f2->offset)
1287 return f1->offset < f2->offset ? -1 : 1;
1289 if (f1->size == f2->size)
1291 if (f1->type == f2->type)
1292 return 0;
1293 /* Put any non-aggregate type before any aggregate type. */
1294 else if (!is_gimple_reg_type (f1->type)
1295 && is_gimple_reg_type (f2->type))
1296 return 1;
1297 else if (is_gimple_reg_type (f1->type)
1298 && !is_gimple_reg_type (f2->type))
1299 return -1;
1300 /* Put any complex or vector type before any other scalar type. */
1301 else if (TREE_CODE (f1->type) != COMPLEX_TYPE
1302 && TREE_CODE (f1->type) != VECTOR_TYPE
1303 && (TREE_CODE (f2->type) == COMPLEX_TYPE
1304 || TREE_CODE (f2->type) == VECTOR_TYPE))
1305 return 1;
1306 else if ((TREE_CODE (f1->type) == COMPLEX_TYPE
1307 || TREE_CODE (f1->type) == VECTOR_TYPE)
1308 && TREE_CODE (f2->type) != COMPLEX_TYPE
1309 && TREE_CODE (f2->type) != VECTOR_TYPE)
1310 return -1;
1311 /* Put the integral type with the bigger precision first. */
1312 else if (INTEGRAL_TYPE_P (f1->type)
1313 && INTEGRAL_TYPE_P (f2->type))
1314 return TYPE_PRECISION (f2->type) - TYPE_PRECISION (f1->type);
1315 /* Put any integral type with non-full precision last. */
1316 else if (INTEGRAL_TYPE_P (f1->type)
1317 && (TREE_INT_CST_LOW (TYPE_SIZE (f1->type))
1318 != TYPE_PRECISION (f1->type)))
1319 return 1;
1320 else if (INTEGRAL_TYPE_P (f2->type)
1321 && (TREE_INT_CST_LOW (TYPE_SIZE (f2->type))
1322 != TYPE_PRECISION (f2->type)))
1323 return -1;
1324 /* Stabilize the sort. */
1325 return TYPE_UID (f1->type) - TYPE_UID (f2->type);
1328 /* We want the bigger accesses first, thus the opposite operator in the next
1329 line: */
1330 return f1->size > f2->size ? -1 : 1;
1334 /* Append a name of the declaration to the name obstack. A helper function for
1335 make_fancy_name. */
1337 static void
1338 make_fancy_decl_name (tree decl)
1340 char buffer[32];
1342 tree name = DECL_NAME (decl);
1343 if (name)
1344 obstack_grow (&name_obstack, IDENTIFIER_POINTER (name),
1345 IDENTIFIER_LENGTH (name));
1346 else
1348 sprintf (buffer, "D%u", DECL_UID (decl));
1349 obstack_grow (&name_obstack, buffer, strlen (buffer));
1353 /* Helper for make_fancy_name. */
1355 static void
1356 make_fancy_name_1 (tree expr)
1358 char buffer[32];
1359 tree index;
1361 if (DECL_P (expr))
1363 make_fancy_decl_name (expr);
1364 return;
1367 switch (TREE_CODE (expr))
1369 case COMPONENT_REF:
1370 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1371 obstack_1grow (&name_obstack, '$');
1372 make_fancy_decl_name (TREE_OPERAND (expr, 1));
1373 break;
1375 case ARRAY_REF:
1376 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1377 obstack_1grow (&name_obstack, '$');
1378 /* Arrays with only one element may not have a constant as their
1379 index. */
1380 index = TREE_OPERAND (expr, 1);
1381 if (TREE_CODE (index) != INTEGER_CST)
1382 break;
1383 sprintf (buffer, HOST_WIDE_INT_PRINT_DEC, TREE_INT_CST_LOW (index));
1384 obstack_grow (&name_obstack, buffer, strlen (buffer));
1385 break;
1387 case ADDR_EXPR:
1388 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1389 break;
1391 case MEM_REF:
1392 make_fancy_name_1 (TREE_OPERAND (expr, 0));
1393 if (!integer_zerop (TREE_OPERAND (expr, 1)))
1395 obstack_1grow (&name_obstack, '$');
1396 sprintf (buffer, HOST_WIDE_INT_PRINT_DEC,
1397 TREE_INT_CST_LOW (TREE_OPERAND (expr, 1)));
1398 obstack_grow (&name_obstack, buffer, strlen (buffer));
1400 break;
1402 case BIT_FIELD_REF:
1403 case REALPART_EXPR:
1404 case IMAGPART_EXPR:
1405 gcc_unreachable (); /* we treat these as scalars. */
1406 break;
1407 default:
1408 break;
1412 /* Create a human readable name for replacement variable of ACCESS. */
1414 static char *
1415 make_fancy_name (tree expr)
1417 make_fancy_name_1 (expr);
1418 obstack_1grow (&name_obstack, '\0');
1419 return XOBFINISH (&name_obstack, char *);
1422 /* Construct a MEM_REF that would reference a part of aggregate BASE of type
1423 EXP_TYPE at the given OFFSET. If BASE is something for which
1424 get_addr_base_and_unit_offset returns NULL, gsi must be non-NULL and is used
1425 to insert new statements either before or below the current one as specified
1426 by INSERT_AFTER. This function is not capable of handling bitfields. */
1428 tree
1429 build_ref_for_offset (location_t loc, tree base, HOST_WIDE_INT offset,
1430 tree exp_type, gimple_stmt_iterator *gsi,
1431 bool insert_after)
1433 tree prev_base = base;
1434 tree off;
1435 HOST_WIDE_INT base_offset;
1436 unsigned HOST_WIDE_INT misalign;
1437 unsigned int align;
1439 gcc_checking_assert (offset % BITS_PER_UNIT == 0);
1441 base = get_addr_base_and_unit_offset (base, &base_offset);
1443 /* get_addr_base_and_unit_offset returns NULL for references with a variable
1444 offset such as array[var_index]. */
1445 if (!base)
1447 gimple stmt;
1448 tree tmp, addr;
1450 gcc_checking_assert (gsi);
1451 tmp = make_ssa_name (build_pointer_type (TREE_TYPE (prev_base)), NULL);
1452 addr = build_fold_addr_expr (unshare_expr (prev_base));
1453 STRIP_USELESS_TYPE_CONVERSION (addr);
1454 stmt = gimple_build_assign (tmp, addr);
1455 gimple_set_location (stmt, loc);
1456 if (insert_after)
1457 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
1458 else
1459 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
1461 off = build_int_cst (reference_alias_ptr_type (prev_base),
1462 offset / BITS_PER_UNIT);
1463 base = tmp;
1465 else if (TREE_CODE (base) == MEM_REF)
1467 off = build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)),
1468 base_offset + offset / BITS_PER_UNIT);
1469 off = int_const_binop (PLUS_EXPR, TREE_OPERAND (base, 1), off);
1470 base = unshare_expr (TREE_OPERAND (base, 0));
1472 else
1474 off = build_int_cst (reference_alias_ptr_type (base),
1475 base_offset + offset / BITS_PER_UNIT);
1476 base = build_fold_addr_expr (unshare_expr (base));
1479 /* If prev_base were always an originally performed access
1480 we can extract more optimistic alignment information
1481 by looking at the access mode. That would constrain the
1482 alignment of base + base_offset which we would need to
1483 adjust according to offset. */
1484 if (!get_pointer_alignment_1 (base, &align, &misalign))
1486 gcc_assert (misalign == 0);
1487 if (TREE_CODE (prev_base) == MEM_REF
1488 || TREE_CODE (prev_base) == TARGET_MEM_REF)
1489 align = TYPE_ALIGN (TREE_TYPE (prev_base));
1491 misalign += (tree_to_double_int (off)
1492 .sext (TYPE_PRECISION (TREE_TYPE (off))).low
1493 * BITS_PER_UNIT);
1494 misalign = misalign & (align - 1);
1495 if (misalign != 0)
1496 align = (misalign & -misalign);
1497 if (align < TYPE_ALIGN (exp_type))
1498 exp_type = build_aligned_type (exp_type, align);
1500 return fold_build2_loc (loc, MEM_REF, exp_type, base, off);
1503 /* Construct a memory reference to a part of an aggregate BASE at the given
1504 OFFSET and of the same type as MODEL. In case this is a reference to a
1505 bit-field, the function will replicate the last component_ref of model's
1506 expr to access it. GSI and INSERT_AFTER have the same meaning as in
1507 build_ref_for_offset. */
1509 static tree
1510 build_ref_for_model (location_t loc, tree base, HOST_WIDE_INT offset,
1511 struct access *model, gimple_stmt_iterator *gsi,
1512 bool insert_after)
1514 if (TREE_CODE (model->expr) == COMPONENT_REF
1515 && DECL_BIT_FIELD (TREE_OPERAND (model->expr, 1)))
1517 /* This access represents a bit-field. */
1518 tree t, exp_type, fld = TREE_OPERAND (model->expr, 1);
1520 offset -= int_bit_position (fld);
1521 exp_type = TREE_TYPE (TREE_OPERAND (model->expr, 0));
1522 t = build_ref_for_offset (loc, base, offset, exp_type, gsi, insert_after);
1523 return fold_build3_loc (loc, COMPONENT_REF, TREE_TYPE (fld), t, fld,
1524 NULL_TREE);
1526 else
1527 return build_ref_for_offset (loc, base, offset, model->type,
1528 gsi, insert_after);
1531 /* Attempt to build a memory reference that we could but into a gimple
1532 debug_bind statement. Similar to build_ref_for_model but punts if it has to
1533 create statements and return s NULL instead. This function also ignores
1534 alignment issues and so its results should never end up in non-debug
1535 statements. */
1537 static tree
1538 build_debug_ref_for_model (location_t loc, tree base, HOST_WIDE_INT offset,
1539 struct access *model)
1541 HOST_WIDE_INT base_offset;
1542 tree off;
1544 if (TREE_CODE (model->expr) == COMPONENT_REF
1545 && DECL_BIT_FIELD (TREE_OPERAND (model->expr, 1)))
1546 return NULL_TREE;
1548 base = get_addr_base_and_unit_offset (base, &base_offset);
1549 if (!base)
1550 return NULL_TREE;
1551 if (TREE_CODE (base) == MEM_REF)
1553 off = build_int_cst (TREE_TYPE (TREE_OPERAND (base, 1)),
1554 base_offset + offset / BITS_PER_UNIT);
1555 off = int_const_binop (PLUS_EXPR, TREE_OPERAND (base, 1), off);
1556 base = unshare_expr (TREE_OPERAND (base, 0));
1558 else
1560 off = build_int_cst (reference_alias_ptr_type (base),
1561 base_offset + offset / BITS_PER_UNIT);
1562 base = build_fold_addr_expr (unshare_expr (base));
1565 return fold_build2_loc (loc, MEM_REF, model->type, base, off);
1568 /* Construct a memory reference consisting of component_refs and array_refs to
1569 a part of an aggregate *RES (which is of type TYPE). The requested part
1570 should have type EXP_TYPE at be the given OFFSET. This function might not
1571 succeed, it returns true when it does and only then *RES points to something
1572 meaningful. This function should be used only to build expressions that we
1573 might need to present to user (e.g. in warnings). In all other situations,
1574 build_ref_for_model or build_ref_for_offset should be used instead. */
1576 static bool
1577 build_user_friendly_ref_for_offset (tree *res, tree type, HOST_WIDE_INT offset,
1578 tree exp_type)
1580 while (1)
1582 tree fld;
1583 tree tr_size, index, minidx;
1584 HOST_WIDE_INT el_size;
1586 if (offset == 0 && exp_type
1587 && types_compatible_p (exp_type, type))
1588 return true;
1590 switch (TREE_CODE (type))
1592 case UNION_TYPE:
1593 case QUAL_UNION_TYPE:
1594 case RECORD_TYPE:
1595 for (fld = TYPE_FIELDS (type); fld; fld = DECL_CHAIN (fld))
1597 HOST_WIDE_INT pos, size;
1598 tree tr_pos, expr, *expr_ptr;
1600 if (TREE_CODE (fld) != FIELD_DECL)
1601 continue;
1603 tr_pos = bit_position (fld);
1604 if (!tr_pos || !host_integerp (tr_pos, 1))
1605 continue;
1606 pos = TREE_INT_CST_LOW (tr_pos);
1607 gcc_assert (TREE_CODE (type) == RECORD_TYPE || pos == 0);
1608 tr_size = DECL_SIZE (fld);
1609 if (!tr_size || !host_integerp (tr_size, 1))
1610 continue;
1611 size = TREE_INT_CST_LOW (tr_size);
1612 if (size == 0)
1614 if (pos != offset)
1615 continue;
1617 else if (pos > offset || (pos + size) <= offset)
1618 continue;
1620 expr = build3 (COMPONENT_REF, TREE_TYPE (fld), *res, fld,
1621 NULL_TREE);
1622 expr_ptr = &expr;
1623 if (build_user_friendly_ref_for_offset (expr_ptr, TREE_TYPE (fld),
1624 offset - pos, exp_type))
1626 *res = expr;
1627 return true;
1630 return false;
1632 case ARRAY_TYPE:
1633 tr_size = TYPE_SIZE (TREE_TYPE (type));
1634 if (!tr_size || !host_integerp (tr_size, 1))
1635 return false;
1636 el_size = tree_low_cst (tr_size, 1);
1638 minidx = TYPE_MIN_VALUE (TYPE_DOMAIN (type));
1639 if (TREE_CODE (minidx) != INTEGER_CST || el_size == 0)
1640 return false;
1641 index = build_int_cst (TYPE_DOMAIN (type), offset / el_size);
1642 if (!integer_zerop (minidx))
1643 index = int_const_binop (PLUS_EXPR, index, minidx);
1644 *res = build4 (ARRAY_REF, TREE_TYPE (type), *res, index,
1645 NULL_TREE, NULL_TREE);
1646 offset = offset % el_size;
1647 type = TREE_TYPE (type);
1648 break;
1650 default:
1651 if (offset != 0)
1652 return false;
1654 if (exp_type)
1655 return false;
1656 else
1657 return true;
1662 /* Return true iff TYPE is stdarg va_list type. */
1664 static inline bool
1665 is_va_list_type (tree type)
1667 return TYPE_MAIN_VARIANT (type) == TYPE_MAIN_VARIANT (va_list_type_node);
1670 /* Print message to dump file why a variable was rejected. */
1672 static void
1673 reject (tree var, const char *msg)
1675 if (dump_file && (dump_flags & TDF_DETAILS))
1677 fprintf (dump_file, "Rejected (%d): %s: ", DECL_UID (var), msg);
1678 print_generic_expr (dump_file, var, 0);
1679 fprintf (dump_file, "\n");
1683 /* Return true if VAR is a candidate for SRA. */
1685 static bool
1686 maybe_add_sra_candidate (tree var)
1688 tree type = TREE_TYPE (var);
1689 const char *msg;
1690 void **slot;
1692 if (!AGGREGATE_TYPE_P (type))
1694 reject (var, "not aggregate");
1695 return false;
1697 if (needs_to_live_in_memory (var))
1699 reject (var, "needs to live in memory");
1700 return false;
1702 if (TREE_THIS_VOLATILE (var))
1704 reject (var, "is volatile");
1705 return false;
1707 if (!COMPLETE_TYPE_P (type))
1709 reject (var, "has incomplete type");
1710 return false;
1712 if (!host_integerp (TYPE_SIZE (type), 1))
1714 reject (var, "type size not fixed");
1715 return false;
1717 if (tree_low_cst (TYPE_SIZE (type), 1) == 0)
1719 reject (var, "type size is zero");
1720 return false;
1722 if (type_internals_preclude_sra_p (type, &msg))
1724 reject (var, msg);
1725 return false;
1727 if (/* Fix for PR 41089. tree-stdarg.c needs to have va_lists intact but
1728 we also want to schedule it rather late. Thus we ignore it in
1729 the early pass. */
1730 (sra_mode == SRA_MODE_EARLY_INTRA
1731 && is_va_list_type (type)))
1733 reject (var, "is va_list");
1734 return false;
1737 bitmap_set_bit (candidate_bitmap, DECL_UID (var));
1738 slot = htab_find_slot_with_hash (candidates, var, DECL_UID (var), INSERT);
1739 *slot = (void *) var;
1741 if (dump_file && (dump_flags & TDF_DETAILS))
1743 fprintf (dump_file, "Candidate (%d): ", DECL_UID (var));
1744 print_generic_expr (dump_file, var, 0);
1745 fprintf (dump_file, "\n");
1748 return true;
1751 /* The very first phase of intraprocedural SRA. It marks in candidate_bitmap
1752 those with type which is suitable for scalarization. */
1754 static bool
1755 find_var_candidates (void)
1757 tree var, parm;
1758 unsigned int i;
1759 bool ret = false;
1761 for (parm = DECL_ARGUMENTS (current_function_decl);
1762 parm;
1763 parm = DECL_CHAIN (parm))
1764 ret |= maybe_add_sra_candidate (parm);
1766 FOR_EACH_LOCAL_DECL (cfun, i, var)
1768 if (TREE_CODE (var) != VAR_DECL)
1769 continue;
1771 ret |= maybe_add_sra_candidate (var);
1774 return ret;
1777 /* Sort all accesses for the given variable, check for partial overlaps and
1778 return NULL if there are any. If there are none, pick a representative for
1779 each combination of offset and size and create a linked list out of them.
1780 Return the pointer to the first representative and make sure it is the first
1781 one in the vector of accesses. */
1783 static struct access *
1784 sort_and_splice_var_accesses (tree var)
1786 int i, j, access_count;
1787 struct access *res, **prev_acc_ptr = &res;
1788 vec<access_p> *access_vec;
1789 bool first = true;
1790 HOST_WIDE_INT low = -1, high = 0;
1792 access_vec = get_base_access_vector (var);
1793 if (!access_vec)
1794 return NULL;
1795 access_count = access_vec->length ();
1797 /* Sort by <OFFSET, SIZE>. */
1798 access_vec->qsort (compare_access_positions);
1800 i = 0;
1801 while (i < access_count)
1803 struct access *access = (*access_vec)[i];
1804 bool grp_write = access->write;
1805 bool grp_read = !access->write;
1806 bool grp_scalar_write = access->write
1807 && is_gimple_reg_type (access->type);
1808 bool grp_scalar_read = !access->write
1809 && is_gimple_reg_type (access->type);
1810 bool grp_assignment_read = access->grp_assignment_read;
1811 bool grp_assignment_write = access->grp_assignment_write;
1812 bool multiple_scalar_reads = false;
1813 bool total_scalarization = access->grp_total_scalarization;
1814 bool grp_partial_lhs = access->grp_partial_lhs;
1815 bool first_scalar = is_gimple_reg_type (access->type);
1816 bool unscalarizable_region = access->grp_unscalarizable_region;
1818 if (first || access->offset >= high)
1820 first = false;
1821 low = access->offset;
1822 high = access->offset + access->size;
1824 else if (access->offset > low && access->offset + access->size > high)
1825 return NULL;
1826 else
1827 gcc_assert (access->offset >= low
1828 && access->offset + access->size <= high);
1830 j = i + 1;
1831 while (j < access_count)
1833 struct access *ac2 = (*access_vec)[j];
1834 if (ac2->offset != access->offset || ac2->size != access->size)
1835 break;
1836 if (ac2->write)
1838 grp_write = true;
1839 grp_scalar_write = (grp_scalar_write
1840 || is_gimple_reg_type (ac2->type));
1842 else
1844 grp_read = true;
1845 if (is_gimple_reg_type (ac2->type))
1847 if (grp_scalar_read)
1848 multiple_scalar_reads = true;
1849 else
1850 grp_scalar_read = true;
1853 grp_assignment_read |= ac2->grp_assignment_read;
1854 grp_assignment_write |= ac2->grp_assignment_write;
1855 grp_partial_lhs |= ac2->grp_partial_lhs;
1856 unscalarizable_region |= ac2->grp_unscalarizable_region;
1857 total_scalarization |= ac2->grp_total_scalarization;
1858 relink_to_new_repr (access, ac2);
1860 /* If there are both aggregate-type and scalar-type accesses with
1861 this combination of size and offset, the comparison function
1862 should have put the scalars first. */
1863 gcc_assert (first_scalar || !is_gimple_reg_type (ac2->type));
1864 ac2->group_representative = access;
1865 j++;
1868 i = j;
1870 access->group_representative = access;
1871 access->grp_write = grp_write;
1872 access->grp_read = grp_read;
1873 access->grp_scalar_read = grp_scalar_read;
1874 access->grp_scalar_write = grp_scalar_write;
1875 access->grp_assignment_read = grp_assignment_read;
1876 access->grp_assignment_write = grp_assignment_write;
1877 access->grp_hint = multiple_scalar_reads || total_scalarization;
1878 access->grp_total_scalarization = total_scalarization;
1879 access->grp_partial_lhs = grp_partial_lhs;
1880 access->grp_unscalarizable_region = unscalarizable_region;
1881 if (access->first_link)
1882 add_access_to_work_queue (access);
1884 *prev_acc_ptr = access;
1885 prev_acc_ptr = &access->next_grp;
1888 gcc_assert (res == (*access_vec)[0]);
1889 return res;
1892 /* Create a variable for the given ACCESS which determines the type, name and a
1893 few other properties. Return the variable declaration and store it also to
1894 ACCESS->replacement. */
1896 static tree
1897 create_access_replacement (struct access *access)
1899 tree repl;
1901 if (access->grp_to_be_debug_replaced)
1903 repl = create_tmp_var_raw (access->type, NULL);
1904 DECL_CONTEXT (repl) = current_function_decl;
1906 else
1907 repl = create_tmp_var (access->type, "SR");
1908 if (TREE_CODE (access->type) == COMPLEX_TYPE
1909 || TREE_CODE (access->type) == VECTOR_TYPE)
1911 if (!access->grp_partial_lhs)
1912 DECL_GIMPLE_REG_P (repl) = 1;
1914 else if (access->grp_partial_lhs
1915 && is_gimple_reg_type (access->type))
1916 TREE_ADDRESSABLE (repl) = 1;
1918 DECL_SOURCE_LOCATION (repl) = DECL_SOURCE_LOCATION (access->base);
1919 DECL_ARTIFICIAL (repl) = 1;
1920 DECL_IGNORED_P (repl) = DECL_IGNORED_P (access->base);
1922 if (DECL_NAME (access->base)
1923 && !DECL_IGNORED_P (access->base)
1924 && !DECL_ARTIFICIAL (access->base))
1926 char *pretty_name = make_fancy_name (access->expr);
1927 tree debug_expr = unshare_expr (access->expr), d;
1928 bool fail = false;
1930 DECL_NAME (repl) = get_identifier (pretty_name);
1931 obstack_free (&name_obstack, pretty_name);
1933 /* Get rid of any SSA_NAMEs embedded in debug_expr,
1934 as DECL_DEBUG_EXPR isn't considered when looking for still
1935 used SSA_NAMEs and thus they could be freed. All debug info
1936 generation cares is whether something is constant or variable
1937 and that get_ref_base_and_extent works properly on the
1938 expression. It cannot handle accesses at a non-constant offset
1939 though, so just give up in those cases. */
1940 for (d = debug_expr;
1941 !fail && (handled_component_p (d) || TREE_CODE (d) == MEM_REF);
1942 d = TREE_OPERAND (d, 0))
1943 switch (TREE_CODE (d))
1945 case ARRAY_REF:
1946 case ARRAY_RANGE_REF:
1947 if (TREE_OPERAND (d, 1)
1948 && TREE_CODE (TREE_OPERAND (d, 1)) != INTEGER_CST)
1949 fail = true;
1950 if (TREE_OPERAND (d, 3)
1951 && TREE_CODE (TREE_OPERAND (d, 3)) != INTEGER_CST)
1952 fail = true;
1953 /* FALLTHRU */
1954 case COMPONENT_REF:
1955 if (TREE_OPERAND (d, 2)
1956 && TREE_CODE (TREE_OPERAND (d, 2)) != INTEGER_CST)
1957 fail = true;
1958 break;
1959 case MEM_REF:
1960 if (TREE_CODE (TREE_OPERAND (d, 0)) != ADDR_EXPR)
1961 fail = true;
1962 else
1963 d = TREE_OPERAND (d, 0);
1964 break;
1965 default:
1966 break;
1968 if (!fail)
1970 SET_DECL_DEBUG_EXPR (repl, debug_expr);
1971 DECL_DEBUG_EXPR_IS_FROM (repl) = 1;
1973 if (access->grp_no_warning)
1974 TREE_NO_WARNING (repl) = 1;
1975 else
1976 TREE_NO_WARNING (repl) = TREE_NO_WARNING (access->base);
1978 else
1979 TREE_NO_WARNING (repl) = 1;
1981 if (dump_file)
1983 if (access->grp_to_be_debug_replaced)
1985 fprintf (dump_file, "Created a debug-only replacement for ");
1986 print_generic_expr (dump_file, access->base, 0);
1987 fprintf (dump_file, " offset: %u, size: %u\n",
1988 (unsigned) access->offset, (unsigned) access->size);
1990 else
1992 fprintf (dump_file, "Created a replacement for ");
1993 print_generic_expr (dump_file, access->base, 0);
1994 fprintf (dump_file, " offset: %u, size: %u: ",
1995 (unsigned) access->offset, (unsigned) access->size);
1996 print_generic_expr (dump_file, repl, 0);
1997 fprintf (dump_file, "\n");
2000 sra_stats.replacements++;
2002 return repl;
2005 /* Return ACCESS scalar replacement, create it if it does not exist yet. */
2007 static inline tree
2008 get_access_replacement (struct access *access)
2010 if (!access->replacement_decl)
2011 access->replacement_decl = create_access_replacement (access);
2012 return access->replacement_decl;
2016 /* Build a subtree of accesses rooted in *ACCESS, and move the pointer in the
2017 linked list along the way. Stop when *ACCESS is NULL or the access pointed
2018 to it is not "within" the root. Return false iff some accesses partially
2019 overlap. */
2021 static bool
2022 build_access_subtree (struct access **access)
2024 struct access *root = *access, *last_child = NULL;
2025 HOST_WIDE_INT limit = root->offset + root->size;
2027 *access = (*access)->next_grp;
2028 while (*access && (*access)->offset + (*access)->size <= limit)
2030 if (!last_child)
2031 root->first_child = *access;
2032 else
2033 last_child->next_sibling = *access;
2034 last_child = *access;
2036 if (!build_access_subtree (access))
2037 return false;
2040 if (*access && (*access)->offset < limit)
2041 return false;
2043 return true;
2046 /* Build a tree of access representatives, ACCESS is the pointer to the first
2047 one, others are linked in a list by the next_grp field. Return false iff
2048 some accesses partially overlap. */
2050 static bool
2051 build_access_trees (struct access *access)
2053 while (access)
2055 struct access *root = access;
2057 if (!build_access_subtree (&access))
2058 return false;
2059 root->next_grp = access;
2061 return true;
2064 /* Return true if expr contains some ARRAY_REFs into a variable bounded
2065 array. */
2067 static bool
2068 expr_with_var_bounded_array_refs_p (tree expr)
2070 while (handled_component_p (expr))
2072 if (TREE_CODE (expr) == ARRAY_REF
2073 && !host_integerp (array_ref_low_bound (expr), 0))
2074 return true;
2075 expr = TREE_OPERAND (expr, 0);
2077 return false;
2080 /* Analyze the subtree of accesses rooted in ROOT, scheduling replacements when
2081 both seeming beneficial and when ALLOW_REPLACEMENTS allows it. Also set all
2082 sorts of access flags appropriately along the way, notably always set
2083 grp_read and grp_assign_read according to MARK_READ and grp_write when
2084 MARK_WRITE is true.
2086 Creating a replacement for a scalar access is considered beneficial if its
2087 grp_hint is set (this means we are either attempting total scalarization or
2088 there is more than one direct read access) or according to the following
2089 table:
2091 Access written to through a scalar type (once or more times)
2093 | Written to in an assignment statement
2095 | | Access read as scalar _once_
2096 | | |
2097 | | | Read in an assignment statement
2098 | | | |
2099 | | | | Scalarize Comment
2100 -----------------------------------------------------------------------------
2101 0 0 0 0 No access for the scalar
2102 0 0 0 1 No access for the scalar
2103 0 0 1 0 No Single read - won't help
2104 0 0 1 1 No The same case
2105 0 1 0 0 No access for the scalar
2106 0 1 0 1 No access for the scalar
2107 0 1 1 0 Yes s = *g; return s.i;
2108 0 1 1 1 Yes The same case as above
2109 1 0 0 0 No Won't help
2110 1 0 0 1 Yes s.i = 1; *g = s;
2111 1 0 1 0 Yes s.i = 5; g = s.i;
2112 1 0 1 1 Yes The same case as above
2113 1 1 0 0 No Won't help.
2114 1 1 0 1 Yes s.i = 1; *g = s;
2115 1 1 1 0 Yes s = *g; return s.i;
2116 1 1 1 1 Yes Any of the above yeses */
2118 static bool
2119 analyze_access_subtree (struct access *root, struct access *parent,
2120 bool allow_replacements)
2122 struct access *child;
2123 HOST_WIDE_INT limit = root->offset + root->size;
2124 HOST_WIDE_INT covered_to = root->offset;
2125 bool scalar = is_gimple_reg_type (root->type);
2126 bool hole = false, sth_created = false;
2128 if (parent)
2130 if (parent->grp_read)
2131 root->grp_read = 1;
2132 if (parent->grp_assignment_read)
2133 root->grp_assignment_read = 1;
2134 if (parent->grp_write)
2135 root->grp_write = 1;
2136 if (parent->grp_assignment_write)
2137 root->grp_assignment_write = 1;
2138 if (parent->grp_total_scalarization)
2139 root->grp_total_scalarization = 1;
2142 if (root->grp_unscalarizable_region)
2143 allow_replacements = false;
2145 if (allow_replacements && expr_with_var_bounded_array_refs_p (root->expr))
2146 allow_replacements = false;
2148 for (child = root->first_child; child; child = child->next_sibling)
2150 hole |= covered_to < child->offset;
2151 sth_created |= analyze_access_subtree (child, root,
2152 allow_replacements && !scalar);
2154 root->grp_unscalarized_data |= child->grp_unscalarized_data;
2155 root->grp_total_scalarization &= child->grp_total_scalarization;
2156 if (child->grp_covered)
2157 covered_to += child->size;
2158 else
2159 hole = true;
2162 if (allow_replacements && scalar && !root->first_child
2163 && (root->grp_hint
2164 || ((root->grp_scalar_read || root->grp_assignment_read)
2165 && (root->grp_scalar_write || root->grp_assignment_write))))
2167 bool new_integer_type;
2168 /* Always create access replacements that cover the whole access.
2169 For integral types this means the precision has to match.
2170 Avoid assumptions based on the integral type kind, too. */
2171 if (INTEGRAL_TYPE_P (root->type)
2172 && (TREE_CODE (root->type) != INTEGER_TYPE
2173 || TYPE_PRECISION (root->type) != root->size)
2174 /* But leave bitfield accesses alone. */
2175 && (TREE_CODE (root->expr) != COMPONENT_REF
2176 || !DECL_BIT_FIELD (TREE_OPERAND (root->expr, 1))))
2178 tree rt = root->type;
2179 gcc_assert ((root->offset % BITS_PER_UNIT) == 0
2180 && (root->size % BITS_PER_UNIT) == 0);
2181 root->type = build_nonstandard_integer_type (root->size,
2182 TYPE_UNSIGNED (rt));
2183 root->expr = build_ref_for_offset (UNKNOWN_LOCATION,
2184 root->base, root->offset,
2185 root->type, NULL, false);
2186 new_integer_type = true;
2188 else
2189 new_integer_type = false;
2191 if (dump_file && (dump_flags & TDF_DETAILS))
2193 fprintf (dump_file, "Marking ");
2194 print_generic_expr (dump_file, root->base, 0);
2195 fprintf (dump_file, " offset: %u, size: %u ",
2196 (unsigned) root->offset, (unsigned) root->size);
2197 fprintf (dump_file, " to be replaced%s.\n",
2198 new_integer_type ? " with an integer": "");
2201 root->grp_to_be_replaced = 1;
2202 sth_created = true;
2203 hole = false;
2205 else
2207 if (MAY_HAVE_DEBUG_STMTS && allow_replacements
2208 && scalar && !root->first_child
2209 && (root->grp_scalar_write || root->grp_assignment_write))
2211 gcc_checking_assert (!root->grp_scalar_read
2212 && !root->grp_assignment_read);
2213 root->grp_to_be_debug_replaced = 1;
2214 if (dump_file && (dump_flags & TDF_DETAILS))
2216 fprintf (dump_file, "Marking ");
2217 print_generic_expr (dump_file, root->base, 0);
2218 fprintf (dump_file, " offset: %u, size: %u ",
2219 (unsigned) root->offset, (unsigned) root->size);
2220 fprintf (dump_file, " to be replaced with debug statements.\n");
2224 if (covered_to < limit)
2225 hole = true;
2226 if (scalar)
2227 root->grp_total_scalarization = 0;
2230 if (sth_created
2231 && (!hole || root->grp_total_scalarization))
2233 root->grp_covered = 1;
2234 return true;
2236 if (root->grp_write || TREE_CODE (root->base) == PARM_DECL)
2237 root->grp_unscalarized_data = 1; /* not covered and written to */
2238 if (sth_created)
2239 return true;
2240 return false;
2243 /* Analyze all access trees linked by next_grp by the means of
2244 analyze_access_subtree. */
2245 static bool
2246 analyze_access_trees (struct access *access)
2248 bool ret = false;
2250 while (access)
2252 if (analyze_access_subtree (access, NULL, true))
2253 ret = true;
2254 access = access->next_grp;
2257 return ret;
2260 /* Return true iff a potential new child of LACC at offset OFFSET and with size
2261 SIZE would conflict with an already existing one. If exactly such a child
2262 already exists in LACC, store a pointer to it in EXACT_MATCH. */
2264 static bool
2265 child_would_conflict_in_lacc (struct access *lacc, HOST_WIDE_INT norm_offset,
2266 HOST_WIDE_INT size, struct access **exact_match)
2268 struct access *child;
2270 for (child = lacc->first_child; child; child = child->next_sibling)
2272 if (child->offset == norm_offset && child->size == size)
2274 *exact_match = child;
2275 return true;
2278 if (child->offset < norm_offset + size
2279 && child->offset + child->size > norm_offset)
2280 return true;
2283 return false;
2286 /* Create a new child access of PARENT, with all properties just like MODEL
2287 except for its offset and with its grp_write false and grp_read true.
2288 Return the new access or NULL if it cannot be created. Note that this access
2289 is created long after all splicing and sorting, it's not located in any
2290 access vector and is automatically a representative of its group. */
2292 static struct access *
2293 create_artificial_child_access (struct access *parent, struct access *model,
2294 HOST_WIDE_INT new_offset)
2296 struct access *access;
2297 struct access **child;
2298 tree expr = parent->base;
2300 gcc_assert (!model->grp_unscalarizable_region);
2302 access = (struct access *) pool_alloc (access_pool);
2303 memset (access, 0, sizeof (struct access));
2304 if (!build_user_friendly_ref_for_offset (&expr, TREE_TYPE (expr), new_offset,
2305 model->type))
2307 access->grp_no_warning = true;
2308 expr = build_ref_for_model (EXPR_LOCATION (parent->base), parent->base,
2309 new_offset, model, NULL, false);
2312 access->base = parent->base;
2313 access->expr = expr;
2314 access->offset = new_offset;
2315 access->size = model->size;
2316 access->type = model->type;
2317 access->grp_write = true;
2318 access->grp_read = false;
2320 child = &parent->first_child;
2321 while (*child && (*child)->offset < new_offset)
2322 child = &(*child)->next_sibling;
2324 access->next_sibling = *child;
2325 *child = access;
2327 return access;
2331 /* Propagate all subaccesses of RACC across an assignment link to LACC. Return
2332 true if any new subaccess was created. Additionally, if RACC is a scalar
2333 access but LACC is not, change the type of the latter, if possible. */
2335 static bool
2336 propagate_subaccesses_across_link (struct access *lacc, struct access *racc)
2338 struct access *rchild;
2339 HOST_WIDE_INT norm_delta = lacc->offset - racc->offset;
2340 bool ret = false;
2342 if (is_gimple_reg_type (lacc->type)
2343 || lacc->grp_unscalarizable_region
2344 || racc->grp_unscalarizable_region)
2345 return false;
2347 if (is_gimple_reg_type (racc->type))
2349 if (!lacc->first_child && !racc->first_child)
2351 tree t = lacc->base;
2353 lacc->type = racc->type;
2354 if (build_user_friendly_ref_for_offset (&t, TREE_TYPE (t),
2355 lacc->offset, racc->type))
2356 lacc->expr = t;
2357 else
2359 lacc->expr = build_ref_for_model (EXPR_LOCATION (lacc->base),
2360 lacc->base, lacc->offset,
2361 racc, NULL, false);
2362 lacc->grp_no_warning = true;
2365 return false;
2368 for (rchild = racc->first_child; rchild; rchild = rchild->next_sibling)
2370 struct access *new_acc = NULL;
2371 HOST_WIDE_INT norm_offset = rchild->offset + norm_delta;
2373 if (rchild->grp_unscalarizable_region)
2374 continue;
2376 if (child_would_conflict_in_lacc (lacc, norm_offset, rchild->size,
2377 &new_acc))
2379 if (new_acc)
2381 rchild->grp_hint = 1;
2382 new_acc->grp_hint |= new_acc->grp_read;
2383 if (rchild->first_child)
2384 ret |= propagate_subaccesses_across_link (new_acc, rchild);
2386 continue;
2389 rchild->grp_hint = 1;
2390 new_acc = create_artificial_child_access (lacc, rchild, norm_offset);
2391 if (new_acc)
2393 ret = true;
2394 if (racc->first_child)
2395 propagate_subaccesses_across_link (new_acc, rchild);
2399 return ret;
2402 /* Propagate all subaccesses across assignment links. */
2404 static void
2405 propagate_all_subaccesses (void)
2407 while (work_queue_head)
2409 struct access *racc = pop_access_from_work_queue ();
2410 struct assign_link *link;
2412 gcc_assert (racc->first_link);
2414 for (link = racc->first_link; link; link = link->next)
2416 struct access *lacc = link->lacc;
2418 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (lacc->base)))
2419 continue;
2420 lacc = lacc->group_representative;
2421 if (propagate_subaccesses_across_link (lacc, racc)
2422 && lacc->first_link)
2423 add_access_to_work_queue (lacc);
2428 /* Go through all accesses collected throughout the (intraprocedural) analysis
2429 stage, exclude overlapping ones, identify representatives and build trees
2430 out of them, making decisions about scalarization on the way. Return true
2431 iff there are any to-be-scalarized variables after this stage. */
2433 static bool
2434 analyze_all_variable_accesses (void)
2436 int res = 0;
2437 bitmap tmp = BITMAP_ALLOC (NULL);
2438 bitmap_iterator bi;
2439 unsigned i, max_total_scalarization_size;
2441 max_total_scalarization_size = UNITS_PER_WORD * BITS_PER_UNIT
2442 * MOVE_RATIO (optimize_function_for_speed_p (cfun));
2444 EXECUTE_IF_SET_IN_BITMAP (candidate_bitmap, 0, i, bi)
2445 if (bitmap_bit_p (should_scalarize_away_bitmap, i)
2446 && !bitmap_bit_p (cannot_scalarize_away_bitmap, i))
2448 tree var = candidate (i);
2450 if (TREE_CODE (var) == VAR_DECL
2451 && type_consists_of_records_p (TREE_TYPE (var)))
2453 if ((unsigned) tree_low_cst (TYPE_SIZE (TREE_TYPE (var)), 1)
2454 <= max_total_scalarization_size)
2456 completely_scalarize_var (var);
2457 if (dump_file && (dump_flags & TDF_DETAILS))
2459 fprintf (dump_file, "Will attempt to totally scalarize ");
2460 print_generic_expr (dump_file, var, 0);
2461 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2464 else if (dump_file && (dump_flags & TDF_DETAILS))
2466 fprintf (dump_file, "Too big to totally scalarize: ");
2467 print_generic_expr (dump_file, var, 0);
2468 fprintf (dump_file, " (UID: %u)\n", DECL_UID (var));
2473 bitmap_copy (tmp, candidate_bitmap);
2474 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2476 tree var = candidate (i);
2477 struct access *access;
2479 access = sort_and_splice_var_accesses (var);
2480 if (!access || !build_access_trees (access))
2481 disqualify_candidate (var,
2482 "No or inhibitingly overlapping accesses.");
2485 propagate_all_subaccesses ();
2487 bitmap_copy (tmp, candidate_bitmap);
2488 EXECUTE_IF_SET_IN_BITMAP (tmp, 0, i, bi)
2490 tree var = candidate (i);
2491 struct access *access = get_first_repr_for_decl (var);
2493 if (analyze_access_trees (access))
2495 res++;
2496 if (dump_file && (dump_flags & TDF_DETAILS))
2498 fprintf (dump_file, "\nAccess trees for ");
2499 print_generic_expr (dump_file, var, 0);
2500 fprintf (dump_file, " (UID: %u): \n", DECL_UID (var));
2501 dump_access_tree (dump_file, access);
2502 fprintf (dump_file, "\n");
2505 else
2506 disqualify_candidate (var, "No scalar replacements to be created.");
2509 BITMAP_FREE (tmp);
2511 if (res)
2513 statistics_counter_event (cfun, "Scalarized aggregates", res);
2514 return true;
2516 else
2517 return false;
2520 /* Generate statements copying scalar replacements of accesses within a subtree
2521 into or out of AGG. ACCESS, all its children, siblings and their children
2522 are to be processed. AGG is an aggregate type expression (can be a
2523 declaration but does not have to be, it can for example also be a mem_ref or
2524 a series of handled components). TOP_OFFSET is the offset of the processed
2525 subtree which has to be subtracted from offsets of individual accesses to
2526 get corresponding offsets for AGG. If CHUNK_SIZE is non-null, copy only
2527 replacements in the interval <start_offset, start_offset + chunk_size>,
2528 otherwise copy all. GSI is a statement iterator used to place the new
2529 statements. WRITE should be true when the statements should write from AGG
2530 to the replacement and false if vice versa. if INSERT_AFTER is true, new
2531 statements will be added after the current statement in GSI, they will be
2532 added before the statement otherwise. */
2534 static void
2535 generate_subtree_copies (struct access *access, tree agg,
2536 HOST_WIDE_INT top_offset,
2537 HOST_WIDE_INT start_offset, HOST_WIDE_INT chunk_size,
2538 gimple_stmt_iterator *gsi, bool write,
2539 bool insert_after, location_t loc)
2543 if (chunk_size && access->offset >= start_offset + chunk_size)
2544 return;
2546 if (access->grp_to_be_replaced
2547 && (chunk_size == 0
2548 || access->offset + access->size > start_offset))
2550 tree expr, repl = get_access_replacement (access);
2551 gimple stmt;
2553 expr = build_ref_for_model (loc, agg, access->offset - top_offset,
2554 access, gsi, insert_after);
2556 if (write)
2558 if (access->grp_partial_lhs)
2559 expr = force_gimple_operand_gsi (gsi, expr, true, NULL_TREE,
2560 !insert_after,
2561 insert_after ? GSI_NEW_STMT
2562 : GSI_SAME_STMT);
2563 stmt = gimple_build_assign (repl, expr);
2565 else
2567 TREE_NO_WARNING (repl) = 1;
2568 if (access->grp_partial_lhs)
2569 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2570 !insert_after,
2571 insert_after ? GSI_NEW_STMT
2572 : GSI_SAME_STMT);
2573 stmt = gimple_build_assign (expr, repl);
2575 gimple_set_location (stmt, loc);
2577 if (insert_after)
2578 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2579 else
2580 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2581 update_stmt (stmt);
2582 sra_stats.subtree_copies++;
2584 else if (write
2585 && access->grp_to_be_debug_replaced
2586 && (chunk_size == 0
2587 || access->offset + access->size > start_offset))
2589 gimple ds;
2590 tree drhs = build_debug_ref_for_model (loc, agg,
2591 access->offset - top_offset,
2592 access);
2593 ds = gimple_build_debug_bind (get_access_replacement (access),
2594 drhs, gsi_stmt (*gsi));
2595 if (insert_after)
2596 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2597 else
2598 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
2601 if (access->first_child)
2602 generate_subtree_copies (access->first_child, agg, top_offset,
2603 start_offset, chunk_size, gsi,
2604 write, insert_after, loc);
2606 access = access->next_sibling;
2608 while (access);
2611 /* Assign zero to all scalar replacements in an access subtree. ACCESS is the
2612 the root of the subtree to be processed. GSI is the statement iterator used
2613 for inserting statements which are added after the current statement if
2614 INSERT_AFTER is true or before it otherwise. */
2616 static void
2617 init_subtree_with_zero (struct access *access, gimple_stmt_iterator *gsi,
2618 bool insert_after, location_t loc)
2621 struct access *child;
2623 if (access->grp_to_be_replaced)
2625 gimple stmt;
2627 stmt = gimple_build_assign (get_access_replacement (access),
2628 build_zero_cst (access->type));
2629 if (insert_after)
2630 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2631 else
2632 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2633 update_stmt (stmt);
2634 gimple_set_location (stmt, loc);
2636 else if (access->grp_to_be_debug_replaced)
2638 gimple ds = gimple_build_debug_bind (get_access_replacement (access),
2639 build_zero_cst (access->type),
2640 gsi_stmt (*gsi));
2641 if (insert_after)
2642 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2643 else
2644 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
2647 for (child = access->first_child; child; child = child->next_sibling)
2648 init_subtree_with_zero (child, gsi, insert_after, loc);
2651 /* Search for an access representative for the given expression EXPR and
2652 return it or NULL if it cannot be found. */
2654 static struct access *
2655 get_access_for_expr (tree expr)
2657 HOST_WIDE_INT offset, size, max_size;
2658 tree base;
2660 /* FIXME: This should not be necessary but Ada produces V_C_Es with a type of
2661 a different size than the size of its argument and we need the latter
2662 one. */
2663 if (TREE_CODE (expr) == VIEW_CONVERT_EXPR)
2664 expr = TREE_OPERAND (expr, 0);
2666 base = get_ref_base_and_extent (expr, &offset, &size, &max_size);
2667 if (max_size == -1 || !DECL_P (base))
2668 return NULL;
2670 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (base)))
2671 return NULL;
2673 return get_var_base_offset_size_access (base, offset, max_size);
2676 /* Replace the expression EXPR with a scalar replacement if there is one and
2677 generate other statements to do type conversion or subtree copying if
2678 necessary. GSI is used to place newly created statements, WRITE is true if
2679 the expression is being written to (it is on a LHS of a statement or output
2680 in an assembly statement). */
2682 static bool
2683 sra_modify_expr (tree *expr, gimple_stmt_iterator *gsi, bool write)
2685 location_t loc;
2686 struct access *access;
2687 tree type, bfr;
2689 if (TREE_CODE (*expr) == BIT_FIELD_REF)
2691 bfr = *expr;
2692 expr = &TREE_OPERAND (*expr, 0);
2694 else
2695 bfr = NULL_TREE;
2697 if (TREE_CODE (*expr) == REALPART_EXPR || TREE_CODE (*expr) == IMAGPART_EXPR)
2698 expr = &TREE_OPERAND (*expr, 0);
2699 access = get_access_for_expr (*expr);
2700 if (!access)
2701 return false;
2702 type = TREE_TYPE (*expr);
2704 loc = gimple_location (gsi_stmt (*gsi));
2705 if (access->grp_to_be_replaced)
2707 tree repl = get_access_replacement (access);
2708 /* If we replace a non-register typed access simply use the original
2709 access expression to extract the scalar component afterwards.
2710 This happens if scalarizing a function return value or parameter
2711 like in gcc.c-torture/execute/20041124-1.c, 20050316-1.c and
2712 gcc.c-torture/compile/20011217-1.c.
2714 We also want to use this when accessing a complex or vector which can
2715 be accessed as a different type too, potentially creating a need for
2716 type conversion (see PR42196) and when scalarized unions are involved
2717 in assembler statements (see PR42398). */
2718 if (!useless_type_conversion_p (type, access->type))
2720 tree ref;
2722 ref = build_ref_for_model (loc, access->base, access->offset, access,
2723 NULL, false);
2725 if (write)
2727 gimple stmt;
2729 if (access->grp_partial_lhs)
2730 ref = force_gimple_operand_gsi (gsi, ref, true, NULL_TREE,
2731 false, GSI_NEW_STMT);
2732 stmt = gimple_build_assign (repl, ref);
2733 gimple_set_location (stmt, loc);
2734 gsi_insert_after (gsi, stmt, GSI_NEW_STMT);
2736 else
2738 gimple stmt;
2740 if (access->grp_partial_lhs)
2741 repl = force_gimple_operand_gsi (gsi, repl, true, NULL_TREE,
2742 true, GSI_SAME_STMT);
2743 stmt = gimple_build_assign (ref, repl);
2744 gimple_set_location (stmt, loc);
2745 gsi_insert_before (gsi, stmt, GSI_SAME_STMT);
2748 else
2749 *expr = repl;
2750 sra_stats.exprs++;
2752 else if (write && access->grp_to_be_debug_replaced)
2754 gimple ds = gimple_build_debug_bind (get_access_replacement (access),
2755 NULL_TREE,
2756 gsi_stmt (*gsi));
2757 gsi_insert_after (gsi, ds, GSI_NEW_STMT);
2760 if (access->first_child)
2762 HOST_WIDE_INT start_offset, chunk_size;
2763 if (bfr
2764 && host_integerp (TREE_OPERAND (bfr, 1), 1)
2765 && host_integerp (TREE_OPERAND (bfr, 2), 1))
2767 chunk_size = tree_low_cst (TREE_OPERAND (bfr, 1), 1);
2768 start_offset = access->offset
2769 + tree_low_cst (TREE_OPERAND (bfr, 2), 1);
2771 else
2772 start_offset = chunk_size = 0;
2774 generate_subtree_copies (access->first_child, access->base, 0,
2775 start_offset, chunk_size, gsi, write, write,
2776 loc);
2778 return true;
2781 /* Where scalar replacements of the RHS have been written to when a replacement
2782 of a LHS of an assigments cannot be direclty loaded from a replacement of
2783 the RHS. */
2784 enum unscalarized_data_handling { SRA_UDH_NONE, /* Nothing done so far. */
2785 SRA_UDH_RIGHT, /* Data flushed to the RHS. */
2786 SRA_UDH_LEFT }; /* Data flushed to the LHS. */
2788 /* Store all replacements in the access tree rooted in TOP_RACC either to their
2789 base aggregate if there are unscalarized data or directly to LHS of the
2790 statement that is pointed to by GSI otherwise. */
2792 static enum unscalarized_data_handling
2793 handle_unscalarized_data_in_subtree (struct access *top_racc,
2794 gimple_stmt_iterator *gsi)
2796 if (top_racc->grp_unscalarized_data)
2798 generate_subtree_copies (top_racc->first_child, top_racc->base, 0, 0, 0,
2799 gsi, false, false,
2800 gimple_location (gsi_stmt (*gsi)));
2801 return SRA_UDH_RIGHT;
2803 else
2805 tree lhs = gimple_assign_lhs (gsi_stmt (*gsi));
2806 generate_subtree_copies (top_racc->first_child, lhs, top_racc->offset,
2807 0, 0, gsi, false, false,
2808 gimple_location (gsi_stmt (*gsi)));
2809 return SRA_UDH_LEFT;
2814 /* Try to generate statements to load all sub-replacements in an access subtree
2815 formed by children of LACC from scalar replacements in the TOP_RACC subtree.
2816 If that is not possible, refresh the TOP_RACC base aggregate and load the
2817 accesses from it. LEFT_OFFSET is the offset of the left whole subtree being
2818 copied. NEW_GSI is stmt iterator used for statement insertions after the
2819 original assignment, OLD_GSI is used to insert statements before the
2820 assignment. *REFRESHED keeps the information whether we have needed to
2821 refresh replacements of the LHS and from which side of the assignments this
2822 takes place. */
2824 static void
2825 load_assign_lhs_subreplacements (struct access *lacc, struct access *top_racc,
2826 HOST_WIDE_INT left_offset,
2827 gimple_stmt_iterator *old_gsi,
2828 gimple_stmt_iterator *new_gsi,
2829 enum unscalarized_data_handling *refreshed)
2831 location_t loc = gimple_location (gsi_stmt (*old_gsi));
2832 for (lacc = lacc->first_child; lacc; lacc = lacc->next_sibling)
2834 HOST_WIDE_INT offset = lacc->offset - left_offset + top_racc->offset;
2836 if (lacc->grp_to_be_replaced)
2838 struct access *racc;
2839 gimple stmt;
2840 tree rhs;
2842 racc = find_access_in_subtree (top_racc, offset, lacc->size);
2843 if (racc && racc->grp_to_be_replaced)
2845 rhs = get_access_replacement (racc);
2846 if (!useless_type_conversion_p (lacc->type, racc->type))
2847 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, lacc->type, rhs);
2849 if (racc->grp_partial_lhs && lacc->grp_partial_lhs)
2850 rhs = force_gimple_operand_gsi (old_gsi, rhs, true, NULL_TREE,
2851 true, GSI_SAME_STMT);
2853 else
2855 /* No suitable access on the right hand side, need to load from
2856 the aggregate. See if we have to update it first... */
2857 if (*refreshed == SRA_UDH_NONE)
2858 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2859 old_gsi);
2861 if (*refreshed == SRA_UDH_LEFT)
2862 rhs = build_ref_for_model (loc, lacc->base, lacc->offset, lacc,
2863 new_gsi, true);
2864 else
2865 rhs = build_ref_for_model (loc, top_racc->base, offset, lacc,
2866 new_gsi, true);
2867 if (lacc->grp_partial_lhs)
2868 rhs = force_gimple_operand_gsi (new_gsi, rhs, true, NULL_TREE,
2869 false, GSI_NEW_STMT);
2872 stmt = gimple_build_assign (get_access_replacement (lacc), rhs);
2873 gsi_insert_after (new_gsi, stmt, GSI_NEW_STMT);
2874 gimple_set_location (stmt, loc);
2875 update_stmt (stmt);
2876 sra_stats.subreplacements++;
2878 else
2880 if (*refreshed == SRA_UDH_NONE
2881 && lacc->grp_read && !lacc->grp_covered)
2882 *refreshed = handle_unscalarized_data_in_subtree (top_racc,
2883 old_gsi);
2884 if (lacc && lacc->grp_to_be_debug_replaced)
2886 gimple ds;
2887 tree drhs;
2888 struct access *racc = find_access_in_subtree (top_racc, offset,
2889 lacc->size);
2891 if (racc && racc->grp_to_be_replaced)
2892 drhs = get_access_replacement (racc);
2893 else if (*refreshed == SRA_UDH_LEFT)
2894 drhs = build_debug_ref_for_model (loc, lacc->base, lacc->offset,
2895 lacc);
2896 else if (*refreshed == SRA_UDH_RIGHT)
2897 drhs = build_debug_ref_for_model (loc, top_racc->base, offset,
2898 lacc);
2899 else
2900 drhs = NULL_TREE;
2901 ds = gimple_build_debug_bind (get_access_replacement (lacc),
2902 drhs, gsi_stmt (*old_gsi));
2903 gsi_insert_after (new_gsi, ds, GSI_NEW_STMT);
2907 if (lacc->first_child)
2908 load_assign_lhs_subreplacements (lacc, top_racc, left_offset,
2909 old_gsi, new_gsi, refreshed);
2913 /* Result code for SRA assignment modification. */
2914 enum assignment_mod_result { SRA_AM_NONE, /* nothing done for the stmt */
2915 SRA_AM_MODIFIED, /* stmt changed but not
2916 removed */
2917 SRA_AM_REMOVED }; /* stmt eliminated */
2919 /* Modify assignments with a CONSTRUCTOR on their RHS. STMT contains a pointer
2920 to the assignment and GSI is the statement iterator pointing at it. Returns
2921 the same values as sra_modify_assign. */
2923 static enum assignment_mod_result
2924 sra_modify_constructor_assign (gimple *stmt, gimple_stmt_iterator *gsi)
2926 tree lhs = gimple_assign_lhs (*stmt);
2927 struct access *acc;
2928 location_t loc;
2930 acc = get_access_for_expr (lhs);
2931 if (!acc)
2932 return SRA_AM_NONE;
2934 if (gimple_clobber_p (*stmt))
2936 /* Remove clobbers of fully scalarized variables, otherwise
2937 do nothing. */
2938 if (acc->grp_covered)
2940 unlink_stmt_vdef (*stmt);
2941 gsi_remove (gsi, true);
2942 release_defs (*stmt);
2943 return SRA_AM_REMOVED;
2945 else
2946 return SRA_AM_NONE;
2949 loc = gimple_location (*stmt);
2950 if (vec_safe_length (CONSTRUCTOR_ELTS (gimple_assign_rhs1 (*stmt))) > 0)
2952 /* I have never seen this code path trigger but if it can happen the
2953 following should handle it gracefully. */
2954 if (access_has_children_p (acc))
2955 generate_subtree_copies (acc->first_child, acc->base, 0, 0, 0, gsi,
2956 true, true, loc);
2957 return SRA_AM_MODIFIED;
2960 if (acc->grp_covered)
2962 init_subtree_with_zero (acc, gsi, false, loc);
2963 unlink_stmt_vdef (*stmt);
2964 gsi_remove (gsi, true);
2965 release_defs (*stmt);
2966 return SRA_AM_REMOVED;
2968 else
2970 init_subtree_with_zero (acc, gsi, true, loc);
2971 return SRA_AM_MODIFIED;
2975 /* Create and return a new suitable default definition SSA_NAME for RACC which
2976 is an access describing an uninitialized part of an aggregate that is being
2977 loaded. */
2979 static tree
2980 get_repl_default_def_ssa_name (struct access *racc)
2982 return get_or_create_ssa_default_def (cfun, get_access_replacement (racc));
2985 /* Return true if REF has a COMPONENT_REF with a bit-field field declaration
2986 somewhere in it. */
2988 static inline bool
2989 contains_bitfld_comp_ref_p (const_tree ref)
2991 while (handled_component_p (ref))
2993 if (TREE_CODE (ref) == COMPONENT_REF
2994 && DECL_BIT_FIELD (TREE_OPERAND (ref, 1)))
2995 return true;
2996 ref = TREE_OPERAND (ref, 0);
2999 return false;
3002 /* Return true if REF has an VIEW_CONVERT_EXPR or a COMPONENT_REF with a
3003 bit-field field declaration somewhere in it. */
3005 static inline bool
3006 contains_vce_or_bfcref_p (const_tree ref)
3008 while (handled_component_p (ref))
3010 if (TREE_CODE (ref) == VIEW_CONVERT_EXPR
3011 || (TREE_CODE (ref) == COMPONENT_REF
3012 && DECL_BIT_FIELD (TREE_OPERAND (ref, 1))))
3013 return true;
3014 ref = TREE_OPERAND (ref, 0);
3017 return false;
3020 /* Examine both sides of the assignment statement pointed to by STMT, replace
3021 them with a scalare replacement if there is one and generate copying of
3022 replacements if scalarized aggregates have been used in the assignment. GSI
3023 is used to hold generated statements for type conversions and subtree
3024 copying. */
3026 static enum assignment_mod_result
3027 sra_modify_assign (gimple *stmt, gimple_stmt_iterator *gsi)
3029 struct access *lacc, *racc;
3030 tree lhs, rhs;
3031 bool modify_this_stmt = false;
3032 bool force_gimple_rhs = false;
3033 location_t loc;
3034 gimple_stmt_iterator orig_gsi = *gsi;
3036 if (!gimple_assign_single_p (*stmt))
3037 return SRA_AM_NONE;
3038 lhs = gimple_assign_lhs (*stmt);
3039 rhs = gimple_assign_rhs1 (*stmt);
3041 if (TREE_CODE (rhs) == CONSTRUCTOR)
3042 return sra_modify_constructor_assign (stmt, gsi);
3044 if (TREE_CODE (rhs) == REALPART_EXPR || TREE_CODE (lhs) == REALPART_EXPR
3045 || TREE_CODE (rhs) == IMAGPART_EXPR || TREE_CODE (lhs) == IMAGPART_EXPR
3046 || TREE_CODE (rhs) == BIT_FIELD_REF || TREE_CODE (lhs) == BIT_FIELD_REF)
3048 modify_this_stmt = sra_modify_expr (gimple_assign_rhs1_ptr (*stmt),
3049 gsi, false);
3050 modify_this_stmt |= sra_modify_expr (gimple_assign_lhs_ptr (*stmt),
3051 gsi, true);
3052 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3055 lacc = get_access_for_expr (lhs);
3056 racc = get_access_for_expr (rhs);
3057 if (!lacc && !racc)
3058 return SRA_AM_NONE;
3060 loc = gimple_location (*stmt);
3061 if (lacc && lacc->grp_to_be_replaced)
3063 lhs = get_access_replacement (lacc);
3064 gimple_assign_set_lhs (*stmt, lhs);
3065 modify_this_stmt = true;
3066 if (lacc->grp_partial_lhs)
3067 force_gimple_rhs = true;
3068 sra_stats.exprs++;
3071 if (racc && racc->grp_to_be_replaced)
3073 rhs = get_access_replacement (racc);
3074 modify_this_stmt = true;
3075 if (racc->grp_partial_lhs)
3076 force_gimple_rhs = true;
3077 sra_stats.exprs++;
3079 else if (racc
3080 && !racc->grp_unscalarized_data
3081 && TREE_CODE (lhs) == SSA_NAME
3082 && !access_has_replacements_p (racc))
3084 rhs = get_repl_default_def_ssa_name (racc);
3085 modify_this_stmt = true;
3086 sra_stats.exprs++;
3089 if (modify_this_stmt)
3091 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3093 /* If we can avoid creating a VIEW_CONVERT_EXPR do so.
3094 ??? This should move to fold_stmt which we simply should
3095 call after building a VIEW_CONVERT_EXPR here. */
3096 if (AGGREGATE_TYPE_P (TREE_TYPE (lhs))
3097 && !contains_bitfld_comp_ref_p (lhs)
3098 && !access_has_children_p (lacc))
3100 lhs = build_ref_for_model (loc, lhs, 0, racc, gsi, false);
3101 gimple_assign_set_lhs (*stmt, lhs);
3103 else if (AGGREGATE_TYPE_P (TREE_TYPE (rhs))
3104 && !contains_vce_or_bfcref_p (rhs)
3105 && !access_has_children_p (racc))
3106 rhs = build_ref_for_model (loc, rhs, 0, lacc, gsi, false);
3108 if (!useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (rhs)))
3110 rhs = fold_build1_loc (loc, VIEW_CONVERT_EXPR, TREE_TYPE (lhs),
3111 rhs);
3112 if (is_gimple_reg_type (TREE_TYPE (lhs))
3113 && TREE_CODE (lhs) != SSA_NAME)
3114 force_gimple_rhs = true;
3119 if (lacc && lacc->grp_to_be_debug_replaced)
3121 gimple ds = gimple_build_debug_bind (get_access_replacement (lacc),
3122 unshare_expr (rhs), *stmt);
3123 gsi_insert_before (gsi, ds, GSI_SAME_STMT);
3126 /* From this point on, the function deals with assignments in between
3127 aggregates when at least one has scalar reductions of some of its
3128 components. There are three possible scenarios: Both the LHS and RHS have
3129 to-be-scalarized components, 2) only the RHS has or 3) only the LHS has.
3131 In the first case, we would like to load the LHS components from RHS
3132 components whenever possible. If that is not possible, we would like to
3133 read it directly from the RHS (after updating it by storing in it its own
3134 components). If there are some necessary unscalarized data in the LHS,
3135 those will be loaded by the original assignment too. If neither of these
3136 cases happen, the original statement can be removed. Most of this is done
3137 by load_assign_lhs_subreplacements.
3139 In the second case, we would like to store all RHS scalarized components
3140 directly into LHS and if they cover the aggregate completely, remove the
3141 statement too. In the third case, we want the LHS components to be loaded
3142 directly from the RHS (DSE will remove the original statement if it
3143 becomes redundant).
3145 This is a bit complex but manageable when types match and when unions do
3146 not cause confusion in a way that we cannot really load a component of LHS
3147 from the RHS or vice versa (the access representing this level can have
3148 subaccesses that are accessible only through a different union field at a
3149 higher level - different from the one used in the examined expression).
3150 Unions are fun.
3152 Therefore, I specially handle a fourth case, happening when there is a
3153 specific type cast or it is impossible to locate a scalarized subaccess on
3154 the other side of the expression. If that happens, I simply "refresh" the
3155 RHS by storing in it is scalarized components leave the original statement
3156 there to do the copying and then load the scalar replacements of the LHS.
3157 This is what the first branch does. */
3159 if (modify_this_stmt
3160 || gimple_has_volatile_ops (*stmt)
3161 || contains_vce_or_bfcref_p (rhs)
3162 || contains_vce_or_bfcref_p (lhs))
3164 if (access_has_children_p (racc))
3165 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3166 gsi, false, false, loc);
3167 if (access_has_children_p (lacc))
3168 generate_subtree_copies (lacc->first_child, lacc->base, 0, 0, 0,
3169 gsi, true, true, loc);
3170 sra_stats.separate_lhs_rhs_handling++;
3172 /* This gimplification must be done after generate_subtree_copies,
3173 lest we insert the subtree copies in the middle of the gimplified
3174 sequence. */
3175 if (force_gimple_rhs)
3176 rhs = force_gimple_operand_gsi (&orig_gsi, rhs, true, NULL_TREE,
3177 true, GSI_SAME_STMT);
3178 if (gimple_assign_rhs1 (*stmt) != rhs)
3180 modify_this_stmt = true;
3181 gimple_assign_set_rhs_from_tree (&orig_gsi, rhs);
3182 gcc_assert (*stmt == gsi_stmt (orig_gsi));
3185 return modify_this_stmt ? SRA_AM_MODIFIED : SRA_AM_NONE;
3187 else
3189 if (access_has_children_p (lacc)
3190 && access_has_children_p (racc)
3191 /* When an access represents an unscalarizable region, it usually
3192 represents accesses with variable offset and thus must not be used
3193 to generate new memory accesses. */
3194 && !lacc->grp_unscalarizable_region
3195 && !racc->grp_unscalarizable_region)
3197 gimple_stmt_iterator orig_gsi = *gsi;
3198 enum unscalarized_data_handling refreshed;
3200 if (lacc->grp_read && !lacc->grp_covered)
3201 refreshed = handle_unscalarized_data_in_subtree (racc, gsi);
3202 else
3203 refreshed = SRA_UDH_NONE;
3205 load_assign_lhs_subreplacements (lacc, racc, lacc->offset,
3206 &orig_gsi, gsi, &refreshed);
3207 if (refreshed != SRA_UDH_RIGHT)
3209 gsi_next (gsi);
3210 unlink_stmt_vdef (*stmt);
3211 gsi_remove (&orig_gsi, true);
3212 release_defs (*stmt);
3213 sra_stats.deleted++;
3214 return SRA_AM_REMOVED;
3217 else
3219 if (access_has_children_p (racc)
3220 && !racc->grp_unscalarized_data)
3222 if (dump_file)
3224 fprintf (dump_file, "Removing load: ");
3225 print_gimple_stmt (dump_file, *stmt, 0, 0);
3227 generate_subtree_copies (racc->first_child, lhs,
3228 racc->offset, 0, 0, gsi,
3229 false, false, loc);
3230 gcc_assert (*stmt == gsi_stmt (*gsi));
3231 unlink_stmt_vdef (*stmt);
3232 gsi_remove (gsi, true);
3233 release_defs (*stmt);
3234 sra_stats.deleted++;
3235 return SRA_AM_REMOVED;
3237 /* Restore the aggregate RHS from its components so the
3238 prevailing aggregate copy does the right thing. */
3239 if (access_has_children_p (racc))
3240 generate_subtree_copies (racc->first_child, racc->base, 0, 0, 0,
3241 gsi, false, false, loc);
3242 /* Re-load the components of the aggregate copy destination.
3243 But use the RHS aggregate to load from to expose more
3244 optimization opportunities. */
3245 if (access_has_children_p (lacc))
3246 generate_subtree_copies (lacc->first_child, rhs, lacc->offset,
3247 0, 0, gsi, true, true, loc);
3250 return SRA_AM_NONE;
3254 /* Traverse the function body and all modifications as decided in
3255 analyze_all_variable_accesses. Return true iff the CFG has been
3256 changed. */
3258 static bool
3259 sra_modify_function_body (void)
3261 bool cfg_changed = false;
3262 basic_block bb;
3264 FOR_EACH_BB (bb)
3266 gimple_stmt_iterator gsi = gsi_start_bb (bb);
3267 while (!gsi_end_p (gsi))
3269 gimple stmt = gsi_stmt (gsi);
3270 enum assignment_mod_result assign_result;
3271 bool modified = false, deleted = false;
3272 tree *t;
3273 unsigned i;
3275 switch (gimple_code (stmt))
3277 case GIMPLE_RETURN:
3278 t = gimple_return_retval_ptr (stmt);
3279 if (*t != NULL_TREE)
3280 modified |= sra_modify_expr (t, &gsi, false);
3281 break;
3283 case GIMPLE_ASSIGN:
3284 assign_result = sra_modify_assign (&stmt, &gsi);
3285 modified |= assign_result == SRA_AM_MODIFIED;
3286 deleted = assign_result == SRA_AM_REMOVED;
3287 break;
3289 case GIMPLE_CALL:
3290 /* Operands must be processed before the lhs. */
3291 for (i = 0; i < gimple_call_num_args (stmt); i++)
3293 t = gimple_call_arg_ptr (stmt, i);
3294 modified |= sra_modify_expr (t, &gsi, false);
3297 if (gimple_call_lhs (stmt))
3299 t = gimple_call_lhs_ptr (stmt);
3300 modified |= sra_modify_expr (t, &gsi, true);
3302 break;
3304 case GIMPLE_ASM:
3305 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
3307 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
3308 modified |= sra_modify_expr (t, &gsi, false);
3310 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
3312 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
3313 modified |= sra_modify_expr (t, &gsi, true);
3315 break;
3317 default:
3318 break;
3321 if (modified)
3323 update_stmt (stmt);
3324 if (maybe_clean_eh_stmt (stmt)
3325 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
3326 cfg_changed = true;
3328 if (!deleted)
3329 gsi_next (&gsi);
3333 return cfg_changed;
3336 /* Generate statements initializing scalar replacements of parts of function
3337 parameters. */
3339 static void
3340 initialize_parameter_reductions (void)
3342 gimple_stmt_iterator gsi;
3343 gimple_seq seq = NULL;
3344 tree parm;
3346 gsi = gsi_start (seq);
3347 for (parm = DECL_ARGUMENTS (current_function_decl);
3348 parm;
3349 parm = DECL_CHAIN (parm))
3351 vec<access_p> *access_vec;
3352 struct access *access;
3354 if (!bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
3355 continue;
3356 access_vec = get_base_access_vector (parm);
3357 if (!access_vec)
3358 continue;
3360 for (access = (*access_vec)[0];
3361 access;
3362 access = access->next_grp)
3363 generate_subtree_copies (access, parm, 0, 0, 0, &gsi, true, true,
3364 EXPR_LOCATION (parm));
3367 seq = gsi_seq (gsi);
3368 if (seq)
3369 gsi_insert_seq_on_edge_immediate (single_succ_edge (ENTRY_BLOCK_PTR), seq);
3372 /* The "main" function of intraprocedural SRA passes. Runs the analysis and if
3373 it reveals there are components of some aggregates to be scalarized, it runs
3374 the required transformations. */
3375 static unsigned int
3376 perform_intra_sra (void)
3378 int ret = 0;
3379 sra_initialize ();
3381 if (!find_var_candidates ())
3382 goto out;
3384 if (!scan_function ())
3385 goto out;
3387 if (!analyze_all_variable_accesses ())
3388 goto out;
3390 if (sra_modify_function_body ())
3391 ret = TODO_update_ssa | TODO_cleanup_cfg;
3392 else
3393 ret = TODO_update_ssa;
3394 initialize_parameter_reductions ();
3396 statistics_counter_event (cfun, "Scalar replacements created",
3397 sra_stats.replacements);
3398 statistics_counter_event (cfun, "Modified expressions", sra_stats.exprs);
3399 statistics_counter_event (cfun, "Subtree copy stmts",
3400 sra_stats.subtree_copies);
3401 statistics_counter_event (cfun, "Subreplacement stmts",
3402 sra_stats.subreplacements);
3403 statistics_counter_event (cfun, "Deleted stmts", sra_stats.deleted);
3404 statistics_counter_event (cfun, "Separate LHS and RHS handling",
3405 sra_stats.separate_lhs_rhs_handling);
3407 out:
3408 sra_deinitialize ();
3409 return ret;
3412 /* Perform early intraprocedural SRA. */
3413 static unsigned int
3414 early_intra_sra (void)
3416 sra_mode = SRA_MODE_EARLY_INTRA;
3417 return perform_intra_sra ();
3420 /* Perform "late" intraprocedural SRA. */
3421 static unsigned int
3422 late_intra_sra (void)
3424 sra_mode = SRA_MODE_INTRA;
3425 return perform_intra_sra ();
3429 static bool
3430 gate_intra_sra (void)
3432 return flag_tree_sra != 0 && dbg_cnt (tree_sra);
3436 struct gimple_opt_pass pass_sra_early =
3439 GIMPLE_PASS,
3440 "esra", /* name */
3441 OPTGROUP_NONE, /* optinfo_flags */
3442 gate_intra_sra, /* gate */
3443 early_intra_sra, /* execute */
3444 NULL, /* sub */
3445 NULL, /* next */
3446 0, /* static_pass_number */
3447 TV_TREE_SRA, /* tv_id */
3448 PROP_cfg | PROP_ssa, /* properties_required */
3449 0, /* properties_provided */
3450 0, /* properties_destroyed */
3451 0, /* todo_flags_start */
3452 TODO_update_ssa
3453 | TODO_ggc_collect
3454 | TODO_verify_ssa /* todo_flags_finish */
3458 struct gimple_opt_pass pass_sra =
3461 GIMPLE_PASS,
3462 "sra", /* name */
3463 OPTGROUP_NONE, /* optinfo_flags */
3464 gate_intra_sra, /* gate */
3465 late_intra_sra, /* execute */
3466 NULL, /* sub */
3467 NULL, /* next */
3468 0, /* static_pass_number */
3469 TV_TREE_SRA, /* tv_id */
3470 PROP_cfg | PROP_ssa, /* properties_required */
3471 0, /* properties_provided */
3472 0, /* properties_destroyed */
3473 TODO_update_address_taken, /* todo_flags_start */
3474 TODO_update_ssa
3475 | TODO_ggc_collect
3476 | TODO_verify_ssa /* todo_flags_finish */
3481 /* Return true iff PARM (which must be a parm_decl) is an unused scalar
3482 parameter. */
3484 static bool
3485 is_unused_scalar_param (tree parm)
3487 tree name;
3488 return (is_gimple_reg (parm)
3489 && (!(name = ssa_default_def (cfun, parm))
3490 || has_zero_uses (name)));
3493 /* Scan immediate uses of a default definition SSA name of a parameter PARM and
3494 examine whether there are any direct or otherwise infeasible ones. If so,
3495 return true, otherwise return false. PARM must be a gimple register with a
3496 non-NULL default definition. */
3498 static bool
3499 ptr_parm_has_direct_uses (tree parm)
3501 imm_use_iterator ui;
3502 gimple stmt;
3503 tree name = ssa_default_def (cfun, parm);
3504 bool ret = false;
3506 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
3508 int uses_ok = 0;
3509 use_operand_p use_p;
3511 if (is_gimple_debug (stmt))
3512 continue;
3514 /* Valid uses include dereferences on the lhs and the rhs. */
3515 if (gimple_has_lhs (stmt))
3517 tree lhs = gimple_get_lhs (stmt);
3518 while (handled_component_p (lhs))
3519 lhs = TREE_OPERAND (lhs, 0);
3520 if (TREE_CODE (lhs) == MEM_REF
3521 && TREE_OPERAND (lhs, 0) == name
3522 && integer_zerop (TREE_OPERAND (lhs, 1))
3523 && types_compatible_p (TREE_TYPE (lhs),
3524 TREE_TYPE (TREE_TYPE (name)))
3525 && !TREE_THIS_VOLATILE (lhs))
3526 uses_ok++;
3528 if (gimple_assign_single_p (stmt))
3530 tree rhs = gimple_assign_rhs1 (stmt);
3531 while (handled_component_p (rhs))
3532 rhs = TREE_OPERAND (rhs, 0);
3533 if (TREE_CODE (rhs) == MEM_REF
3534 && TREE_OPERAND (rhs, 0) == name
3535 && integer_zerop (TREE_OPERAND (rhs, 1))
3536 && types_compatible_p (TREE_TYPE (rhs),
3537 TREE_TYPE (TREE_TYPE (name)))
3538 && !TREE_THIS_VOLATILE (rhs))
3539 uses_ok++;
3541 else if (is_gimple_call (stmt))
3543 unsigned i;
3544 for (i = 0; i < gimple_call_num_args (stmt); ++i)
3546 tree arg = gimple_call_arg (stmt, i);
3547 while (handled_component_p (arg))
3548 arg = TREE_OPERAND (arg, 0);
3549 if (TREE_CODE (arg) == MEM_REF
3550 && TREE_OPERAND (arg, 0) == name
3551 && integer_zerop (TREE_OPERAND (arg, 1))
3552 && types_compatible_p (TREE_TYPE (arg),
3553 TREE_TYPE (TREE_TYPE (name)))
3554 && !TREE_THIS_VOLATILE (arg))
3555 uses_ok++;
3559 /* If the number of valid uses does not match the number of
3560 uses in this stmt there is an unhandled use. */
3561 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
3562 --uses_ok;
3564 if (uses_ok != 0)
3565 ret = true;
3567 if (ret)
3568 BREAK_FROM_IMM_USE_STMT (ui);
3571 return ret;
3574 /* Identify candidates for reduction for IPA-SRA based on their type and mark
3575 them in candidate_bitmap. Note that these do not necessarily include
3576 parameter which are unused and thus can be removed. Return true iff any
3577 such candidate has been found. */
3579 static bool
3580 find_param_candidates (void)
3582 tree parm;
3583 int count = 0;
3584 bool ret = false;
3585 const char *msg;
3587 for (parm = DECL_ARGUMENTS (current_function_decl);
3588 parm;
3589 parm = DECL_CHAIN (parm))
3591 tree type = TREE_TYPE (parm);
3592 void **slot;
3594 count++;
3596 if (TREE_THIS_VOLATILE (parm)
3597 || TREE_ADDRESSABLE (parm)
3598 || (!is_gimple_reg_type (type) && is_va_list_type (type)))
3599 continue;
3601 if (is_unused_scalar_param (parm))
3603 ret = true;
3604 continue;
3607 if (POINTER_TYPE_P (type))
3609 type = TREE_TYPE (type);
3611 if (TREE_CODE (type) == FUNCTION_TYPE
3612 || TYPE_VOLATILE (type)
3613 || upc_shared_type_p (type)
3614 || (TREE_CODE (type) == ARRAY_TYPE
3615 && TYPE_NONALIASED_COMPONENT (type))
3616 || !is_gimple_reg (parm)
3617 || is_va_list_type (type)
3618 || ptr_parm_has_direct_uses (parm))
3619 continue;
3621 else if (!AGGREGATE_TYPE_P (type))
3622 continue;
3624 if (!COMPLETE_TYPE_P (type)
3625 || !host_integerp (TYPE_SIZE (type), 1)
3626 || tree_low_cst (TYPE_SIZE (type), 1) == 0
3627 || (AGGREGATE_TYPE_P (type)
3628 && type_internals_preclude_sra_p (type, &msg)))
3629 continue;
3631 bitmap_set_bit (candidate_bitmap, DECL_UID (parm));
3632 slot = htab_find_slot_with_hash (candidates, parm,
3633 DECL_UID (parm), INSERT);
3634 *slot = (void *) parm;
3636 ret = true;
3637 if (dump_file && (dump_flags & TDF_DETAILS))
3639 fprintf (dump_file, "Candidate (%d): ", DECL_UID (parm));
3640 print_generic_expr (dump_file, parm, 0);
3641 fprintf (dump_file, "\n");
3645 func_param_count = count;
3646 return ret;
3649 /* Callback of walk_aliased_vdefs, marks the access passed as DATA as
3650 maybe_modified. */
3652 static bool
3653 mark_maybe_modified (ao_ref *ao ATTRIBUTE_UNUSED, tree vdef ATTRIBUTE_UNUSED,
3654 void *data)
3656 struct access *repr = (struct access *) data;
3658 repr->grp_maybe_modified = 1;
3659 return true;
3662 /* Analyze what representatives (in linked lists accessible from
3663 REPRESENTATIVES) can be modified by side effects of statements in the
3664 current function. */
3666 static void
3667 analyze_modified_params (vec<access_p> representatives)
3669 int i;
3671 for (i = 0; i < func_param_count; i++)
3673 struct access *repr;
3675 for (repr = representatives[i];
3676 repr;
3677 repr = repr->next_grp)
3679 struct access *access;
3680 bitmap visited;
3681 ao_ref ar;
3683 if (no_accesses_p (repr))
3684 continue;
3685 if (!POINTER_TYPE_P (TREE_TYPE (repr->base))
3686 || repr->grp_maybe_modified)
3687 continue;
3689 ao_ref_init (&ar, repr->expr);
3690 visited = BITMAP_ALLOC (NULL);
3691 for (access = repr; access; access = access->next_sibling)
3693 /* All accesses are read ones, otherwise grp_maybe_modified would
3694 be trivially set. */
3695 walk_aliased_vdefs (&ar, gimple_vuse (access->stmt),
3696 mark_maybe_modified, repr, &visited);
3697 if (repr->grp_maybe_modified)
3698 break;
3700 BITMAP_FREE (visited);
3705 /* Propagate distances in bb_dereferences in the opposite direction than the
3706 control flow edges, in each step storing the maximum of the current value
3707 and the minimum of all successors. These steps are repeated until the table
3708 stabilizes. Note that BBs which might terminate the functions (according to
3709 final_bbs bitmap) never updated in this way. */
3711 static void
3712 propagate_dereference_distances (void)
3714 vec<basic_block> queue;
3715 basic_block bb;
3717 queue.create (last_basic_block_for_function (cfun));
3718 queue.quick_push (ENTRY_BLOCK_PTR);
3719 FOR_EACH_BB (bb)
3721 queue.quick_push (bb);
3722 bb->aux = bb;
3725 while (!queue.is_empty ())
3727 edge_iterator ei;
3728 edge e;
3729 bool change = false;
3730 int i;
3732 bb = queue.pop ();
3733 bb->aux = NULL;
3735 if (bitmap_bit_p (final_bbs, bb->index))
3736 continue;
3738 for (i = 0; i < func_param_count; i++)
3740 int idx = bb->index * func_param_count + i;
3741 bool first = true;
3742 HOST_WIDE_INT inh = 0;
3744 FOR_EACH_EDGE (e, ei, bb->succs)
3746 int succ_idx = e->dest->index * func_param_count + i;
3748 if (e->src == EXIT_BLOCK_PTR)
3749 continue;
3751 if (first)
3753 first = false;
3754 inh = bb_dereferences [succ_idx];
3756 else if (bb_dereferences [succ_idx] < inh)
3757 inh = bb_dereferences [succ_idx];
3760 if (!first && bb_dereferences[idx] < inh)
3762 bb_dereferences[idx] = inh;
3763 change = true;
3767 if (change && !bitmap_bit_p (final_bbs, bb->index))
3768 FOR_EACH_EDGE (e, ei, bb->preds)
3770 if (e->src->aux)
3771 continue;
3773 e->src->aux = e->src;
3774 queue.quick_push (e->src);
3778 queue.release ();
3781 /* Dump a dereferences TABLE with heading STR to file F. */
3783 static void
3784 dump_dereferences_table (FILE *f, const char *str, HOST_WIDE_INT *table)
3786 basic_block bb;
3788 fprintf (dump_file, str);
3789 FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
3791 fprintf (f, "%4i %i ", bb->index, bitmap_bit_p (final_bbs, bb->index));
3792 if (bb != EXIT_BLOCK_PTR)
3794 int i;
3795 for (i = 0; i < func_param_count; i++)
3797 int idx = bb->index * func_param_count + i;
3798 fprintf (f, " %4" HOST_WIDE_INT_PRINT "d", table[idx]);
3801 fprintf (f, "\n");
3803 fprintf (dump_file, "\n");
3806 /* Determine what (parts of) parameters passed by reference that are not
3807 assigned to are not certainly dereferenced in this function and thus the
3808 dereferencing cannot be safely moved to the caller without potentially
3809 introducing a segfault. Mark such REPRESENTATIVES as
3810 grp_not_necessarilly_dereferenced.
3812 The dereferenced maximum "distance," i.e. the offset + size of the accessed
3813 part is calculated rather than simple booleans are calculated for each
3814 pointer parameter to handle cases when only a fraction of the whole
3815 aggregate is allocated (see testsuite/gcc.c-torture/execute/ipa-sra-2.c for
3816 an example).
3818 The maximum dereference distances for each pointer parameter and BB are
3819 already stored in bb_dereference. This routine simply propagates these
3820 values upwards by propagate_dereference_distances and then compares the
3821 distances of individual parameters in the ENTRY BB to the equivalent
3822 distances of each representative of a (fraction of a) parameter. */
3824 static void
3825 analyze_caller_dereference_legality (vec<access_p> representatives)
3827 int i;
3829 if (dump_file && (dump_flags & TDF_DETAILS))
3830 dump_dereferences_table (dump_file,
3831 "Dereference table before propagation:\n",
3832 bb_dereferences);
3834 propagate_dereference_distances ();
3836 if (dump_file && (dump_flags & TDF_DETAILS))
3837 dump_dereferences_table (dump_file,
3838 "Dereference table after propagation:\n",
3839 bb_dereferences);
3841 for (i = 0; i < func_param_count; i++)
3843 struct access *repr = representatives[i];
3844 int idx = ENTRY_BLOCK_PTR->index * func_param_count + i;
3846 if (!repr || no_accesses_p (repr))
3847 continue;
3851 if ((repr->offset + repr->size) > bb_dereferences[idx])
3852 repr->grp_not_necessarilly_dereferenced = 1;
3853 repr = repr->next_grp;
3855 while (repr);
3859 /* Return the representative access for the parameter declaration PARM if it is
3860 a scalar passed by reference which is not written to and the pointer value
3861 is not used directly. Thus, if it is legal to dereference it in the caller
3862 and we can rule out modifications through aliases, such parameter should be
3863 turned into one passed by value. Return NULL otherwise. */
3865 static struct access *
3866 unmodified_by_ref_scalar_representative (tree parm)
3868 int i, access_count;
3869 struct access *repr;
3870 vec<access_p> *access_vec;
3872 access_vec = get_base_access_vector (parm);
3873 gcc_assert (access_vec);
3874 repr = (*access_vec)[0];
3875 if (repr->write)
3876 return NULL;
3877 repr->group_representative = repr;
3879 access_count = access_vec->length ();
3880 for (i = 1; i < access_count; i++)
3882 struct access *access = (*access_vec)[i];
3883 if (access->write)
3884 return NULL;
3885 access->group_representative = repr;
3886 access->next_sibling = repr->next_sibling;
3887 repr->next_sibling = access;
3890 repr->grp_read = 1;
3891 repr->grp_scalar_ptr = 1;
3892 return repr;
3895 /* Return true iff this ACCESS precludes IPA-SRA of the parameter it is
3896 associated with. REQ_ALIGN is the minimum required alignment. */
3898 static bool
3899 access_precludes_ipa_sra_p (struct access *access, unsigned int req_align)
3901 unsigned int exp_align;
3902 /* Avoid issues such as the second simple testcase in PR 42025. The problem
3903 is incompatible assign in a call statement (and possibly even in asm
3904 statements). This can be relaxed by using a new temporary but only for
3905 non-TREE_ADDRESSABLE types and is probably not worth the complexity. (In
3906 intraprocedural SRA we deal with this by keeping the old aggregate around,
3907 something we cannot do in IPA-SRA.) */
3908 if (access->write
3909 && (is_gimple_call (access->stmt)
3910 || gimple_code (access->stmt) == GIMPLE_ASM))
3911 return true;
3913 exp_align = get_object_alignment (access->expr);
3914 if (exp_align < req_align)
3915 return true;
3917 return false;
3921 /* Sort collected accesses for parameter PARM, identify representatives for
3922 each accessed region and link them together. Return NULL if there are
3923 different but overlapping accesses, return the special ptr value meaning
3924 there are no accesses for this parameter if that is the case and return the
3925 first representative otherwise. Set *RO_GRP if there is a group of accesses
3926 with only read (i.e. no write) accesses. */
3928 static struct access *
3929 splice_param_accesses (tree parm, bool *ro_grp)
3931 int i, j, access_count, group_count;
3932 int agg_size, total_size = 0;
3933 struct access *access, *res, **prev_acc_ptr = &res;
3934 vec<access_p> *access_vec;
3936 access_vec = get_base_access_vector (parm);
3937 if (!access_vec)
3938 return &no_accesses_representant;
3939 access_count = access_vec->length ();
3941 access_vec->qsort (compare_access_positions);
3943 i = 0;
3944 total_size = 0;
3945 group_count = 0;
3946 while (i < access_count)
3948 bool modification;
3949 tree a1_alias_type;
3950 access = (*access_vec)[i];
3951 modification = access->write;
3952 if (access_precludes_ipa_sra_p (access, TYPE_ALIGN (access->type)))
3953 return NULL;
3954 a1_alias_type = reference_alias_ptr_type (access->expr);
3956 /* Access is about to become group representative unless we find some
3957 nasty overlap which would preclude us from breaking this parameter
3958 apart. */
3960 j = i + 1;
3961 while (j < access_count)
3963 struct access *ac2 = (*access_vec)[j];
3964 if (ac2->offset != access->offset)
3966 /* All or nothing law for parameters. */
3967 if (access->offset + access->size > ac2->offset)
3968 return NULL;
3969 else
3970 break;
3972 else if (ac2->size != access->size)
3973 return NULL;
3975 if (access_precludes_ipa_sra_p (ac2, TYPE_ALIGN (access->type))
3976 || (ac2->type != access->type
3977 && (TREE_ADDRESSABLE (ac2->type)
3978 || TREE_ADDRESSABLE (access->type)))
3979 || (reference_alias_ptr_type (ac2->expr) != a1_alias_type))
3980 return NULL;
3982 modification |= ac2->write;
3983 ac2->group_representative = access;
3984 ac2->next_sibling = access->next_sibling;
3985 access->next_sibling = ac2;
3986 j++;
3989 group_count++;
3990 access->grp_maybe_modified = modification;
3991 if (!modification)
3992 *ro_grp = true;
3993 *prev_acc_ptr = access;
3994 prev_acc_ptr = &access->next_grp;
3995 total_size += access->size;
3996 i = j;
3999 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4000 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
4001 else
4002 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
4003 if (total_size >= agg_size)
4004 return NULL;
4006 gcc_assert (group_count > 0);
4007 return res;
4010 /* Decide whether parameters with representative accesses given by REPR should
4011 be reduced into components. */
4013 static int
4014 decide_one_param_reduction (struct access *repr)
4016 int total_size, cur_parm_size, agg_size, new_param_count, parm_size_limit;
4017 bool by_ref;
4018 tree parm;
4020 parm = repr->base;
4021 cur_parm_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (parm)), 1);
4022 gcc_assert (cur_parm_size > 0);
4024 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4026 by_ref = true;
4027 agg_size = tree_low_cst (TYPE_SIZE (TREE_TYPE (TREE_TYPE (parm))), 1);
4029 else
4031 by_ref = false;
4032 agg_size = cur_parm_size;
4035 if (dump_file)
4037 struct access *acc;
4038 fprintf (dump_file, "Evaluating PARAM group sizes for ");
4039 print_generic_expr (dump_file, parm, 0);
4040 fprintf (dump_file, " (UID: %u): \n", DECL_UID (parm));
4041 for (acc = repr; acc; acc = acc->next_grp)
4042 dump_access (dump_file, acc, true);
4045 total_size = 0;
4046 new_param_count = 0;
4048 for (; repr; repr = repr->next_grp)
4050 gcc_assert (parm == repr->base);
4052 /* Taking the address of a non-addressable field is verboten. */
4053 if (by_ref && repr->non_addressable)
4054 return 0;
4056 /* Do not decompose a non-BLKmode param in a way that would
4057 create BLKmode params. Especially for by-reference passing
4058 (thus, pointer-type param) this is hardly worthwhile. */
4059 if (DECL_MODE (parm) != BLKmode
4060 && TYPE_MODE (repr->type) == BLKmode)
4061 return 0;
4063 if (!by_ref || (!repr->grp_maybe_modified
4064 && !repr->grp_not_necessarilly_dereferenced))
4065 total_size += repr->size;
4066 else
4067 total_size += cur_parm_size;
4069 new_param_count++;
4072 gcc_assert (new_param_count > 0);
4074 if (optimize_function_for_size_p (cfun))
4075 parm_size_limit = cur_parm_size;
4076 else
4077 parm_size_limit = (PARAM_VALUE (PARAM_IPA_SRA_PTR_GROWTH_FACTOR)
4078 * cur_parm_size);
4080 if (total_size < agg_size
4081 && total_size <= parm_size_limit)
4083 if (dump_file)
4084 fprintf (dump_file, " ....will be split into %i components\n",
4085 new_param_count);
4086 return new_param_count;
4088 else
4089 return 0;
4092 /* The order of the following enums is important, we need to do extra work for
4093 UNUSED_PARAMS, BY_VAL_ACCESSES and UNMODIF_BY_REF_ACCESSES. */
4094 enum ipa_splicing_result { NO_GOOD_ACCESS, UNUSED_PARAMS, BY_VAL_ACCESSES,
4095 MODIF_BY_REF_ACCESSES, UNMODIF_BY_REF_ACCESSES };
4097 /* Identify representatives of all accesses to all candidate parameters for
4098 IPA-SRA. Return result based on what representatives have been found. */
4100 static enum ipa_splicing_result
4101 splice_all_param_accesses (vec<access_p> &representatives)
4103 enum ipa_splicing_result result = NO_GOOD_ACCESS;
4104 tree parm;
4105 struct access *repr;
4107 representatives.create (func_param_count);
4109 for (parm = DECL_ARGUMENTS (current_function_decl);
4110 parm;
4111 parm = DECL_CHAIN (parm))
4113 if (is_unused_scalar_param (parm))
4115 representatives.quick_push (&no_accesses_representant);
4116 if (result == NO_GOOD_ACCESS)
4117 result = UNUSED_PARAMS;
4119 else if (POINTER_TYPE_P (TREE_TYPE (parm))
4120 && is_gimple_reg_type (TREE_TYPE (TREE_TYPE (parm)))
4121 && bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4123 repr = unmodified_by_ref_scalar_representative (parm);
4124 representatives.quick_push (repr);
4125 if (repr)
4126 result = UNMODIF_BY_REF_ACCESSES;
4128 else if (bitmap_bit_p (candidate_bitmap, DECL_UID (parm)))
4130 bool ro_grp = false;
4131 repr = splice_param_accesses (parm, &ro_grp);
4132 representatives.quick_push (repr);
4134 if (repr && !no_accesses_p (repr))
4136 if (POINTER_TYPE_P (TREE_TYPE (parm)))
4138 if (ro_grp)
4139 result = UNMODIF_BY_REF_ACCESSES;
4140 else if (result < MODIF_BY_REF_ACCESSES)
4141 result = MODIF_BY_REF_ACCESSES;
4143 else if (result < BY_VAL_ACCESSES)
4144 result = BY_VAL_ACCESSES;
4146 else if (no_accesses_p (repr) && (result == NO_GOOD_ACCESS))
4147 result = UNUSED_PARAMS;
4149 else
4150 representatives.quick_push (NULL);
4153 if (result == NO_GOOD_ACCESS)
4155 representatives.release ();
4156 return NO_GOOD_ACCESS;
4159 return result;
4162 /* Return the index of BASE in PARMS. Abort if it is not found. */
4164 static inline int
4165 get_param_index (tree base, vec<tree> parms)
4167 int i, len;
4169 len = parms.length ();
4170 for (i = 0; i < len; i++)
4171 if (parms[i] == base)
4172 return i;
4173 gcc_unreachable ();
4176 /* Convert the decisions made at the representative level into compact
4177 parameter adjustments. REPRESENTATIVES are pointers to first
4178 representatives of each param accesses, ADJUSTMENTS_COUNT is the expected
4179 final number of adjustments. */
4181 static ipa_parm_adjustment_vec
4182 turn_representatives_into_adjustments (vec<access_p> representatives,
4183 int adjustments_count)
4185 vec<tree> parms;
4186 ipa_parm_adjustment_vec adjustments;
4187 tree parm;
4188 int i;
4190 gcc_assert (adjustments_count > 0);
4191 parms = ipa_get_vector_of_formal_parms (current_function_decl);
4192 adjustments.create (adjustments_count);
4193 parm = DECL_ARGUMENTS (current_function_decl);
4194 for (i = 0; i < func_param_count; i++, parm = DECL_CHAIN (parm))
4196 struct access *repr = representatives[i];
4198 if (!repr || no_accesses_p (repr))
4200 struct ipa_parm_adjustment adj;
4202 memset (&adj, 0, sizeof (adj));
4203 adj.base_index = get_param_index (parm, parms);
4204 adj.base = parm;
4205 if (!repr)
4206 adj.copy_param = 1;
4207 else
4208 adj.remove_param = 1;
4209 adjustments.quick_push (adj);
4211 else
4213 struct ipa_parm_adjustment adj;
4214 int index = get_param_index (parm, parms);
4216 for (; repr; repr = repr->next_grp)
4218 memset (&adj, 0, sizeof (adj));
4219 gcc_assert (repr->base == parm);
4220 adj.base_index = index;
4221 adj.base = repr->base;
4222 adj.type = repr->type;
4223 adj.alias_ptr_type = reference_alias_ptr_type (repr->expr);
4224 adj.offset = repr->offset;
4225 adj.by_ref = (POINTER_TYPE_P (TREE_TYPE (repr->base))
4226 && (repr->grp_maybe_modified
4227 || repr->grp_not_necessarilly_dereferenced));
4228 adjustments.quick_push (adj);
4232 parms.release ();
4233 return adjustments;
4236 /* Analyze the collected accesses and produce a plan what to do with the
4237 parameters in the form of adjustments, NULL meaning nothing. */
4239 static ipa_parm_adjustment_vec
4240 analyze_all_param_acesses (void)
4242 enum ipa_splicing_result repr_state;
4243 bool proceed = false;
4244 int i, adjustments_count = 0;
4245 vec<access_p> representatives;
4246 ipa_parm_adjustment_vec adjustments;
4248 repr_state = splice_all_param_accesses (representatives);
4249 if (repr_state == NO_GOOD_ACCESS)
4250 return ipa_parm_adjustment_vec();
4252 /* If there are any parameters passed by reference which are not modified
4253 directly, we need to check whether they can be modified indirectly. */
4254 if (repr_state == UNMODIF_BY_REF_ACCESSES)
4256 analyze_caller_dereference_legality (representatives);
4257 analyze_modified_params (representatives);
4260 for (i = 0; i < func_param_count; i++)
4262 struct access *repr = representatives[i];
4264 if (repr && !no_accesses_p (repr))
4266 if (repr->grp_scalar_ptr)
4268 adjustments_count++;
4269 if (repr->grp_not_necessarilly_dereferenced
4270 || repr->grp_maybe_modified)
4271 representatives[i] = NULL;
4272 else
4274 proceed = true;
4275 sra_stats.scalar_by_ref_to_by_val++;
4278 else
4280 int new_components = decide_one_param_reduction (repr);
4282 if (new_components == 0)
4284 representatives[i] = NULL;
4285 adjustments_count++;
4287 else
4289 adjustments_count += new_components;
4290 sra_stats.aggregate_params_reduced++;
4291 sra_stats.param_reductions_created += new_components;
4292 proceed = true;
4296 else
4298 if (no_accesses_p (repr))
4300 proceed = true;
4301 sra_stats.deleted_unused_parameters++;
4303 adjustments_count++;
4307 if (!proceed && dump_file)
4308 fprintf (dump_file, "NOT proceeding to change params.\n");
4310 if (proceed)
4311 adjustments = turn_representatives_into_adjustments (representatives,
4312 adjustments_count);
4313 else
4314 adjustments = ipa_parm_adjustment_vec();
4316 representatives.release ();
4317 return adjustments;
4320 /* If a parameter replacement identified by ADJ does not yet exist in the form
4321 of declaration, create it and record it, otherwise return the previously
4322 created one. */
4324 static tree
4325 get_replaced_param_substitute (struct ipa_parm_adjustment *adj)
4327 tree repl;
4328 if (!adj->new_ssa_base)
4330 char *pretty_name = make_fancy_name (adj->base);
4332 repl = create_tmp_reg (TREE_TYPE (adj->base), "ISR");
4333 DECL_NAME (repl) = get_identifier (pretty_name);
4334 obstack_free (&name_obstack, pretty_name);
4336 adj->new_ssa_base = repl;
4338 else
4339 repl = adj->new_ssa_base;
4340 return repl;
4343 /* Find the first adjustment for a particular parameter BASE in a vector of
4344 ADJUSTMENTS which is not a copy_param. Return NULL if there is no such
4345 adjustment. */
4347 static struct ipa_parm_adjustment *
4348 get_adjustment_for_base (ipa_parm_adjustment_vec adjustments, tree base)
4350 int i, len;
4352 len = adjustments.length ();
4353 for (i = 0; i < len; i++)
4355 struct ipa_parm_adjustment *adj;
4357 adj = &adjustments[i];
4358 if (!adj->copy_param && adj->base == base)
4359 return adj;
4362 return NULL;
4365 /* If the statement STMT defines an SSA_NAME of a parameter which is to be
4366 removed because its value is not used, replace the SSA_NAME with a one
4367 relating to a created VAR_DECL together all of its uses and return true.
4368 ADJUSTMENTS is a pointer to an adjustments vector. */
4370 static bool
4371 replace_removed_params_ssa_names (gimple stmt,
4372 ipa_parm_adjustment_vec adjustments)
4374 struct ipa_parm_adjustment *adj;
4375 tree lhs, decl, repl, name;
4377 if (gimple_code (stmt) == GIMPLE_PHI)
4378 lhs = gimple_phi_result (stmt);
4379 else if (is_gimple_assign (stmt))
4380 lhs = gimple_assign_lhs (stmt);
4381 else if (is_gimple_call (stmt))
4382 lhs = gimple_call_lhs (stmt);
4383 else
4384 gcc_unreachable ();
4386 if (TREE_CODE (lhs) != SSA_NAME)
4387 return false;
4389 decl = SSA_NAME_VAR (lhs);
4390 if (decl == NULL_TREE
4391 || TREE_CODE (decl) != PARM_DECL)
4392 return false;
4394 adj = get_adjustment_for_base (adjustments, decl);
4395 if (!adj)
4396 return false;
4398 repl = get_replaced_param_substitute (adj);
4399 name = make_ssa_name (repl, stmt);
4401 if (dump_file)
4403 fprintf (dump_file, "replacing an SSA name of a removed param ");
4404 print_generic_expr (dump_file, lhs, 0);
4405 fprintf (dump_file, " with ");
4406 print_generic_expr (dump_file, name, 0);
4407 fprintf (dump_file, "\n");
4410 if (is_gimple_assign (stmt))
4411 gimple_assign_set_lhs (stmt, name);
4412 else if (is_gimple_call (stmt))
4413 gimple_call_set_lhs (stmt, name);
4414 else
4415 gimple_phi_set_result (stmt, name);
4417 replace_uses_by (lhs, name);
4418 release_ssa_name (lhs);
4419 return true;
4422 /* If the expression *EXPR should be replaced by a reduction of a parameter, do
4423 so. ADJUSTMENTS is a pointer to a vector of adjustments. CONVERT
4424 specifies whether the function should care about type incompatibility the
4425 current and new expressions. If it is false, the function will leave
4426 incompatibility issues to the caller. Return true iff the expression
4427 was modified. */
4429 static bool
4430 sra_ipa_modify_expr (tree *expr, bool convert,
4431 ipa_parm_adjustment_vec adjustments)
4433 int i, len;
4434 struct ipa_parm_adjustment *adj, *cand = NULL;
4435 HOST_WIDE_INT offset, size, max_size;
4436 tree base, src;
4438 len = adjustments.length ();
4440 if (TREE_CODE (*expr) == BIT_FIELD_REF
4441 || TREE_CODE (*expr) == IMAGPART_EXPR
4442 || TREE_CODE (*expr) == REALPART_EXPR)
4444 expr = &TREE_OPERAND (*expr, 0);
4445 convert = true;
4448 base = get_ref_base_and_extent (*expr, &offset, &size, &max_size);
4449 if (!base || size == -1 || max_size == -1)
4450 return false;
4452 if (TREE_CODE (base) == MEM_REF)
4454 offset += mem_ref_offset (base).low * BITS_PER_UNIT;
4455 base = TREE_OPERAND (base, 0);
4458 base = get_ssa_base_param (base);
4459 if (!base || TREE_CODE (base) != PARM_DECL)
4460 return false;
4462 for (i = 0; i < len; i++)
4464 adj = &adjustments[i];
4466 if (adj->base == base &&
4467 (adj->offset == offset || adj->remove_param))
4469 cand = adj;
4470 break;
4473 if (!cand || cand->copy_param || cand->remove_param)
4474 return false;
4476 if (cand->by_ref)
4477 src = build_simple_mem_ref (cand->reduction);
4478 else
4479 src = cand->reduction;
4481 if (dump_file && (dump_flags & TDF_DETAILS))
4483 fprintf (dump_file, "About to replace expr ");
4484 print_generic_expr (dump_file, *expr, 0);
4485 fprintf (dump_file, " with ");
4486 print_generic_expr (dump_file, src, 0);
4487 fprintf (dump_file, "\n");
4490 if (convert && !useless_type_conversion_p (TREE_TYPE (*expr), cand->type))
4492 tree vce = build1 (VIEW_CONVERT_EXPR, TREE_TYPE (*expr), src);
4493 *expr = vce;
4495 else
4496 *expr = src;
4497 return true;
4500 /* If the statement pointed to by STMT_PTR contains any expressions that need
4501 to replaced with a different one as noted by ADJUSTMENTS, do so. Handle any
4502 potential type incompatibilities (GSI is used to accommodate conversion
4503 statements and must point to the statement). Return true iff the statement
4504 was modified. */
4506 static bool
4507 sra_ipa_modify_assign (gimple *stmt_ptr, gimple_stmt_iterator *gsi,
4508 ipa_parm_adjustment_vec adjustments)
4510 gimple stmt = *stmt_ptr;
4511 tree *lhs_p, *rhs_p;
4512 bool any;
4514 if (!gimple_assign_single_p (stmt))
4515 return false;
4517 rhs_p = gimple_assign_rhs1_ptr (stmt);
4518 lhs_p = gimple_assign_lhs_ptr (stmt);
4520 any = sra_ipa_modify_expr (rhs_p, false, adjustments);
4521 any |= sra_ipa_modify_expr (lhs_p, false, adjustments);
4522 if (any)
4524 tree new_rhs = NULL_TREE;
4526 if (!useless_type_conversion_p (TREE_TYPE (*lhs_p), TREE_TYPE (*rhs_p)))
4528 if (TREE_CODE (*rhs_p) == CONSTRUCTOR)
4530 /* V_C_Es of constructors can cause trouble (PR 42714). */
4531 if (is_gimple_reg_type (TREE_TYPE (*lhs_p)))
4532 *rhs_p = build_zero_cst (TREE_TYPE (*lhs_p));
4533 else
4534 *rhs_p = build_constructor (TREE_TYPE (*lhs_p),
4535 NULL);
4537 else
4538 new_rhs = fold_build1_loc (gimple_location (stmt),
4539 VIEW_CONVERT_EXPR, TREE_TYPE (*lhs_p),
4540 *rhs_p);
4542 else if (REFERENCE_CLASS_P (*rhs_p)
4543 && is_gimple_reg_type (TREE_TYPE (*lhs_p))
4544 && !is_gimple_reg (*lhs_p))
4545 /* This can happen when an assignment in between two single field
4546 structures is turned into an assignment in between two pointers to
4547 scalars (PR 42237). */
4548 new_rhs = *rhs_p;
4550 if (new_rhs)
4552 tree tmp = force_gimple_operand_gsi (gsi, new_rhs, true, NULL_TREE,
4553 true, GSI_SAME_STMT);
4555 gimple_assign_set_rhs_from_tree (gsi, tmp);
4558 return true;
4561 return false;
4564 /* Traverse the function body and all modifications as described in
4565 ADJUSTMENTS. Return true iff the CFG has been changed. */
4567 static bool
4568 ipa_sra_modify_function_body (ipa_parm_adjustment_vec adjustments)
4570 bool cfg_changed = false;
4571 basic_block bb;
4573 FOR_EACH_BB (bb)
4575 gimple_stmt_iterator gsi;
4577 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4578 replace_removed_params_ssa_names (gsi_stmt (gsi), adjustments);
4580 gsi = gsi_start_bb (bb);
4581 while (!gsi_end_p (gsi))
4583 gimple stmt = gsi_stmt (gsi);
4584 bool modified = false;
4585 tree *t;
4586 unsigned i;
4588 switch (gimple_code (stmt))
4590 case GIMPLE_RETURN:
4591 t = gimple_return_retval_ptr (stmt);
4592 if (*t != NULL_TREE)
4593 modified |= sra_ipa_modify_expr (t, true, adjustments);
4594 break;
4596 case GIMPLE_ASSIGN:
4597 modified |= sra_ipa_modify_assign (&stmt, &gsi, adjustments);
4598 modified |= replace_removed_params_ssa_names (stmt, adjustments);
4599 break;
4601 case GIMPLE_CALL:
4602 /* Operands must be processed before the lhs. */
4603 for (i = 0; i < gimple_call_num_args (stmt); i++)
4605 t = gimple_call_arg_ptr (stmt, i);
4606 modified |= sra_ipa_modify_expr (t, true, adjustments);
4609 if (gimple_call_lhs (stmt))
4611 t = gimple_call_lhs_ptr (stmt);
4612 modified |= sra_ipa_modify_expr (t, false, adjustments);
4613 modified |= replace_removed_params_ssa_names (stmt,
4614 adjustments);
4616 break;
4618 case GIMPLE_ASM:
4619 for (i = 0; i < gimple_asm_ninputs (stmt); i++)
4621 t = &TREE_VALUE (gimple_asm_input_op (stmt, i));
4622 modified |= sra_ipa_modify_expr (t, true, adjustments);
4624 for (i = 0; i < gimple_asm_noutputs (stmt); i++)
4626 t = &TREE_VALUE (gimple_asm_output_op (stmt, i));
4627 modified |= sra_ipa_modify_expr (t, false, adjustments);
4629 break;
4631 default:
4632 break;
4635 if (modified)
4637 update_stmt (stmt);
4638 if (maybe_clean_eh_stmt (stmt)
4639 && gimple_purge_dead_eh_edges (gimple_bb (stmt)))
4640 cfg_changed = true;
4642 gsi_next (&gsi);
4646 return cfg_changed;
4649 /* Call gimple_debug_bind_reset_value on all debug statements describing
4650 gimple register parameters that are being removed or replaced. */
4652 static void
4653 sra_ipa_reset_debug_stmts (ipa_parm_adjustment_vec adjustments)
4655 int i, len;
4656 gimple_stmt_iterator *gsip = NULL, gsi;
4658 if (MAY_HAVE_DEBUG_STMTS && single_succ_p (ENTRY_BLOCK_PTR))
4660 gsi = gsi_after_labels (single_succ (ENTRY_BLOCK_PTR));
4661 gsip = &gsi;
4663 len = adjustments.length ();
4664 for (i = 0; i < len; i++)
4666 struct ipa_parm_adjustment *adj;
4667 imm_use_iterator ui;
4668 gimple stmt, def_temp;
4669 tree name, vexpr, copy = NULL_TREE;
4670 use_operand_p use_p;
4672 adj = &adjustments[i];
4673 if (adj->copy_param || !is_gimple_reg (adj->base))
4674 continue;
4675 name = ssa_default_def (cfun, adj->base);
4676 vexpr = NULL;
4677 if (name)
4678 FOR_EACH_IMM_USE_STMT (stmt, ui, name)
4680 /* All other users must have been removed by
4681 ipa_sra_modify_function_body. */
4682 gcc_assert (is_gimple_debug (stmt));
4683 if (vexpr == NULL && gsip != NULL)
4685 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4686 vexpr = make_node (DEBUG_EXPR_DECL);
4687 def_temp = gimple_build_debug_source_bind (vexpr, adj->base,
4688 NULL);
4689 DECL_ARTIFICIAL (vexpr) = 1;
4690 TREE_TYPE (vexpr) = TREE_TYPE (name);
4691 DECL_MODE (vexpr) = DECL_MODE (adj->base);
4692 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4694 if (vexpr)
4696 FOR_EACH_IMM_USE_ON_STMT (use_p, ui)
4697 SET_USE (use_p, vexpr);
4699 else
4700 gimple_debug_bind_reset_value (stmt);
4701 update_stmt (stmt);
4703 /* Create a VAR_DECL for debug info purposes. */
4704 if (!DECL_IGNORED_P (adj->base))
4706 copy = build_decl (DECL_SOURCE_LOCATION (current_function_decl),
4707 VAR_DECL, DECL_NAME (adj->base),
4708 TREE_TYPE (adj->base));
4709 if (DECL_PT_UID_SET_P (adj->base))
4710 SET_DECL_PT_UID (copy, DECL_PT_UID (adj->base));
4711 TREE_ADDRESSABLE (copy) = TREE_ADDRESSABLE (adj->base);
4712 TREE_READONLY (copy) = TREE_READONLY (adj->base);
4713 TREE_THIS_VOLATILE (copy) = TREE_THIS_VOLATILE (adj->base);
4714 DECL_GIMPLE_REG_P (copy) = DECL_GIMPLE_REG_P (adj->base);
4715 DECL_ARTIFICIAL (copy) = DECL_ARTIFICIAL (adj->base);
4716 DECL_IGNORED_P (copy) = DECL_IGNORED_P (adj->base);
4717 DECL_ABSTRACT_ORIGIN (copy) = DECL_ORIGIN (adj->base);
4718 DECL_SEEN_IN_BIND_EXPR_P (copy) = 1;
4719 SET_DECL_RTL (copy, 0);
4720 TREE_USED (copy) = 1;
4721 DECL_CONTEXT (copy) = current_function_decl;
4722 add_local_decl (cfun, copy);
4723 DECL_CHAIN (copy) =
4724 BLOCK_VARS (DECL_INITIAL (current_function_decl));
4725 BLOCK_VARS (DECL_INITIAL (current_function_decl)) = copy;
4727 if (gsip != NULL && copy && target_for_debug_bind (adj->base))
4729 gcc_assert (TREE_CODE (adj->base) == PARM_DECL);
4730 if (vexpr)
4731 def_temp = gimple_build_debug_bind (copy, vexpr, NULL);
4732 else
4733 def_temp = gimple_build_debug_source_bind (copy, adj->base,
4734 NULL);
4735 gsi_insert_before (gsip, def_temp, GSI_SAME_STMT);
4740 /* Return false iff all callers have at least as many actual arguments as there
4741 are formal parameters in the current function. */
4743 static bool
4744 not_all_callers_have_enough_arguments_p (struct cgraph_node *node,
4745 void *data ATTRIBUTE_UNUSED)
4747 struct cgraph_edge *cs;
4748 for (cs = node->callers; cs; cs = cs->next_caller)
4749 if (!callsite_has_enough_arguments_p (cs->call_stmt))
4750 return true;
4752 return false;
4755 /* Convert all callers of NODE. */
4757 static bool
4758 convert_callers_for_node (struct cgraph_node *node,
4759 void *data)
4761 ipa_parm_adjustment_vec *adjustments = (ipa_parm_adjustment_vec *) data;
4762 bitmap recomputed_callers = BITMAP_ALLOC (NULL);
4763 struct cgraph_edge *cs;
4765 for (cs = node->callers; cs; cs = cs->next_caller)
4767 push_cfun (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl));
4769 if (dump_file)
4770 fprintf (dump_file, "Adjusting call (%i -> %i) %s -> %s\n",
4771 cs->caller->uid, cs->callee->uid,
4772 xstrdup (cgraph_node_name (cs->caller)),
4773 xstrdup (cgraph_node_name (cs->callee)));
4775 ipa_modify_call_arguments (cs, cs->call_stmt, *adjustments);
4777 pop_cfun ();
4780 for (cs = node->callers; cs; cs = cs->next_caller)
4781 if (bitmap_set_bit (recomputed_callers, cs->caller->uid)
4782 && gimple_in_ssa_p (DECL_STRUCT_FUNCTION (cs->caller->symbol.decl)))
4783 compute_inline_parameters (cs->caller, true);
4784 BITMAP_FREE (recomputed_callers);
4786 return true;
4789 /* Convert all callers of NODE to pass parameters as given in ADJUSTMENTS. */
4791 static void
4792 convert_callers (struct cgraph_node *node, tree old_decl,
4793 ipa_parm_adjustment_vec adjustments)
4795 basic_block this_block;
4797 cgraph_for_node_and_aliases (node, convert_callers_for_node,
4798 &adjustments, false);
4800 if (!encountered_recursive_call)
4801 return;
4803 FOR_EACH_BB (this_block)
4805 gimple_stmt_iterator gsi;
4807 for (gsi = gsi_start_bb (this_block); !gsi_end_p (gsi); gsi_next (&gsi))
4809 gimple stmt = gsi_stmt (gsi);
4810 tree call_fndecl;
4811 if (gimple_code (stmt) != GIMPLE_CALL)
4812 continue;
4813 call_fndecl = gimple_call_fndecl (stmt);
4814 if (call_fndecl == old_decl)
4816 if (dump_file)
4817 fprintf (dump_file, "Adjusting recursive call");
4818 gimple_call_set_fndecl (stmt, node->symbol.decl);
4819 ipa_modify_call_arguments (NULL, stmt, adjustments);
4824 return;
4827 /* Perform all the modification required in IPA-SRA for NODE to have parameters
4828 as given in ADJUSTMENTS. Return true iff the CFG has been changed. */
4830 static bool
4831 modify_function (struct cgraph_node *node, ipa_parm_adjustment_vec adjustments)
4833 struct cgraph_node *new_node;
4834 bool cfg_changed;
4835 vec<cgraph_edge_p> redirect_callers = collect_callers_of_node (node);
4837 rebuild_cgraph_edges ();
4838 free_dominance_info (CDI_DOMINATORS);
4839 pop_cfun ();
4841 new_node = cgraph_function_versioning (node, redirect_callers,
4842 NULL,
4843 NULL, false, NULL, NULL, "isra");
4844 redirect_callers.release ();
4846 push_cfun (DECL_STRUCT_FUNCTION (new_node->symbol.decl));
4847 ipa_modify_formal_parameters (current_function_decl, adjustments, "ISRA");
4848 cfg_changed = ipa_sra_modify_function_body (adjustments);
4849 sra_ipa_reset_debug_stmts (adjustments);
4850 convert_callers (new_node, node->symbol.decl, adjustments);
4851 cgraph_make_node_local (new_node);
4852 return cfg_changed;
4855 /* Return false the function is apparently unsuitable for IPA-SRA based on it's
4856 attributes, return true otherwise. NODE is the cgraph node of the current
4857 function. */
4859 static bool
4860 ipa_sra_preliminary_function_checks (struct cgraph_node *node)
4862 if (!cgraph_node_can_be_local_p (node))
4864 if (dump_file)
4865 fprintf (dump_file, "Function not local to this compilation unit.\n");
4866 return false;
4869 if (!node->local.can_change_signature)
4871 if (dump_file)
4872 fprintf (dump_file, "Function can not change signature.\n");
4873 return false;
4876 if (!tree_versionable_function_p (node->symbol.decl))
4878 if (dump_file)
4879 fprintf (dump_file, "Function is not versionable.\n");
4880 return false;
4883 if (DECL_VIRTUAL_P (current_function_decl))
4885 if (dump_file)
4886 fprintf (dump_file, "Function is a virtual method.\n");
4887 return false;
4890 if ((DECL_COMDAT (node->symbol.decl) || DECL_EXTERNAL (node->symbol.decl))
4891 && inline_summary(node)->size >= MAX_INLINE_INSNS_AUTO)
4893 if (dump_file)
4894 fprintf (dump_file, "Function too big to be made truly local.\n");
4895 return false;
4898 if (!node->callers)
4900 if (dump_file)
4901 fprintf (dump_file,
4902 "Function has no callers in this compilation unit.\n");
4903 return false;
4906 if (cfun->stdarg)
4908 if (dump_file)
4909 fprintf (dump_file, "Function uses stdarg. \n");
4910 return false;
4913 if (TYPE_ATTRIBUTES (TREE_TYPE (node->symbol.decl)))
4914 return false;
4916 return true;
4919 /* Perform early interprocedural SRA. */
4921 static unsigned int
4922 ipa_early_sra (void)
4924 struct cgraph_node *node = cgraph_get_node (current_function_decl);
4925 ipa_parm_adjustment_vec adjustments;
4926 int ret = 0;
4928 if (!ipa_sra_preliminary_function_checks (node))
4929 return 0;
4931 sra_initialize ();
4932 sra_mode = SRA_MODE_EARLY_IPA;
4934 if (!find_param_candidates ())
4936 if (dump_file)
4937 fprintf (dump_file, "Function has no IPA-SRA candidates.\n");
4938 goto simple_out;
4941 if (cgraph_for_node_and_aliases (node, not_all_callers_have_enough_arguments_p,
4942 NULL, true))
4944 if (dump_file)
4945 fprintf (dump_file, "There are callers with insufficient number of "
4946 "arguments.\n");
4947 goto simple_out;
4950 bb_dereferences = XCNEWVEC (HOST_WIDE_INT,
4951 func_param_count
4952 * last_basic_block_for_function (cfun));
4953 final_bbs = BITMAP_ALLOC (NULL);
4955 scan_function ();
4956 if (encountered_apply_args)
4958 if (dump_file)
4959 fprintf (dump_file, "Function calls __builtin_apply_args().\n");
4960 goto out;
4963 if (encountered_unchangable_recursive_call)
4965 if (dump_file)
4966 fprintf (dump_file, "Function calls itself with insufficient "
4967 "number of arguments.\n");
4968 goto out;
4971 adjustments = analyze_all_param_acesses ();
4972 if (!adjustments.exists ())
4973 goto out;
4974 if (dump_file)
4975 ipa_dump_param_adjustments (dump_file, adjustments, current_function_decl);
4977 if (modify_function (node, adjustments))
4978 ret = TODO_update_ssa | TODO_cleanup_cfg;
4979 else
4980 ret = TODO_update_ssa;
4981 adjustments.release ();
4983 statistics_counter_event (cfun, "Unused parameters deleted",
4984 sra_stats.deleted_unused_parameters);
4985 statistics_counter_event (cfun, "Scalar parameters converted to by-value",
4986 sra_stats.scalar_by_ref_to_by_val);
4987 statistics_counter_event (cfun, "Aggregate parameters broken up",
4988 sra_stats.aggregate_params_reduced);
4989 statistics_counter_event (cfun, "Aggregate parameter components created",
4990 sra_stats.param_reductions_created);
4992 out:
4993 BITMAP_FREE (final_bbs);
4994 free (bb_dereferences);
4995 simple_out:
4996 sra_deinitialize ();
4997 return ret;
5000 /* Return if early ipa sra shall be performed. */
5001 static bool
5002 ipa_early_sra_gate (void)
5004 return flag_ipa_sra && dbg_cnt (eipa_sra);
5007 struct gimple_opt_pass pass_early_ipa_sra =
5010 GIMPLE_PASS,
5011 "eipa_sra", /* name */
5012 OPTGROUP_NONE, /* optinfo_flags */
5013 ipa_early_sra_gate, /* gate */
5014 ipa_early_sra, /* execute */
5015 NULL, /* sub */
5016 NULL, /* next */
5017 0, /* static_pass_number */
5018 TV_IPA_SRA, /* tv_id */
5019 0, /* properties_required */
5020 0, /* properties_provided */
5021 0, /* properties_destroyed */
5022 0, /* todo_flags_start */
5023 TODO_dump_symtab /* todo_flags_finish */