OSDN Git Service

PR tree-optimization/46590
[pf3gnuchains/gcc-fork.git] / gcc / cfgexpand.c
1 /* A pass for lowering trees to RTL.
2    Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011
3    Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 3, or (at your option)
10 any later version.
11
12 GCC is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "tree.h"
26 #include "rtl.h"
27 #include "tm_p.h"
28 #include "basic-block.h"
29 #include "function.h"
30 #include "expr.h"
31 #include "langhooks.h"
32 #include "tree-flow.h"
33 #include "timevar.h"
34 #include "tree-dump.h"
35 #include "tree-pass.h"
36 #include "except.h"
37 #include "flags.h"
38 #include "diagnostic.h"
39 #include "tree-pretty-print.h"
40 #include "gimple-pretty-print.h"
41 #include "toplev.h"
42 #include "debug.h"
43 #include "params.h"
44 #include "tree-inline.h"
45 #include "value-prof.h"
46 #include "target.h"
47 #include "ssaexpand.h"
48 #include "bitmap.h"
49 #include "sbitmap.h"
50 #include "insn-attr.h" /* For INSN_SCHEDULING.  */
51
52 /* This variable holds information helping the rewriting of SSA trees
53    into RTL.  */
54 struct ssaexpand SA;
55
56 /* This variable holds the currently expanded gimple statement for purposes
57    of comminucating the profile info to the builtin expanders.  */
58 gimple currently_expanding_gimple_stmt;
59
60 static rtx expand_debug_expr (tree);
61
62 /* Return an expression tree corresponding to the RHS of GIMPLE
63    statement STMT.  */
64
65 tree
66 gimple_assign_rhs_to_tree (gimple stmt)
67 {
68   tree t;
69   enum gimple_rhs_class grhs_class;
70
71   grhs_class = get_gimple_rhs_class (gimple_expr_code (stmt));
72
73   if (grhs_class == GIMPLE_TERNARY_RHS)
74     t = build3 (gimple_assign_rhs_code (stmt),
75                 TREE_TYPE (gimple_assign_lhs (stmt)),
76                 gimple_assign_rhs1 (stmt),
77                 gimple_assign_rhs2 (stmt),
78                 gimple_assign_rhs3 (stmt));
79   else if (grhs_class == GIMPLE_BINARY_RHS)
80     t = build2 (gimple_assign_rhs_code (stmt),
81                 TREE_TYPE (gimple_assign_lhs (stmt)),
82                 gimple_assign_rhs1 (stmt),
83                 gimple_assign_rhs2 (stmt));
84   else if (grhs_class == GIMPLE_UNARY_RHS)
85     t = build1 (gimple_assign_rhs_code (stmt),
86                 TREE_TYPE (gimple_assign_lhs (stmt)),
87                 gimple_assign_rhs1 (stmt));
88   else if (grhs_class == GIMPLE_SINGLE_RHS)
89     {
90       t = gimple_assign_rhs1 (stmt);
91       /* Avoid modifying this tree in place below.  */
92       if ((gimple_has_location (stmt) && CAN_HAVE_LOCATION_P (t)
93            && gimple_location (stmt) != EXPR_LOCATION (t))
94           || (gimple_block (stmt)
95               && currently_expanding_to_rtl
96               && EXPR_P (t)
97               && gimple_block (stmt) != TREE_BLOCK (t)))
98         t = copy_node (t);
99     }
100   else
101     gcc_unreachable ();
102
103   if (gimple_has_location (stmt) && CAN_HAVE_LOCATION_P (t))
104     SET_EXPR_LOCATION (t, gimple_location (stmt));
105   if (gimple_block (stmt) && currently_expanding_to_rtl && EXPR_P (t))
106     TREE_BLOCK (t) = gimple_block (stmt);
107
108   return t;
109 }
110
111
112 #ifndef STACK_ALIGNMENT_NEEDED
113 #define STACK_ALIGNMENT_NEEDED 1
114 #endif
115
116 #define SSAVAR(x) (TREE_CODE (x) == SSA_NAME ? SSA_NAME_VAR (x) : x)
117
118 /* Associate declaration T with storage space X.  If T is no
119    SSA name this is exactly SET_DECL_RTL, otherwise make the
120    partition of T associated with X.  */
121 static inline void
122 set_rtl (tree t, rtx x)
123 {
124   if (TREE_CODE (t) == SSA_NAME)
125     {
126       SA.partition_to_pseudo[var_to_partition (SA.map, t)] = x;
127       if (x && !MEM_P (x))
128         set_reg_attrs_for_decl_rtl (SSA_NAME_VAR (t), x);
129       /* For the benefit of debug information at -O0 (where vartracking
130          doesn't run) record the place also in the base DECL if it's
131          a normal variable (not a parameter).  */
132       if (x && x != pc_rtx && TREE_CODE (SSA_NAME_VAR (t)) == VAR_DECL)
133         {
134           tree var = SSA_NAME_VAR (t);
135           /* If we don't yet have something recorded, just record it now.  */
136           if (!DECL_RTL_SET_P (var))
137             SET_DECL_RTL (var, x);
138           /* If we have it set already to "multiple places" don't
139              change this.  */
140           else if (DECL_RTL (var) == pc_rtx)
141             ;
142           /* If we have something recorded and it's not the same place
143              as we want to record now, we have multiple partitions for the
144              same base variable, with different places.  We can't just
145              randomly chose one, hence we have to say that we don't know.
146              This only happens with optimization, and there var-tracking
147              will figure out the right thing.  */
148           else if (DECL_RTL (var) != x)
149             SET_DECL_RTL (var, pc_rtx);
150         }
151     }
152   else
153     SET_DECL_RTL (t, x);
154 }
155
156 /* This structure holds data relevant to one variable that will be
157    placed in a stack slot.  */
158 struct stack_var
159 {
160   /* The Variable.  */
161   tree decl;
162
163   /* Initially, the size of the variable.  Later, the size of the partition,
164      if this variable becomes it's partition's representative.  */
165   HOST_WIDE_INT size;
166
167   /* The *byte* alignment required for this variable.  Or as, with the
168      size, the alignment for this partition.  */
169   unsigned int alignb;
170
171   /* The partition representative.  */
172   size_t representative;
173
174   /* The next stack variable in the partition, or EOC.  */
175   size_t next;
176
177   /* The numbers of conflicting stack variables.  */
178   bitmap conflicts;
179 };
180
181 #define EOC  ((size_t)-1)
182
183 /* We have an array of such objects while deciding allocation.  */
184 static struct stack_var *stack_vars;
185 static size_t stack_vars_alloc;
186 static size_t stack_vars_num;
187 static struct pointer_map_t *decl_to_stack_part;
188
189 /* An array of indices such that stack_vars[stack_vars_sorted[i]].size
190    is non-decreasing.  */
191 static size_t *stack_vars_sorted;
192
193 /* The phase of the stack frame.  This is the known misalignment of
194    virtual_stack_vars_rtx from PREFERRED_STACK_BOUNDARY.  That is,
195    (frame_offset+frame_phase) % PREFERRED_STACK_BOUNDARY == 0.  */
196 static int frame_phase;
197
198 /* Used during expand_used_vars to remember if we saw any decls for
199    which we'd like to enable stack smashing protection.  */
200 static bool has_protected_decls;
201
202 /* Used during expand_used_vars.  Remember if we say a character buffer
203    smaller than our cutoff threshold.  Used for -Wstack-protector.  */
204 static bool has_short_buffer;
205
206 /* Compute the byte alignment to use for DECL.  Ignore alignment
207    we can't do with expected alignment of the stack boundary.  */
208
209 static unsigned int
210 align_local_variable (tree decl)
211 {
212   unsigned int align = LOCAL_DECL_ALIGNMENT (decl);
213   DECL_ALIGN (decl) = align;
214   return align / BITS_PER_UNIT;
215 }
216
217 /* Allocate SIZE bytes at byte alignment ALIGN from the stack frame.
218    Return the frame offset.  */
219
220 static HOST_WIDE_INT
221 alloc_stack_frame_space (HOST_WIDE_INT size, unsigned HOST_WIDE_INT align)
222 {
223   HOST_WIDE_INT offset, new_frame_offset;
224
225   new_frame_offset = frame_offset;
226   if (FRAME_GROWS_DOWNWARD)
227     {
228       new_frame_offset -= size + frame_phase;
229       new_frame_offset &= -align;
230       new_frame_offset += frame_phase;
231       offset = new_frame_offset;
232     }
233   else
234     {
235       new_frame_offset -= frame_phase;
236       new_frame_offset += align - 1;
237       new_frame_offset &= -align;
238       new_frame_offset += frame_phase;
239       offset = new_frame_offset;
240       new_frame_offset += size;
241     }
242   frame_offset = new_frame_offset;
243
244   if (frame_offset_overflow (frame_offset, cfun->decl))
245     frame_offset = offset = 0;
246
247   return offset;
248 }
249
250 /* Accumulate DECL into STACK_VARS.  */
251
252 static void
253 add_stack_var (tree decl)
254 {
255   struct stack_var *v;
256
257   if (stack_vars_num >= stack_vars_alloc)
258     {
259       if (stack_vars_alloc)
260         stack_vars_alloc = stack_vars_alloc * 3 / 2;
261       else
262         stack_vars_alloc = 32;
263       stack_vars
264         = XRESIZEVEC (struct stack_var, stack_vars, stack_vars_alloc);
265     }
266   if (!decl_to_stack_part)
267     decl_to_stack_part = pointer_map_create ();
268
269   v = &stack_vars[stack_vars_num];
270   * (size_t *)pointer_map_insert (decl_to_stack_part, decl) = stack_vars_num;
271
272   v->decl = decl;
273   v->size = tree_low_cst (DECL_SIZE_UNIT (SSAVAR (decl)), 1);
274   /* Ensure that all variables have size, so that &a != &b for any two
275      variables that are simultaneously live.  */
276   if (v->size == 0)
277     v->size = 1;
278   v->alignb = align_local_variable (SSAVAR (decl));
279   /* An alignment of zero can mightily confuse us later.  */
280   gcc_assert (v->alignb != 0);
281
282   /* All variables are initially in their own partition.  */
283   v->representative = stack_vars_num;
284   v->next = EOC;
285
286   /* All variables initially conflict with no other.  */
287   v->conflicts = NULL;
288
289   /* Ensure that this decl doesn't get put onto the list twice.  */
290   set_rtl (decl, pc_rtx);
291
292   stack_vars_num++;
293 }
294
295 /* Make the decls associated with luid's X and Y conflict.  */
296
297 static void
298 add_stack_var_conflict (size_t x, size_t y)
299 {
300   struct stack_var *a = &stack_vars[x];
301   struct stack_var *b = &stack_vars[y];
302   if (!a->conflicts)
303     a->conflicts = BITMAP_ALLOC (NULL);
304   if (!b->conflicts)
305     b->conflicts = BITMAP_ALLOC (NULL);
306   bitmap_set_bit (a->conflicts, y);
307   bitmap_set_bit (b->conflicts, x);
308 }
309
310 /* Check whether the decls associated with luid's X and Y conflict.  */
311
312 static bool
313 stack_var_conflict_p (size_t x, size_t y)
314 {
315   struct stack_var *a = &stack_vars[x];
316   struct stack_var *b = &stack_vars[y];
317   if (x == y)
318     return false;
319   /* Partitions containing an SSA name result from gimple registers
320      with things like unsupported modes.  They are top-level and
321      hence conflict with everything else.  */
322   if (TREE_CODE (a->decl) == SSA_NAME || TREE_CODE (b->decl) == SSA_NAME)
323     return true;
324
325   if (!a->conflicts || !b->conflicts)
326     return false;
327   return bitmap_bit_p (a->conflicts, y);
328 }
329
330 /* Returns true if TYPE is or contains a union type.  */
331
332 static bool
333 aggregate_contains_union_type (tree type)
334 {
335   tree field;
336
337   if (TREE_CODE (type) == UNION_TYPE
338       || TREE_CODE (type) == QUAL_UNION_TYPE)
339     return true;
340   if (TREE_CODE (type) == ARRAY_TYPE)
341     return aggregate_contains_union_type (TREE_TYPE (type));
342   if (TREE_CODE (type) != RECORD_TYPE)
343     return false;
344
345   for (field = TYPE_FIELDS (type); field; field = DECL_CHAIN (field))
346     if (TREE_CODE (field) == FIELD_DECL)
347       if (aggregate_contains_union_type (TREE_TYPE (field)))
348         return true;
349
350   return false;
351 }
352
353 /* A subroutine of expand_used_vars.  If two variables X and Y have alias
354    sets that do not conflict, then do add a conflict for these variables
355    in the interference graph.  We also need to make sure to add conflicts
356    for union containing structures.  Else RTL alias analysis comes along
357    and due to type based aliasing rules decides that for two overlapping
358    union temporaries { short s; int i; } accesses to the same mem through
359    different types may not alias and happily reorders stores across
360    life-time boundaries of the temporaries (See PR25654).
361    We also have to mind MEM_IN_STRUCT_P and MEM_SCALAR_P.  */
362
363 static void
364 add_alias_set_conflicts (void)
365 {
366   size_t i, j, n = stack_vars_num;
367
368   for (i = 0; i < n; ++i)
369     {
370       tree type_i = TREE_TYPE (stack_vars[i].decl);
371       bool aggr_i = AGGREGATE_TYPE_P (type_i);
372       bool contains_union;
373
374       contains_union = aggregate_contains_union_type (type_i);
375       for (j = 0; j < i; ++j)
376         {
377           tree type_j = TREE_TYPE (stack_vars[j].decl);
378           bool aggr_j = AGGREGATE_TYPE_P (type_j);
379           if (aggr_i != aggr_j
380               /* Either the objects conflict by means of type based
381                  aliasing rules, or we need to add a conflict.  */
382               || !objects_must_conflict_p (type_i, type_j)
383               /* In case the types do not conflict ensure that access
384                  to elements will conflict.  In case of unions we have
385                  to be careful as type based aliasing rules may say
386                  access to the same memory does not conflict.  So play
387                  safe and add a conflict in this case when
388                  -fstrict-aliasing is used.  */
389               || (contains_union && flag_strict_aliasing))
390             add_stack_var_conflict (i, j);
391         }
392     }
393 }
394
395 /* Callback for walk_stmt_ops.  If OP is a decl touched by add_stack_var
396    enter its partition number into bitmap DATA.  */
397
398 static bool
399 visit_op (gimple stmt ATTRIBUTE_UNUSED, tree op, void *data)
400 {
401   bitmap active = (bitmap)data;
402   op = get_base_address (op);
403   if (op
404       && DECL_P (op)
405       && DECL_RTL_IF_SET (op) == pc_rtx)
406     {
407       size_t *v = (size_t *) pointer_map_contains (decl_to_stack_part, op);
408       if (v)
409         bitmap_set_bit (active, *v);
410     }
411   return false;
412 }
413
414 /* Callback for walk_stmt_ops.  If OP is a decl touched by add_stack_var
415    record conflicts between it and all currently active other partitions
416    from bitmap DATA.  */
417
418 static bool
419 visit_conflict (gimple stmt ATTRIBUTE_UNUSED, tree op, void *data)
420 {
421   bitmap active = (bitmap)data;
422   op = get_base_address (op);
423   if (op
424       && DECL_P (op)
425       && DECL_RTL_IF_SET (op) == pc_rtx)
426     {
427       size_t *v =
428         (size_t *) pointer_map_contains (decl_to_stack_part, op);
429       if (v && bitmap_set_bit (active, *v))
430         {
431           size_t num = *v;
432           bitmap_iterator bi;
433           unsigned i;
434           gcc_assert (num < stack_vars_num);
435           EXECUTE_IF_SET_IN_BITMAP (active, 0, i, bi)
436             add_stack_var_conflict (num, i);
437         }
438     }
439   return false;
440 }
441
442 /* Helper routine for add_scope_conflicts, calculating the active partitions
443    at the end of BB, leaving the result in WORK.  We're called to generate
444    conflicts when OLD_CONFLICTS is non-null, otherwise we're just tracking
445    liveness.  If we generate conflicts then OLD_CONFLICTS stores the bits
446    for which we generated conflicts already.  */
447
448 static void
449 add_scope_conflicts_1 (basic_block bb, bitmap work, bitmap old_conflicts)
450 {
451   edge e;
452   edge_iterator ei;
453   gimple_stmt_iterator gsi;
454   bool (*visit)(gimple, tree, void *);
455
456   bitmap_clear (work);
457   FOR_EACH_EDGE (e, ei, bb->preds)
458     bitmap_ior_into (work, (bitmap)e->src->aux);
459
460   visit = visit_op;
461
462   for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
463     {
464       gimple stmt = gsi_stmt (gsi);
465       walk_stmt_load_store_addr_ops (stmt, work, NULL, NULL, visit);
466     }
467   for (gsi = gsi_after_labels (bb); !gsi_end_p (gsi); gsi_next (&gsi))
468     {
469       gimple stmt = gsi_stmt (gsi);
470
471       if (gimple_clobber_p (stmt))
472         {
473           tree lhs = gimple_assign_lhs (stmt);
474           size_t *v;
475           /* Nested function lowering might introduce LHSs
476              that are COMPONENT_REFs.  */
477           if (TREE_CODE (lhs) != VAR_DECL)
478             continue;
479           if (DECL_RTL_IF_SET (lhs) == pc_rtx
480               && (v = (size_t *)
481                   pointer_map_contains (decl_to_stack_part, lhs)))
482             bitmap_clear_bit (work, *v);
483         }
484       else if (!is_gimple_debug (stmt))
485         {
486           if (old_conflicts
487               && visit == visit_op)
488             {
489               /* If this is the first real instruction in this BB we need
490                  to add conflicts for everything live at this point now.
491                  Unlike classical liveness for named objects we can't
492                  rely on seeing a def/use of the names we're interested in.
493                  There might merely be indirect loads/stores.  We'd not add any
494                  conflicts for such partitions.  We know that we generated
495                  conflicts between all partitions in old_conflicts already,
496                  so we need to generate only the new ones, avoiding to
497                  repeatedly pay the O(N^2) cost for each basic block.  */
498               bitmap_iterator bi;
499               unsigned i;
500
501               EXECUTE_IF_AND_COMPL_IN_BITMAP (work, old_conflicts, 0, i, bi)
502                 {
503                   unsigned j;
504                   bitmap_iterator bj;
505                   /* First the conflicts between new and old_conflicts.  */
506                   EXECUTE_IF_SET_IN_BITMAP (old_conflicts, 0, j, bj)
507                     add_stack_var_conflict (i, j);
508                   /* Then the conflicts between only the new members.  */
509                   EXECUTE_IF_AND_COMPL_IN_BITMAP (work, old_conflicts, i + 1,
510                                                   j, bj)
511                     add_stack_var_conflict (i, j);
512                 }
513               /* And remember for the next basic block.  */
514               bitmap_ior_into (old_conflicts, work);
515               visit = visit_conflict;
516             }
517           walk_stmt_load_store_addr_ops (stmt, work, visit, visit, visit);
518         }
519     }
520 }
521
522 /* Generate stack partition conflicts between all partitions that are
523    simultaneously live.  */
524
525 static void
526 add_scope_conflicts (void)
527 {
528   basic_block bb;
529   bool changed;
530   bitmap work = BITMAP_ALLOC (NULL);
531   bitmap old_conflicts;
532
533   /* We approximate the live range of a stack variable by taking the first
534      mention of its name as starting point(s), and by the end-of-scope
535      death clobber added by gimplify as ending point(s) of the range.
536      This overapproximates in the case we for instance moved an address-taken
537      operation upward, without also moving a dereference to it upwards.
538      But it's conservatively correct as a variable never can hold values
539      before its name is mentioned at least once.
540
541      We then do a mostly classical bitmap liveness algorithm.  */
542
543   FOR_ALL_BB (bb)
544     bb->aux = BITMAP_ALLOC (NULL);
545
546   changed = true;
547   while (changed)
548     {
549       changed = false;
550       FOR_EACH_BB (bb)
551         {
552           bitmap active = (bitmap)bb->aux;
553           add_scope_conflicts_1 (bb, work, NULL);
554           if (bitmap_ior_into (active, work))
555             changed = true;
556         }
557     }
558
559   old_conflicts = BITMAP_ALLOC (NULL);
560
561   FOR_EACH_BB (bb)
562     add_scope_conflicts_1 (bb, work, old_conflicts);
563
564   BITMAP_FREE (old_conflicts);
565   BITMAP_FREE (work);
566   FOR_ALL_BB (bb)
567     BITMAP_FREE (bb->aux);
568 }
569
570 /* A subroutine of partition_stack_vars.  A comparison function for qsort,
571    sorting an array of indices by the properties of the object.  */
572
573 static int
574 stack_var_cmp (const void *a, const void *b)
575 {
576   size_t ia = *(const size_t *)a;
577   size_t ib = *(const size_t *)b;
578   unsigned int aligna = stack_vars[ia].alignb;
579   unsigned int alignb = stack_vars[ib].alignb;
580   HOST_WIDE_INT sizea = stack_vars[ia].size;
581   HOST_WIDE_INT sizeb = stack_vars[ib].size;
582   tree decla = stack_vars[ia].decl;
583   tree declb = stack_vars[ib].decl;
584   bool largea, largeb;
585   unsigned int uida, uidb;
586
587   /* Primary compare on "large" alignment.  Large comes first.  */
588   largea = (aligna * BITS_PER_UNIT > MAX_SUPPORTED_STACK_ALIGNMENT);
589   largeb = (alignb * BITS_PER_UNIT > MAX_SUPPORTED_STACK_ALIGNMENT);
590   if (largea != largeb)
591     return (int)largeb - (int)largea;
592
593   /* Secondary compare on size, decreasing  */
594   if (sizea > sizeb)
595     return -1;
596   if (sizea < sizeb)
597     return 1;
598
599   /* Tertiary compare on true alignment, decreasing.  */
600   if (aligna < alignb)
601     return -1;
602   if (aligna > alignb)
603     return 1;
604
605   /* Final compare on ID for sort stability, increasing.
606      Two SSA names are compared by their version, SSA names come before
607      non-SSA names, and two normal decls are compared by their DECL_UID.  */
608   if (TREE_CODE (decla) == SSA_NAME)
609     {
610       if (TREE_CODE (declb) == SSA_NAME)
611         uida = SSA_NAME_VERSION (decla), uidb = SSA_NAME_VERSION (declb);
612       else
613         return -1;
614     }
615   else if (TREE_CODE (declb) == SSA_NAME)
616     return 1;
617   else
618     uida = DECL_UID (decla), uidb = DECL_UID (declb);
619   if (uida < uidb)
620     return 1;
621   if (uida > uidb)
622     return -1;
623   return 0;
624 }
625
626
627 /* If the points-to solution *PI points to variables that are in a partition
628    together with other variables add all partition members to the pointed-to
629    variables bitmap.  */
630
631 static void
632 add_partitioned_vars_to_ptset (struct pt_solution *pt,
633                                struct pointer_map_t *decls_to_partitions,
634                                struct pointer_set_t *visited, bitmap temp)
635 {
636   bitmap_iterator bi;
637   unsigned i;
638   bitmap *part;
639
640   if (pt->anything
641       || pt->vars == NULL
642       /* The pointed-to vars bitmap is shared, it is enough to
643          visit it once.  */
644       || pointer_set_insert(visited, pt->vars))
645     return;
646
647   bitmap_clear (temp);
648
649   /* By using a temporary bitmap to store all members of the partitions
650      we have to add we make sure to visit each of the partitions only
651      once.  */
652   EXECUTE_IF_SET_IN_BITMAP (pt->vars, 0, i, bi)
653     if ((!temp
654          || !bitmap_bit_p (temp, i))
655         && (part = (bitmap *) pointer_map_contains (decls_to_partitions,
656                                                     (void *)(size_t) i)))
657       bitmap_ior_into (temp, *part);
658   if (!bitmap_empty_p (temp))
659     bitmap_ior_into (pt->vars, temp);
660 }
661
662 /* Update points-to sets based on partition info, so we can use them on RTL.
663    The bitmaps representing stack partitions will be saved until expand,
664    where partitioned decls used as bases in memory expressions will be
665    rewritten.  */
666
667 static void
668 update_alias_info_with_stack_vars (void)
669 {
670   struct pointer_map_t *decls_to_partitions = NULL;
671   size_t i, j;
672   tree var = NULL_TREE;
673
674   for (i = 0; i < stack_vars_num; i++)
675     {
676       bitmap part = NULL;
677       tree name;
678       struct ptr_info_def *pi;
679
680       /* Not interested in partitions with single variable.  */
681       if (stack_vars[i].representative != i
682           || stack_vars[i].next == EOC)
683         continue;
684
685       if (!decls_to_partitions)
686         {
687           decls_to_partitions = pointer_map_create ();
688           cfun->gimple_df->decls_to_pointers = pointer_map_create ();
689         }
690
691       /* Create an SSA_NAME that points to the partition for use
692          as base during alias-oracle queries on RTL for bases that
693          have been partitioned.  */
694       if (var == NULL_TREE)
695         var = create_tmp_var (ptr_type_node, NULL);
696       name = make_ssa_name (var, NULL);
697
698       /* Create bitmaps representing partitions.  They will be used for
699          points-to sets later, so use GGC alloc.  */
700       part = BITMAP_GGC_ALLOC ();
701       for (j = i; j != EOC; j = stack_vars[j].next)
702         {
703           tree decl = stack_vars[j].decl;
704           unsigned int uid = DECL_PT_UID (decl);
705           /* We should never end up partitioning SSA names (though they
706              may end up on the stack).  Neither should we allocate stack
707              space to something that is unused and thus unreferenced, except
708              for -O0 where we are preserving even unreferenced variables.  */
709           gcc_assert (DECL_P (decl)
710                       && (!optimize
711                           || referenced_var_lookup (cfun, DECL_UID (decl))));
712           bitmap_set_bit (part, uid);
713           *((bitmap *) pointer_map_insert (decls_to_partitions,
714                                            (void *)(size_t) uid)) = part;
715           *((tree *) pointer_map_insert (cfun->gimple_df->decls_to_pointers,
716                                          decl)) = name;
717         }
718
719       /* Make the SSA name point to all partition members.  */
720       pi = get_ptr_info (name);
721       pt_solution_set (&pi->pt, part, false);
722     }
723
724   /* Make all points-to sets that contain one member of a partition
725      contain all members of the partition.  */
726   if (decls_to_partitions)
727     {
728       unsigned i;
729       struct pointer_set_t *visited = pointer_set_create ();
730       bitmap temp = BITMAP_ALLOC (NULL);
731
732       for (i = 1; i < num_ssa_names; i++)
733         {
734           tree name = ssa_name (i);
735           struct ptr_info_def *pi;
736
737           if (name
738               && POINTER_TYPE_P (TREE_TYPE (name))
739               && ((pi = SSA_NAME_PTR_INFO (name)) != NULL))
740             add_partitioned_vars_to_ptset (&pi->pt, decls_to_partitions,
741                                            visited, temp);
742         }
743
744       add_partitioned_vars_to_ptset (&cfun->gimple_df->escaped,
745                                      decls_to_partitions, visited, temp);
746
747       pointer_set_destroy (visited);
748       pointer_map_destroy (decls_to_partitions);
749       BITMAP_FREE (temp);
750     }
751 }
752
753 /* A subroutine of partition_stack_vars.  The UNION portion of a UNION/FIND
754    partitioning algorithm.  Partitions A and B are known to be non-conflicting.
755    Merge them into a single partition A.  */
756
757 static void
758 union_stack_vars (size_t a, size_t b)
759 {
760   struct stack_var *vb = &stack_vars[b];
761   bitmap_iterator bi;
762   unsigned u;
763
764   gcc_assert (stack_vars[b].next == EOC);
765    /* Add B to A's partition.  */
766   stack_vars[b].next = stack_vars[a].next;
767   stack_vars[b].representative = a;
768   stack_vars[a].next = b;
769
770   /* Update the required alignment of partition A to account for B.  */
771   if (stack_vars[a].alignb < stack_vars[b].alignb)
772     stack_vars[a].alignb = stack_vars[b].alignb;
773
774   /* Update the interference graph and merge the conflicts.  */
775   if (vb->conflicts)
776     {
777       EXECUTE_IF_SET_IN_BITMAP (vb->conflicts, 0, u, bi)
778         add_stack_var_conflict (a, stack_vars[u].representative);
779       BITMAP_FREE (vb->conflicts);
780     }
781 }
782
783 /* A subroutine of expand_used_vars.  Binpack the variables into
784    partitions constrained by the interference graph.  The overall
785    algorithm used is as follows:
786
787         Sort the objects by size in descending order.
788         For each object A {
789           S = size(A)
790           O = 0
791           loop {
792             Look for the largest non-conflicting object B with size <= S.
793             UNION (A, B)
794           }
795         }
796 */
797
798 static void
799 partition_stack_vars (void)
800 {
801   size_t si, sj, n = stack_vars_num;
802
803   stack_vars_sorted = XNEWVEC (size_t, stack_vars_num);
804   for (si = 0; si < n; ++si)
805     stack_vars_sorted[si] = si;
806
807   if (n == 1)
808     return;
809
810   qsort (stack_vars_sorted, n, sizeof (size_t), stack_var_cmp);
811
812   for (si = 0; si < n; ++si)
813     {
814       size_t i = stack_vars_sorted[si];
815       unsigned int ialign = stack_vars[i].alignb;
816
817       /* Ignore objects that aren't partition representatives. If we
818          see a var that is not a partition representative, it must
819          have been merged earlier.  */
820       if (stack_vars[i].representative != i)
821         continue;
822
823       for (sj = si + 1; sj < n; ++sj)
824         {
825           size_t j = stack_vars_sorted[sj];
826           unsigned int jalign = stack_vars[j].alignb;
827
828           /* Ignore objects that aren't partition representatives.  */
829           if (stack_vars[j].representative != j)
830             continue;
831
832           /* Ignore conflicting objects.  */
833           if (stack_var_conflict_p (i, j))
834             continue;
835
836           /* Do not mix objects of "small" (supported) alignment
837              and "large" (unsupported) alignment.  */
838           if ((ialign * BITS_PER_UNIT <= MAX_SUPPORTED_STACK_ALIGNMENT)
839               != (jalign * BITS_PER_UNIT <= MAX_SUPPORTED_STACK_ALIGNMENT))
840             continue;
841
842           /* UNION the objects, placing J at OFFSET.  */
843           union_stack_vars (i, j);
844         }
845     }
846
847   update_alias_info_with_stack_vars ();
848 }
849
850 /* A debugging aid for expand_used_vars.  Dump the generated partitions.  */
851
852 static void
853 dump_stack_var_partition (void)
854 {
855   size_t si, i, j, n = stack_vars_num;
856
857   for (si = 0; si < n; ++si)
858     {
859       i = stack_vars_sorted[si];
860
861       /* Skip variables that aren't partition representatives, for now.  */
862       if (stack_vars[i].representative != i)
863         continue;
864
865       fprintf (dump_file, "Partition %lu: size " HOST_WIDE_INT_PRINT_DEC
866                " align %u\n", (unsigned long) i, stack_vars[i].size,
867                stack_vars[i].alignb);
868
869       for (j = i; j != EOC; j = stack_vars[j].next)
870         {
871           fputc ('\t', dump_file);
872           print_generic_expr (dump_file, stack_vars[j].decl, dump_flags);
873         }
874       fputc ('\n', dump_file);
875     }
876 }
877
878 /* Assign rtl to DECL at BASE + OFFSET.  */
879
880 static void
881 expand_one_stack_var_at (tree decl, rtx base, unsigned base_align,
882                          HOST_WIDE_INT offset)
883 {
884   unsigned align;
885   rtx x;
886
887   /* If this fails, we've overflowed the stack frame.  Error nicely?  */
888   gcc_assert (offset == trunc_int_for_mode (offset, Pmode));
889
890   x = plus_constant (base, offset);
891   x = gen_rtx_MEM (DECL_MODE (SSAVAR (decl)), x);
892
893   if (TREE_CODE (decl) != SSA_NAME)
894     {
895       /* Set alignment we actually gave this decl if it isn't an SSA name.
896          If it is we generate stack slots only accidentally so it isn't as
897          important, we'll simply use the alignment that is already set.  */
898       if (base == virtual_stack_vars_rtx)
899         offset -= frame_phase;
900       align = offset & -offset;
901       align *= BITS_PER_UNIT;
902       if (align == 0 || align > base_align)
903         align = base_align;
904
905       /* One would think that we could assert that we're not decreasing
906          alignment here, but (at least) the i386 port does exactly this
907          via the MINIMUM_ALIGNMENT hook.  */
908
909       DECL_ALIGN (decl) = align;
910       DECL_USER_ALIGN (decl) = 0;
911     }
912
913   set_mem_attributes (x, SSAVAR (decl), true);
914   set_rtl (decl, x);
915 }
916
917 /* A subroutine of expand_used_vars.  Give each partition representative
918    a unique location within the stack frame.  Update each partition member
919    with that location.  */
920
921 static void
922 expand_stack_vars (bool (*pred) (tree))
923 {
924   size_t si, i, j, n = stack_vars_num;
925   HOST_WIDE_INT large_size = 0, large_alloc = 0;
926   rtx large_base = NULL;
927   unsigned large_align = 0;
928   tree decl;
929
930   /* Determine if there are any variables requiring "large" alignment.
931      Since these are dynamically allocated, we only process these if
932      no predicate involved.  */
933   large_align = stack_vars[stack_vars_sorted[0]].alignb * BITS_PER_UNIT;
934   if (pred == NULL && large_align > MAX_SUPPORTED_STACK_ALIGNMENT)
935     {
936       /* Find the total size of these variables.  */
937       for (si = 0; si < n; ++si)
938         {
939           unsigned alignb;
940
941           i = stack_vars_sorted[si];
942           alignb = stack_vars[i].alignb;
943
944           /* Stop when we get to the first decl with "small" alignment.  */
945           if (alignb * BITS_PER_UNIT <= MAX_SUPPORTED_STACK_ALIGNMENT)
946             break;
947
948           /* Skip variables that aren't partition representatives.  */
949           if (stack_vars[i].representative != i)
950             continue;
951
952           /* Skip variables that have already had rtl assigned.  See also
953              add_stack_var where we perpetrate this pc_rtx hack.  */
954           decl = stack_vars[i].decl;
955           if ((TREE_CODE (decl) == SSA_NAME
956               ? SA.partition_to_pseudo[var_to_partition (SA.map, decl)]
957               : DECL_RTL (decl)) != pc_rtx)
958             continue;
959
960           large_size += alignb - 1;
961           large_size &= -(HOST_WIDE_INT)alignb;
962           large_size += stack_vars[i].size;
963         }
964
965       /* If there were any, allocate space.  */
966       if (large_size > 0)
967         large_base = allocate_dynamic_stack_space (GEN_INT (large_size), 0,
968                                                    large_align, true);
969     }
970
971   for (si = 0; si < n; ++si)
972     {
973       rtx base;
974       unsigned base_align, alignb;
975       HOST_WIDE_INT offset;
976
977       i = stack_vars_sorted[si];
978
979       /* Skip variables that aren't partition representatives, for now.  */
980       if (stack_vars[i].representative != i)
981         continue;
982
983       /* Skip variables that have already had rtl assigned.  See also
984          add_stack_var where we perpetrate this pc_rtx hack.  */
985       decl = stack_vars[i].decl;
986       if ((TREE_CODE (decl) == SSA_NAME
987            ? SA.partition_to_pseudo[var_to_partition (SA.map, decl)]
988            : DECL_RTL (decl)) != pc_rtx)
989         continue;
990
991       /* Check the predicate to see whether this variable should be
992          allocated in this pass.  */
993       if (pred && !pred (decl))
994         continue;
995
996       alignb = stack_vars[i].alignb;
997       if (alignb * BITS_PER_UNIT <= MAX_SUPPORTED_STACK_ALIGNMENT)
998         {
999           offset = alloc_stack_frame_space (stack_vars[i].size, alignb);
1000           base = virtual_stack_vars_rtx;
1001           base_align = crtl->max_used_stack_slot_alignment;
1002         }
1003       else
1004         {
1005           /* Large alignment is only processed in the last pass.  */
1006           if (pred)
1007             continue;
1008           gcc_assert (large_base != NULL);
1009
1010           large_alloc += alignb - 1;
1011           large_alloc &= -(HOST_WIDE_INT)alignb;
1012           offset = large_alloc;
1013           large_alloc += stack_vars[i].size;
1014
1015           base = large_base;
1016           base_align = large_align;
1017         }
1018
1019       /* Create rtl for each variable based on their location within the
1020          partition.  */
1021       for (j = i; j != EOC; j = stack_vars[j].next)
1022         {
1023           expand_one_stack_var_at (stack_vars[j].decl,
1024                                    base, base_align,
1025                                    offset);
1026         }
1027     }
1028
1029   gcc_assert (large_alloc == large_size);
1030 }
1031
1032 /* Take into account all sizes of partitions and reset DECL_RTLs.  */
1033 static HOST_WIDE_INT
1034 account_stack_vars (void)
1035 {
1036   size_t si, j, i, n = stack_vars_num;
1037   HOST_WIDE_INT size = 0;
1038
1039   for (si = 0; si < n; ++si)
1040     {
1041       i = stack_vars_sorted[si];
1042
1043       /* Skip variables that aren't partition representatives, for now.  */
1044       if (stack_vars[i].representative != i)
1045         continue;
1046
1047       size += stack_vars[i].size;
1048       for (j = i; j != EOC; j = stack_vars[j].next)
1049         set_rtl (stack_vars[j].decl, NULL);
1050     }
1051   return size;
1052 }
1053
1054 /* A subroutine of expand_one_var.  Called to immediately assign rtl
1055    to a variable to be allocated in the stack frame.  */
1056
1057 static void
1058 expand_one_stack_var (tree var)
1059 {
1060   HOST_WIDE_INT size, offset;
1061   unsigned byte_align;
1062
1063   size = tree_low_cst (DECL_SIZE_UNIT (SSAVAR (var)), 1);
1064   byte_align = align_local_variable (SSAVAR (var));
1065
1066   /* We handle highly aligned variables in expand_stack_vars.  */
1067   gcc_assert (byte_align * BITS_PER_UNIT <= MAX_SUPPORTED_STACK_ALIGNMENT);
1068
1069   offset = alloc_stack_frame_space (size, byte_align);
1070
1071   expand_one_stack_var_at (var, virtual_stack_vars_rtx,
1072                            crtl->max_used_stack_slot_alignment, offset);
1073 }
1074
1075 /* A subroutine of expand_one_var.  Called to assign rtl to a VAR_DECL
1076    that will reside in a hard register.  */
1077
1078 static void
1079 expand_one_hard_reg_var (tree var)
1080 {
1081   rest_of_decl_compilation (var, 0, 0);
1082 }
1083
1084 /* A subroutine of expand_one_var.  Called to assign rtl to a VAR_DECL
1085    that will reside in a pseudo register.  */
1086
1087 static void
1088 expand_one_register_var (tree var)
1089 {
1090   tree decl = SSAVAR (var);
1091   tree type = TREE_TYPE (decl);
1092   enum machine_mode reg_mode = promote_decl_mode (decl, NULL);
1093   rtx x = gen_reg_rtx (reg_mode);
1094
1095   set_rtl (var, x);
1096
1097   /* Note if the object is a user variable.  */
1098   if (!DECL_ARTIFICIAL (decl))
1099     mark_user_reg (x);
1100
1101   if (POINTER_TYPE_P (type))
1102     mark_reg_pointer (x, get_pointer_alignment (var));
1103 }
1104
1105 /* A subroutine of expand_one_var.  Called to assign rtl to a VAR_DECL that
1106    has some associated error, e.g. its type is error-mark.  We just need
1107    to pick something that won't crash the rest of the compiler.  */
1108
1109 static void
1110 expand_one_error_var (tree var)
1111 {
1112   enum machine_mode mode = DECL_MODE (var);
1113   rtx x;
1114
1115   if (mode == BLKmode)
1116     x = gen_rtx_MEM (BLKmode, const0_rtx);
1117   else if (mode == VOIDmode)
1118     x = const0_rtx;
1119   else
1120     x = gen_reg_rtx (mode);
1121
1122   SET_DECL_RTL (var, x);
1123 }
1124
1125 /* A subroutine of expand_one_var.  VAR is a variable that will be
1126    allocated to the local stack frame.  Return true if we wish to
1127    add VAR to STACK_VARS so that it will be coalesced with other
1128    variables.  Return false to allocate VAR immediately.
1129
1130    This function is used to reduce the number of variables considered
1131    for coalescing, which reduces the size of the quadratic problem.  */
1132
1133 static bool
1134 defer_stack_allocation (tree var, bool toplevel)
1135 {
1136   /* If stack protection is enabled, *all* stack variables must be deferred,
1137      so that we can re-order the strings to the top of the frame.  */
1138   if (flag_stack_protect)
1139     return true;
1140
1141   /* We handle "large" alignment via dynamic allocation.  We want to handle
1142      this extra complication in only one place, so defer them.  */
1143   if (DECL_ALIGN (var) > MAX_SUPPORTED_STACK_ALIGNMENT)
1144     return true;
1145
1146   /* Variables in the outermost scope automatically conflict with
1147      every other variable.  The only reason to want to defer them
1148      at all is that, after sorting, we can more efficiently pack
1149      small variables in the stack frame.  Continue to defer at -O2.  */
1150   if (toplevel && optimize < 2)
1151     return false;
1152
1153   /* Without optimization, *most* variables are allocated from the
1154      stack, which makes the quadratic problem large exactly when we
1155      want compilation to proceed as quickly as possible.  On the
1156      other hand, we don't want the function's stack frame size to
1157      get completely out of hand.  So we avoid adding scalars and
1158      "small" aggregates to the list at all.  */
1159   if (optimize == 0 && tree_low_cst (DECL_SIZE_UNIT (var), 1) < 32)
1160     return false;
1161
1162   return true;
1163 }
1164
1165 /* A subroutine of expand_used_vars.  Expand one variable according to
1166    its flavor.  Variables to be placed on the stack are not actually
1167    expanded yet, merely recorded.
1168    When REALLY_EXPAND is false, only add stack values to be allocated.
1169    Return stack usage this variable is supposed to take.
1170 */
1171
1172 static HOST_WIDE_INT
1173 expand_one_var (tree var, bool toplevel, bool really_expand)
1174 {
1175   unsigned int align = BITS_PER_UNIT;
1176   tree origvar = var;
1177
1178   var = SSAVAR (var);
1179
1180   if (TREE_TYPE (var) != error_mark_node && TREE_CODE (var) == VAR_DECL)
1181     {
1182       /* Because we don't know if VAR will be in register or on stack,
1183          we conservatively assume it will be on stack even if VAR is
1184          eventually put into register after RA pass.  For non-automatic
1185          variables, which won't be on stack, we collect alignment of
1186          type and ignore user specified alignment.  */
1187       if (TREE_STATIC (var) || DECL_EXTERNAL (var))
1188         align = MINIMUM_ALIGNMENT (TREE_TYPE (var),
1189                                    TYPE_MODE (TREE_TYPE (var)),
1190                                    TYPE_ALIGN (TREE_TYPE (var)));
1191       else if (DECL_HAS_VALUE_EXPR_P (var)
1192                || (DECL_RTL_SET_P (var) && MEM_P (DECL_RTL (var))))
1193         /* Don't consider debug only variables with DECL_HAS_VALUE_EXPR_P set
1194            or variables which were assigned a stack slot already by
1195            expand_one_stack_var_at - in the latter case DECL_ALIGN has been
1196            changed from the offset chosen to it.  */
1197         align = crtl->stack_alignment_estimated;
1198       else
1199         align = MINIMUM_ALIGNMENT (var, DECL_MODE (var), DECL_ALIGN (var));
1200
1201       /* If the variable alignment is very large we'll dynamicaly allocate
1202          it, which means that in-frame portion is just a pointer.  */
1203       if (align > MAX_SUPPORTED_STACK_ALIGNMENT)
1204         align = POINTER_SIZE;
1205     }
1206
1207   if (SUPPORTS_STACK_ALIGNMENT
1208       && crtl->stack_alignment_estimated < align)
1209     {
1210       /* stack_alignment_estimated shouldn't change after stack
1211          realign decision made */
1212       gcc_assert(!crtl->stack_realign_processed);
1213       crtl->stack_alignment_estimated = align;
1214     }
1215
1216   /* stack_alignment_needed > PREFERRED_STACK_BOUNDARY is permitted.
1217      So here we only make sure stack_alignment_needed >= align.  */
1218   if (crtl->stack_alignment_needed < align)
1219     crtl->stack_alignment_needed = align;
1220   if (crtl->max_used_stack_slot_alignment < align)
1221     crtl->max_used_stack_slot_alignment = align;
1222
1223   if (TREE_CODE (origvar) == SSA_NAME)
1224     {
1225       gcc_assert (TREE_CODE (var) != VAR_DECL
1226                   || (!DECL_EXTERNAL (var)
1227                       && !DECL_HAS_VALUE_EXPR_P (var)
1228                       && !TREE_STATIC (var)
1229                       && TREE_TYPE (var) != error_mark_node
1230                       && !DECL_HARD_REGISTER (var)
1231                       && really_expand));
1232     }
1233   if (TREE_CODE (var) != VAR_DECL && TREE_CODE (origvar) != SSA_NAME)
1234     ;
1235   else if (DECL_EXTERNAL (var))
1236     ;
1237   else if (DECL_HAS_VALUE_EXPR_P (var))
1238     ;
1239   else if (TREE_STATIC (var))
1240     ;
1241   else if (TREE_CODE (origvar) != SSA_NAME && DECL_RTL_SET_P (var))
1242     ;
1243   else if (TREE_TYPE (var) == error_mark_node)
1244     {
1245       if (really_expand)
1246         expand_one_error_var (var);
1247     }
1248   else if (TREE_CODE (var) == VAR_DECL && DECL_HARD_REGISTER (var))
1249     {
1250       if (really_expand)
1251         expand_one_hard_reg_var (var);
1252     }
1253   else if (use_register_for_decl (var))
1254     {
1255       if (really_expand)
1256         expand_one_register_var (origvar);
1257     }
1258   else if (!host_integerp (DECL_SIZE_UNIT (var), 1))
1259     {
1260       if (really_expand)
1261         {
1262           error ("size of variable %q+D is too large", var);
1263           expand_one_error_var (var);
1264         }
1265     }
1266   else if (defer_stack_allocation (var, toplevel))
1267     add_stack_var (origvar);
1268   else
1269     {
1270       if (really_expand)
1271         expand_one_stack_var (origvar);
1272       return tree_low_cst (DECL_SIZE_UNIT (var), 1);
1273     }
1274   return 0;
1275 }
1276
1277 /* A subroutine of expand_used_vars.  Walk down through the BLOCK tree
1278    expanding variables.  Those variables that can be put into registers
1279    are allocated pseudos; those that can't are put on the stack.
1280
1281    TOPLEVEL is true if this is the outermost BLOCK.  */
1282
1283 static void
1284 expand_used_vars_for_block (tree block, bool toplevel)
1285 {
1286   tree t;
1287
1288   /* Expand all variables at this level.  */
1289   for (t = BLOCK_VARS (block); t ; t = DECL_CHAIN (t))
1290     if (TREE_USED (t)
1291         && ((TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != RESULT_DECL)
1292             || !DECL_NONSHAREABLE (t)))
1293       expand_one_var (t, toplevel, true);
1294
1295   /* Expand all variables at containing levels.  */
1296   for (t = BLOCK_SUBBLOCKS (block); t ; t = BLOCK_CHAIN (t))
1297     expand_used_vars_for_block (t, false);
1298 }
1299
1300 /* A subroutine of expand_used_vars.  Walk down through the BLOCK tree
1301    and clear TREE_USED on all local variables.  */
1302
1303 static void
1304 clear_tree_used (tree block)
1305 {
1306   tree t;
1307
1308   for (t = BLOCK_VARS (block); t ; t = DECL_CHAIN (t))
1309     /* if (!TREE_STATIC (t) && !DECL_EXTERNAL (t)) */
1310     if ((TREE_CODE (t) != VAR_DECL && TREE_CODE (t) != RESULT_DECL)
1311         || !DECL_NONSHAREABLE (t))
1312       TREE_USED (t) = 0;
1313
1314   for (t = BLOCK_SUBBLOCKS (block); t ; t = BLOCK_CHAIN (t))
1315     clear_tree_used (t);
1316 }
1317
1318 /* Examine TYPE and determine a bit mask of the following features.  */
1319
1320 #define SPCT_HAS_LARGE_CHAR_ARRAY       1
1321 #define SPCT_HAS_SMALL_CHAR_ARRAY       2
1322 #define SPCT_HAS_ARRAY                  4
1323 #define SPCT_HAS_AGGREGATE              8
1324
1325 static unsigned int
1326 stack_protect_classify_type (tree type)
1327 {
1328   unsigned int ret = 0;
1329   tree t;
1330
1331   switch (TREE_CODE (type))
1332     {
1333     case ARRAY_TYPE:
1334       t = TYPE_MAIN_VARIANT (TREE_TYPE (type));
1335       if (t == char_type_node
1336           || t == signed_char_type_node
1337           || t == unsigned_char_type_node)
1338         {
1339           unsigned HOST_WIDE_INT max = PARAM_VALUE (PARAM_SSP_BUFFER_SIZE);
1340           unsigned HOST_WIDE_INT len;
1341
1342           if (!TYPE_SIZE_UNIT (type)
1343               || !host_integerp (TYPE_SIZE_UNIT (type), 1))
1344             len = max;
1345           else
1346             len = tree_low_cst (TYPE_SIZE_UNIT (type), 1);
1347
1348           if (len < max)
1349             ret = SPCT_HAS_SMALL_CHAR_ARRAY | SPCT_HAS_ARRAY;
1350           else
1351             ret = SPCT_HAS_LARGE_CHAR_ARRAY | SPCT_HAS_ARRAY;
1352         }
1353       else
1354         ret = SPCT_HAS_ARRAY;
1355       break;
1356
1357     case UNION_TYPE:
1358     case QUAL_UNION_TYPE:
1359     case RECORD_TYPE:
1360       ret = SPCT_HAS_AGGREGATE;
1361       for (t = TYPE_FIELDS (type); t ; t = TREE_CHAIN (t))
1362         if (TREE_CODE (t) == FIELD_DECL)
1363           ret |= stack_protect_classify_type (TREE_TYPE (t));
1364       break;
1365
1366     default:
1367       break;
1368     }
1369
1370   return ret;
1371 }
1372
1373 /* Return nonzero if DECL should be segregated into the "vulnerable" upper
1374    part of the local stack frame.  Remember if we ever return nonzero for
1375    any variable in this function.  The return value is the phase number in
1376    which the variable should be allocated.  */
1377
1378 static int
1379 stack_protect_decl_phase (tree decl)
1380 {
1381   unsigned int bits = stack_protect_classify_type (TREE_TYPE (decl));
1382   int ret = 0;
1383
1384   if (bits & SPCT_HAS_SMALL_CHAR_ARRAY)
1385     has_short_buffer = true;
1386
1387   if (flag_stack_protect == 2)
1388     {
1389       if ((bits & (SPCT_HAS_SMALL_CHAR_ARRAY | SPCT_HAS_LARGE_CHAR_ARRAY))
1390           && !(bits & SPCT_HAS_AGGREGATE))
1391         ret = 1;
1392       else if (bits & SPCT_HAS_ARRAY)
1393         ret = 2;
1394     }
1395   else
1396     ret = (bits & SPCT_HAS_LARGE_CHAR_ARRAY) != 0;
1397
1398   if (ret)
1399     has_protected_decls = true;
1400
1401   return ret;
1402 }
1403
1404 /* Two helper routines that check for phase 1 and phase 2.  These are used
1405    as callbacks for expand_stack_vars.  */
1406
1407 static bool
1408 stack_protect_decl_phase_1 (tree decl)
1409 {
1410   return stack_protect_decl_phase (decl) == 1;
1411 }
1412
1413 static bool
1414 stack_protect_decl_phase_2 (tree decl)
1415 {
1416   return stack_protect_decl_phase (decl) == 2;
1417 }
1418
1419 /* Ensure that variables in different stack protection phases conflict
1420    so that they are not merged and share the same stack slot.  */
1421
1422 static void
1423 add_stack_protection_conflicts (void)
1424 {
1425   size_t i, j, n = stack_vars_num;
1426   unsigned char *phase;
1427
1428   phase = XNEWVEC (unsigned char, n);
1429   for (i = 0; i < n; ++i)
1430     phase[i] = stack_protect_decl_phase (stack_vars[i].decl);
1431
1432   for (i = 0; i < n; ++i)
1433     {
1434       unsigned char ph_i = phase[i];
1435       for (j = 0; j < i; ++j)
1436         if (ph_i != phase[j])
1437           add_stack_var_conflict (i, j);
1438     }
1439
1440   XDELETEVEC (phase);
1441 }
1442
1443 /* Create a decl for the guard at the top of the stack frame.  */
1444
1445 static void
1446 create_stack_guard (void)
1447 {
1448   tree guard = build_decl (DECL_SOURCE_LOCATION (current_function_decl),
1449                            VAR_DECL, NULL, ptr_type_node);
1450   TREE_THIS_VOLATILE (guard) = 1;
1451   TREE_USED (guard) = 1;
1452   expand_one_stack_var (guard);
1453   crtl->stack_protect_guard = guard;
1454 }
1455
1456 /* Prepare for expanding variables.  */
1457 static void
1458 init_vars_expansion (void)
1459 {
1460   tree t;
1461   unsigned ix;
1462   /* Set TREE_USED on all variables in the local_decls.  */
1463   FOR_EACH_LOCAL_DECL (cfun, ix, t)
1464     TREE_USED (t) = 1;
1465
1466   /* Clear TREE_USED on all variables associated with a block scope.  */
1467   clear_tree_used (DECL_INITIAL (current_function_decl));
1468
1469   /* Initialize local stack smashing state.  */
1470   has_protected_decls = false;
1471   has_short_buffer = false;
1472 }
1473
1474 /* Free up stack variable graph data.  */
1475 static void
1476 fini_vars_expansion (void)
1477 {
1478   size_t i, n = stack_vars_num;
1479   for (i = 0; i < n; i++)
1480     BITMAP_FREE (stack_vars[i].conflicts);
1481   XDELETEVEC (stack_vars);
1482   XDELETEVEC (stack_vars_sorted);
1483   stack_vars = NULL;
1484   stack_vars_alloc = stack_vars_num = 0;
1485   pointer_map_destroy (decl_to_stack_part);
1486   decl_to_stack_part = NULL;
1487 }
1488
1489 /* Make a fair guess for the size of the stack frame of the function
1490    in NODE.  This doesn't have to be exact, the result is only used in
1491    the inline heuristics.  So we don't want to run the full stack var
1492    packing algorithm (which is quadratic in the number of stack vars).
1493    Instead, we calculate the total size of all stack vars.  This turns
1494    out to be a pretty fair estimate -- packing of stack vars doesn't
1495    happen very often.  */
1496
1497 HOST_WIDE_INT
1498 estimated_stack_frame_size (struct cgraph_node *node)
1499 {
1500   HOST_WIDE_INT size = 0;
1501   size_t i;
1502   tree var;
1503   tree old_cur_fun_decl = current_function_decl;
1504   referenced_var_iterator rvi;
1505   struct function *fn = DECL_STRUCT_FUNCTION (node->decl);
1506
1507   current_function_decl = node->decl;
1508   push_cfun (fn);
1509
1510   gcc_checking_assert (gimple_referenced_vars (fn));
1511   FOR_EACH_REFERENCED_VAR (fn, var, rvi)
1512     size += expand_one_var (var, true, false);
1513
1514   if (stack_vars_num > 0)
1515     {
1516       /* Fake sorting the stack vars for account_stack_vars ().  */
1517       stack_vars_sorted = XNEWVEC (size_t, stack_vars_num);
1518       for (i = 0; i < stack_vars_num; ++i)
1519         stack_vars_sorted[i] = i;
1520       size += account_stack_vars ();
1521       fini_vars_expansion ();
1522     }
1523   pop_cfun ();
1524   current_function_decl = old_cur_fun_decl;
1525   return size;
1526 }
1527
1528 /* Expand all variables used in the function.  */
1529
1530 static void
1531 expand_used_vars (void)
1532 {
1533   tree var, outer_block = DECL_INITIAL (current_function_decl);
1534   VEC(tree,heap) *maybe_local_decls = NULL;
1535   unsigned i;
1536   unsigned len;
1537
1538   /* Compute the phase of the stack frame for this function.  */
1539   {
1540     int align = PREFERRED_STACK_BOUNDARY / BITS_PER_UNIT;
1541     int off = STARTING_FRAME_OFFSET % align;
1542     frame_phase = off ? align - off : 0;
1543   }
1544
1545   init_vars_expansion ();
1546
1547   for (i = 0; i < SA.map->num_partitions; i++)
1548     {
1549       tree var = partition_to_var (SA.map, i);
1550
1551       gcc_assert (is_gimple_reg (var));
1552       if (TREE_CODE (SSA_NAME_VAR (var)) == VAR_DECL)
1553         expand_one_var (var, true, true);
1554       else
1555         {
1556           /* This is a PARM_DECL or RESULT_DECL.  For those partitions that
1557              contain the default def (representing the parm or result itself)
1558              we don't do anything here.  But those which don't contain the
1559              default def (representing a temporary based on the parm/result)
1560              we need to allocate space just like for normal VAR_DECLs.  */
1561           if (!bitmap_bit_p (SA.partition_has_default_def, i))
1562             {
1563               expand_one_var (var, true, true);
1564               gcc_assert (SA.partition_to_pseudo[i]);
1565             }
1566         }
1567     }
1568
1569   /* At this point all variables on the local_decls with TREE_USED
1570      set are not associated with any block scope.  Lay them out.  */
1571
1572   len = VEC_length (tree, cfun->local_decls);
1573   FOR_EACH_LOCAL_DECL (cfun, i, var)
1574     {
1575       bool expand_now = false;
1576
1577       /* Expanded above already.  */
1578       if (is_gimple_reg (var))
1579         {
1580           TREE_USED (var) = 0;
1581           goto next;
1582         }
1583       /* We didn't set a block for static or extern because it's hard
1584          to tell the difference between a global variable (re)declared
1585          in a local scope, and one that's really declared there to
1586          begin with.  And it doesn't really matter much, since we're
1587          not giving them stack space.  Expand them now.  */
1588       else if (TREE_STATIC (var) || DECL_EXTERNAL (var))
1589         expand_now = true;
1590
1591       /* If the variable is not associated with any block, then it
1592          was created by the optimizers, and could be live anywhere
1593          in the function.  */
1594       else if (TREE_USED (var))
1595         expand_now = true;
1596
1597       /* Finally, mark all variables on the list as used.  We'll use
1598          this in a moment when we expand those associated with scopes.  */
1599       TREE_USED (var) = 1;
1600
1601       if (expand_now)
1602         expand_one_var (var, true, true);
1603
1604     next:
1605       if (DECL_ARTIFICIAL (var) && !DECL_IGNORED_P (var))
1606         {
1607           rtx rtl = DECL_RTL_IF_SET (var);
1608
1609           /* Keep artificial non-ignored vars in cfun->local_decls
1610              chain until instantiate_decls.  */
1611           if (rtl && (MEM_P (rtl) || GET_CODE (rtl) == CONCAT))
1612             add_local_decl (cfun, var);
1613           else if (rtl == NULL_RTX)
1614             /* If rtl isn't set yet, which can happen e.g. with
1615                -fstack-protector, retry before returning from this
1616                function.  */
1617             VEC_safe_push (tree, heap, maybe_local_decls, var);
1618         }
1619     }
1620
1621   /* We duplicated some of the decls in CFUN->LOCAL_DECLS.
1622
1623      +-----------------+-----------------+
1624      | ...processed... | ...duplicates...|
1625      +-----------------+-----------------+
1626                        ^
1627                        +-- LEN points here.
1628
1629      We just want the duplicates, as those are the artificial
1630      non-ignored vars that we want to keep until instantiate_decls.
1631      Move them down and truncate the array.  */
1632   if (!VEC_empty (tree, cfun->local_decls))
1633     VEC_block_remove (tree, cfun->local_decls, 0, len);
1634
1635   /* At this point, all variables within the block tree with TREE_USED
1636      set are actually used by the optimized function.  Lay them out.  */
1637   expand_used_vars_for_block (outer_block, true);
1638
1639   if (stack_vars_num > 0)
1640     {
1641       add_scope_conflicts ();
1642       /* Due to the way alias sets work, no variables with non-conflicting
1643          alias sets may be assigned the same address.  Add conflicts to
1644          reflect this.  */
1645       add_alias_set_conflicts ();
1646
1647       /* If stack protection is enabled, we don't share space between
1648          vulnerable data and non-vulnerable data.  */
1649       if (flag_stack_protect)
1650         add_stack_protection_conflicts ();
1651
1652       /* Now that we have collected all stack variables, and have computed a
1653          minimal interference graph, attempt to save some stack space.  */
1654       partition_stack_vars ();
1655       if (dump_file)
1656         dump_stack_var_partition ();
1657     }
1658
1659   /* There are several conditions under which we should create a
1660      stack guard: protect-all, alloca used, protected decls present.  */
1661   if (flag_stack_protect == 2
1662       || (flag_stack_protect
1663           && (cfun->calls_alloca || has_protected_decls)))
1664     create_stack_guard ();
1665
1666   /* Assign rtl to each variable based on these partitions.  */
1667   if (stack_vars_num > 0)
1668     {
1669       /* Reorder decls to be protected by iterating over the variables
1670          array multiple times, and allocating out of each phase in turn.  */
1671       /* ??? We could probably integrate this into the qsort we did
1672          earlier, such that we naturally see these variables first,
1673          and thus naturally allocate things in the right order.  */
1674       if (has_protected_decls)
1675         {
1676           /* Phase 1 contains only character arrays.  */
1677           expand_stack_vars (stack_protect_decl_phase_1);
1678
1679           /* Phase 2 contains other kinds of arrays.  */
1680           if (flag_stack_protect == 2)
1681             expand_stack_vars (stack_protect_decl_phase_2);
1682         }
1683
1684       expand_stack_vars (NULL);
1685
1686       fini_vars_expansion ();
1687     }
1688
1689   /* If there were any artificial non-ignored vars without rtl
1690      found earlier, see if deferred stack allocation hasn't assigned
1691      rtl to them.  */
1692   FOR_EACH_VEC_ELT_REVERSE (tree, maybe_local_decls, i, var)
1693     {
1694       rtx rtl = DECL_RTL_IF_SET (var);
1695
1696       /* Keep artificial non-ignored vars in cfun->local_decls
1697          chain until instantiate_decls.  */
1698       if (rtl && (MEM_P (rtl) || GET_CODE (rtl) == CONCAT))
1699         add_local_decl (cfun, var);
1700     }
1701   VEC_free (tree, heap, maybe_local_decls);
1702
1703   /* If the target requires that FRAME_OFFSET be aligned, do it.  */
1704   if (STACK_ALIGNMENT_NEEDED)
1705     {
1706       HOST_WIDE_INT align = PREFERRED_STACK_BOUNDARY / BITS_PER_UNIT;
1707       if (!FRAME_GROWS_DOWNWARD)
1708         frame_offset += align - 1;
1709       frame_offset &= -align;
1710     }
1711 }
1712
1713
1714 /* If we need to produce a detailed dump, print the tree representation
1715    for STMT to the dump file.  SINCE is the last RTX after which the RTL
1716    generated for STMT should have been appended.  */
1717
1718 static void
1719 maybe_dump_rtl_for_gimple_stmt (gimple stmt, rtx since)
1720 {
1721   if (dump_file && (dump_flags & TDF_DETAILS))
1722     {
1723       fprintf (dump_file, "\n;; ");
1724       print_gimple_stmt (dump_file, stmt, 0,
1725                          TDF_SLIM | (dump_flags & TDF_LINENO));
1726       fprintf (dump_file, "\n");
1727
1728       print_rtl (dump_file, since ? NEXT_INSN (since) : since);
1729     }
1730 }
1731
1732 /* Maps the blocks that do not contain tree labels to rtx labels.  */
1733
1734 static struct pointer_map_t *lab_rtx_for_bb;
1735
1736 /* Returns the label_rtx expression for a label starting basic block BB.  */
1737
1738 static rtx
1739 label_rtx_for_bb (basic_block bb ATTRIBUTE_UNUSED)
1740 {
1741   gimple_stmt_iterator gsi;
1742   tree lab;
1743   gimple lab_stmt;
1744   void **elt;
1745
1746   if (bb->flags & BB_RTL)
1747     return block_label (bb);
1748
1749   elt = pointer_map_contains (lab_rtx_for_bb, bb);
1750   if (elt)
1751     return (rtx) *elt;
1752
1753   /* Find the tree label if it is present.  */
1754
1755   for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1756     {
1757       lab_stmt = gsi_stmt (gsi);
1758       if (gimple_code (lab_stmt) != GIMPLE_LABEL)
1759         break;
1760
1761       lab = gimple_label_label (lab_stmt);
1762       if (DECL_NONLOCAL (lab))
1763         break;
1764
1765       return label_rtx (lab);
1766     }
1767
1768   elt = pointer_map_insert (lab_rtx_for_bb, bb);
1769   *elt = gen_label_rtx ();
1770   return (rtx) *elt;
1771 }
1772
1773
1774 /* A subroutine of expand_gimple_cond.  Given E, a fallthrough edge
1775    of a basic block where we just expanded the conditional at the end,
1776    possibly clean up the CFG and instruction sequence.  LAST is the
1777    last instruction before the just emitted jump sequence.  */
1778
1779 static void
1780 maybe_cleanup_end_of_block (edge e, rtx last)
1781 {
1782   /* Special case: when jumpif decides that the condition is
1783      trivial it emits an unconditional jump (and the necessary
1784      barrier).  But we still have two edges, the fallthru one is
1785      wrong.  purge_dead_edges would clean this up later.  Unfortunately
1786      we have to insert insns (and split edges) before
1787      find_many_sub_basic_blocks and hence before purge_dead_edges.
1788      But splitting edges might create new blocks which depend on the
1789      fact that if there are two edges there's no barrier.  So the
1790      barrier would get lost and verify_flow_info would ICE.  Instead
1791      of auditing all edge splitters to care for the barrier (which
1792      normally isn't there in a cleaned CFG), fix it here.  */
1793   if (BARRIER_P (get_last_insn ()))
1794     {
1795       rtx insn;
1796       remove_edge (e);
1797       /* Now, we have a single successor block, if we have insns to
1798          insert on the remaining edge we potentially will insert
1799          it at the end of this block (if the dest block isn't feasible)
1800          in order to avoid splitting the edge.  This insertion will take
1801          place in front of the last jump.  But we might have emitted
1802          multiple jumps (conditional and one unconditional) to the
1803          same destination.  Inserting in front of the last one then
1804          is a problem.  See PR 40021.  We fix this by deleting all
1805          jumps except the last unconditional one.  */
1806       insn = PREV_INSN (get_last_insn ());
1807       /* Make sure we have an unconditional jump.  Otherwise we're
1808          confused.  */
1809       gcc_assert (JUMP_P (insn) && !any_condjump_p (insn));
1810       for (insn = PREV_INSN (insn); insn != last;)
1811         {
1812           insn = PREV_INSN (insn);
1813           if (JUMP_P (NEXT_INSN (insn)))
1814             {
1815               if (!any_condjump_p (NEXT_INSN (insn)))
1816                 {
1817                   gcc_assert (BARRIER_P (NEXT_INSN (NEXT_INSN (insn))));
1818                   delete_insn (NEXT_INSN (NEXT_INSN (insn)));
1819                 }
1820               delete_insn (NEXT_INSN (insn));
1821             }
1822         }
1823     }
1824 }
1825
1826 /* A subroutine of expand_gimple_basic_block.  Expand one GIMPLE_COND.
1827    Returns a new basic block if we've terminated the current basic
1828    block and created a new one.  */
1829
1830 static basic_block
1831 expand_gimple_cond (basic_block bb, gimple stmt)
1832 {
1833   basic_block new_bb, dest;
1834   edge new_edge;
1835   edge true_edge;
1836   edge false_edge;
1837   rtx last2, last;
1838   enum tree_code code;
1839   tree op0, op1;
1840
1841   code = gimple_cond_code (stmt);
1842   op0 = gimple_cond_lhs (stmt);
1843   op1 = gimple_cond_rhs (stmt);
1844   /* We're sometimes presented with such code:
1845        D.123_1 = x < y;
1846        if (D.123_1 != 0)
1847          ...
1848      This would expand to two comparisons which then later might
1849      be cleaned up by combine.  But some pattern matchers like if-conversion
1850      work better when there's only one compare, so make up for this
1851      here as special exception if TER would have made the same change.  */
1852   if (gimple_cond_single_var_p (stmt)
1853       && SA.values
1854       && TREE_CODE (op0) == SSA_NAME
1855       && bitmap_bit_p (SA.values, SSA_NAME_VERSION (op0)))
1856     {
1857       gimple second = SSA_NAME_DEF_STMT (op0);
1858       if (gimple_code (second) == GIMPLE_ASSIGN)
1859         {
1860           enum tree_code code2 = gimple_assign_rhs_code (second);
1861           if (TREE_CODE_CLASS (code2) == tcc_comparison)
1862             {
1863               code = code2;
1864               op0 = gimple_assign_rhs1 (second);
1865               op1 = gimple_assign_rhs2 (second);
1866             }
1867           /* If jumps are cheap turn some more codes into
1868              jumpy sequences.  */
1869           else if (BRANCH_COST (optimize_insn_for_speed_p (), false) < 4)
1870             {
1871               if ((code2 == BIT_AND_EXPR
1872                    && TYPE_PRECISION (TREE_TYPE (op0)) == 1
1873                    && TREE_CODE (gimple_assign_rhs2 (second)) != INTEGER_CST)
1874                   || code2 == TRUTH_AND_EXPR)
1875                 {
1876                   code = TRUTH_ANDIF_EXPR;
1877                   op0 = gimple_assign_rhs1 (second);
1878                   op1 = gimple_assign_rhs2 (second);
1879                 }
1880               else if (code2 == BIT_IOR_EXPR || code2 == TRUTH_OR_EXPR)
1881                 {
1882                   code = TRUTH_ORIF_EXPR;
1883                   op0 = gimple_assign_rhs1 (second);
1884                   op1 = gimple_assign_rhs2 (second);
1885                 }
1886             }
1887         }
1888     }
1889
1890   last2 = last = get_last_insn ();
1891
1892   extract_true_false_edges_from_block (bb, &true_edge, &false_edge);
1893   set_curr_insn_source_location (gimple_location (stmt));
1894   set_curr_insn_block (gimple_block (stmt));
1895
1896   /* These flags have no purpose in RTL land.  */
1897   true_edge->flags &= ~EDGE_TRUE_VALUE;
1898   false_edge->flags &= ~EDGE_FALSE_VALUE;
1899
1900   /* We can either have a pure conditional jump with one fallthru edge or
1901      two-way jump that needs to be decomposed into two basic blocks.  */
1902   if (false_edge->dest == bb->next_bb)
1903     {
1904       jumpif_1 (code, op0, op1, label_rtx_for_bb (true_edge->dest),
1905                 true_edge->probability);
1906       maybe_dump_rtl_for_gimple_stmt (stmt, last);
1907       if (true_edge->goto_locus)
1908         {
1909           set_curr_insn_source_location (true_edge->goto_locus);
1910           set_curr_insn_block (true_edge->goto_block);
1911           true_edge->goto_locus = curr_insn_locator ();
1912         }
1913       true_edge->goto_block = NULL;
1914       false_edge->flags |= EDGE_FALLTHRU;
1915       maybe_cleanup_end_of_block (false_edge, last);
1916       return NULL;
1917     }
1918   if (true_edge->dest == bb->next_bb)
1919     {
1920       jumpifnot_1 (code, op0, op1, label_rtx_for_bb (false_edge->dest),
1921                    false_edge->probability);
1922       maybe_dump_rtl_for_gimple_stmt (stmt, last);
1923       if (false_edge->goto_locus)
1924         {
1925           set_curr_insn_source_location (false_edge->goto_locus);
1926           set_curr_insn_block (false_edge->goto_block);
1927           false_edge->goto_locus = curr_insn_locator ();
1928         }
1929       false_edge->goto_block = NULL;
1930       true_edge->flags |= EDGE_FALLTHRU;
1931       maybe_cleanup_end_of_block (true_edge, last);
1932       return NULL;
1933     }
1934
1935   jumpif_1 (code, op0, op1, label_rtx_for_bb (true_edge->dest),
1936             true_edge->probability);
1937   last = get_last_insn ();
1938   if (false_edge->goto_locus)
1939     {
1940       set_curr_insn_source_location (false_edge->goto_locus);
1941       set_curr_insn_block (false_edge->goto_block);
1942       false_edge->goto_locus = curr_insn_locator ();
1943     }
1944   false_edge->goto_block = NULL;
1945   emit_jump (label_rtx_for_bb (false_edge->dest));
1946
1947   BB_END (bb) = last;
1948   if (BARRIER_P (BB_END (bb)))
1949     BB_END (bb) = PREV_INSN (BB_END (bb));
1950   update_bb_for_insn (bb);
1951
1952   new_bb = create_basic_block (NEXT_INSN (last), get_last_insn (), bb);
1953   dest = false_edge->dest;
1954   redirect_edge_succ (false_edge, new_bb);
1955   false_edge->flags |= EDGE_FALLTHRU;
1956   new_bb->count = false_edge->count;
1957   new_bb->frequency = EDGE_FREQUENCY (false_edge);
1958   new_edge = make_edge (new_bb, dest, 0);
1959   new_edge->probability = REG_BR_PROB_BASE;
1960   new_edge->count = new_bb->count;
1961   if (BARRIER_P (BB_END (new_bb)))
1962     BB_END (new_bb) = PREV_INSN (BB_END (new_bb));
1963   update_bb_for_insn (new_bb);
1964
1965   maybe_dump_rtl_for_gimple_stmt (stmt, last2);
1966
1967   if (true_edge->goto_locus)
1968     {
1969       set_curr_insn_source_location (true_edge->goto_locus);
1970       set_curr_insn_block (true_edge->goto_block);
1971       true_edge->goto_locus = curr_insn_locator ();
1972     }
1973   true_edge->goto_block = NULL;
1974
1975   return new_bb;
1976 }
1977
1978 /* Mark all calls that can have a transaction restart.  */
1979
1980 static void
1981 mark_transaction_restart_calls (gimple stmt)
1982 {
1983   struct tm_restart_node dummy;
1984   void **slot;
1985
1986   if (!cfun->gimple_df->tm_restart)
1987     return;
1988
1989   dummy.stmt = stmt;
1990   slot = htab_find_slot (cfun->gimple_df->tm_restart, &dummy, NO_INSERT);
1991   if (slot)
1992     {
1993       struct tm_restart_node *n = (struct tm_restart_node *) *slot;
1994       tree list = n->label_or_list;
1995       rtx insn;
1996
1997       for (insn = next_real_insn (get_last_insn ());
1998            !CALL_P (insn);
1999            insn = next_real_insn (insn))
2000         continue;
2001
2002       if (TREE_CODE (list) == LABEL_DECL)
2003         add_reg_note (insn, REG_TM, label_rtx (list));
2004       else
2005         for (; list ; list = TREE_CHAIN (list))
2006           add_reg_note (insn, REG_TM, label_rtx (TREE_VALUE (list)));
2007     }
2008 }
2009
2010 /* A subroutine of expand_gimple_stmt_1, expanding one GIMPLE_CALL
2011    statement STMT.  */
2012
2013 static void
2014 expand_call_stmt (gimple stmt)
2015 {
2016   tree exp, decl, lhs;
2017   bool builtin_p;
2018   size_t i;
2019
2020   if (gimple_call_internal_p (stmt))
2021     {
2022       expand_internal_call (stmt);
2023       return;
2024     }
2025
2026   exp = build_vl_exp (CALL_EXPR, gimple_call_num_args (stmt) + 3);
2027
2028   CALL_EXPR_FN (exp) = gimple_call_fn (stmt);
2029   decl = gimple_call_fndecl (stmt);
2030   builtin_p = decl && DECL_BUILT_IN (decl);
2031
2032   /* If this is not a builtin function, the function type through which the
2033      call is made may be different from the type of the function.  */
2034   if (!builtin_p)
2035     CALL_EXPR_FN (exp)
2036       = fold_convert (build_pointer_type (gimple_call_fntype (stmt)),
2037                       CALL_EXPR_FN (exp));
2038
2039   TREE_TYPE (exp) = gimple_call_return_type (stmt);
2040   CALL_EXPR_STATIC_CHAIN (exp) = gimple_call_chain (stmt);
2041
2042   for (i = 0; i < gimple_call_num_args (stmt); i++)
2043     {
2044       tree arg = gimple_call_arg (stmt, i);
2045       gimple def;
2046       /* TER addresses into arguments of builtin functions so we have a
2047          chance to infer more correct alignment information.  See PR39954.  */
2048       if (builtin_p
2049           && TREE_CODE (arg) == SSA_NAME
2050           && (def = get_gimple_for_ssa_name (arg))
2051           && gimple_assign_rhs_code (def) == ADDR_EXPR)
2052         arg = gimple_assign_rhs1 (def);
2053       CALL_EXPR_ARG (exp, i) = arg;
2054     }
2055
2056   if (gimple_has_side_effects (stmt))
2057     TREE_SIDE_EFFECTS (exp) = 1;
2058
2059   if (gimple_call_nothrow_p (stmt))
2060     TREE_NOTHROW (exp) = 1;
2061
2062   CALL_EXPR_TAILCALL (exp) = gimple_call_tail_p (stmt);
2063   CALL_EXPR_RETURN_SLOT_OPT (exp) = gimple_call_return_slot_opt_p (stmt);
2064   if (decl
2065       && DECL_BUILT_IN_CLASS (decl) == BUILT_IN_NORMAL
2066       && (DECL_FUNCTION_CODE (decl) == BUILT_IN_ALLOCA
2067           || DECL_FUNCTION_CODE (decl) == BUILT_IN_ALLOCA_WITH_ALIGN))
2068     CALL_ALLOCA_FOR_VAR_P (exp) = gimple_call_alloca_for_var_p (stmt);
2069   else
2070     CALL_FROM_THUNK_P (exp) = gimple_call_from_thunk_p (stmt);
2071   CALL_EXPR_VA_ARG_PACK (exp) = gimple_call_va_arg_pack_p (stmt);
2072   SET_EXPR_LOCATION (exp, gimple_location (stmt));
2073   TREE_BLOCK (exp) = gimple_block (stmt);
2074
2075   /* Ensure RTL is created for debug args.  */
2076   if (decl && DECL_HAS_DEBUG_ARGS_P (decl))
2077     {
2078       VEC(tree, gc) **debug_args = decl_debug_args_lookup (decl);
2079       unsigned int ix;
2080       tree dtemp;
2081
2082       if (debug_args)
2083         for (ix = 1; VEC_iterate (tree, *debug_args, ix, dtemp); ix += 2)
2084           {
2085             gcc_assert (TREE_CODE (dtemp) == DEBUG_EXPR_DECL);
2086             expand_debug_expr (dtemp);
2087           }
2088     }
2089
2090   lhs = gimple_call_lhs (stmt);
2091   if (lhs)
2092     expand_assignment (lhs, exp, false);
2093   else
2094     expand_expr_real_1 (exp, const0_rtx, VOIDmode, EXPAND_NORMAL, NULL);
2095
2096   mark_transaction_restart_calls (stmt);
2097 }
2098
2099 /* A subroutine of expand_gimple_stmt, expanding one gimple statement
2100    STMT that doesn't require special handling for outgoing edges.  That
2101    is no tailcalls and no GIMPLE_COND.  */
2102
2103 static void
2104 expand_gimple_stmt_1 (gimple stmt)
2105 {
2106   tree op0;
2107
2108   set_curr_insn_source_location (gimple_location (stmt));
2109   set_curr_insn_block (gimple_block (stmt));
2110
2111   switch (gimple_code (stmt))
2112     {
2113     case GIMPLE_GOTO:
2114       op0 = gimple_goto_dest (stmt);
2115       if (TREE_CODE (op0) == LABEL_DECL)
2116         expand_goto (op0);
2117       else
2118         expand_computed_goto (op0);
2119       break;
2120     case GIMPLE_LABEL:
2121       expand_label (gimple_label_label (stmt));
2122       break;
2123     case GIMPLE_NOP:
2124     case GIMPLE_PREDICT:
2125       break;
2126     case GIMPLE_SWITCH:
2127       expand_case (stmt);
2128       break;
2129     case GIMPLE_ASM:
2130       expand_asm_stmt (stmt);
2131       break;
2132     case GIMPLE_CALL:
2133       expand_call_stmt (stmt);
2134       break;
2135
2136     case GIMPLE_RETURN:
2137       op0 = gimple_return_retval (stmt);
2138
2139       if (op0 && op0 != error_mark_node)
2140         {
2141           tree result = DECL_RESULT (current_function_decl);
2142
2143           /* If we are not returning the current function's RESULT_DECL,
2144              build an assignment to it.  */
2145           if (op0 != result)
2146             {
2147               /* I believe that a function's RESULT_DECL is unique.  */
2148               gcc_assert (TREE_CODE (op0) != RESULT_DECL);
2149
2150               /* ??? We'd like to use simply expand_assignment here,
2151                  but this fails if the value is of BLKmode but the return
2152                  decl is a register.  expand_return has special handling
2153                  for this combination, which eventually should move
2154                  to common code.  See comments there.  Until then, let's
2155                  build a modify expression :-/  */
2156               op0 = build2 (MODIFY_EXPR, TREE_TYPE (result),
2157                             result, op0);
2158             }
2159         }
2160       if (!op0)
2161         expand_null_return ();
2162       else
2163         expand_return (op0);
2164       break;
2165
2166     case GIMPLE_ASSIGN:
2167       {
2168         tree lhs = gimple_assign_lhs (stmt);
2169
2170         /* Tree expand used to fiddle with |= and &= of two bitfield
2171            COMPONENT_REFs here.  This can't happen with gimple, the LHS
2172            of binary assigns must be a gimple reg.  */
2173
2174         if (TREE_CODE (lhs) != SSA_NAME
2175             || get_gimple_rhs_class (gimple_expr_code (stmt))
2176                == GIMPLE_SINGLE_RHS)
2177           {
2178             tree rhs = gimple_assign_rhs1 (stmt);
2179             gcc_assert (get_gimple_rhs_class (gimple_expr_code (stmt))
2180                         == GIMPLE_SINGLE_RHS);
2181             if (gimple_has_location (stmt) && CAN_HAVE_LOCATION_P (rhs))
2182               SET_EXPR_LOCATION (rhs, gimple_location (stmt));
2183             if (TREE_CLOBBER_P (rhs))
2184               /* This is a clobber to mark the going out of scope for
2185                  this LHS.  */
2186               ;
2187             else
2188               expand_assignment (lhs, rhs,
2189                                  gimple_assign_nontemporal_move_p (stmt));
2190           }
2191         else
2192           {
2193             rtx target, temp;
2194             bool nontemporal = gimple_assign_nontemporal_move_p (stmt);
2195             struct separate_ops ops;
2196             bool promoted = false;
2197
2198             target = expand_expr (lhs, NULL_RTX, VOIDmode, EXPAND_WRITE);
2199             if (GET_CODE (target) == SUBREG && SUBREG_PROMOTED_VAR_P (target))
2200               promoted = true;
2201
2202             ops.code = gimple_assign_rhs_code (stmt);
2203             ops.type = TREE_TYPE (lhs);
2204             switch (get_gimple_rhs_class (gimple_expr_code (stmt)))
2205               {
2206                 case GIMPLE_TERNARY_RHS:
2207                   ops.op2 = gimple_assign_rhs3 (stmt);
2208                   /* Fallthru */
2209                 case GIMPLE_BINARY_RHS:
2210                   ops.op1 = gimple_assign_rhs2 (stmt);
2211                   /* Fallthru */
2212                 case GIMPLE_UNARY_RHS:
2213                   ops.op0 = gimple_assign_rhs1 (stmt);
2214                   break;
2215                 default:
2216                   gcc_unreachable ();
2217               }
2218             ops.location = gimple_location (stmt);
2219
2220             /* If we want to use a nontemporal store, force the value to
2221                register first.  If we store into a promoted register,
2222                don't directly expand to target.  */
2223             temp = nontemporal || promoted ? NULL_RTX : target;
2224             temp = expand_expr_real_2 (&ops, temp, GET_MODE (target),
2225                                        EXPAND_NORMAL);
2226
2227             if (temp == target)
2228               ;
2229             else if (promoted)
2230               {
2231                 int unsignedp = SUBREG_PROMOTED_UNSIGNED_P (target);
2232                 /* If TEMP is a VOIDmode constant, use convert_modes to make
2233                    sure that we properly convert it.  */
2234                 if (CONSTANT_P (temp) && GET_MODE (temp) == VOIDmode)
2235                   {
2236                     temp = convert_modes (GET_MODE (target),
2237                                           TYPE_MODE (ops.type),
2238                                           temp, unsignedp);
2239                     temp = convert_modes (GET_MODE (SUBREG_REG (target)),
2240                                           GET_MODE (target), temp, unsignedp);
2241                   }
2242
2243                 convert_move (SUBREG_REG (target), temp, unsignedp);
2244               }
2245             else if (nontemporal && emit_storent_insn (target, temp))
2246               ;
2247             else
2248               {
2249                 temp = force_operand (temp, target);
2250                 if (temp != target)
2251                   emit_move_insn (target, temp);
2252               }
2253           }
2254       }
2255       break;
2256
2257     default:
2258       gcc_unreachable ();
2259     }
2260 }
2261
2262 /* Expand one gimple statement STMT and return the last RTL instruction
2263    before any of the newly generated ones.
2264
2265    In addition to generating the necessary RTL instructions this also
2266    sets REG_EH_REGION notes if necessary and sets the current source
2267    location for diagnostics.  */
2268
2269 static rtx
2270 expand_gimple_stmt (gimple stmt)
2271 {
2272   location_t saved_location = input_location;
2273   rtx last = get_last_insn ();
2274   int lp_nr;
2275
2276   gcc_assert (cfun);
2277
2278   /* We need to save and restore the current source location so that errors
2279      discovered during expansion are emitted with the right location.  But
2280      it would be better if the diagnostic routines used the source location
2281      embedded in the tree nodes rather than globals.  */
2282   if (gimple_has_location (stmt))
2283     input_location = gimple_location (stmt);
2284
2285   expand_gimple_stmt_1 (stmt);
2286
2287   /* Free any temporaries used to evaluate this statement.  */
2288   free_temp_slots ();
2289
2290   input_location = saved_location;
2291
2292   /* Mark all insns that may trap.  */
2293   lp_nr = lookup_stmt_eh_lp (stmt);
2294   if (lp_nr)
2295     {
2296       rtx insn;
2297       for (insn = next_real_insn (last); insn;
2298            insn = next_real_insn (insn))
2299         {
2300           if (! find_reg_note (insn, REG_EH_REGION, NULL_RTX)
2301               /* If we want exceptions for non-call insns, any
2302                  may_trap_p instruction may throw.  */
2303               && GET_CODE (PATTERN (insn)) != CLOBBER
2304               && GET_CODE (PATTERN (insn)) != USE
2305               && insn_could_throw_p (insn))
2306             make_reg_eh_region_note (insn, 0, lp_nr);
2307         }
2308     }
2309
2310   return last;
2311 }
2312
2313 /* A subroutine of expand_gimple_basic_block.  Expand one GIMPLE_CALL
2314    that has CALL_EXPR_TAILCALL set.  Returns non-null if we actually
2315    generated a tail call (something that might be denied by the ABI
2316    rules governing the call; see calls.c).
2317
2318    Sets CAN_FALLTHRU if we generated a *conditional* tail call, and
2319    can still reach the rest of BB.  The case here is __builtin_sqrt,
2320    where the NaN result goes through the external function (with a
2321    tailcall) and the normal result happens via a sqrt instruction.  */
2322
2323 static basic_block
2324 expand_gimple_tailcall (basic_block bb, gimple stmt, bool *can_fallthru)
2325 {
2326   rtx last2, last;
2327   edge e;
2328   edge_iterator ei;
2329   int probability;
2330   gcov_type count;
2331
2332   last2 = last = expand_gimple_stmt (stmt);
2333
2334   for (last = NEXT_INSN (last); last; last = NEXT_INSN (last))
2335     if (CALL_P (last) && SIBLING_CALL_P (last))
2336       goto found;
2337
2338   maybe_dump_rtl_for_gimple_stmt (stmt, last2);
2339
2340   *can_fallthru = true;
2341   return NULL;
2342
2343  found:
2344   /* ??? Wouldn't it be better to just reset any pending stack adjust?
2345      Any instructions emitted here are about to be deleted.  */
2346   do_pending_stack_adjust ();
2347
2348   /* Remove any non-eh, non-abnormal edges that don't go to exit.  */
2349   /* ??? I.e. the fallthrough edge.  HOWEVER!  If there were to be
2350      EH or abnormal edges, we shouldn't have created a tail call in
2351      the first place.  So it seems to me we should just be removing
2352      all edges here, or redirecting the existing fallthru edge to
2353      the exit block.  */
2354
2355   probability = 0;
2356   count = 0;
2357
2358   for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
2359     {
2360       if (!(e->flags & (EDGE_ABNORMAL | EDGE_EH)))
2361         {
2362           if (e->dest != EXIT_BLOCK_PTR)
2363             {
2364               e->dest->count -= e->count;
2365               e->dest->frequency -= EDGE_FREQUENCY (e);
2366               if (e->dest->count < 0)
2367                 e->dest->count = 0;
2368               if (e->dest->frequency < 0)
2369                 e->dest->frequency = 0;
2370             }
2371           count += e->count;
2372           probability += e->probability;
2373           remove_edge (e);
2374         }
2375       else
2376         ei_next (&ei);
2377     }
2378
2379   /* This is somewhat ugly: the call_expr expander often emits instructions
2380      after the sibcall (to perform the function return).  These confuse the
2381      find_many_sub_basic_blocks code, so we need to get rid of these.  */
2382   last = NEXT_INSN (last);
2383   gcc_assert (BARRIER_P (last));
2384
2385   *can_fallthru = false;
2386   while (NEXT_INSN (last))
2387     {
2388       /* For instance an sqrt builtin expander expands if with
2389          sibcall in the then and label for `else`.  */
2390       if (LABEL_P (NEXT_INSN (last)))
2391         {
2392           *can_fallthru = true;
2393           break;
2394         }
2395       delete_insn (NEXT_INSN (last));
2396     }
2397
2398   e = make_edge (bb, EXIT_BLOCK_PTR, EDGE_ABNORMAL | EDGE_SIBCALL);
2399   e->probability += probability;
2400   e->count += count;
2401   BB_END (bb) = last;
2402   update_bb_for_insn (bb);
2403
2404   if (NEXT_INSN (last))
2405     {
2406       bb = create_basic_block (NEXT_INSN (last), get_last_insn (), bb);
2407
2408       last = BB_END (bb);
2409       if (BARRIER_P (last))
2410         BB_END (bb) = PREV_INSN (last);
2411     }
2412
2413   maybe_dump_rtl_for_gimple_stmt (stmt, last2);
2414
2415   return bb;
2416 }
2417
2418 /* Return the difference between the floor and the truncated result of
2419    a signed division by OP1 with remainder MOD.  */
2420 static rtx
2421 floor_sdiv_adjust (enum machine_mode mode, rtx mod, rtx op1)
2422 {
2423   /* (mod != 0 ? (op1 / mod < 0 ? -1 : 0) : 0) */
2424   return gen_rtx_IF_THEN_ELSE
2425     (mode, gen_rtx_NE (BImode, mod, const0_rtx),
2426      gen_rtx_IF_THEN_ELSE
2427      (mode, gen_rtx_LT (BImode,
2428                         gen_rtx_DIV (mode, op1, mod),
2429                         const0_rtx),
2430       constm1_rtx, const0_rtx),
2431      const0_rtx);
2432 }
2433
2434 /* Return the difference between the ceil and the truncated result of
2435    a signed division by OP1 with remainder MOD.  */
2436 static rtx
2437 ceil_sdiv_adjust (enum machine_mode mode, rtx mod, rtx op1)
2438 {
2439   /* (mod != 0 ? (op1 / mod > 0 ? 1 : 0) : 0) */
2440   return gen_rtx_IF_THEN_ELSE
2441     (mode, gen_rtx_NE (BImode, mod, const0_rtx),
2442      gen_rtx_IF_THEN_ELSE
2443      (mode, gen_rtx_GT (BImode,
2444                         gen_rtx_DIV (mode, op1, mod),
2445                         const0_rtx),
2446       const1_rtx, const0_rtx),
2447      const0_rtx);
2448 }
2449
2450 /* Return the difference between the ceil and the truncated result of
2451    an unsigned division by OP1 with remainder MOD.  */
2452 static rtx
2453 ceil_udiv_adjust (enum machine_mode mode, rtx mod, rtx op1 ATTRIBUTE_UNUSED)
2454 {
2455   /* (mod != 0 ? 1 : 0) */
2456   return gen_rtx_IF_THEN_ELSE
2457     (mode, gen_rtx_NE (BImode, mod, const0_rtx),
2458      const1_rtx, const0_rtx);
2459 }
2460
2461 /* Return the difference between the rounded and the truncated result
2462    of a signed division by OP1 with remainder MOD.  Halfway cases are
2463    rounded away from zero, rather than to the nearest even number.  */
2464 static rtx
2465 round_sdiv_adjust (enum machine_mode mode, rtx mod, rtx op1)
2466 {
2467   /* (abs (mod) >= abs (op1) - abs (mod)
2468       ? (op1 / mod > 0 ? 1 : -1)
2469       : 0) */
2470   return gen_rtx_IF_THEN_ELSE
2471     (mode, gen_rtx_GE (BImode, gen_rtx_ABS (mode, mod),
2472                        gen_rtx_MINUS (mode,
2473                                       gen_rtx_ABS (mode, op1),
2474                                       gen_rtx_ABS (mode, mod))),
2475      gen_rtx_IF_THEN_ELSE
2476      (mode, gen_rtx_GT (BImode,
2477                         gen_rtx_DIV (mode, op1, mod),
2478                         const0_rtx),
2479       const1_rtx, constm1_rtx),
2480      const0_rtx);
2481 }
2482
2483 /* Return the difference between the rounded and the truncated result
2484    of a unsigned division by OP1 with remainder MOD.  Halfway cases
2485    are rounded away from zero, rather than to the nearest even
2486    number.  */
2487 static rtx
2488 round_udiv_adjust (enum machine_mode mode, rtx mod, rtx op1)
2489 {
2490   /* (mod >= op1 - mod ? 1 : 0) */
2491   return gen_rtx_IF_THEN_ELSE
2492     (mode, gen_rtx_GE (BImode, mod,
2493                        gen_rtx_MINUS (mode, op1, mod)),
2494      const1_rtx, const0_rtx);
2495 }
2496
2497 /* Convert X to MODE, that must be Pmode or ptr_mode, without emitting
2498    any rtl.  */
2499
2500 static rtx
2501 convert_debug_memory_address (enum machine_mode mode, rtx x,
2502                               addr_space_t as)
2503 {
2504   enum machine_mode xmode = GET_MODE (x);
2505
2506 #ifndef POINTERS_EXTEND_UNSIGNED
2507   gcc_assert (mode == Pmode
2508               || mode == targetm.addr_space.address_mode (as));
2509   gcc_assert (xmode == mode || xmode == VOIDmode);
2510 #else
2511   rtx temp;
2512
2513   gcc_assert (targetm.addr_space.valid_pointer_mode (mode, as));
2514
2515   if (GET_MODE (x) == mode || GET_MODE (x) == VOIDmode)
2516     return x;
2517
2518   if (GET_MODE_PRECISION (mode) < GET_MODE_PRECISION (xmode))
2519     x = simplify_gen_subreg (mode, x, xmode,
2520                              subreg_lowpart_offset
2521                              (mode, xmode));
2522   else if (POINTERS_EXTEND_UNSIGNED > 0)
2523     x = gen_rtx_ZERO_EXTEND (mode, x);
2524   else if (!POINTERS_EXTEND_UNSIGNED)
2525     x = gen_rtx_SIGN_EXTEND (mode, x);
2526   else
2527     {
2528       switch (GET_CODE (x))
2529         {
2530         case SUBREG:
2531           if ((SUBREG_PROMOTED_VAR_P (x)
2532                || (REG_P (SUBREG_REG (x)) && REG_POINTER (SUBREG_REG (x)))
2533                || (GET_CODE (SUBREG_REG (x)) == PLUS
2534                    && REG_P (XEXP (SUBREG_REG (x), 0))
2535                    && REG_POINTER (XEXP (SUBREG_REG (x), 0))
2536                    && CONST_INT_P (XEXP (SUBREG_REG (x), 1))))
2537               && GET_MODE (SUBREG_REG (x)) == mode)
2538             return SUBREG_REG (x);
2539           break;
2540         case LABEL_REF:
2541           temp = gen_rtx_LABEL_REF (mode, XEXP (x, 0));
2542           LABEL_REF_NONLOCAL_P (temp) = LABEL_REF_NONLOCAL_P (x);
2543           return temp;
2544         case SYMBOL_REF:
2545           temp = shallow_copy_rtx (x);
2546           PUT_MODE (temp, mode);
2547           return temp;
2548         case CONST:
2549           temp = convert_debug_memory_address (mode, XEXP (x, 0), as);
2550           if (temp)
2551             temp = gen_rtx_CONST (mode, temp);
2552           return temp;
2553         case PLUS:
2554         case MINUS:
2555           if (CONST_INT_P (XEXP (x, 1)))
2556             {
2557               temp = convert_debug_memory_address (mode, XEXP (x, 0), as);
2558               if (temp)
2559                 return gen_rtx_fmt_ee (GET_CODE (x), mode, temp, XEXP (x, 1));
2560             }
2561           break;
2562         default:
2563           break;
2564         }
2565       /* Don't know how to express ptr_extend as operation in debug info.  */
2566       return NULL;
2567     }
2568 #endif /* POINTERS_EXTEND_UNSIGNED */
2569
2570   return x;
2571 }
2572
2573 /* Return an RTX equivalent to the value of the parameter DECL.  */
2574
2575 static rtx
2576 expand_debug_parm_decl (tree decl)
2577 {
2578   rtx incoming = DECL_INCOMING_RTL (decl);
2579
2580   if (incoming
2581       && GET_MODE (incoming) != BLKmode
2582       && ((REG_P (incoming) && HARD_REGISTER_P (incoming))
2583           || (MEM_P (incoming)
2584               && REG_P (XEXP (incoming, 0))
2585               && HARD_REGISTER_P (XEXP (incoming, 0)))))
2586     {
2587       rtx rtl = gen_rtx_ENTRY_VALUE (GET_MODE (incoming));
2588
2589 #ifdef HAVE_window_save
2590       /* DECL_INCOMING_RTL uses the INCOMING_REGNO of parameter registers.
2591          If the target machine has an explicit window save instruction, the
2592          actual entry value is the corresponding OUTGOING_REGNO instead.  */
2593       if (REG_P (incoming)
2594           && OUTGOING_REGNO (REGNO (incoming)) != REGNO (incoming))
2595         incoming
2596           = gen_rtx_REG_offset (incoming, GET_MODE (incoming),
2597                                 OUTGOING_REGNO (REGNO (incoming)), 0);
2598       else if (MEM_P (incoming))
2599         {
2600           rtx reg = XEXP (incoming, 0);
2601           if (OUTGOING_REGNO (REGNO (reg)) != REGNO (reg))
2602             {
2603               reg = gen_raw_REG (GET_MODE (reg), OUTGOING_REGNO (REGNO (reg)));
2604               incoming = replace_equiv_address_nv (incoming, reg);
2605             }
2606         }
2607 #endif
2608
2609       ENTRY_VALUE_EXP (rtl) = incoming;
2610       return rtl;
2611     }
2612
2613   if (incoming
2614       && GET_MODE (incoming) != BLKmode
2615       && !TREE_ADDRESSABLE (decl)
2616       && MEM_P (incoming)
2617       && (XEXP (incoming, 0) == virtual_incoming_args_rtx
2618           || (GET_CODE (XEXP (incoming, 0)) == PLUS
2619               && XEXP (XEXP (incoming, 0), 0) == virtual_incoming_args_rtx
2620               && CONST_INT_P (XEXP (XEXP (incoming, 0), 1)))))
2621     return incoming;
2622
2623   return NULL_RTX;
2624 }
2625
2626 /* Return an RTX equivalent to the value of the tree expression EXP.  */
2627
2628 static rtx
2629 expand_debug_expr (tree exp)
2630 {
2631   rtx op0 = NULL_RTX, op1 = NULL_RTX, op2 = NULL_RTX;
2632   enum machine_mode mode = TYPE_MODE (TREE_TYPE (exp));
2633   enum machine_mode inner_mode = VOIDmode;
2634   int unsignedp = TYPE_UNSIGNED (TREE_TYPE (exp));
2635   addr_space_t as;
2636
2637   switch (TREE_CODE_CLASS (TREE_CODE (exp)))
2638     {
2639     case tcc_expression:
2640       switch (TREE_CODE (exp))
2641         {
2642         case COND_EXPR:
2643         case DOT_PROD_EXPR:
2644         case WIDEN_MULT_PLUS_EXPR:
2645         case WIDEN_MULT_MINUS_EXPR:
2646         case FMA_EXPR:
2647           goto ternary;
2648
2649         case TRUTH_ANDIF_EXPR:
2650         case TRUTH_ORIF_EXPR:
2651         case TRUTH_AND_EXPR:
2652         case TRUTH_OR_EXPR:
2653         case TRUTH_XOR_EXPR:
2654           goto binary;
2655
2656         case TRUTH_NOT_EXPR:
2657           goto unary;
2658
2659         default:
2660           break;
2661         }
2662       break;
2663
2664     ternary:
2665       op2 = expand_debug_expr (TREE_OPERAND (exp, 2));
2666       if (!op2)
2667         return NULL_RTX;
2668       /* Fall through.  */
2669
2670     binary:
2671     case tcc_binary:
2672     case tcc_comparison:
2673       op1 = expand_debug_expr (TREE_OPERAND (exp, 1));
2674       if (!op1)
2675         return NULL_RTX;
2676       /* Fall through.  */
2677
2678     unary:
2679     case tcc_unary:
2680       inner_mode = TYPE_MODE (TREE_TYPE (TREE_OPERAND (exp, 0)));
2681       op0 = expand_debug_expr (TREE_OPERAND (exp, 0));
2682       if (!op0)
2683         return NULL_RTX;
2684       break;
2685
2686     case tcc_type:
2687     case tcc_statement:
2688       gcc_unreachable ();
2689
2690     case tcc_constant:
2691     case tcc_exceptional:
2692     case tcc_declaration:
2693     case tcc_reference:
2694     case tcc_vl_exp:
2695       break;
2696     }
2697
2698   switch (TREE_CODE (exp))
2699     {
2700     case STRING_CST:
2701       if (!lookup_constant_def (exp))
2702         {
2703           if (strlen (TREE_STRING_POINTER (exp)) + 1
2704               != (size_t) TREE_STRING_LENGTH (exp))
2705             return NULL_RTX;
2706           op0 = gen_rtx_CONST_STRING (Pmode, TREE_STRING_POINTER (exp));
2707           op0 = gen_rtx_MEM (BLKmode, op0);
2708           set_mem_attributes (op0, exp, 0);
2709           return op0;
2710         }
2711       /* Fall through...  */
2712
2713     case INTEGER_CST:
2714     case REAL_CST:
2715     case FIXED_CST:
2716       op0 = expand_expr (exp, NULL_RTX, mode, EXPAND_INITIALIZER);
2717       return op0;
2718
2719     case COMPLEX_CST:
2720       gcc_assert (COMPLEX_MODE_P (mode));
2721       op0 = expand_debug_expr (TREE_REALPART (exp));
2722       op1 = expand_debug_expr (TREE_IMAGPART (exp));
2723       return gen_rtx_CONCAT (mode, op0, op1);
2724
2725     case DEBUG_EXPR_DECL:
2726       op0 = DECL_RTL_IF_SET (exp);
2727
2728       if (op0)
2729         return op0;
2730
2731       op0 = gen_rtx_DEBUG_EXPR (mode);
2732       DEBUG_EXPR_TREE_DECL (op0) = exp;
2733       SET_DECL_RTL (exp, op0);
2734
2735       return op0;
2736
2737     case VAR_DECL:
2738     case PARM_DECL:
2739     case FUNCTION_DECL:
2740     case LABEL_DECL:
2741     case CONST_DECL:
2742     case RESULT_DECL:
2743       op0 = DECL_RTL_IF_SET (exp);
2744
2745       /* This decl was probably optimized away.  */
2746       if (!op0)
2747         {
2748           if (TREE_CODE (exp) != VAR_DECL
2749               || DECL_EXTERNAL (exp)
2750               || !TREE_STATIC (exp)
2751               || !DECL_NAME (exp)
2752               || DECL_HARD_REGISTER (exp)
2753               || DECL_IN_CONSTANT_POOL (exp)
2754               || mode == VOIDmode)
2755             return NULL;
2756
2757           op0 = make_decl_rtl_for_debug (exp);
2758           if (!MEM_P (op0)
2759               || GET_CODE (XEXP (op0, 0)) != SYMBOL_REF
2760               || SYMBOL_REF_DECL (XEXP (op0, 0)) != exp)
2761             return NULL;
2762         }
2763       else
2764         op0 = copy_rtx (op0);
2765
2766       if (GET_MODE (op0) == BLKmode
2767           /* If op0 is not BLKmode, but BLKmode is, adjust_mode
2768              below would ICE.  While it is likely a FE bug,
2769              try to be robust here.  See PR43166.  */
2770           || mode == BLKmode
2771           || (mode == VOIDmode && GET_MODE (op0) != VOIDmode))
2772         {
2773           gcc_assert (MEM_P (op0));
2774           op0 = adjust_address_nv (op0, mode, 0);
2775           return op0;
2776         }
2777
2778       /* Fall through.  */
2779
2780     adjust_mode:
2781     case PAREN_EXPR:
2782     case NOP_EXPR:
2783     case CONVERT_EXPR:
2784       {
2785         inner_mode = GET_MODE (op0);
2786
2787         if (mode == inner_mode)
2788           return op0;
2789
2790         if (inner_mode == VOIDmode)
2791           {
2792             if (TREE_CODE (exp) == SSA_NAME)
2793               inner_mode = TYPE_MODE (TREE_TYPE (exp));
2794             else
2795               inner_mode = TYPE_MODE (TREE_TYPE (TREE_OPERAND (exp, 0)));
2796             if (mode == inner_mode)
2797               return op0;
2798           }
2799
2800         if (FLOAT_MODE_P (mode) && FLOAT_MODE_P (inner_mode))
2801           {
2802             if (GET_MODE_BITSIZE (mode) == GET_MODE_BITSIZE (inner_mode))
2803               op0 = simplify_gen_subreg (mode, op0, inner_mode, 0);
2804             else if (GET_MODE_BITSIZE (mode) < GET_MODE_BITSIZE (inner_mode))
2805               op0 = simplify_gen_unary (FLOAT_TRUNCATE, mode, op0, inner_mode);
2806             else
2807               op0 = simplify_gen_unary (FLOAT_EXTEND, mode, op0, inner_mode);
2808           }
2809         else if (FLOAT_MODE_P (mode))
2810           {
2811             gcc_assert (TREE_CODE (exp) != SSA_NAME);
2812             if (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp, 0))))
2813               op0 = simplify_gen_unary (UNSIGNED_FLOAT, mode, op0, inner_mode);
2814             else
2815               op0 = simplify_gen_unary (FLOAT, mode, op0, inner_mode);
2816           }
2817         else if (FLOAT_MODE_P (inner_mode))
2818           {
2819             if (unsignedp)
2820               op0 = simplify_gen_unary (UNSIGNED_FIX, mode, op0, inner_mode);
2821             else
2822               op0 = simplify_gen_unary (FIX, mode, op0, inner_mode);
2823           }
2824         else if (CONSTANT_P (op0)
2825                  || GET_MODE_PRECISION (mode) <= GET_MODE_PRECISION (inner_mode))
2826           op0 = simplify_gen_subreg (mode, op0, inner_mode,
2827                                      subreg_lowpart_offset (mode,
2828                                                             inner_mode));
2829         else if (TREE_CODE_CLASS (TREE_CODE (exp)) == tcc_unary
2830                  ? TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp, 0)))
2831                  : unsignedp)
2832           op0 = simplify_gen_unary (ZERO_EXTEND, mode, op0, inner_mode);
2833         else
2834           op0 = simplify_gen_unary (SIGN_EXTEND, mode, op0, inner_mode);
2835
2836         return op0;
2837       }
2838
2839     case MEM_REF:
2840       if (!is_gimple_mem_ref_addr (TREE_OPERAND (exp, 0)))
2841         {
2842           tree newexp = fold_binary (MEM_REF, TREE_TYPE (exp),
2843                                      TREE_OPERAND (exp, 0),
2844                                      TREE_OPERAND (exp, 1));
2845           if (newexp)
2846             return expand_debug_expr (newexp);
2847         }
2848       /* FALLTHROUGH */
2849     case INDIRECT_REF:
2850       op0 = expand_debug_expr (TREE_OPERAND (exp, 0));
2851       if (!op0)
2852         return NULL;
2853
2854       if (TREE_CODE (exp) == MEM_REF)
2855         {
2856           if (GET_CODE (op0) == DEBUG_IMPLICIT_PTR
2857               || (GET_CODE (op0) == PLUS
2858                   && GET_CODE (XEXP (op0, 0)) == DEBUG_IMPLICIT_PTR))
2859             /* (mem (debug_implicit_ptr)) might confuse aliasing.
2860                Instead just use get_inner_reference.  */
2861             goto component_ref;
2862
2863           op1 = expand_debug_expr (TREE_OPERAND (exp, 1));
2864           if (!op1 || !CONST_INT_P (op1))
2865             return NULL;
2866
2867           op0 = plus_constant (op0, INTVAL (op1));
2868         }
2869
2870       if (POINTER_TYPE_P (TREE_TYPE (exp)))
2871         as = TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (exp)));
2872       else
2873         as = ADDR_SPACE_GENERIC;
2874
2875       op0 = convert_debug_memory_address (targetm.addr_space.address_mode (as),
2876                                           op0, as);
2877       if (op0 == NULL_RTX)
2878         return NULL;
2879
2880       op0 = gen_rtx_MEM (mode, op0);
2881       set_mem_attributes (op0, exp, 0);
2882       if (TREE_CODE (exp) == MEM_REF
2883           && !is_gimple_mem_ref_addr (TREE_OPERAND (exp, 0)))
2884         set_mem_expr (op0, NULL_TREE);
2885       set_mem_addr_space (op0, as);
2886
2887       return op0;
2888
2889     case TARGET_MEM_REF:
2890       if (TREE_CODE (TMR_BASE (exp)) == ADDR_EXPR
2891           && !DECL_RTL_SET_P (TREE_OPERAND (TMR_BASE (exp), 0)))
2892         return NULL;
2893
2894       op0 = expand_debug_expr
2895             (tree_mem_ref_addr (build_pointer_type (TREE_TYPE (exp)), exp));
2896       if (!op0)
2897         return NULL;
2898
2899       if (POINTER_TYPE_P (TREE_TYPE (exp)))
2900         as = TYPE_ADDR_SPACE (TREE_TYPE (TREE_TYPE (exp)));
2901       else
2902         as = ADDR_SPACE_GENERIC;
2903
2904       op0 = convert_debug_memory_address (targetm.addr_space.address_mode (as),
2905                                           op0, as);
2906       if (op0 == NULL_RTX)
2907         return NULL;
2908
2909       op0 = gen_rtx_MEM (mode, op0);
2910
2911       set_mem_attributes (op0, exp, 0);
2912       set_mem_addr_space (op0, as);
2913
2914       return op0;
2915
2916     component_ref:
2917     case ARRAY_REF:
2918     case ARRAY_RANGE_REF:
2919     case COMPONENT_REF:
2920     case BIT_FIELD_REF:
2921     case REALPART_EXPR:
2922     case IMAGPART_EXPR:
2923     case VIEW_CONVERT_EXPR:
2924       {
2925         enum machine_mode mode1;
2926         HOST_WIDE_INT bitsize, bitpos;
2927         tree offset;
2928         int volatilep = 0;
2929         tree tem = get_inner_reference (exp, &bitsize, &bitpos, &offset,
2930                                         &mode1, &unsignedp, &volatilep, false);
2931         rtx orig_op0;
2932
2933         if (bitsize == 0)
2934           return NULL;
2935
2936         orig_op0 = op0 = expand_debug_expr (tem);
2937
2938         if (!op0)
2939           return NULL;
2940
2941         if (offset)
2942           {
2943             enum machine_mode addrmode, offmode;
2944
2945             if (!MEM_P (op0))
2946               return NULL;
2947
2948             op0 = XEXP (op0, 0);
2949             addrmode = GET_MODE (op0);
2950             if (addrmode == VOIDmode)
2951               addrmode = Pmode;
2952
2953             op1 = expand_debug_expr (offset);
2954             if (!op1)
2955               return NULL;
2956
2957             offmode = GET_MODE (op1);
2958             if (offmode == VOIDmode)
2959               offmode = TYPE_MODE (TREE_TYPE (offset));
2960
2961             if (addrmode != offmode)
2962               op1 = simplify_gen_subreg (addrmode, op1, offmode,
2963                                          subreg_lowpart_offset (addrmode,
2964                                                                 offmode));
2965
2966             /* Don't use offset_address here, we don't need a
2967                recognizable address, and we don't want to generate
2968                code.  */
2969             op0 = gen_rtx_MEM (mode, simplify_gen_binary (PLUS, addrmode,
2970                                                           op0, op1));
2971           }
2972
2973         if (MEM_P (op0))
2974           {
2975             if (mode1 == VOIDmode)
2976               /* Bitfield.  */
2977               mode1 = smallest_mode_for_size (bitsize, MODE_INT);
2978             if (bitpos >= BITS_PER_UNIT)
2979               {
2980                 op0 = adjust_address_nv (op0, mode1, bitpos / BITS_PER_UNIT);
2981                 bitpos %= BITS_PER_UNIT;
2982               }
2983             else if (bitpos < 0)
2984               {
2985                 HOST_WIDE_INT units
2986                   = (-bitpos + BITS_PER_UNIT - 1) / BITS_PER_UNIT;
2987                 op0 = adjust_address_nv (op0, mode1, units);
2988                 bitpos += units * BITS_PER_UNIT;
2989               }
2990             else if (bitpos == 0 && bitsize == GET_MODE_BITSIZE (mode))
2991               op0 = adjust_address_nv (op0, mode, 0);
2992             else if (GET_MODE (op0) != mode1)
2993               op0 = adjust_address_nv (op0, mode1, 0);
2994             else
2995               op0 = copy_rtx (op0);
2996             if (op0 == orig_op0)
2997               op0 = shallow_copy_rtx (op0);
2998             set_mem_attributes (op0, exp, 0);
2999           }
3000
3001         if (bitpos == 0 && mode == GET_MODE (op0))
3002           return op0;
3003
3004         if (bitpos < 0)
3005           return NULL;
3006
3007         if (GET_MODE (op0) == BLKmode)
3008           return NULL;
3009
3010         if ((bitpos % BITS_PER_UNIT) == 0
3011             && bitsize == GET_MODE_BITSIZE (mode1))
3012           {
3013             enum machine_mode opmode = GET_MODE (op0);
3014
3015             if (opmode == VOIDmode)
3016               opmode = TYPE_MODE (TREE_TYPE (tem));
3017
3018             /* This condition may hold if we're expanding the address
3019                right past the end of an array that turned out not to
3020                be addressable (i.e., the address was only computed in
3021                debug stmts).  The gen_subreg below would rightfully
3022                crash, and the address doesn't really exist, so just
3023                drop it.  */
3024             if (bitpos >= GET_MODE_BITSIZE (opmode))
3025               return NULL;
3026
3027             if ((bitpos % GET_MODE_BITSIZE (mode)) == 0)
3028               return simplify_gen_subreg (mode, op0, opmode,
3029                                           bitpos / BITS_PER_UNIT);
3030           }
3031
3032         return simplify_gen_ternary (SCALAR_INT_MODE_P (GET_MODE (op0))
3033                                      && TYPE_UNSIGNED (TREE_TYPE (exp))
3034                                      ? SIGN_EXTRACT
3035                                      : ZERO_EXTRACT, mode,
3036                                      GET_MODE (op0) != VOIDmode
3037                                      ? GET_MODE (op0)
3038                                      : TYPE_MODE (TREE_TYPE (tem)),
3039                                      op0, GEN_INT (bitsize), GEN_INT (bitpos));
3040       }
3041
3042     case ABS_EXPR:
3043       return simplify_gen_unary (ABS, mode, op0, mode);
3044
3045     case NEGATE_EXPR:
3046       return simplify_gen_unary (NEG, mode, op0, mode);
3047
3048     case BIT_NOT_EXPR:
3049       return simplify_gen_unary (NOT, mode, op0, mode);
3050
3051     case FLOAT_EXPR:
3052       return simplify_gen_unary (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp,
3053                                                                          0)))
3054                                  ? UNSIGNED_FLOAT : FLOAT, mode, op0,
3055                                  inner_mode);
3056
3057     case FIX_TRUNC_EXPR:
3058       return simplify_gen_unary (unsignedp ? UNSIGNED_FIX : FIX, mode, op0,
3059                                  inner_mode);
3060
3061     case POINTER_PLUS_EXPR:
3062       /* For the rare target where pointers are not the same size as
3063          size_t, we need to check for mis-matched modes and correct
3064          the addend.  */
3065       if (op0 && op1
3066           && GET_MODE (op0) != VOIDmode && GET_MODE (op1) != VOIDmode
3067           && GET_MODE (op0) != GET_MODE (op1))
3068         {
3069           if (GET_MODE_BITSIZE (GET_MODE (op0)) < GET_MODE_BITSIZE (GET_MODE (op1)))
3070             op1 = simplify_gen_unary (TRUNCATE, GET_MODE (op0), op1,
3071                                       GET_MODE (op1));
3072           else
3073             /* We always sign-extend, regardless of the signedness of
3074                the operand, because the operand is always unsigned
3075                here even if the original C expression is signed.  */
3076             op1 = simplify_gen_unary (SIGN_EXTEND, GET_MODE (op0), op1,
3077                                       GET_MODE (op1));
3078         }
3079       /* Fall through.  */
3080     case PLUS_EXPR:
3081       return simplify_gen_binary (PLUS, mode, op0, op1);
3082
3083     case MINUS_EXPR:
3084       return simplify_gen_binary (MINUS, mode, op0, op1);
3085
3086     case MULT_EXPR:
3087       return simplify_gen_binary (MULT, mode, op0, op1);
3088
3089     case RDIV_EXPR:
3090     case TRUNC_DIV_EXPR:
3091     case EXACT_DIV_EXPR:
3092       if (unsignedp)
3093         return simplify_gen_binary (UDIV, mode, op0, op1);
3094       else
3095         return simplify_gen_binary (DIV, mode, op0, op1);
3096
3097     case TRUNC_MOD_EXPR:
3098       return simplify_gen_binary (unsignedp ? UMOD : MOD, mode, op0, op1);
3099
3100     case FLOOR_DIV_EXPR:
3101       if (unsignedp)
3102         return simplify_gen_binary (UDIV, mode, op0, op1);
3103       else
3104         {
3105           rtx div = simplify_gen_binary (DIV, mode, op0, op1);
3106           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
3107           rtx adj = floor_sdiv_adjust (mode, mod, op1);
3108           return simplify_gen_binary (PLUS, mode, div, adj);
3109         }
3110
3111     case FLOOR_MOD_EXPR:
3112       if (unsignedp)
3113         return simplify_gen_binary (UMOD, mode, op0, op1);
3114       else
3115         {
3116           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
3117           rtx adj = floor_sdiv_adjust (mode, mod, op1);
3118           adj = simplify_gen_unary (NEG, mode,
3119                                     simplify_gen_binary (MULT, mode, adj, op1),
3120                                     mode);
3121           return simplify_gen_binary (PLUS, mode, mod, adj);
3122         }
3123
3124     case CEIL_DIV_EXPR:
3125       if (unsignedp)
3126         {
3127           rtx div = simplify_gen_binary (UDIV, mode, op0, op1);
3128           rtx mod = simplify_gen_binary (UMOD, mode, op0, op1);
3129           rtx adj = ceil_udiv_adjust (mode, mod, op1);
3130           return simplify_gen_binary (PLUS, mode, div, adj);
3131         }
3132       else
3133         {
3134           rtx div = simplify_gen_binary (DIV, mode, op0, op1);
3135           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
3136           rtx adj = ceil_sdiv_adjust (mode, mod, op1);
3137           return simplify_gen_binary (PLUS, mode, div, adj);
3138         }
3139
3140     case CEIL_MOD_EXPR:
3141       if (unsignedp)
3142         {
3143           rtx mod = simplify_gen_binary (UMOD, mode, op0, op1);
3144           rtx adj = ceil_udiv_adjust (mode, mod, op1);
3145           adj = simplify_gen_unary (NEG, mode,
3146                                     simplify_gen_binary (MULT, mode, adj, op1),
3147                                     mode);
3148           return simplify_gen_binary (PLUS, mode, mod, adj);
3149         }
3150       else
3151         {
3152           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
3153           rtx adj = ceil_sdiv_adjust (mode, mod, op1);
3154           adj = simplify_gen_unary (NEG, mode,
3155                                     simplify_gen_binary (MULT, mode, adj, op1),
3156                                     mode);
3157           return simplify_gen_binary (PLUS, mode, mod, adj);
3158         }
3159
3160     case ROUND_DIV_EXPR:
3161       if (unsignedp)
3162         {
3163           rtx div = simplify_gen_binary (UDIV, mode, op0, op1);
3164           rtx mod = simplify_gen_binary (UMOD, mode, op0, op1);
3165           rtx adj = round_udiv_adjust (mode, mod, op1);
3166           return simplify_gen_binary (PLUS, mode, div, adj);
3167         }
3168       else
3169         {
3170           rtx div = simplify_gen_binary (DIV, mode, op0, op1);
3171           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
3172           rtx adj = round_sdiv_adjust (mode, mod, op1);
3173           return simplify_gen_binary (PLUS, mode, div, adj);
3174         }
3175
3176     case ROUND_MOD_EXPR:
3177       if (unsignedp)
3178         {
3179           rtx mod = simplify_gen_binary (UMOD, mode, op0, op1);
3180           rtx adj = round_udiv_adjust (mode, mod, op1);
3181           adj = simplify_gen_unary (NEG, mode,
3182                                     simplify_gen_binary (MULT, mode, adj, op1),
3183                                     mode);
3184           return simplify_gen_binary (PLUS, mode, mod, adj);
3185         }
3186       else
3187         {
3188           rtx mod = simplify_gen_binary (MOD, mode, op0, op1);
3189           rtx adj = round_sdiv_adjust (mode, mod, op1);
3190           adj = simplify_gen_unary (NEG, mode,
3191                                     simplify_gen_binary (MULT, mode, adj, op1),
3192                                     mode);
3193           return simplify_gen_binary (PLUS, mode, mod, adj);
3194         }
3195
3196     case LSHIFT_EXPR:
3197       return simplify_gen_binary (ASHIFT, mode, op0, op1);
3198
3199     case RSHIFT_EXPR:
3200       if (unsignedp)
3201         return simplify_gen_binary (LSHIFTRT, mode, op0, op1);
3202       else
3203         return simplify_gen_binary (ASHIFTRT, mode, op0, op1);
3204
3205     case LROTATE_EXPR:
3206       return simplify_gen_binary (ROTATE, mode, op0, op1);
3207
3208     case RROTATE_EXPR:
3209       return simplify_gen_binary (ROTATERT, mode, op0, op1);
3210
3211     case MIN_EXPR:
3212       return simplify_gen_binary (unsignedp ? UMIN : SMIN, mode, op0, op1);
3213
3214     case MAX_EXPR:
3215       return simplify_gen_binary (unsignedp ? UMAX : SMAX, mode, op0, op1);
3216
3217     case BIT_AND_EXPR:
3218     case TRUTH_AND_EXPR:
3219       return simplify_gen_binary (AND, mode, op0, op1);
3220
3221     case BIT_IOR_EXPR:
3222     case TRUTH_OR_EXPR:
3223       return simplify_gen_binary (IOR, mode, op0, op1);
3224
3225     case BIT_XOR_EXPR:
3226     case TRUTH_XOR_EXPR:
3227       return simplify_gen_binary (XOR, mode, op0, op1);
3228
3229     case TRUTH_ANDIF_EXPR:
3230       return gen_rtx_IF_THEN_ELSE (mode, op0, op1, const0_rtx);
3231
3232     case TRUTH_ORIF_EXPR:
3233       return gen_rtx_IF_THEN_ELSE (mode, op0, const_true_rtx, op1);
3234
3235     case TRUTH_NOT_EXPR:
3236       return simplify_gen_relational (EQ, mode, inner_mode, op0, const0_rtx);
3237
3238     case LT_EXPR:
3239       return simplify_gen_relational (unsignedp ? LTU : LT, mode, inner_mode,
3240                                       op0, op1);
3241
3242     case LE_EXPR:
3243       return simplify_gen_relational (unsignedp ? LEU : LE, mode, inner_mode,
3244                                       op0, op1);
3245
3246     case GT_EXPR:
3247       return simplify_gen_relational (unsignedp ? GTU : GT, mode, inner_mode,
3248                                       op0, op1);
3249
3250     case GE_EXPR:
3251       return simplify_gen_relational (unsignedp ? GEU : GE, mode, inner_mode,
3252                                       op0, op1);
3253
3254     case EQ_EXPR:
3255       return simplify_gen_relational (EQ, mode, inner_mode, op0, op1);
3256
3257     case NE_EXPR:
3258       return simplify_gen_relational (NE, mode, inner_mode, op0, op1);
3259
3260     case UNORDERED_EXPR:
3261       return simplify_gen_relational (UNORDERED, mode, inner_mode, op0, op1);
3262
3263     case ORDERED_EXPR:
3264       return simplify_gen_relational (ORDERED, mode, inner_mode, op0, op1);
3265
3266     case UNLT_EXPR:
3267       return simplify_gen_relational (UNLT, mode, inner_mode, op0, op1);
3268
3269     case UNLE_EXPR:
3270       return simplify_gen_relational (UNLE, mode, inner_mode, op0, op1);
3271
3272     case UNGT_EXPR:
3273       return simplify_gen_relational (UNGT, mode, inner_mode, op0, op1);
3274
3275     case UNGE_EXPR:
3276       return simplify_gen_relational (UNGE, mode, inner_mode, op0, op1);
3277
3278     case UNEQ_EXPR:
3279       return simplify_gen_relational (UNEQ, mode, inner_mode, op0, op1);
3280
3281     case LTGT_EXPR:
3282       return simplify_gen_relational (LTGT, mode, inner_mode, op0, op1);
3283
3284     case COND_EXPR:
3285       return gen_rtx_IF_THEN_ELSE (mode, op0, op1, op2);
3286
3287     case COMPLEX_EXPR:
3288       gcc_assert (COMPLEX_MODE_P (mode));
3289       if (GET_MODE (op0) == VOIDmode)
3290         op0 = gen_rtx_CONST (GET_MODE_INNER (mode), op0);
3291       if (GET_MODE (op1) == VOIDmode)
3292         op1 = gen_rtx_CONST (GET_MODE_INNER (mode), op1);
3293       return gen_rtx_CONCAT (mode, op0, op1);
3294
3295     case CONJ_EXPR:
3296       if (GET_CODE (op0) == CONCAT)
3297         return gen_rtx_CONCAT (mode, XEXP (op0, 0),
3298                                simplify_gen_unary (NEG, GET_MODE_INNER (mode),
3299                                                    XEXP (op0, 1),
3300                                                    GET_MODE_INNER (mode)));
3301       else
3302         {
3303           enum machine_mode imode = GET_MODE_INNER (mode);
3304           rtx re, im;
3305
3306           if (MEM_P (op0))
3307             {
3308               re = adjust_address_nv (op0, imode, 0);
3309               im = adjust_address_nv (op0, imode, GET_MODE_SIZE (imode));
3310             }
3311           else
3312             {
3313               enum machine_mode ifmode = int_mode_for_mode (mode);
3314               enum machine_mode ihmode = int_mode_for_mode (imode);
3315               rtx halfsize;
3316               if (ifmode == BLKmode || ihmode == BLKmode)
3317                 return NULL;
3318               halfsize = GEN_INT (GET_MODE_BITSIZE (ihmode));
3319               re = op0;
3320               if (mode != ifmode)
3321                 re = gen_rtx_SUBREG (ifmode, re, 0);
3322               re = gen_rtx_ZERO_EXTRACT (ihmode, re, halfsize, const0_rtx);
3323               if (imode != ihmode)
3324                 re = gen_rtx_SUBREG (imode, re, 0);
3325               im = copy_rtx (op0);
3326               if (mode != ifmode)
3327                 im = gen_rtx_SUBREG (ifmode, im, 0);
3328               im = gen_rtx_ZERO_EXTRACT (ihmode, im, halfsize, halfsize);
3329               if (imode != ihmode)
3330                 im = gen_rtx_SUBREG (imode, im, 0);
3331             }
3332           im = gen_rtx_NEG (imode, im);
3333           return gen_rtx_CONCAT (mode, re, im);
3334         }
3335
3336     case ADDR_EXPR:
3337       op0 = expand_debug_expr (TREE_OPERAND (exp, 0));
3338       if (!op0 || !MEM_P (op0))
3339         {
3340           if ((TREE_CODE (TREE_OPERAND (exp, 0)) == VAR_DECL
3341                || TREE_CODE (TREE_OPERAND (exp, 0)) == PARM_DECL
3342                || TREE_CODE (TREE_OPERAND (exp, 0)) == RESULT_DECL)
3343               && (!TREE_ADDRESSABLE (TREE_OPERAND (exp, 0))
3344                   || target_for_debug_bind (TREE_OPERAND (exp, 0))))
3345             return gen_rtx_DEBUG_IMPLICIT_PTR (mode, TREE_OPERAND (exp, 0));
3346
3347           if (handled_component_p (TREE_OPERAND (exp, 0)))
3348             {
3349               HOST_WIDE_INT bitoffset, bitsize, maxsize;
3350               tree decl
3351                 = get_ref_base_and_extent (TREE_OPERAND (exp, 0),
3352                                            &bitoffset, &bitsize, &maxsize);
3353               if ((TREE_CODE (decl) == VAR_DECL
3354                    || TREE_CODE (decl) == PARM_DECL
3355                    || TREE_CODE (decl) == RESULT_DECL)
3356                   && (!TREE_ADDRESSABLE (decl)
3357                       || target_for_debug_bind (decl))
3358                   && (bitoffset % BITS_PER_UNIT) == 0
3359                   && bitsize > 0
3360                   && bitsize == maxsize)
3361                 return plus_constant (gen_rtx_DEBUG_IMPLICIT_PTR (mode, decl),
3362                                       bitoffset / BITS_PER_UNIT);
3363             }
3364
3365           return NULL;
3366         }
3367
3368       as = TYPE_ADDR_SPACE (TREE_TYPE (exp));
3369       op0 = convert_debug_memory_address (mode, XEXP (op0, 0), as);
3370
3371       return op0;
3372
3373     case VECTOR_CST:
3374       exp = build_constructor_from_list (TREE_TYPE (exp),
3375                                          TREE_VECTOR_CST_ELTS (exp));
3376       /* Fall through.  */
3377
3378     case CONSTRUCTOR:
3379       if (TREE_CLOBBER_P (exp))
3380         return NULL;
3381       else if (TREE_CODE (TREE_TYPE (exp)) == VECTOR_TYPE)
3382         {
3383           unsigned i;
3384           tree val;
3385
3386           op0 = gen_rtx_CONCATN
3387             (mode, rtvec_alloc (TYPE_VECTOR_SUBPARTS (TREE_TYPE (exp))));
3388
3389           FOR_EACH_CONSTRUCTOR_VALUE (CONSTRUCTOR_ELTS (exp), i, val)
3390             {
3391               op1 = expand_debug_expr (val);
3392               if (!op1)
3393                 return NULL;
3394               XVECEXP (op0, 0, i) = op1;
3395             }
3396
3397           if (i < TYPE_VECTOR_SUBPARTS (TREE_TYPE (exp)))
3398             {
3399               op1 = expand_debug_expr
3400                 (build_zero_cst (TREE_TYPE (TREE_TYPE (exp))));
3401
3402               if (!op1)
3403                 return NULL;
3404
3405               for (; i < TYPE_VECTOR_SUBPARTS (TREE_TYPE (exp)); i++)
3406                 XVECEXP (op0, 0, i) = op1;
3407             }
3408
3409           return op0;
3410         }
3411       else
3412         goto flag_unsupported;
3413
3414     case CALL_EXPR:
3415       /* ??? Maybe handle some builtins?  */
3416       return NULL;
3417
3418     case SSA_NAME:
3419       {
3420         gimple g = get_gimple_for_ssa_name (exp);
3421         if (g)
3422           {
3423             op0 = expand_debug_expr (gimple_assign_rhs_to_tree (g));
3424             if (!op0)
3425               return NULL;
3426           }
3427         else
3428           {
3429             int part = var_to_partition (SA.map, exp);
3430
3431             if (part == NO_PARTITION)
3432               {
3433                 /* If this is a reference to an incoming value of parameter
3434                    that is never used in the code or where the incoming
3435                    value is never used in the code, use PARM_DECL's
3436                    DECL_RTL if set.  */
3437                 if (SSA_NAME_IS_DEFAULT_DEF (exp)
3438                     && TREE_CODE (SSA_NAME_VAR (exp)) == PARM_DECL)
3439                   {
3440                     op0 = expand_debug_parm_decl (SSA_NAME_VAR (exp));
3441                     if (op0)
3442                       goto adjust_mode;
3443                     op0 = expand_debug_expr (SSA_NAME_VAR (exp));
3444                     if (op0)
3445                       goto adjust_mode;
3446                   }
3447                 return NULL;
3448               }
3449
3450             gcc_assert (part >= 0 && (unsigned)part < SA.map->num_partitions);
3451
3452             op0 = copy_rtx (SA.partition_to_pseudo[part]);
3453           }
3454         goto adjust_mode;
3455       }
3456
3457     case ERROR_MARK:
3458       return NULL;
3459
3460     /* Vector stuff.  For most of the codes we don't have rtl codes.  */
3461     case REALIGN_LOAD_EXPR:
3462     case REDUC_MAX_EXPR:
3463     case REDUC_MIN_EXPR:
3464     case REDUC_PLUS_EXPR:
3465     case VEC_COND_EXPR:
3466     case VEC_LSHIFT_EXPR:
3467     case VEC_PACK_FIX_TRUNC_EXPR:
3468     case VEC_PACK_SAT_EXPR:
3469     case VEC_PACK_TRUNC_EXPR:
3470     case VEC_RSHIFT_EXPR:
3471     case VEC_UNPACK_FLOAT_HI_EXPR:
3472     case VEC_UNPACK_FLOAT_LO_EXPR:
3473     case VEC_UNPACK_HI_EXPR:
3474     case VEC_UNPACK_LO_EXPR:
3475     case VEC_WIDEN_MULT_HI_EXPR:
3476     case VEC_WIDEN_MULT_LO_EXPR:
3477     case VEC_WIDEN_LSHIFT_HI_EXPR:
3478     case VEC_WIDEN_LSHIFT_LO_EXPR:
3479     case VEC_PERM_EXPR:
3480       return NULL;
3481
3482    /* Misc codes.  */
3483     case ADDR_SPACE_CONVERT_EXPR:
3484     case FIXED_CONVERT_EXPR:
3485     case OBJ_TYPE_REF:
3486     case WITH_SIZE_EXPR:
3487       return NULL;
3488
3489     case DOT_PROD_EXPR:
3490       if (SCALAR_INT_MODE_P (GET_MODE (op0))
3491           && SCALAR_INT_MODE_P (mode))
3492         {
3493           op0
3494             = simplify_gen_unary (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp,
3495                                                                           0)))
3496                                   ? ZERO_EXTEND : SIGN_EXTEND, mode, op0,
3497                                   inner_mode);
3498           op1
3499             = simplify_gen_unary (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp,
3500                                                                           1)))
3501                                   ? ZERO_EXTEND : SIGN_EXTEND, mode, op1,
3502                                   inner_mode);
3503           op0 = simplify_gen_binary (MULT, mode, op0, op1);
3504           return simplify_gen_binary (PLUS, mode, op0, op2);
3505         }
3506       return NULL;
3507
3508     case WIDEN_MULT_EXPR:
3509     case WIDEN_MULT_PLUS_EXPR:
3510     case WIDEN_MULT_MINUS_EXPR:
3511       if (SCALAR_INT_MODE_P (GET_MODE (op0))
3512           && SCALAR_INT_MODE_P (mode))
3513         {
3514           inner_mode = GET_MODE (op0);
3515           if (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp, 0))))
3516             op0 = simplify_gen_unary (ZERO_EXTEND, mode, op0, inner_mode);
3517           else
3518             op0 = simplify_gen_unary (SIGN_EXTEND, mode, op0, inner_mode);
3519           if (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp, 1))))
3520             op1 = simplify_gen_unary (ZERO_EXTEND, mode, op1, inner_mode);
3521           else
3522             op1 = simplify_gen_unary (SIGN_EXTEND, mode, op1, inner_mode);
3523           op0 = simplify_gen_binary (MULT, mode, op0, op1);
3524           if (TREE_CODE (exp) == WIDEN_MULT_EXPR)
3525             return op0;
3526           else if (TREE_CODE (exp) == WIDEN_MULT_PLUS_EXPR)
3527             return simplify_gen_binary (PLUS, mode, op0, op2);
3528           else
3529             return simplify_gen_binary (MINUS, mode, op2, op0);
3530         }
3531       return NULL;
3532
3533     case WIDEN_SUM_EXPR:
3534     case WIDEN_LSHIFT_EXPR:
3535       if (SCALAR_INT_MODE_P (GET_MODE (op0))
3536           && SCALAR_INT_MODE_P (mode))
3537         {
3538           op0
3539             = simplify_gen_unary (TYPE_UNSIGNED (TREE_TYPE (TREE_OPERAND (exp,
3540                                                                           0)))
3541                                   ? ZERO_EXTEND : SIGN_EXTEND, mode, op0,
3542                                   inner_mode);
3543           return simplify_gen_binary (TREE_CODE (exp) == WIDEN_LSHIFT_EXPR
3544                                       ? ASHIFT : PLUS, mode, op0, op1);
3545         }
3546       return NULL;
3547
3548     case FMA_EXPR:
3549       return simplify_gen_ternary (FMA, mode, inner_mode, op0, op1, op2);
3550
3551     default:
3552     flag_unsupported:
3553 #ifdef ENABLE_CHECKING
3554       debug_tree (exp);
3555       gcc_unreachable ();
3556 #else
3557       return NULL;
3558 #endif
3559     }
3560 }
3561
3562 /* Return an RTX equivalent to the source bind value of the tree expression
3563    EXP.  */
3564
3565 static rtx
3566 expand_debug_source_expr (tree exp)
3567 {
3568   rtx op0 = NULL_RTX;
3569   enum machine_mode mode = VOIDmode, inner_mode;
3570
3571   switch (TREE_CODE (exp))
3572     {
3573     case PARM_DECL:
3574       {
3575         mode = DECL_MODE (exp);
3576         op0 = expand_debug_parm_decl (exp);
3577         if (op0)
3578            break;
3579         /* See if this isn't an argument that has been completely
3580            optimized out.  */
3581         if (!DECL_RTL_SET_P (exp)
3582             && !DECL_INCOMING_RTL (exp)
3583             && DECL_ABSTRACT_ORIGIN (current_function_decl))
3584           {
3585             tree aexp = exp;
3586             if (DECL_ABSTRACT_ORIGIN (exp))
3587               aexp = DECL_ABSTRACT_ORIGIN (exp);
3588             if (DECL_CONTEXT (aexp)
3589                 == DECL_ABSTRACT_ORIGIN (current_function_decl))
3590               {
3591                 VEC(tree, gc) **debug_args;
3592                 unsigned int ix;
3593                 tree ddecl;
3594 #ifdef ENABLE_CHECKING
3595                 tree parm;
3596                 for (parm = DECL_ARGUMENTS (current_function_decl);
3597                      parm; parm = DECL_CHAIN (parm))
3598                   gcc_assert (parm != exp
3599                               && DECL_ABSTRACT_ORIGIN (parm) != aexp);
3600 #endif
3601                 debug_args = decl_debug_args_lookup (current_function_decl);
3602                 if (debug_args != NULL)
3603                   {
3604                     for (ix = 0; VEC_iterate (tree, *debug_args, ix, ddecl);
3605                          ix += 2)
3606                       if (ddecl == aexp)
3607                         return gen_rtx_DEBUG_PARAMETER_REF (mode, aexp);
3608                   }
3609               }
3610           }
3611         break;
3612       }
3613     default:
3614       break;
3615     }
3616
3617   if (op0 == NULL_RTX)
3618     return NULL_RTX;
3619
3620   inner_mode = GET_MODE (op0);
3621   if (mode == inner_mode)
3622     return op0;
3623
3624   if (FLOAT_MODE_P (mode) && FLOAT_MODE_P (inner_mode))
3625     {
3626       if (GET_MODE_BITSIZE (mode) == GET_MODE_BITSIZE (inner_mode))
3627         op0 = simplify_gen_subreg (mode, op0, inner_mode, 0);
3628       else if (GET_MODE_BITSIZE (mode) < GET_MODE_BITSIZE (inner_mode))
3629         op0 = simplify_gen_unary (FLOAT_TRUNCATE, mode, op0, inner_mode);
3630       else
3631         op0 = simplify_gen_unary (FLOAT_EXTEND, mode, op0, inner_mode);
3632     }
3633   else if (FLOAT_MODE_P (mode))
3634     gcc_unreachable ();
3635   else if (FLOAT_MODE_P (inner_mode))
3636     {
3637       if (TYPE_UNSIGNED (TREE_TYPE (exp)))
3638         op0 = simplify_gen_unary (UNSIGNED_FIX, mode, op0, inner_mode);
3639       else
3640         op0 = simplify_gen_unary (FIX, mode, op0, inner_mode);
3641     }
3642   else if (CONSTANT_P (op0)
3643            || GET_MODE_BITSIZE (mode) <= GET_MODE_BITSIZE (inner_mode))
3644     op0 = simplify_gen_subreg (mode, op0, inner_mode,
3645                                subreg_lowpart_offset (mode, inner_mode));
3646   else if (TYPE_UNSIGNED (TREE_TYPE (exp)))
3647     op0 = simplify_gen_unary (ZERO_EXTEND, mode, op0, inner_mode);
3648   else
3649     op0 = simplify_gen_unary (SIGN_EXTEND, mode, op0, inner_mode);
3650
3651   return op0;
3652 }
3653
3654 /* Expand the _LOCs in debug insns.  We run this after expanding all
3655    regular insns, so that any variables referenced in the function
3656    will have their DECL_RTLs set.  */
3657
3658 static void
3659 expand_debug_locations (void)
3660 {
3661   rtx insn;
3662   rtx last = get_last_insn ();
3663   int save_strict_alias = flag_strict_aliasing;
3664
3665   /* New alias sets while setting up memory attributes cause
3666      -fcompare-debug failures, even though it doesn't bring about any
3667      codegen changes.  */
3668   flag_strict_aliasing = 0;
3669
3670   for (insn = get_insns (); insn; insn = NEXT_INSN (insn))
3671     if (DEBUG_INSN_P (insn))
3672       {
3673         tree value = (tree)INSN_VAR_LOCATION_LOC (insn);
3674         rtx val;
3675         enum machine_mode mode;
3676
3677         if (value == NULL_TREE)
3678           val = NULL_RTX;
3679         else
3680           {
3681             if (INSN_VAR_LOCATION_STATUS (insn)
3682                 == VAR_INIT_STATUS_UNINITIALIZED)
3683               val = expand_debug_source_expr (value);
3684             else
3685               val = expand_debug_expr (value);
3686             gcc_assert (last == get_last_insn ());
3687           }
3688
3689         if (!val)
3690           val = gen_rtx_UNKNOWN_VAR_LOC ();
3691         else
3692           {
3693             mode = GET_MODE (INSN_VAR_LOCATION (insn));
3694
3695             gcc_assert (mode == GET_MODE (val)
3696                         || (GET_MODE (val) == VOIDmode
3697                             && (CONST_INT_P (val)
3698                                 || GET_CODE (val) == CONST_FIXED
3699                                 || GET_CODE (val) == CONST_DOUBLE
3700                                 || GET_CODE (val) == LABEL_REF)));
3701           }
3702
3703         INSN_VAR_LOCATION_LOC (insn) = val;
3704       }
3705
3706   flag_strict_aliasing = save_strict_alias;
3707 }
3708
3709 /* Expand basic block BB from GIMPLE trees to RTL.  */
3710
3711 static basic_block
3712 expand_gimple_basic_block (basic_block bb)
3713 {
3714   gimple_stmt_iterator gsi;
3715   gimple_seq stmts;
3716   gimple stmt = NULL;
3717   rtx note, last;
3718   edge e;
3719   edge_iterator ei;
3720   void **elt;
3721
3722   if (dump_file)
3723     fprintf (dump_file, "\n;; Generating RTL for gimple basic block %d\n",
3724              bb->index);
3725
3726   /* Note that since we are now transitioning from GIMPLE to RTL, we
3727      cannot use the gsi_*_bb() routines because they expect the basic
3728      block to be in GIMPLE, instead of RTL.  Therefore, we need to
3729      access the BB sequence directly.  */
3730   stmts = bb_seq (bb);
3731   bb->il.gimple = NULL;
3732   rtl_profile_for_bb (bb);
3733   init_rtl_bb_info (bb);
3734   bb->flags |= BB_RTL;
3735
3736   /* Remove the RETURN_EXPR if we may fall though to the exit
3737      instead.  */
3738   gsi = gsi_last (stmts);
3739   if (!gsi_end_p (gsi)
3740       && gimple_code (gsi_stmt (gsi)) == GIMPLE_RETURN)
3741     {
3742       gimple ret_stmt = gsi_stmt (gsi);
3743
3744       gcc_assert (single_succ_p (bb));
3745       gcc_assert (single_succ (bb) == EXIT_BLOCK_PTR);
3746
3747       if (bb->next_bb == EXIT_BLOCK_PTR
3748           && !gimple_return_retval (ret_stmt))
3749         {
3750           gsi_remove (&gsi, false);
3751           single_succ_edge (bb)->flags |= EDGE_FALLTHRU;
3752         }
3753     }
3754
3755   gsi = gsi_start (stmts);
3756   if (!gsi_end_p (gsi))
3757     {
3758       stmt = gsi_stmt (gsi);
3759       if (gimple_code (stmt) != GIMPLE_LABEL)
3760         stmt = NULL;
3761     }
3762
3763   elt = pointer_map_contains (lab_rtx_for_bb, bb);
3764
3765   if (stmt || elt)
3766     {
3767       last = get_last_insn ();
3768
3769       if (stmt)
3770         {
3771           expand_gimple_stmt (stmt);
3772           gsi_next (&gsi);
3773         }
3774
3775       if (elt)
3776         emit_label ((rtx) *elt);
3777
3778       /* Java emits line number notes in the top of labels.
3779          ??? Make this go away once line number notes are obsoleted.  */
3780       BB_HEAD (bb) = NEXT_INSN (last);
3781       if (NOTE_P (BB_HEAD (bb)))
3782         BB_HEAD (bb) = NEXT_INSN (BB_HEAD (bb));
3783       note = emit_note_after (NOTE_INSN_BASIC_BLOCK, BB_HEAD (bb));
3784
3785       maybe_dump_rtl_for_gimple_stmt (stmt, last);
3786     }
3787   else
3788     note = BB_HEAD (bb) = emit_note (NOTE_INSN_BASIC_BLOCK);
3789
3790   NOTE_BASIC_BLOCK (note) = bb;
3791
3792   for (; !gsi_end_p (gsi); gsi_next (&gsi))
3793     {
3794       basic_block new_bb;
3795
3796       stmt = gsi_stmt (gsi);
3797
3798       /* If this statement is a non-debug one, and we generate debug
3799          insns, then this one might be the last real use of a TERed
3800          SSA_NAME, but where there are still some debug uses further
3801          down.  Expanding the current SSA name in such further debug
3802          uses by their RHS might lead to wrong debug info, as coalescing
3803          might make the operands of such RHS be placed into the same
3804          pseudo as something else.  Like so:
3805            a_1 = a_0 + 1;   // Assume a_1 is TERed and a_0 is dead
3806            use(a_1);
3807            a_2 = ...
3808            #DEBUG ... => a_1
3809          As a_0 and a_2 don't overlap in lifetime, assume they are coalesced.
3810          If we now would expand a_1 by it's RHS (a_0 + 1) in the debug use,
3811          the write to a_2 would actually have clobbered the place which
3812          formerly held a_0.
3813
3814          So, instead of that, we recognize the situation, and generate
3815          debug temporaries at the last real use of TERed SSA names:
3816            a_1 = a_0 + 1;
3817            #DEBUG #D1 => a_1
3818            use(a_1);
3819            a_2 = ...
3820            #DEBUG ... => #D1
3821          */
3822       if (MAY_HAVE_DEBUG_INSNS
3823           && SA.values
3824           && !is_gimple_debug (stmt))
3825         {
3826           ssa_op_iter iter;
3827           tree op;
3828           gimple def;
3829
3830           location_t sloc = get_curr_insn_source_location ();
3831           tree sblock = get_curr_insn_block ();
3832
3833           /* Look for SSA names that have their last use here (TERed
3834              names always have only one real use).  */
3835           FOR_EACH_SSA_TREE_OPERAND (op, stmt, iter, SSA_OP_USE)
3836             if ((def = get_gimple_for_ssa_name (op)))
3837               {
3838                 imm_use_iterator imm_iter;
3839                 use_operand_p use_p;
3840                 bool have_debug_uses = false;
3841
3842                 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, op)
3843                   {
3844                     if (gimple_debug_bind_p (USE_STMT (use_p)))
3845                       {
3846                         have_debug_uses = true;
3847                         break;
3848                       }
3849                   }
3850
3851                 if (have_debug_uses)
3852                   {
3853                     /* OP is a TERed SSA name, with DEF it's defining
3854                        statement, and where OP is used in further debug
3855                        instructions.  Generate a debug temporary, and
3856                        replace all uses of OP in debug insns with that
3857                        temporary.  */
3858                     gimple debugstmt;
3859                     tree value = gimple_assign_rhs_to_tree (def);
3860                     tree vexpr = make_node (DEBUG_EXPR_DECL);
3861                     rtx val;
3862                     enum machine_mode mode;
3863
3864                     set_curr_insn_source_location (gimple_location (def));
3865                     set_curr_insn_block (gimple_block (def));
3866
3867                     DECL_ARTIFICIAL (vexpr) = 1;
3868                     TREE_TYPE (vexpr) = TREE_TYPE (value);
3869                     if (DECL_P (value))
3870                       mode = DECL_MODE (value);
3871                     else
3872                       mode = TYPE_MODE (TREE_TYPE (value));
3873                     DECL_MODE (vexpr) = mode;
3874
3875                     val = gen_rtx_VAR_LOCATION
3876                         (mode, vexpr, (rtx)value, VAR_INIT_STATUS_INITIALIZED);
3877
3878                     emit_debug_insn (val);
3879
3880                     FOR_EACH_IMM_USE_STMT (debugstmt, imm_iter, op)
3881                       {
3882                         if (!gimple_debug_bind_p (debugstmt))
3883                           continue;
3884
3885                         FOR_EACH_IMM_USE_ON_STMT (use_p, imm_iter)
3886                           SET_USE (use_p, vexpr);
3887
3888                         update_stmt (debugstmt);
3889                       }
3890                   }
3891               }
3892           set_curr_insn_source_location (sloc);
3893           set_curr_insn_block (sblock);
3894         }
3895
3896       currently_expanding_gimple_stmt = stmt;
3897
3898       /* Expand this statement, then evaluate the resulting RTL and
3899          fixup the CFG accordingly.  */
3900       if (gimple_code (stmt) == GIMPLE_COND)
3901         {
3902           new_bb = expand_gimple_cond (bb, stmt);
3903           if (new_bb)
3904             return new_bb;
3905         }
3906       else if (gimple_debug_bind_p (stmt))
3907         {
3908           location_t sloc = get_curr_insn_source_location ();
3909           tree sblock = get_curr_insn_block ();
3910           gimple_stmt_iterator nsi = gsi;
3911
3912           for (;;)
3913             {
3914               tree var = gimple_debug_bind_get_var (stmt);
3915               tree value;
3916               rtx val;
3917               enum machine_mode mode;
3918
3919               if (TREE_CODE (var) != DEBUG_EXPR_DECL
3920                   && TREE_CODE (var) != LABEL_DECL
3921                   && !target_for_debug_bind (var))
3922                 goto delink_debug_stmt;
3923
3924               if (gimple_debug_bind_has_value_p (stmt))
3925                 value = gimple_debug_bind_get_value (stmt);
3926               else
3927                 value = NULL_TREE;
3928
3929               last = get_last_insn ();
3930
3931               set_curr_insn_source_location (gimple_location (stmt));
3932               set_curr_insn_block (gimple_block (stmt));
3933
3934               if (DECL_P (var))
3935                 mode = DECL_MODE (var);
3936               else
3937                 mode = TYPE_MODE (TREE_TYPE (var));
3938
3939               val = gen_rtx_VAR_LOCATION
3940                 (mode, var, (rtx)value, VAR_INIT_STATUS_INITIALIZED);
3941
3942               emit_debug_insn (val);
3943
3944               if (dump_file && (dump_flags & TDF_DETAILS))
3945                 {
3946                   /* We can't dump the insn with a TREE where an RTX
3947                      is expected.  */
3948                   PAT_VAR_LOCATION_LOC (val) = const0_rtx;
3949                   maybe_dump_rtl_for_gimple_stmt (stmt, last);
3950                   PAT_VAR_LOCATION_LOC (val) = (rtx)value;
3951                 }
3952
3953             delink_debug_stmt:
3954               /* In order not to generate too many debug temporaries,
3955                  we delink all uses of debug statements we already expanded.
3956                  Therefore debug statements between definition and real
3957                  use of TERed SSA names will continue to use the SSA name,
3958                  and not be replaced with debug temps.  */
3959               delink_stmt_imm_use (stmt);
3960
3961               gsi = nsi;
3962               gsi_next (&nsi);
3963               if (gsi_end_p (nsi))
3964                 break;
3965               stmt = gsi_stmt (nsi);
3966               if (!gimple_debug_bind_p (stmt))
3967                 break;
3968             }
3969
3970           set_curr_insn_source_location (sloc);
3971           set_curr_insn_block (sblock);
3972         }
3973       else if (gimple_debug_source_bind_p (stmt))
3974         {
3975           location_t sloc = get_curr_insn_source_location ();
3976           tree sblock = get_curr_insn_block ();
3977           tree var = gimple_debug_source_bind_get_var (stmt);
3978           tree value = gimple_debug_source_bind_get_value (stmt);
3979           rtx val;
3980           enum machine_mode mode;
3981
3982           last = get_last_insn ();
3983
3984           set_curr_insn_source_location (gimple_location (stmt));
3985           set_curr_insn_block (gimple_block (stmt));
3986
3987           mode = DECL_MODE (var);
3988
3989           val = gen_rtx_VAR_LOCATION (mode, var, (rtx)value,
3990                                       VAR_INIT_STATUS_UNINITIALIZED);
3991
3992           emit_debug_insn (val);
3993
3994           if (dump_file && (dump_flags & TDF_DETAILS))
3995             {
3996               /* We can't dump the insn with a TREE where an RTX
3997                  is expected.  */
3998               PAT_VAR_LOCATION_LOC (val) = const0_rtx;
3999               maybe_dump_rtl_for_gimple_stmt (stmt, last);
4000               PAT_VAR_LOCATION_LOC (val) = (rtx)value;
4001             }
4002
4003           set_curr_insn_source_location (sloc);
4004           set_curr_insn_block (sblock);
4005         }
4006       else
4007         {
4008           if (is_gimple_call (stmt) && gimple_call_tail_p (stmt))
4009             {
4010               bool can_fallthru;
4011               new_bb = expand_gimple_tailcall (bb, stmt, &can_fallthru);
4012               if (new_bb)
4013                 {
4014                   if (can_fallthru)
4015                     bb = new_bb;
4016                   else
4017                     return new_bb;
4018                 }
4019             }
4020           else
4021             {
4022               def_operand_p def_p;
4023               def_p = SINGLE_SSA_DEF_OPERAND (stmt, SSA_OP_DEF);
4024
4025               if (def_p != NULL)
4026                 {
4027                   /* Ignore this stmt if it is in the list of
4028                      replaceable expressions.  */
4029                   if (SA.values
4030                       && bitmap_bit_p (SA.values,
4031                                        SSA_NAME_VERSION (DEF_FROM_PTR (def_p))))
4032                     continue;
4033                 }
4034               last = expand_gimple_stmt (stmt);
4035               maybe_dump_rtl_for_gimple_stmt (stmt, last);
4036             }
4037         }
4038     }
4039
4040   currently_expanding_gimple_stmt = NULL;
4041
4042   /* Expand implicit goto and convert goto_locus.  */
4043   FOR_EACH_EDGE (e, ei, bb->succs)
4044     {
4045       if (e->goto_locus && e->goto_block)
4046         {
4047           set_curr_insn_source_location (e->goto_locus);
4048           set_curr_insn_block (e->goto_block);
4049           e->goto_locus = curr_insn_locator ();
4050         }
4051       e->goto_block = NULL;
4052       if ((e->flags & EDGE_FALLTHRU) && e->dest != bb->next_bb)
4053         {
4054           emit_jump (label_rtx_for_bb (e->dest));
4055           e->flags &= ~EDGE_FALLTHRU;
4056         }
4057     }
4058
4059   /* Expanded RTL can create a jump in the last instruction of block.
4060      This later might be assumed to be a jump to successor and break edge insertion.
4061      We need to insert dummy move to prevent this. PR41440. */
4062   if (single_succ_p (bb)
4063       && (single_succ_edge (bb)->flags & EDGE_FALLTHRU)
4064       && (last = get_last_insn ())
4065       && JUMP_P (last))
4066     {
4067       rtx dummy = gen_reg_rtx (SImode);
4068       emit_insn_after_noloc (gen_move_insn (dummy, dummy), last, NULL);
4069     }
4070
4071   do_pending_stack_adjust ();
4072
4073   /* Find the block tail.  The last insn in the block is the insn
4074      before a barrier and/or table jump insn.  */
4075   last = get_last_insn ();
4076   if (BARRIER_P (last))
4077     last = PREV_INSN (last);
4078   if (JUMP_TABLE_DATA_P (last))
4079     last = PREV_INSN (PREV_INSN (last));
4080   BB_END (bb) = last;
4081
4082   update_bb_for_insn (bb);
4083
4084   return bb;
4085 }
4086
4087
4088 /* Create a basic block for initialization code.  */
4089
4090 static basic_block
4091 construct_init_block (void)
4092 {
4093   basic_block init_block, first_block;
4094   edge e = NULL;
4095   int flags;
4096
4097   /* Multiple entry points not supported yet.  */
4098   gcc_assert (EDGE_COUNT (ENTRY_BLOCK_PTR->succs) == 1);
4099   init_rtl_bb_info (ENTRY_BLOCK_PTR);
4100   init_rtl_bb_info (EXIT_BLOCK_PTR);
4101   ENTRY_BLOCK_PTR->flags |= BB_RTL;
4102   EXIT_BLOCK_PTR->flags |= BB_RTL;
4103
4104   e = EDGE_SUCC (ENTRY_BLOCK_PTR, 0);
4105
4106   /* When entry edge points to first basic block, we don't need jump,
4107      otherwise we have to jump into proper target.  */
4108   if (e && e->dest != ENTRY_BLOCK_PTR->next_bb)
4109     {
4110       tree label = gimple_block_label (e->dest);
4111
4112       emit_jump (label_rtx (label));
4113       flags = 0;
4114     }
4115   else
4116     flags = EDGE_FALLTHRU;
4117
4118   init_block = create_basic_block (NEXT_INSN (get_insns ()),
4119                                    get_last_insn (),
4120                                    ENTRY_BLOCK_PTR);
4121   init_block->frequency = ENTRY_BLOCK_PTR->frequency;
4122   init_block->count = ENTRY_BLOCK_PTR->count;
4123   if (e)
4124     {
4125       first_block = e->dest;
4126       redirect_edge_succ (e, init_block);
4127       e = make_edge (init_block, first_block, flags);
4128     }
4129   else
4130     e = make_edge (init_block, EXIT_BLOCK_PTR, EDGE_FALLTHRU);
4131   e->probability = REG_BR_PROB_BASE;
4132   e->count = ENTRY_BLOCK_PTR->count;
4133
4134   update_bb_for_insn (init_block);
4135   return init_block;
4136 }
4137
4138 /* For each lexical block, set BLOCK_NUMBER to the depth at which it is
4139    found in the block tree.  */
4140
4141 static void
4142 set_block_levels (tree block, int level)
4143 {
4144   while (block)
4145     {
4146       BLOCK_NUMBER (block) = level;
4147       set_block_levels (BLOCK_SUBBLOCKS (block), level + 1);
4148       block = BLOCK_CHAIN (block);
4149     }
4150 }
4151
4152 /* Create a block containing landing pads and similar stuff.  */
4153
4154 static void
4155 construct_exit_block (void)
4156 {
4157   rtx head = get_last_insn ();
4158   rtx end;
4159   basic_block exit_block;
4160   edge e, e2;
4161   unsigned ix;
4162   edge_iterator ei;
4163   rtx orig_end = BB_END (EXIT_BLOCK_PTR->prev_bb);
4164
4165   rtl_profile_for_bb (EXIT_BLOCK_PTR);
4166
4167   /* Make sure the locus is set to the end of the function, so that
4168      epilogue line numbers and warnings are set properly.  */
4169   if (cfun->function_end_locus != UNKNOWN_LOCATION)
4170     input_location = cfun->function_end_locus;
4171
4172   /* The following insns belong to the top scope.  */
4173   set_curr_insn_block (DECL_INITIAL (current_function_decl));
4174
4175   /* Generate rtl for function exit.  */
4176   expand_function_end ();
4177
4178   end = get_last_insn ();
4179   if (head == end)
4180     return;
4181   /* While emitting the function end we could move end of the last basic block.
4182    */
4183   BB_END (EXIT_BLOCK_PTR->prev_bb) = orig_end;
4184   while (NEXT_INSN (head) && NOTE_P (NEXT_INSN (head)))
4185     head = NEXT_INSN (head);
4186   exit_block = create_basic_block (NEXT_INSN (head), end,
4187                                    EXIT_BLOCK_PTR->prev_bb);
4188   exit_block->frequency = EXIT_BLOCK_PTR->frequency;
4189   exit_block->count = EXIT_BLOCK_PTR->count;
4190
4191   ix = 0;
4192   while (ix < EDGE_COUNT (EXIT_BLOCK_PTR->preds))
4193     {
4194       e = EDGE_PRED (EXIT_BLOCK_PTR, ix);
4195       if (!(e->flags & EDGE_ABNORMAL))
4196         redirect_edge_succ (e, exit_block);
4197       else
4198         ix++;
4199     }
4200
4201   e = make_edge (exit_block, EXIT_BLOCK_PTR, EDGE_FALLTHRU);
4202   e->probability = REG_BR_PROB_BASE;
4203   e->count = EXIT_BLOCK_PTR->count;
4204   FOR_EACH_EDGE (e2, ei, EXIT_BLOCK_PTR->preds)
4205     if (e2 != e)
4206       {
4207         e->count -= e2->count;
4208         exit_block->count -= e2->count;
4209         exit_block->frequency -= EDGE_FREQUENCY (e2);
4210       }
4211   if (e->count < 0)
4212     e->count = 0;
4213   if (exit_block->count < 0)
4214     exit_block->count = 0;
4215   if (exit_block->frequency < 0)
4216     exit_block->frequency = 0;
4217   update_bb_for_insn (exit_block);
4218 }
4219
4220 /* Helper function for discover_nonconstant_array_refs.
4221    Look for ARRAY_REF nodes with non-constant indexes and mark them
4222    addressable.  */
4223
4224 static tree
4225 discover_nonconstant_array_refs_r (tree * tp, int *walk_subtrees,
4226                                    void *data ATTRIBUTE_UNUSED)
4227 {
4228   tree t = *tp;
4229
4230   if (IS_TYPE_OR_DECL_P (t))
4231     *walk_subtrees = 0;
4232   else if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
4233     {
4234       while (((TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
4235               && is_gimple_min_invariant (TREE_OPERAND (t, 1))
4236               && (!TREE_OPERAND (t, 2)
4237                   || is_gimple_min_invariant (TREE_OPERAND (t, 2))))
4238              || (TREE_CODE (t) == COMPONENT_REF
4239                  && (!TREE_OPERAND (t,2)
4240                      || is_gimple_min_invariant (TREE_OPERAND (t, 2))))
4241              || TREE_CODE (t) == BIT_FIELD_REF
4242              || TREE_CODE (t) == REALPART_EXPR
4243              || TREE_CODE (t) == IMAGPART_EXPR
4244              || TREE_CODE (t) == VIEW_CONVERT_EXPR
4245              || CONVERT_EXPR_P (t))
4246         t = TREE_OPERAND (t, 0);
4247
4248       if (TREE_CODE (t) == ARRAY_REF || TREE_CODE (t) == ARRAY_RANGE_REF)
4249         {
4250           t = get_base_address (t);
4251           if (t && DECL_P (t)
4252               && DECL_MODE (t) != BLKmode)
4253             TREE_ADDRESSABLE (t) = 1;
4254         }
4255
4256       *walk_subtrees = 0;
4257     }
4258
4259   return NULL_TREE;
4260 }
4261
4262 /* RTL expansion is not able to compile array references with variable
4263    offsets for arrays stored in single register.  Discover such
4264    expressions and mark variables as addressable to avoid this
4265    scenario.  */
4266
4267 static void
4268 discover_nonconstant_array_refs (void)
4269 {
4270   basic_block bb;
4271   gimple_stmt_iterator gsi;
4272
4273   FOR_EACH_BB (bb)
4274     for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
4275       {
4276         gimple stmt = gsi_stmt (gsi);
4277         if (!is_gimple_debug (stmt))
4278           walk_gimple_op (stmt, discover_nonconstant_array_refs_r, NULL);
4279       }
4280 }
4281
4282 /* This function sets crtl->args.internal_arg_pointer to a virtual
4283    register if DRAP is needed.  Local register allocator will replace
4284    virtual_incoming_args_rtx with the virtual register.  */
4285
4286 static void
4287 expand_stack_alignment (void)
4288 {
4289   rtx drap_rtx;
4290   unsigned int preferred_stack_boundary;
4291
4292   if (! SUPPORTS_STACK_ALIGNMENT)
4293     return;
4294
4295   if (cfun->calls_alloca
4296       || cfun->has_nonlocal_label
4297       || crtl->has_nonlocal_goto)
4298     crtl->need_drap = true;
4299
4300   /* Call update_stack_boundary here again to update incoming stack
4301      boundary.  It may set incoming stack alignment to a different
4302      value after RTL expansion.  TARGET_FUNCTION_OK_FOR_SIBCALL may
4303      use the minimum incoming stack alignment to check if it is OK
4304      to perform sibcall optimization since sibcall optimization will
4305      only align the outgoing stack to incoming stack boundary.  */
4306   if (targetm.calls.update_stack_boundary)
4307     targetm.calls.update_stack_boundary ();
4308
4309   /* The incoming stack frame has to be aligned at least at
4310      parm_stack_boundary.  */
4311   gcc_assert (crtl->parm_stack_boundary <= INCOMING_STACK_BOUNDARY);
4312
4313   /* Update crtl->stack_alignment_estimated and use it later to align
4314      stack.  We check PREFERRED_STACK_BOUNDARY if there may be non-call
4315      exceptions since callgraph doesn't collect incoming stack alignment
4316      in this case.  */
4317   if (cfun->can_throw_non_call_exceptions
4318       && PREFERRED_STACK_BOUNDARY > crtl->preferred_stack_boundary)
4319     preferred_stack_boundary = PREFERRED_STACK_BOUNDARY;
4320   else
4321     preferred_stack_boundary = crtl->preferred_stack_boundary;
4322   if (preferred_stack_boundary > crtl->stack_alignment_estimated)
4323     crtl->stack_alignment_estimated = preferred_stack_boundary;
4324   if (preferred_stack_boundary > crtl->stack_alignment_needed)
4325     crtl->stack_alignment_needed = preferred_stack_boundary;
4326
4327   gcc_assert (crtl->stack_alignment_needed
4328               <= crtl->stack_alignment_estimated);
4329
4330   crtl->stack_realign_needed
4331     = INCOMING_STACK_BOUNDARY < crtl->stack_alignment_estimated;
4332   crtl->stack_realign_tried = crtl->stack_realign_needed;
4333
4334   crtl->stack_realign_processed = true;
4335
4336   /* Target has to redefine TARGET_GET_DRAP_RTX to support stack
4337      alignment.  */
4338   gcc_assert (targetm.calls.get_drap_rtx != NULL);
4339   drap_rtx = targetm.calls.get_drap_rtx ();
4340
4341   /* stack_realign_drap and drap_rtx must match.  */
4342   gcc_assert ((stack_realign_drap != 0) == (drap_rtx != NULL));
4343
4344   /* Do nothing if NULL is returned, which means DRAP is not needed.  */
4345   if (NULL != drap_rtx)
4346     {
4347       crtl->args.internal_arg_pointer = drap_rtx;
4348
4349       /* Call fixup_tail_calls to clean up REG_EQUIV note if DRAP is
4350          needed. */
4351       fixup_tail_calls ();
4352     }
4353 }
4354
4355 /* Translate the intermediate representation contained in the CFG
4356    from GIMPLE trees to RTL.
4357
4358    We do conversion per basic block and preserve/update the tree CFG.
4359    This implies we have to do some magic as the CFG can simultaneously
4360    consist of basic blocks containing RTL and GIMPLE trees.  This can
4361    confuse the CFG hooks, so be careful to not manipulate CFG during
4362    the expansion.  */
4363
4364 static unsigned int
4365 gimple_expand_cfg (void)
4366 {
4367   basic_block bb, init_block;
4368   sbitmap blocks;
4369   edge_iterator ei;
4370   edge e;
4371   rtx var_seq;
4372   unsigned i;
4373
4374   timevar_push (TV_OUT_OF_SSA);
4375   rewrite_out_of_ssa (&SA);
4376   timevar_pop (TV_OUT_OF_SSA);
4377   SA.partition_to_pseudo = (rtx *)xcalloc (SA.map->num_partitions,
4378                                            sizeof (rtx));
4379
4380   /* Some backends want to know that we are expanding to RTL.  */
4381   currently_expanding_to_rtl = 1;
4382
4383   rtl_profile_for_bb (ENTRY_BLOCK_PTR);
4384
4385   insn_locators_alloc ();
4386   if (!DECL_IS_BUILTIN (current_function_decl))
4387     {
4388       /* Eventually, all FEs should explicitly set function_start_locus.  */
4389       if (cfun->function_start_locus == UNKNOWN_LOCATION)
4390        set_curr_insn_source_location
4391          (DECL_SOURCE_LOCATION (current_function_decl));
4392       else
4393        set_curr_insn_source_location (cfun->function_start_locus);
4394     }
4395   else
4396     set_curr_insn_source_location (UNKNOWN_LOCATION);
4397   set_curr_insn_block (DECL_INITIAL (current_function_decl));
4398   prologue_locator = curr_insn_locator ();
4399
4400 #ifdef INSN_SCHEDULING
4401   init_sched_attrs ();
4402 #endif
4403
4404   /* Make sure first insn is a note even if we don't want linenums.
4405      This makes sure the first insn will never be deleted.
4406      Also, final expects a note to appear there.  */
4407   emit_note (NOTE_INSN_DELETED);
4408
4409   /* Mark arrays indexed with non-constant indices with TREE_ADDRESSABLE.  */
4410   discover_nonconstant_array_refs ();
4411
4412   targetm.expand_to_rtl_hook ();
4413   crtl->stack_alignment_needed = STACK_BOUNDARY;
4414   crtl->max_used_stack_slot_alignment = STACK_BOUNDARY;
4415   crtl->stack_alignment_estimated = 0;
4416   crtl->preferred_stack_boundary = STACK_BOUNDARY;
4417   cfun->cfg->max_jumptable_ents = 0;
4418
4419   /* Resovle the function section.  Some targets, like ARM EABI rely on knowledge
4420      of the function section at exapnsion time to predict distance of calls.  */
4421   resolve_unique_section (current_function_decl, 0, flag_function_sections);
4422
4423   /* Expand the variables recorded during gimple lowering.  */
4424   timevar_push (TV_VAR_EXPAND);
4425   start_sequence ();
4426
4427   expand_used_vars ();
4428
4429   var_seq = get_insns ();
4430   end_sequence ();
4431   timevar_pop (TV_VAR_EXPAND);
4432
4433   /* Honor stack protection warnings.  */
4434   if (warn_stack_protect)
4435     {
4436       if (cfun->calls_alloca)
4437         warning (OPT_Wstack_protector,
4438                  "stack protector not protecting local variables: "
4439                  "variable length buffer");
4440       if (has_short_buffer && !crtl->stack_protect_guard)
4441         warning (OPT_Wstack_protector,
4442                  "stack protector not protecting function: "
4443                  "all local arrays are less than %d bytes long",
4444                  (int) PARAM_VALUE (PARAM_SSP_BUFFER_SIZE));
4445     }
4446
4447   /* Set up parameters and prepare for return, for the function.  */
4448   expand_function_start (current_function_decl);
4449
4450   /* If we emitted any instructions for setting up the variables,
4451      emit them before the FUNCTION_START note.  */
4452   if (var_seq)
4453     {
4454       emit_insn_before (var_seq, parm_birth_insn);
4455
4456       /* In expand_function_end we'll insert the alloca save/restore
4457          before parm_birth_insn.  We've just insertted an alloca call.
4458          Adjust the pointer to match.  */
4459       parm_birth_insn = var_seq;
4460     }
4461
4462   /* Now that we also have the parameter RTXs, copy them over to our
4463      partitions.  */
4464   for (i = 0; i < SA.map->num_partitions; i++)
4465     {
4466       tree var = SSA_NAME_VAR (partition_to_var (SA.map, i));
4467
4468       if (TREE_CODE (var) != VAR_DECL
4469           && !SA.partition_to_pseudo[i])
4470         SA.partition_to_pseudo[i] = DECL_RTL_IF_SET (var);
4471       gcc_assert (SA.partition_to_pseudo[i]);
4472
4473       /* If this decl was marked as living in multiple places, reset
4474          this now to NULL.  */
4475       if (DECL_RTL_IF_SET (var) == pc_rtx)
4476         SET_DECL_RTL (var, NULL);
4477
4478       /* Some RTL parts really want to look at DECL_RTL(x) when x
4479          was a decl marked in REG_ATTR or MEM_ATTR.  We could use
4480          SET_DECL_RTL here making this available, but that would mean
4481          to select one of the potentially many RTLs for one DECL.  Instead
4482          of doing that we simply reset the MEM_EXPR of the RTL in question,
4483          then nobody can get at it and hence nobody can call DECL_RTL on it.  */
4484       if (!DECL_RTL_SET_P (var))
4485         {
4486           if (MEM_P (SA.partition_to_pseudo[i]))
4487             set_mem_expr (SA.partition_to_pseudo[i], NULL);
4488         }
4489     }
4490
4491   /* If we have a class containing differently aligned pointers
4492      we need to merge those into the corresponding RTL pointer
4493      alignment.  */
4494   for (i = 1; i < num_ssa_names; i++)
4495     {
4496       tree name = ssa_name (i);
4497       int part;
4498       rtx r;
4499
4500       if (!name
4501           || !POINTER_TYPE_P (TREE_TYPE (name))
4502           /* We might have generated new SSA names in
4503              update_alias_info_with_stack_vars.  They will have a NULL
4504              defining statements, and won't be part of the partitioning,
4505              so ignore those.  */
4506           || !SSA_NAME_DEF_STMT (name))
4507         continue;
4508       part = var_to_partition (SA.map, name);
4509       if (part == NO_PARTITION)
4510         continue;
4511       r = SA.partition_to_pseudo[part];
4512       if (REG_P (r))
4513         mark_reg_pointer (r, get_pointer_alignment (name));
4514     }
4515
4516   /* If this function is `main', emit a call to `__main'
4517      to run global initializers, etc.  */
4518   if (DECL_NAME (current_function_decl)
4519       && MAIN_NAME_P (DECL_NAME (current_function_decl))
4520       && DECL_FILE_SCOPE_P (current_function_decl))
4521     expand_main_function ();
4522
4523   /* Initialize the stack_protect_guard field.  This must happen after the
4524      call to __main (if any) so that the external decl is initialized.  */
4525   if (crtl->stack_protect_guard)
4526     stack_protect_prologue ();
4527
4528   expand_phi_nodes (&SA);
4529
4530   /* Register rtl specific functions for cfg.  */
4531   rtl_register_cfg_hooks ();
4532
4533   init_block = construct_init_block ();
4534
4535   /* Clear EDGE_EXECUTABLE on the entry edge(s).  It is cleaned from the
4536      remaining edges later.  */
4537   FOR_EACH_EDGE (e, ei, ENTRY_BLOCK_PTR->succs)
4538     e->flags &= ~EDGE_EXECUTABLE;
4539
4540   lab_rtx_for_bb = pointer_map_create ();
4541   FOR_BB_BETWEEN (bb, init_block->next_bb, EXIT_BLOCK_PTR, next_bb)
4542     bb = expand_gimple_basic_block (bb);
4543
4544   if (MAY_HAVE_DEBUG_INSNS)
4545     expand_debug_locations ();
4546
4547   execute_free_datastructures ();
4548   timevar_push (TV_OUT_OF_SSA);
4549   finish_out_of_ssa (&SA);
4550   timevar_pop (TV_OUT_OF_SSA);
4551
4552   timevar_push (TV_POST_EXPAND);
4553   /* We are no longer in SSA form.  */
4554   cfun->gimple_df->in_ssa_p = false;
4555
4556   /* Expansion is used by optimization passes too, set maybe_hot_insn_p
4557      conservatively to true until they are all profile aware.  */
4558   pointer_map_destroy (lab_rtx_for_bb);
4559   free_histograms ();
4560
4561   construct_exit_block ();
4562   set_curr_insn_block (DECL_INITIAL (current_function_decl));
4563   insn_locators_finalize ();
4564
4565   /* Zap the tree EH table.  */
4566   set_eh_throw_stmt_table (cfun, NULL);
4567
4568   /* We need JUMP_LABEL be set in order to redirect jumps, and hence
4569      split edges which edge insertions might do.  */
4570   rebuild_jump_labels (get_insns ());
4571
4572   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR, EXIT_BLOCK_PTR, next_bb)
4573     {
4574       edge e;
4575       edge_iterator ei;
4576       for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
4577         {
4578           if (e->insns.r)
4579             {
4580               rebuild_jump_labels_chain (e->insns.r);
4581               /* Avoid putting insns before parm_birth_insn.  */
4582               if (e->src == ENTRY_BLOCK_PTR
4583                   && single_succ_p (ENTRY_BLOCK_PTR)
4584                   && parm_birth_insn)
4585                 {
4586                   rtx insns = e->insns.r;
4587                   e->insns.r = NULL_RTX;
4588                   emit_insn_after_noloc (insns, parm_birth_insn, e->dest);
4589                 }
4590               else
4591                 commit_one_edge_insertion (e);
4592             }
4593           else
4594             ei_next (&ei);
4595         }
4596     }
4597
4598   /* We're done expanding trees to RTL.  */
4599   currently_expanding_to_rtl = 0;
4600
4601   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR->next_bb, EXIT_BLOCK_PTR, next_bb)
4602     {
4603       edge e;
4604       edge_iterator ei;
4605       for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); )
4606         {
4607           /* Clear EDGE_EXECUTABLE.  This flag is never used in the backend.  */
4608           e->flags &= ~EDGE_EXECUTABLE;
4609
4610           /* At the moment not all abnormal edges match the RTL
4611              representation.  It is safe to remove them here as
4612              find_many_sub_basic_blocks will rediscover them.
4613              In the future we should get this fixed properly.  */
4614           if ((e->flags & EDGE_ABNORMAL)
4615               && !(e->flags & EDGE_SIBCALL))
4616             remove_edge (e);
4617           else
4618             ei_next (&ei);
4619         }
4620     }
4621
4622   blocks = sbitmap_alloc (last_basic_block);
4623   sbitmap_ones (blocks);
4624   find_many_sub_basic_blocks (blocks);
4625   sbitmap_free (blocks);
4626   purge_all_dead_edges ();
4627
4628   compact_blocks ();
4629
4630   expand_stack_alignment ();
4631
4632 #ifdef ENABLE_CHECKING
4633   verify_flow_info ();
4634 #endif
4635
4636   /* There's no need to defer outputting this function any more; we
4637      know we want to output it.  */
4638   DECL_DEFER_OUTPUT (current_function_decl) = 0;
4639
4640   /* Now that we're done expanding trees to RTL, we shouldn't have any
4641      more CONCATs anywhere.  */
4642   generating_concat_p = 0;
4643
4644   if (dump_file)
4645     {
4646       fprintf (dump_file,
4647                "\n\n;;\n;; Full RTL generated for this function:\n;;\n");
4648       /* And the pass manager will dump RTL for us.  */
4649     }
4650
4651   /* If we're emitting a nested function, make sure its parent gets
4652      emitted as well.  Doing otherwise confuses debug info.  */
4653   {
4654     tree parent;
4655     for (parent = DECL_CONTEXT (current_function_decl);
4656          parent != NULL_TREE;
4657          parent = get_containing_scope (parent))
4658       if (TREE_CODE (parent) == FUNCTION_DECL)
4659         TREE_SYMBOL_REFERENCED (DECL_ASSEMBLER_NAME (parent)) = 1;
4660   }
4661
4662   /* We are now committed to emitting code for this function.  Do any
4663      preparation, such as emitting abstract debug info for the inline
4664      before it gets mangled by optimization.  */
4665   if (cgraph_function_possibly_inlined_p (current_function_decl))
4666     (*debug_hooks->outlining_inline_function) (current_function_decl);
4667
4668   TREE_ASM_WRITTEN (current_function_decl) = 1;
4669
4670   /* After expanding, the return labels are no longer needed. */
4671   return_label = NULL;
4672   naked_return_label = NULL;
4673
4674   /* After expanding, the tm_restart map is no longer needed.  */
4675   if (cfun->gimple_df->tm_restart)
4676     {
4677       htab_delete (cfun->gimple_df->tm_restart);
4678       cfun->gimple_df->tm_restart = NULL;
4679     }
4680
4681   /* Tag the blocks with a depth number so that change_scope can find
4682      the common parent easily.  */
4683   set_block_levels (DECL_INITIAL (cfun->decl), 0);
4684   default_rtl_profile ();
4685   timevar_pop (TV_POST_EXPAND);
4686   return 0;
4687 }
4688
4689 struct rtl_opt_pass pass_expand =
4690 {
4691  {
4692   RTL_PASS,
4693   "expand",                             /* name */
4694   NULL,                                 /* gate */
4695   gimple_expand_cfg,                    /* execute */
4696   NULL,                                 /* sub */
4697   NULL,                                 /* next */
4698   0,                                    /* static_pass_number */
4699   TV_EXPAND,                            /* tv_id */
4700   PROP_ssa | PROP_gimple_leh | PROP_cfg
4701     | PROP_gimple_lcx,                  /* properties_required */
4702   PROP_rtl,                             /* properties_provided */
4703   PROP_ssa | PROP_trees,                /* properties_destroyed */
4704   TODO_verify_ssa | TODO_verify_flow
4705     | TODO_verify_stmts,                /* todo_flags_start */
4706   TODO_ggc_collect                      /* todo_flags_finish */
4707  }
4708 };