coretypes.h: Include input.h and as-a.h.
[platform/upstream/gcc.git] / gcc / tree-ssa-forwprop.c
1 /* Forward propagation of expressions for single use variables.
2    Copyright (C) 2004-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 3, or (at your option)
9 any later version.
10
11 GCC is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 GNU General Public License for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "alias.h"
25 #include "symtab.h"
26 #include "tree.h"
27 #include "fold-const.h"
28 #include "stor-layout.h"
29 #include "tm_p.h"
30 #include "predict.h"
31 #include "hard-reg-set.h"
32 #include "function.h"
33 #include "dominance.h"
34 #include "cfg.h"
35 #include "basic-block.h"
36 #include "gimple-pretty-print.h"
37 #include "tree-ssa-alias.h"
38 #include "internal-fn.h"
39 #include "gimple-fold.h"
40 #include "tree-eh.h"
41 #include "gimple-expr.h"
42 #include "gimple.h"
43 #include "gimplify.h"
44 #include "gimple-iterator.h"
45 #include "gimplify-me.h"
46 #include "gimple-ssa.h"
47 #include "tree-cfg.h"
48 #include "tree-phinodes.h"
49 #include "ssa-iterators.h"
50 #include "stringpool.h"
51 #include "tree-ssanames.h"
52 #include "rtl.h"
53 #include "flags.h"
54 #include "insn-config.h"
55 #include "expmed.h"
56 #include "dojump.h"
57 #include "explow.h"
58 #include "calls.h"
59 #include "emit-rtl.h"
60 #include "varasm.h"
61 #include "stmt.h"
62 #include "expr.h"
63 #include "tree-dfa.h"
64 #include "tree-pass.h"
65 #include "langhooks.h"
66 #include "diagnostic.h"
67 #include "cfgloop.h"
68 #include "insn-codes.h"
69 #include "optabs.h"
70 #include "tree-ssa-propagate.h"
71 #include "tree-ssa-dom.h"
72 #include "builtins.h"
73 #include "tree-cfgcleanup.h"
74 #include "tree-into-ssa.h"
75 #include "cfganal.h"
76
77 /* This pass propagates the RHS of assignment statements into use
78    sites of the LHS of the assignment.  It's basically a specialized
79    form of tree combination.   It is hoped all of this can disappear
80    when we have a generalized tree combiner.
81
82    One class of common cases we handle is forward propagating a single use
83    variable into a COND_EXPR.
84
85      bb0:
86        x = a COND b;
87        if (x) goto ... else goto ...
88
89    Will be transformed into:
90
91      bb0:
92        if (a COND b) goto ... else goto ...
93
94    Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
95
96    Or (assuming c1 and c2 are constants):
97
98      bb0:
99        x = a + c1;
100        if (x EQ/NEQ c2) goto ... else goto ...
101
102    Will be transformed into:
103
104      bb0:
105         if (a EQ/NEQ (c2 - c1)) goto ... else goto ...
106
107    Similarly for x = a - c1.
108
109    Or
110
111      bb0:
112        x = !a
113        if (x) goto ... else goto ...
114
115    Will be transformed into:
116
117      bb0:
118         if (a == 0) goto ... else goto ...
119
120    Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
121    For these cases, we propagate A into all, possibly more than one,
122    COND_EXPRs that use X.
123
124    Or
125
126      bb0:
127        x = (typecast) a
128        if (x) goto ... else goto ...
129
130    Will be transformed into:
131
132      bb0:
133         if (a != 0) goto ... else goto ...
134
135    (Assuming a is an integral type and x is a boolean or x is an
136     integral and a is a boolean.)
137
138    Similarly for the tests (x == 0), (x != 0), (x == 1) and (x != 1).
139    For these cases, we propagate A into all, possibly more than one,
140    COND_EXPRs that use X.
141
142    In addition to eliminating the variable and the statement which assigns
143    a value to the variable, we may be able to later thread the jump without
144    adding insane complexity in the dominator optimizer.
145
146    Also note these transformations can cascade.  We handle this by having
147    a worklist of COND_EXPR statements to examine.  As we make a change to
148    a statement, we put it back on the worklist to examine on the next
149    iteration of the main loop.
150
151    A second class of propagation opportunities arises for ADDR_EXPR
152    nodes.
153
154      ptr = &x->y->z;
155      res = *ptr;
156
157    Will get turned into
158
159      res = x->y->z;
160
161    Or
162      ptr = (type1*)&type2var;
163      res = *ptr
164
165    Will get turned into (if type1 and type2 are the same size
166    and neither have volatile on them):
167      res = VIEW_CONVERT_EXPR<type1>(type2var)
168
169    Or
170
171      ptr = &x[0];
172      ptr2 = ptr + <constant>;
173
174    Will get turned into
175
176      ptr2 = &x[constant/elementsize];
177
178   Or
179
180      ptr = &x[0];
181      offset = index * element_size;
182      offset_p = (pointer) offset;
183      ptr2 = ptr + offset_p
184
185   Will get turned into:
186
187      ptr2 = &x[index];
188
189   Or
190     ssa = (int) decl
191     res = ssa & 1
192
193   Provided that decl has known alignment >= 2, will get turned into
194
195     res = 0
196
197   We also propagate casts into SWITCH_EXPR and COND_EXPR conditions to
198   allow us to remove the cast and {NOT_EXPR,NEG_EXPR} into a subsequent
199   {NOT_EXPR,NEG_EXPR}.
200
201    This will (of course) be extended as other needs arise.  */
202
203 static bool forward_propagate_addr_expr (tree, tree, bool);
204
205 /* Set to true if we delete dead edges during the optimization.  */
206 static bool cfg_changed;
207
208 static tree rhs_to_tree (tree type, gimple stmt);
209
210 static bitmap to_purge;
211
212 /* Const-and-copy lattice.  */
213 static vec<tree> lattice;
214
215 /* Set the lattice entry for NAME to VAL.  */
216 static void
217 fwprop_set_lattice_val (tree name, tree val)
218 {
219   if (TREE_CODE (name) == SSA_NAME)
220     {
221       if (SSA_NAME_VERSION (name) >= lattice.length ())
222         {
223           lattice.reserve (num_ssa_names - lattice.length ());
224           lattice.quick_grow_cleared (num_ssa_names);
225         }
226       lattice[SSA_NAME_VERSION (name)] = val;
227     }
228 }
229
230 /* Invalidate the lattice entry for NAME, done when releasing SSA names.  */
231 static void
232 fwprop_invalidate_lattice (tree name)
233 {
234   if (name
235       && TREE_CODE (name) == SSA_NAME
236       && SSA_NAME_VERSION (name) < lattice.length ())
237     lattice[SSA_NAME_VERSION (name)] = NULL_TREE;
238 }
239
240
241 /* Get the statement we can propagate from into NAME skipping
242    trivial copies.  Returns the statement which defines the
243    propagation source or NULL_TREE if there is no such one.
244    If SINGLE_USE_ONLY is set considers only sources which have
245    a single use chain up to NAME.  If SINGLE_USE_P is non-null,
246    it is set to whether the chain to NAME is a single use chain
247    or not.  SINGLE_USE_P is not written to if SINGLE_USE_ONLY is set.  */
248
249 static gimple
250 get_prop_source_stmt (tree name, bool single_use_only, bool *single_use_p)
251 {
252   bool single_use = true;
253
254   do {
255     gimple def_stmt = SSA_NAME_DEF_STMT (name);
256
257     if (!has_single_use (name))
258       {
259         single_use = false;
260         if (single_use_only)
261           return NULL;
262       }
263
264     /* If name is defined by a PHI node or is the default def, bail out.  */
265     if (!is_gimple_assign (def_stmt))
266       return NULL;
267
268     /* If def_stmt is a simple copy, continue looking.  */
269     if (gimple_assign_rhs_code (def_stmt) == SSA_NAME)
270       name = gimple_assign_rhs1 (def_stmt);
271     else
272       {
273         if (!single_use_only && single_use_p)
274           *single_use_p = single_use;
275
276         return def_stmt;
277       }
278   } while (1);
279 }
280
281 /* Checks if the destination ssa name in DEF_STMT can be used as
282    propagation source.  Returns true if so, otherwise false.  */
283
284 static bool
285 can_propagate_from (gimple def_stmt)
286 {
287   gcc_assert (is_gimple_assign (def_stmt));
288
289   /* If the rhs has side-effects we cannot propagate from it.  */
290   if (gimple_has_volatile_ops (def_stmt))
291     return false;
292
293   /* If the rhs is a load we cannot propagate from it.  */
294   if (TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)) == tcc_reference
295       || TREE_CODE_CLASS (gimple_assign_rhs_code (def_stmt)) == tcc_declaration)
296     return false;
297
298   /* Constants can be always propagated.  */
299   if (gimple_assign_single_p (def_stmt)
300       && is_gimple_min_invariant (gimple_assign_rhs1 (def_stmt)))
301     return true;
302
303   /* We cannot propagate ssa names that occur in abnormal phi nodes.  */
304   if (stmt_references_abnormal_ssa_name (def_stmt))
305     return false;
306
307   /* If the definition is a conversion of a pointer to a function type,
308      then we can not apply optimizations as some targets require
309      function pointers to be canonicalized and in this case this
310      optimization could eliminate a necessary canonicalization.  */
311   if (CONVERT_EXPR_CODE_P (gimple_assign_rhs_code (def_stmt)))
312     {
313       tree rhs = gimple_assign_rhs1 (def_stmt);
314       if (POINTER_TYPE_P (TREE_TYPE (rhs))
315           && TREE_CODE (TREE_TYPE (TREE_TYPE (rhs))) == FUNCTION_TYPE)
316         return false;
317     }
318
319   return true;
320 }
321
322 /* Remove a chain of dead statements starting at the definition of
323    NAME.  The chain is linked via the first operand of the defining statements.
324    If NAME was replaced in its only use then this function can be used
325    to clean up dead stmts.  The function handles already released SSA
326    names gracefully.
327    Returns true if cleanup-cfg has to run.  */
328
329 static bool
330 remove_prop_source_from_use (tree name)
331 {
332   gimple_stmt_iterator gsi;
333   gimple stmt;
334   bool cfg_changed = false;
335
336   do {
337     basic_block bb;
338
339     if (SSA_NAME_IN_FREE_LIST (name)
340         || SSA_NAME_IS_DEFAULT_DEF (name)
341         || !has_zero_uses (name))
342       return cfg_changed;
343
344     stmt = SSA_NAME_DEF_STMT (name);
345     if (gimple_code (stmt) == GIMPLE_PHI
346         || gimple_has_side_effects (stmt))
347       return cfg_changed;
348
349     bb = gimple_bb (stmt);
350     gsi = gsi_for_stmt (stmt);
351     unlink_stmt_vdef (stmt);
352     if (gsi_remove (&gsi, true))
353       bitmap_set_bit (to_purge, bb->index);
354     fwprop_invalidate_lattice (gimple_get_lhs (stmt));
355     release_defs (stmt);
356
357     name = is_gimple_assign (stmt) ? gimple_assign_rhs1 (stmt) : NULL_TREE;
358   } while (name && TREE_CODE (name) == SSA_NAME);
359
360   return cfg_changed;
361 }
362
363 /* Return the rhs of a gassign *STMT in a form of a single tree,
364    converted to type TYPE.
365
366    This should disappear, but is needed so we can combine expressions and use
367    the fold() interfaces. Long term, we need to develop folding and combine
368    routines that deal with gimple exclusively . */
369
370 static tree
371 rhs_to_tree (tree type, gimple stmt)
372 {
373   location_t loc = gimple_location (stmt);
374   enum tree_code code = gimple_assign_rhs_code (stmt);
375   if (get_gimple_rhs_class (code) == GIMPLE_TERNARY_RHS)
376     return fold_build3_loc (loc, code, type, gimple_assign_rhs1 (stmt),
377                             gimple_assign_rhs2 (stmt),
378                             gimple_assign_rhs3 (stmt));
379   else if (get_gimple_rhs_class (code) == GIMPLE_BINARY_RHS)
380     return fold_build2_loc (loc, code, type, gimple_assign_rhs1 (stmt),
381                         gimple_assign_rhs2 (stmt));
382   else if (get_gimple_rhs_class (code) == GIMPLE_UNARY_RHS)
383     return build1 (code, type, gimple_assign_rhs1 (stmt));
384   else if (get_gimple_rhs_class (code) == GIMPLE_SINGLE_RHS)
385     return gimple_assign_rhs1 (stmt);
386   else
387     gcc_unreachable ();
388 }
389
390 /* Combine OP0 CODE OP1 in the context of a COND_EXPR.  Returns
391    the folded result in a form suitable for COND_EXPR_COND or
392    NULL_TREE, if there is no suitable simplified form.  If
393    INVARIANT_ONLY is true only gimple_min_invariant results are
394    considered simplified.  */
395
396 static tree
397 combine_cond_expr_cond (gimple stmt, enum tree_code code, tree type,
398                         tree op0, tree op1, bool invariant_only)
399 {
400   tree t;
401
402   gcc_assert (TREE_CODE_CLASS (code) == tcc_comparison);
403
404   fold_defer_overflow_warnings ();
405   t = fold_binary_loc (gimple_location (stmt), code, type, op0, op1);
406   if (!t)
407     {
408       fold_undefer_overflow_warnings (false, NULL, 0);
409       return NULL_TREE;
410     }
411
412   /* Require that we got a boolean type out if we put one in.  */
413   gcc_assert (TREE_CODE (TREE_TYPE (t)) == TREE_CODE (type));
414
415   /* Canonicalize the combined condition for use in a COND_EXPR.  */
416   t = canonicalize_cond_expr_cond (t);
417
418   /* Bail out if we required an invariant but didn't get one.  */
419   if (!t || (invariant_only && !is_gimple_min_invariant (t)))
420     {
421       fold_undefer_overflow_warnings (false, NULL, 0);
422       return NULL_TREE;
423     }
424
425   fold_undefer_overflow_warnings (!gimple_no_warning_p (stmt), stmt, 0);
426
427   return t;
428 }
429
430 /* Combine the comparison OP0 CODE OP1 at LOC with the defining statements
431    of its operand.  Return a new comparison tree or NULL_TREE if there
432    were no simplifying combines.  */
433
434 static tree
435 forward_propagate_into_comparison_1 (gimple stmt,
436                                      enum tree_code code, tree type,
437                                      tree op0, tree op1)
438 {
439   tree tmp = NULL_TREE;
440   tree rhs0 = NULL_TREE, rhs1 = NULL_TREE;
441   bool single_use0_p = false, single_use1_p = false;
442
443   /* For comparisons use the first operand, that is likely to
444      simplify comparisons against constants.  */
445   if (TREE_CODE (op0) == SSA_NAME)
446     {
447       gimple def_stmt = get_prop_source_stmt (op0, false, &single_use0_p);
448       if (def_stmt && can_propagate_from (def_stmt))
449         {
450           enum tree_code def_code = gimple_assign_rhs_code (def_stmt);
451           bool invariant_only_p = !single_use0_p;
452
453           rhs0 = rhs_to_tree (TREE_TYPE (op1), def_stmt);
454
455           /* Always combine comparisons or conversions from booleans.  */
456           if (TREE_CODE (op1) == INTEGER_CST
457               && ((CONVERT_EXPR_CODE_P (def_code)
458                    && TREE_CODE (TREE_TYPE (TREE_OPERAND (rhs0, 0)))
459                       == BOOLEAN_TYPE)
460                   || TREE_CODE_CLASS (def_code) == tcc_comparison))
461             invariant_only_p = false;
462
463           tmp = combine_cond_expr_cond (stmt, code, type,
464                                         rhs0, op1, invariant_only_p);
465           if (tmp)
466             return tmp;
467         }
468     }
469
470   /* If that wasn't successful, try the second operand.  */
471   if (TREE_CODE (op1) == SSA_NAME)
472     {
473       gimple def_stmt = get_prop_source_stmt (op1, false, &single_use1_p);
474       if (def_stmt && can_propagate_from (def_stmt))
475         {
476           rhs1 = rhs_to_tree (TREE_TYPE (op0), def_stmt);
477           tmp = combine_cond_expr_cond (stmt, code, type,
478                                         op0, rhs1, !single_use1_p);
479           if (tmp)
480             return tmp;
481         }
482     }
483
484   /* If that wasn't successful either, try both operands.  */
485   if (rhs0 != NULL_TREE
486       && rhs1 != NULL_TREE)
487     tmp = combine_cond_expr_cond (stmt, code, type,
488                                   rhs0, rhs1,
489                                   !(single_use0_p && single_use1_p));
490
491   return tmp;
492 }
493
494 /* Propagate from the ssa name definition statements of the assignment
495    from a comparison at *GSI into the conditional if that simplifies it.
496    Returns 1 if the stmt was modified and 2 if the CFG needs cleanup,
497    otherwise returns 0.  */
498
499 static int 
500 forward_propagate_into_comparison (gimple_stmt_iterator *gsi)
501 {
502   gimple stmt = gsi_stmt (*gsi);
503   tree tmp;
504   bool cfg_changed = false;
505   tree type = TREE_TYPE (gimple_assign_lhs (stmt));
506   tree rhs1 = gimple_assign_rhs1 (stmt);
507   tree rhs2 = gimple_assign_rhs2 (stmt);
508
509   /* Combine the comparison with defining statements.  */
510   tmp = forward_propagate_into_comparison_1 (stmt,
511                                              gimple_assign_rhs_code (stmt),
512                                              type, rhs1, rhs2);
513   if (tmp && useless_type_conversion_p (type, TREE_TYPE (tmp)))
514     {
515       gimple_assign_set_rhs_from_tree (gsi, tmp);
516       fold_stmt (gsi);
517       update_stmt (gsi_stmt (*gsi));
518
519       if (TREE_CODE (rhs1) == SSA_NAME)
520         cfg_changed |= remove_prop_source_from_use (rhs1);
521       if (TREE_CODE (rhs2) == SSA_NAME)
522         cfg_changed |= remove_prop_source_from_use (rhs2);
523       return cfg_changed ? 2 : 1;
524     }
525
526   return 0;
527 }
528
529 /* Propagate from the ssa name definition statements of COND_EXPR
530    in GIMPLE_COND statement STMT into the conditional if that simplifies it.
531    Returns zero if no statement was changed, one if there were
532    changes and two if cfg_cleanup needs to run.
533
534    This must be kept in sync with forward_propagate_into_cond.  */
535
536 static int
537 forward_propagate_into_gimple_cond (gcond *stmt)
538 {
539   tree tmp;
540   enum tree_code code = gimple_cond_code (stmt);
541   bool cfg_changed = false;
542   tree rhs1 = gimple_cond_lhs (stmt);
543   tree rhs2 = gimple_cond_rhs (stmt);
544
545   /* We can do tree combining on SSA_NAME and comparison expressions.  */
546   if (TREE_CODE_CLASS (gimple_cond_code (stmt)) != tcc_comparison)
547     return 0;
548
549   tmp = forward_propagate_into_comparison_1 (stmt, code,
550                                              boolean_type_node,
551                                              rhs1, rhs2);
552   if (tmp)
553     {
554       if (dump_file && tmp)
555         {
556           fprintf (dump_file, "  Replaced '");
557           print_gimple_expr (dump_file, stmt, 0, 0);
558           fprintf (dump_file, "' with '");
559           print_generic_expr (dump_file, tmp, 0);
560           fprintf (dump_file, "'\n");
561         }
562
563       gimple_cond_set_condition_from_tree (stmt, unshare_expr (tmp));
564       update_stmt (stmt);
565
566       if (TREE_CODE (rhs1) == SSA_NAME)
567         cfg_changed |= remove_prop_source_from_use (rhs1);
568       if (TREE_CODE (rhs2) == SSA_NAME)
569         cfg_changed |= remove_prop_source_from_use (rhs2);
570       return (cfg_changed || is_gimple_min_invariant (tmp)) ? 2 : 1;
571     }
572
573   /* Canonicalize _Bool == 0 and _Bool != 1 to _Bool != 0 by swapping edges.  */
574   if ((TREE_CODE (TREE_TYPE (rhs1)) == BOOLEAN_TYPE
575        || (INTEGRAL_TYPE_P (TREE_TYPE (rhs1))
576            && TYPE_PRECISION (TREE_TYPE (rhs1)) == 1))
577       && ((code == EQ_EXPR
578            && integer_zerop (rhs2))
579           || (code == NE_EXPR
580               && integer_onep (rhs2))))
581     {
582       basic_block bb = gimple_bb (stmt);
583       gimple_cond_set_code (stmt, NE_EXPR);
584       gimple_cond_set_rhs (stmt, build_zero_cst (TREE_TYPE (rhs1)));
585       EDGE_SUCC (bb, 0)->flags ^= (EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
586       EDGE_SUCC (bb, 1)->flags ^= (EDGE_TRUE_VALUE|EDGE_FALSE_VALUE);
587       return 1;
588     }
589
590   return 0;
591 }
592
593
594 /* Propagate from the ssa name definition statements of COND_EXPR
595    in the rhs of statement STMT into the conditional if that simplifies it.
596    Returns true zero if the stmt was changed.  */
597
598 static bool
599 forward_propagate_into_cond (gimple_stmt_iterator *gsi_p)
600 {
601   gimple stmt = gsi_stmt (*gsi_p);
602   tree tmp = NULL_TREE;
603   tree cond = gimple_assign_rhs1 (stmt);
604   enum tree_code code = gimple_assign_rhs_code (stmt);
605
606   /* We can do tree combining on SSA_NAME and comparison expressions.  */
607   if (COMPARISON_CLASS_P (cond))
608     tmp = forward_propagate_into_comparison_1 (stmt, TREE_CODE (cond),
609                                                TREE_TYPE (cond),
610                                                TREE_OPERAND (cond, 0),
611                                                TREE_OPERAND (cond, 1));
612   else if (TREE_CODE (cond) == SSA_NAME)
613     {
614       enum tree_code def_code;
615       tree name = cond;
616       gimple def_stmt = get_prop_source_stmt (name, true, NULL);
617       if (!def_stmt || !can_propagate_from (def_stmt))
618         return 0;
619
620       def_code = gimple_assign_rhs_code (def_stmt);
621       if (TREE_CODE_CLASS (def_code) == tcc_comparison)
622         tmp = fold_build2_loc (gimple_location (def_stmt),
623                                def_code,
624                                TREE_TYPE (cond),
625                                gimple_assign_rhs1 (def_stmt),
626                                gimple_assign_rhs2 (def_stmt));
627     }
628
629   if (tmp
630       && is_gimple_condexpr (tmp))
631     {
632       if (dump_file && tmp)
633         {
634           fprintf (dump_file, "  Replaced '");
635           print_generic_expr (dump_file, cond, 0);
636           fprintf (dump_file, "' with '");
637           print_generic_expr (dump_file, tmp, 0);
638           fprintf (dump_file, "'\n");
639         }
640
641       if ((code == VEC_COND_EXPR) ? integer_all_onesp (tmp)
642                                   : integer_onep (tmp))
643         gimple_assign_set_rhs_from_tree (gsi_p, gimple_assign_rhs2 (stmt));
644       else if (integer_zerop (tmp))
645         gimple_assign_set_rhs_from_tree (gsi_p, gimple_assign_rhs3 (stmt));
646       else
647         gimple_assign_set_rhs1 (stmt, unshare_expr (tmp));
648       stmt = gsi_stmt (*gsi_p);
649       update_stmt (stmt);
650
651       return true;
652     }
653
654   return 0;
655 }
656
657 /* We've just substituted an ADDR_EXPR into stmt.  Update all the
658    relevant data structures to match.  */
659
660 static void
661 tidy_after_forward_propagate_addr (gimple stmt)
662 {
663   /* We may have turned a trapping insn into a non-trapping insn.  */
664   if (maybe_clean_or_replace_eh_stmt (stmt, stmt))
665     bitmap_set_bit (to_purge, gimple_bb (stmt)->index);
666
667   if (TREE_CODE (gimple_assign_rhs1 (stmt)) == ADDR_EXPR)
668      recompute_tree_invariant_for_addr_expr (gimple_assign_rhs1 (stmt));
669 }
670
671 /* NAME is a SSA_NAME representing DEF_RHS which is of the form
672    ADDR_EXPR <whatever>.
673
674    Try to forward propagate the ADDR_EXPR into the use USE_STMT.
675    Often this will allow for removal of an ADDR_EXPR and INDIRECT_REF
676    node or for recovery of array indexing from pointer arithmetic.
677
678    Return true if the propagation was successful (the propagation can
679    be not totally successful, yet things may have been changed).  */
680
681 static bool
682 forward_propagate_addr_expr_1 (tree name, tree def_rhs,
683                                gimple_stmt_iterator *use_stmt_gsi,
684                                bool single_use_p)
685 {
686   tree lhs, rhs, rhs2, array_ref;
687   gimple use_stmt = gsi_stmt (*use_stmt_gsi);
688   enum tree_code rhs_code;
689   bool res = true;
690
691   gcc_assert (TREE_CODE (def_rhs) == ADDR_EXPR);
692
693   lhs = gimple_assign_lhs (use_stmt);
694   rhs_code = gimple_assign_rhs_code (use_stmt);
695   rhs = gimple_assign_rhs1 (use_stmt);
696
697   /* Do not perform copy-propagation but recurse through copy chains.  */
698   if (TREE_CODE (lhs) == SSA_NAME
699       && rhs_code == SSA_NAME)
700     return forward_propagate_addr_expr (lhs, def_rhs, single_use_p);
701
702   /* The use statement could be a conversion.  Recurse to the uses of the
703      lhs as copyprop does not copy through pointer to integer to pointer
704      conversions and FRE does not catch all cases either.
705      Treat the case of a single-use name and
706      a conversion to def_rhs type separate, though.  */
707   if (TREE_CODE (lhs) == SSA_NAME
708       && CONVERT_EXPR_CODE_P (rhs_code))
709     {
710       /* If there is a point in a conversion chain where the types match
711          so we can remove a conversion re-materialize the address here
712          and stop.  */
713       if (single_use_p
714           && useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (def_rhs)))
715         {
716           gimple_assign_set_rhs1 (use_stmt, unshare_expr (def_rhs));
717           gimple_assign_set_rhs_code (use_stmt, TREE_CODE (def_rhs));
718           return true;
719         }
720
721       /* Else recurse if the conversion preserves the address value.  */
722       if ((INTEGRAL_TYPE_P (TREE_TYPE (lhs))
723            || POINTER_TYPE_P (TREE_TYPE (lhs)))
724           && (TYPE_PRECISION (TREE_TYPE (lhs))
725               >= TYPE_PRECISION (TREE_TYPE (def_rhs))))
726         return forward_propagate_addr_expr (lhs, def_rhs, single_use_p);
727
728       return false;
729     }
730
731   /* If this isn't a conversion chain from this on we only can propagate
732      into compatible pointer contexts.  */
733   if (!types_compatible_p (TREE_TYPE (name), TREE_TYPE (def_rhs)))
734     return false;
735
736   /* Propagate through constant pointer adjustments.  */
737   if (TREE_CODE (lhs) == SSA_NAME
738       && rhs_code == POINTER_PLUS_EXPR
739       && rhs == name
740       && TREE_CODE (gimple_assign_rhs2 (use_stmt)) == INTEGER_CST)
741     {
742       tree new_def_rhs;
743       /* As we come here with non-invariant addresses in def_rhs we need
744          to make sure we can build a valid constant offsetted address
745          for further propagation.  Simply rely on fold building that
746          and check after the fact.  */
747       new_def_rhs = fold_build2 (MEM_REF, TREE_TYPE (TREE_TYPE (rhs)),
748                                  def_rhs,
749                                  fold_convert (ptr_type_node,
750                                                gimple_assign_rhs2 (use_stmt)));
751       if (TREE_CODE (new_def_rhs) == MEM_REF
752           && !is_gimple_mem_ref_addr (TREE_OPERAND (new_def_rhs, 0)))
753         return false;
754       new_def_rhs = build_fold_addr_expr_with_type (new_def_rhs,
755                                                     TREE_TYPE (rhs));
756
757       /* Recurse.  If we could propagate into all uses of lhs do not
758          bother to replace into the current use but just pretend we did.  */
759       if (TREE_CODE (new_def_rhs) == ADDR_EXPR
760           && forward_propagate_addr_expr (lhs, new_def_rhs, single_use_p))
761         return true;
762
763       if (useless_type_conversion_p (TREE_TYPE (lhs), TREE_TYPE (new_def_rhs)))
764         gimple_assign_set_rhs_with_ops (use_stmt_gsi, TREE_CODE (new_def_rhs),
765                                         new_def_rhs);
766       else if (is_gimple_min_invariant (new_def_rhs))
767         gimple_assign_set_rhs_with_ops (use_stmt_gsi, NOP_EXPR, new_def_rhs);
768       else
769         return false;
770       gcc_assert (gsi_stmt (*use_stmt_gsi) == use_stmt);
771       update_stmt (use_stmt);
772       return true;
773     }
774
775   /* Now strip away any outer COMPONENT_REF/ARRAY_REF nodes from the LHS.
776      ADDR_EXPR will not appear on the LHS.  */
777   tree *lhsp = gimple_assign_lhs_ptr (use_stmt);
778   while (handled_component_p (*lhsp))
779     lhsp = &TREE_OPERAND (*lhsp, 0);
780   lhs = *lhsp;
781
782   /* Now see if the LHS node is a MEM_REF using NAME.  If so,
783      propagate the ADDR_EXPR into the use of NAME and fold the result.  */
784   if (TREE_CODE (lhs) == MEM_REF
785       && TREE_OPERAND (lhs, 0) == name)
786     {
787       tree def_rhs_base;
788       HOST_WIDE_INT def_rhs_offset;
789       /* If the address is invariant we can always fold it.  */
790       if ((def_rhs_base = get_addr_base_and_unit_offset (TREE_OPERAND (def_rhs, 0),
791                                                          &def_rhs_offset)))
792         {
793           offset_int off = mem_ref_offset (lhs);
794           tree new_ptr;
795           off += def_rhs_offset;
796           if (TREE_CODE (def_rhs_base) == MEM_REF)
797             {
798               off += mem_ref_offset (def_rhs_base);
799               new_ptr = TREE_OPERAND (def_rhs_base, 0);
800             }
801           else
802             new_ptr = build_fold_addr_expr (def_rhs_base);
803           TREE_OPERAND (lhs, 0) = new_ptr;
804           TREE_OPERAND (lhs, 1)
805             = wide_int_to_tree (TREE_TYPE (TREE_OPERAND (lhs, 1)), off);
806           tidy_after_forward_propagate_addr (use_stmt);
807           /* Continue propagating into the RHS if this was not the only use.  */
808           if (single_use_p)
809             return true;
810         }
811       /* If the LHS is a plain dereference and the value type is the same as
812          that of the pointed-to type of the address we can put the
813          dereferenced address on the LHS preserving the original alias-type.  */
814       else if (integer_zerop (TREE_OPERAND (lhs, 1))
815                && ((gimple_assign_lhs (use_stmt) == lhs
816                     && useless_type_conversion_p
817                          (TREE_TYPE (TREE_OPERAND (def_rhs, 0)),
818                           TREE_TYPE (gimple_assign_rhs1 (use_stmt))))
819                    || types_compatible_p (TREE_TYPE (lhs),
820                                           TREE_TYPE (TREE_OPERAND (def_rhs, 0))))
821                /* Don't forward anything into clobber stmts if it would result
822                   in the lhs no longer being a MEM_REF.  */
823                && (!gimple_clobber_p (use_stmt)
824                    || TREE_CODE (TREE_OPERAND (def_rhs, 0)) == MEM_REF))
825         {
826           tree *def_rhs_basep = &TREE_OPERAND (def_rhs, 0);
827           tree new_offset, new_base, saved, new_lhs;
828           while (handled_component_p (*def_rhs_basep))
829             def_rhs_basep = &TREE_OPERAND (*def_rhs_basep, 0);
830           saved = *def_rhs_basep;
831           if (TREE_CODE (*def_rhs_basep) == MEM_REF)
832             {
833               new_base = TREE_OPERAND (*def_rhs_basep, 0);
834               new_offset = fold_convert (TREE_TYPE (TREE_OPERAND (lhs, 1)),
835                                          TREE_OPERAND (*def_rhs_basep, 1));
836             }
837           else
838             {
839               new_base = build_fold_addr_expr (*def_rhs_basep);
840               new_offset = TREE_OPERAND (lhs, 1);
841             }
842           *def_rhs_basep = build2 (MEM_REF, TREE_TYPE (*def_rhs_basep),
843                                    new_base, new_offset);
844           TREE_THIS_VOLATILE (*def_rhs_basep) = TREE_THIS_VOLATILE (lhs);
845           TREE_SIDE_EFFECTS (*def_rhs_basep) = TREE_SIDE_EFFECTS (lhs);
846           TREE_THIS_NOTRAP (*def_rhs_basep) = TREE_THIS_NOTRAP (lhs);
847           new_lhs = unshare_expr (TREE_OPERAND (def_rhs, 0));
848           *lhsp = new_lhs;
849           TREE_THIS_VOLATILE (new_lhs) = TREE_THIS_VOLATILE (lhs);
850           TREE_SIDE_EFFECTS (new_lhs) = TREE_SIDE_EFFECTS (lhs);
851           *def_rhs_basep = saved;
852           tidy_after_forward_propagate_addr (use_stmt);
853           /* Continue propagating into the RHS if this was not the
854              only use.  */
855           if (single_use_p)
856             return true;
857         }
858       else
859         /* We can have a struct assignment dereferencing our name twice.
860            Note that we didn't propagate into the lhs to not falsely
861            claim we did when propagating into the rhs.  */
862         res = false;
863     }
864
865   /* Strip away any outer COMPONENT_REF, ARRAY_REF or ADDR_EXPR
866      nodes from the RHS.  */
867   tree *rhsp = gimple_assign_rhs1_ptr (use_stmt);
868   if (TREE_CODE (*rhsp) == ADDR_EXPR)
869     rhsp = &TREE_OPERAND (*rhsp, 0);
870   while (handled_component_p (*rhsp))
871     rhsp = &TREE_OPERAND (*rhsp, 0);
872   rhs = *rhsp;
873
874   /* Now see if the RHS node is a MEM_REF using NAME.  If so,
875      propagate the ADDR_EXPR into the use of NAME and fold the result.  */
876   if (TREE_CODE (rhs) == MEM_REF
877       && TREE_OPERAND (rhs, 0) == name)
878     {
879       tree def_rhs_base;
880       HOST_WIDE_INT def_rhs_offset;
881       if ((def_rhs_base = get_addr_base_and_unit_offset (TREE_OPERAND (def_rhs, 0),
882                                                          &def_rhs_offset)))
883         {
884           offset_int off = mem_ref_offset (rhs);
885           tree new_ptr;
886           off += def_rhs_offset;
887           if (TREE_CODE (def_rhs_base) == MEM_REF)
888             {
889               off += mem_ref_offset (def_rhs_base);
890               new_ptr = TREE_OPERAND (def_rhs_base, 0);
891             }
892           else
893             new_ptr = build_fold_addr_expr (def_rhs_base);
894           TREE_OPERAND (rhs, 0) = new_ptr;
895           TREE_OPERAND (rhs, 1)
896             = wide_int_to_tree (TREE_TYPE (TREE_OPERAND (rhs, 1)), off);
897           fold_stmt_inplace (use_stmt_gsi);
898           tidy_after_forward_propagate_addr (use_stmt);
899           return res;
900         }
901       /* If the RHS is a plain dereference and the value type is the same as
902          that of the pointed-to type of the address we can put the
903          dereferenced address on the RHS preserving the original alias-type.  */
904       else if (integer_zerop (TREE_OPERAND (rhs, 1))
905                && ((gimple_assign_rhs1 (use_stmt) == rhs
906                     && useless_type_conversion_p
907                          (TREE_TYPE (gimple_assign_lhs (use_stmt)),
908                           TREE_TYPE (TREE_OPERAND (def_rhs, 0))))
909                    || types_compatible_p (TREE_TYPE (rhs),
910                                           TREE_TYPE (TREE_OPERAND (def_rhs, 0)))))
911         {
912           tree *def_rhs_basep = &TREE_OPERAND (def_rhs, 0);
913           tree new_offset, new_base, saved, new_rhs;
914           while (handled_component_p (*def_rhs_basep))
915             def_rhs_basep = &TREE_OPERAND (*def_rhs_basep, 0);
916           saved = *def_rhs_basep;
917           if (TREE_CODE (*def_rhs_basep) == MEM_REF)
918             {
919               new_base = TREE_OPERAND (*def_rhs_basep, 0);
920               new_offset = fold_convert (TREE_TYPE (TREE_OPERAND (rhs, 1)),
921                                          TREE_OPERAND (*def_rhs_basep, 1));
922             }
923           else
924             {
925               new_base = build_fold_addr_expr (*def_rhs_basep);
926               new_offset = TREE_OPERAND (rhs, 1);
927             }
928           *def_rhs_basep = build2 (MEM_REF, TREE_TYPE (*def_rhs_basep),
929                                    new_base, new_offset);
930           TREE_THIS_VOLATILE (*def_rhs_basep) = TREE_THIS_VOLATILE (rhs);
931           TREE_SIDE_EFFECTS (*def_rhs_basep) = TREE_SIDE_EFFECTS (rhs);
932           TREE_THIS_NOTRAP (*def_rhs_basep) = TREE_THIS_NOTRAP (rhs);
933           new_rhs = unshare_expr (TREE_OPERAND (def_rhs, 0));
934           *rhsp = new_rhs;
935           TREE_THIS_VOLATILE (new_rhs) = TREE_THIS_VOLATILE (rhs);
936           TREE_SIDE_EFFECTS (new_rhs) = TREE_SIDE_EFFECTS (rhs);
937           *def_rhs_basep = saved;
938           fold_stmt_inplace (use_stmt_gsi);
939           tidy_after_forward_propagate_addr (use_stmt);
940           return res;
941         }
942     }
943
944   /* If the use of the ADDR_EXPR is not a POINTER_PLUS_EXPR, there
945      is nothing to do. */
946   if (gimple_assign_rhs_code (use_stmt) != POINTER_PLUS_EXPR
947       || gimple_assign_rhs1 (use_stmt) != name)
948     return false;
949
950   /* The remaining cases are all for turning pointer arithmetic into
951      array indexing.  They only apply when we have the address of
952      element zero in an array.  If that is not the case then there
953      is nothing to do.  */
954   array_ref = TREE_OPERAND (def_rhs, 0);
955   if ((TREE_CODE (array_ref) != ARRAY_REF
956        || TREE_CODE (TREE_TYPE (TREE_OPERAND (array_ref, 0))) != ARRAY_TYPE
957        || TREE_CODE (TREE_OPERAND (array_ref, 1)) != INTEGER_CST)
958       && TREE_CODE (TREE_TYPE (array_ref)) != ARRAY_TYPE)
959     return false;
960
961   rhs2 = gimple_assign_rhs2 (use_stmt);
962   /* Optimize &x[C1] p+ C2 to  &x p+ C3 with C3 = C1 * element_size + C2.  */
963   if (TREE_CODE (rhs2) == INTEGER_CST)
964     {
965       tree new_rhs = build1_loc (gimple_location (use_stmt),
966                                  ADDR_EXPR, TREE_TYPE (def_rhs),
967                                  fold_build2 (MEM_REF,
968                                               TREE_TYPE (TREE_TYPE (def_rhs)),
969                                               unshare_expr (def_rhs),
970                                               fold_convert (ptr_type_node,
971                                                             rhs2)));
972       gimple_assign_set_rhs_from_tree (use_stmt_gsi, new_rhs);
973       use_stmt = gsi_stmt (*use_stmt_gsi);
974       update_stmt (use_stmt);
975       tidy_after_forward_propagate_addr (use_stmt);
976       return true;
977     }
978
979   return false;
980 }
981
982 /* STMT is a statement of the form SSA_NAME = ADDR_EXPR <whatever>.
983
984    Try to forward propagate the ADDR_EXPR into all uses of the SSA_NAME.
985    Often this will allow for removal of an ADDR_EXPR and INDIRECT_REF
986    node or for recovery of array indexing from pointer arithmetic.
987
988    PARENT_SINGLE_USE_P tells if, when in a recursive invocation, NAME was
989    the single use in the previous invocation.  Pass true when calling
990    this as toplevel.
991
992    Returns true, if all uses have been propagated into.  */
993
994 static bool
995 forward_propagate_addr_expr (tree name, tree rhs, bool parent_single_use_p)
996 {
997   imm_use_iterator iter;
998   gimple use_stmt;
999   bool all = true;
1000   bool single_use_p = parent_single_use_p && has_single_use (name);
1001
1002   FOR_EACH_IMM_USE_STMT (use_stmt, iter, name)
1003     {
1004       bool result;
1005       tree use_rhs;
1006
1007       /* If the use is not in a simple assignment statement, then
1008          there is nothing we can do.  */
1009       if (!is_gimple_assign (use_stmt))
1010         {
1011           if (!is_gimple_debug (use_stmt))
1012             all = false;
1013           continue;
1014         }
1015
1016       gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
1017       result = forward_propagate_addr_expr_1 (name, rhs, &gsi,
1018                                               single_use_p);
1019       /* If the use has moved to a different statement adjust
1020          the update machinery for the old statement too.  */
1021       if (use_stmt != gsi_stmt (gsi))
1022         {
1023           update_stmt (use_stmt);
1024           use_stmt = gsi_stmt (gsi);
1025         }
1026       update_stmt (use_stmt);
1027       all &= result;
1028
1029       /* Remove intermediate now unused copy and conversion chains.  */
1030       use_rhs = gimple_assign_rhs1 (use_stmt);
1031       if (result
1032           && TREE_CODE (gimple_assign_lhs (use_stmt)) == SSA_NAME
1033           && TREE_CODE (use_rhs) == SSA_NAME
1034           && has_zero_uses (gimple_assign_lhs (use_stmt)))
1035         {
1036           gimple_stmt_iterator gsi = gsi_for_stmt (use_stmt);
1037           fwprop_invalidate_lattice (gimple_get_lhs (use_stmt));
1038           release_defs (use_stmt);
1039           gsi_remove (&gsi, true);
1040         }
1041     }
1042
1043   return all && has_zero_uses (name);
1044 }
1045
1046
1047 /* Helper function for simplify_gimple_switch.  Remove case labels that
1048    have values outside the range of the new type.  */
1049
1050 static void
1051 simplify_gimple_switch_label_vec (gswitch *stmt, tree index_type)
1052 {
1053   unsigned int branch_num = gimple_switch_num_labels (stmt);
1054   auto_vec<tree> labels (branch_num);
1055   unsigned int i, len;
1056
1057   /* Collect the existing case labels in a VEC, and preprocess it as if
1058      we are gimplifying a GENERIC SWITCH_EXPR.  */
1059   for (i = 1; i < branch_num; i++)
1060     labels.quick_push (gimple_switch_label (stmt, i));
1061   preprocess_case_label_vec_for_gimple (labels, index_type, NULL);
1062
1063   /* If any labels were removed, replace the existing case labels
1064      in the GIMPLE_SWITCH statement with the correct ones.
1065      Note that the type updates were done in-place on the case labels,
1066      so we only have to replace the case labels in the GIMPLE_SWITCH
1067      if the number of labels changed.  */
1068   len = labels.length ();
1069   if (len < branch_num - 1)
1070     {
1071       bitmap target_blocks;
1072       edge_iterator ei;
1073       edge e;
1074
1075       /* Corner case: *all* case labels have been removed as being
1076          out-of-range for INDEX_TYPE.  Push one label and let the
1077          CFG cleanups deal with this further.  */
1078       if (len == 0)
1079         {
1080           tree label, elt;
1081
1082           label = CASE_LABEL (gimple_switch_default_label (stmt));
1083           elt = build_case_label (build_int_cst (index_type, 0), NULL, label);
1084           labels.quick_push (elt);
1085           len = 1;
1086         }
1087
1088       for (i = 0; i < labels.length (); i++)
1089         gimple_switch_set_label (stmt, i + 1, labels[i]);
1090       for (i++ ; i < branch_num; i++)
1091         gimple_switch_set_label (stmt, i, NULL_TREE);
1092       gimple_switch_set_num_labels (stmt, len + 1);
1093
1094       /* Cleanup any edges that are now dead.  */
1095       target_blocks = BITMAP_ALLOC (NULL);
1096       for (i = 0; i < gimple_switch_num_labels (stmt); i++)
1097         {
1098           tree elt = gimple_switch_label (stmt, i);
1099           basic_block target = label_to_block (CASE_LABEL (elt));
1100           bitmap_set_bit (target_blocks, target->index);
1101         }
1102       for (ei = ei_start (gimple_bb (stmt)->succs); (e = ei_safe_edge (ei)); )
1103         {
1104           if (! bitmap_bit_p (target_blocks, e->dest->index))
1105             {
1106               remove_edge (e);
1107               cfg_changed = true;
1108               free_dominance_info (CDI_DOMINATORS);
1109             }
1110           else
1111             ei_next (&ei);
1112         } 
1113       BITMAP_FREE (target_blocks);
1114     }
1115 }
1116
1117 /* STMT is a SWITCH_EXPR for which we attempt to find equivalent forms of
1118    the condition which we may be able to optimize better.  */
1119
1120 static bool
1121 simplify_gimple_switch (gswitch *stmt)
1122 {
1123   /* The optimization that we really care about is removing unnecessary
1124      casts.  That will let us do much better in propagating the inferred
1125      constant at the switch target.  */
1126   tree cond = gimple_switch_index (stmt);
1127   if (TREE_CODE (cond) == SSA_NAME)
1128     {
1129       gimple def_stmt = SSA_NAME_DEF_STMT (cond);
1130       if (gimple_assign_cast_p (def_stmt))
1131         {
1132           tree def = gimple_assign_rhs1 (def_stmt);
1133           if (TREE_CODE (def) != SSA_NAME)
1134             return false;
1135
1136           /* If we have an extension or sign-change that preserves the
1137              values we check against then we can copy the source value into
1138              the switch.  */
1139           tree ti = TREE_TYPE (def);
1140           if (INTEGRAL_TYPE_P (ti)
1141               && TYPE_PRECISION (ti) <= TYPE_PRECISION (TREE_TYPE (cond)))
1142             {
1143               size_t n = gimple_switch_num_labels (stmt);
1144               tree min = NULL_TREE, max = NULL_TREE;
1145               if (n > 1)
1146                 {
1147                   min = CASE_LOW (gimple_switch_label (stmt, 1));
1148                   if (CASE_HIGH (gimple_switch_label (stmt, n - 1)))
1149                     max = CASE_HIGH (gimple_switch_label (stmt, n - 1));
1150                   else
1151                     max = CASE_LOW (gimple_switch_label (stmt, n - 1));
1152                 }
1153               if ((!min || int_fits_type_p (min, ti))
1154                   && (!max || int_fits_type_p (max, ti)))
1155                 {
1156                   gimple_switch_set_index (stmt, def);
1157                   simplify_gimple_switch_label_vec (stmt, ti);
1158                   update_stmt (stmt);
1159                   return true;
1160                 }
1161             }
1162         }
1163     }
1164
1165   return false;
1166 }
1167
1168 /* For pointers p2 and p1 return p2 - p1 if the
1169    difference is known and constant, otherwise return NULL.  */
1170
1171 static tree
1172 constant_pointer_difference (tree p1, tree p2)
1173 {
1174   int i, j;
1175 #define CPD_ITERATIONS 5
1176   tree exps[2][CPD_ITERATIONS];
1177   tree offs[2][CPD_ITERATIONS];
1178   int cnt[2];
1179
1180   for (i = 0; i < 2; i++)
1181     {
1182       tree p = i ? p1 : p2;
1183       tree off = size_zero_node;
1184       gimple stmt;
1185       enum tree_code code;
1186
1187       /* For each of p1 and p2 we need to iterate at least
1188          twice, to handle ADDR_EXPR directly in p1/p2,
1189          SSA_NAME with ADDR_EXPR or POINTER_PLUS_EXPR etc.
1190          on definition's stmt RHS.  Iterate a few extra times.  */
1191       j = 0;
1192       do
1193         {
1194           if (!POINTER_TYPE_P (TREE_TYPE (p)))
1195             break;
1196           if (TREE_CODE (p) == ADDR_EXPR)
1197             {
1198               tree q = TREE_OPERAND (p, 0);
1199               HOST_WIDE_INT offset;
1200               tree base = get_addr_base_and_unit_offset (q, &offset);
1201               if (base)
1202                 {
1203                   q = base;
1204                   if (offset)
1205                     off = size_binop (PLUS_EXPR, off, size_int (offset));
1206                 }
1207               if (TREE_CODE (q) == MEM_REF
1208                   && TREE_CODE (TREE_OPERAND (q, 0)) == SSA_NAME)
1209                 {
1210                   p = TREE_OPERAND (q, 0);
1211                   off = size_binop (PLUS_EXPR, off,
1212                                     wide_int_to_tree (sizetype,
1213                                                       mem_ref_offset (q)));
1214                 }
1215               else
1216                 {
1217                   exps[i][j] = q;
1218                   offs[i][j++] = off;
1219                   break;
1220                 }
1221             }
1222           if (TREE_CODE (p) != SSA_NAME)
1223             break;
1224           exps[i][j] = p;
1225           offs[i][j++] = off;
1226           if (j == CPD_ITERATIONS)
1227             break;
1228           stmt = SSA_NAME_DEF_STMT (p);
1229           if (!is_gimple_assign (stmt) || gimple_assign_lhs (stmt) != p)
1230             break;
1231           code = gimple_assign_rhs_code (stmt);
1232           if (code == POINTER_PLUS_EXPR)
1233             {
1234               if (TREE_CODE (gimple_assign_rhs2 (stmt)) != INTEGER_CST)
1235                 break;
1236               off = size_binop (PLUS_EXPR, off, gimple_assign_rhs2 (stmt));
1237               p = gimple_assign_rhs1 (stmt);
1238             }
1239           else if (code == ADDR_EXPR || CONVERT_EXPR_CODE_P (code))
1240             p = gimple_assign_rhs1 (stmt);
1241           else
1242             break;
1243         }
1244       while (1);
1245       cnt[i] = j;
1246     }
1247
1248   for (i = 0; i < cnt[0]; i++)
1249     for (j = 0; j < cnt[1]; j++)
1250       if (exps[0][i] == exps[1][j])
1251         return size_binop (MINUS_EXPR, offs[0][i], offs[1][j]);
1252
1253   return NULL_TREE;
1254 }
1255
1256 /* *GSI_P is a GIMPLE_CALL to a builtin function.
1257    Optimize
1258    memcpy (p, "abcd", 4);
1259    memset (p + 4, ' ', 3);
1260    into
1261    memcpy (p, "abcd   ", 7);
1262    call if the latter can be stored by pieces during expansion.  */
1263
1264 static bool
1265 simplify_builtin_call (gimple_stmt_iterator *gsi_p, tree callee2)
1266 {
1267   gimple stmt1, stmt2 = gsi_stmt (*gsi_p);
1268   tree vuse = gimple_vuse (stmt2);
1269   if (vuse == NULL)
1270     return false;
1271   stmt1 = SSA_NAME_DEF_STMT (vuse);
1272
1273   switch (DECL_FUNCTION_CODE (callee2))
1274     {
1275     case BUILT_IN_MEMSET:
1276       if (gimple_call_num_args (stmt2) != 3
1277           || gimple_call_lhs (stmt2)
1278           || CHAR_BIT != 8
1279           || BITS_PER_UNIT != 8)
1280         break;
1281       else
1282         {
1283           tree callee1;
1284           tree ptr1, src1, str1, off1, len1, lhs1;
1285           tree ptr2 = gimple_call_arg (stmt2, 0);
1286           tree val2 = gimple_call_arg (stmt2, 1);
1287           tree len2 = gimple_call_arg (stmt2, 2);
1288           tree diff, vdef, new_str_cst;
1289           gimple use_stmt;
1290           unsigned int ptr1_align;
1291           unsigned HOST_WIDE_INT src_len;
1292           char *src_buf;
1293           use_operand_p use_p;
1294
1295           if (!tree_fits_shwi_p (val2)
1296               || !tree_fits_uhwi_p (len2)
1297               || compare_tree_int (len2, 1024) == 1)
1298             break;
1299           if (is_gimple_call (stmt1))
1300             {
1301               /* If first stmt is a call, it needs to be memcpy
1302                  or mempcpy, with string literal as second argument and
1303                  constant length.  */
1304               callee1 = gimple_call_fndecl (stmt1);
1305               if (callee1 == NULL_TREE
1306                   || DECL_BUILT_IN_CLASS (callee1) != BUILT_IN_NORMAL
1307                   || gimple_call_num_args (stmt1) != 3)
1308                 break;
1309               if (DECL_FUNCTION_CODE (callee1) != BUILT_IN_MEMCPY
1310                   && DECL_FUNCTION_CODE (callee1) != BUILT_IN_MEMPCPY)
1311                 break;
1312               ptr1 = gimple_call_arg (stmt1, 0);
1313               src1 = gimple_call_arg (stmt1, 1);
1314               len1 = gimple_call_arg (stmt1, 2);
1315               lhs1 = gimple_call_lhs (stmt1);
1316               if (!tree_fits_uhwi_p (len1))
1317                 break;
1318               str1 = string_constant (src1, &off1);
1319               if (str1 == NULL_TREE)
1320                 break;
1321               if (!tree_fits_uhwi_p (off1)
1322                   || compare_tree_int (off1, TREE_STRING_LENGTH (str1) - 1) > 0
1323                   || compare_tree_int (len1, TREE_STRING_LENGTH (str1)
1324                                              - tree_to_uhwi (off1)) > 0
1325                   || TREE_CODE (TREE_TYPE (str1)) != ARRAY_TYPE
1326                   || TYPE_MODE (TREE_TYPE (TREE_TYPE (str1)))
1327                      != TYPE_MODE (char_type_node))
1328                 break;
1329             }
1330           else if (gimple_assign_single_p (stmt1))
1331             {
1332               /* Otherwise look for length 1 memcpy optimized into
1333                  assignment.  */
1334               ptr1 = gimple_assign_lhs (stmt1);
1335               src1 = gimple_assign_rhs1 (stmt1);
1336               if (TREE_CODE (ptr1) != MEM_REF
1337                   || TYPE_MODE (TREE_TYPE (ptr1)) != TYPE_MODE (char_type_node)
1338                   || !tree_fits_shwi_p (src1))
1339                 break;
1340               ptr1 = build_fold_addr_expr (ptr1);
1341               callee1 = NULL_TREE;
1342               len1 = size_one_node;
1343               lhs1 = NULL_TREE;
1344               off1 = size_zero_node;
1345               str1 = NULL_TREE;
1346             }
1347           else
1348             break;
1349
1350           diff = constant_pointer_difference (ptr1, ptr2);
1351           if (diff == NULL && lhs1 != NULL)
1352             {
1353               diff = constant_pointer_difference (lhs1, ptr2);
1354               if (DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY
1355                   && diff != NULL)
1356                 diff = size_binop (PLUS_EXPR, diff,
1357                                    fold_convert (sizetype, len1));
1358             }
1359           /* If the difference between the second and first destination pointer
1360              is not constant, or is bigger than memcpy length, bail out.  */
1361           if (diff == NULL
1362               || !tree_fits_uhwi_p (diff)
1363               || tree_int_cst_lt (len1, diff)
1364               || compare_tree_int (diff, 1024) == 1)
1365             break;
1366
1367           /* Use maximum of difference plus memset length and memcpy length
1368              as the new memcpy length, if it is too big, bail out.  */
1369           src_len = tree_to_uhwi (diff);
1370           src_len += tree_to_uhwi (len2);
1371           if (src_len < tree_to_uhwi (len1))
1372             src_len = tree_to_uhwi (len1);
1373           if (src_len > 1024)
1374             break;
1375
1376           /* If mempcpy value is used elsewhere, bail out, as mempcpy
1377              with bigger length will return different result.  */
1378           if (lhs1 != NULL_TREE
1379               && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY
1380               && (TREE_CODE (lhs1) != SSA_NAME
1381                   || !single_imm_use (lhs1, &use_p, &use_stmt)
1382                   || use_stmt != stmt2))
1383             break;
1384
1385           /* If anything reads memory in between memcpy and memset
1386              call, the modified memcpy call might change it.  */
1387           vdef = gimple_vdef (stmt1);
1388           if (vdef != NULL
1389               && (!single_imm_use (vdef, &use_p, &use_stmt)
1390                   || use_stmt != stmt2))
1391             break;
1392
1393           ptr1_align = get_pointer_alignment (ptr1);
1394           /* Construct the new source string literal.  */
1395           src_buf = XALLOCAVEC (char, src_len + 1);
1396           if (callee1)
1397             memcpy (src_buf,
1398                     TREE_STRING_POINTER (str1) + tree_to_uhwi (off1),
1399                     tree_to_uhwi (len1));
1400           else
1401             src_buf[0] = tree_to_shwi (src1);
1402           memset (src_buf + tree_to_uhwi (diff),
1403                   tree_to_shwi (val2), tree_to_uhwi (len2));
1404           src_buf[src_len] = '\0';
1405           /* Neither builtin_strncpy_read_str nor builtin_memcpy_read_str
1406              handle embedded '\0's.  */
1407           if (strlen (src_buf) != src_len)
1408             break;
1409           rtl_profile_for_bb (gimple_bb (stmt2));
1410           /* If the new memcpy wouldn't be emitted by storing the literal
1411              by pieces, this optimization might enlarge .rodata too much,
1412              as commonly used string literals couldn't be shared any
1413              longer.  */
1414           if (!can_store_by_pieces (src_len,
1415                                     builtin_strncpy_read_str,
1416                                     src_buf, ptr1_align, false))
1417             break;
1418
1419           new_str_cst = build_string_literal (src_len, src_buf);
1420           if (callee1)
1421             {
1422               /* If STMT1 is a mem{,p}cpy call, adjust it and remove
1423                  memset call.  */
1424               if (lhs1 && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY)
1425                 gimple_call_set_lhs (stmt1, NULL_TREE);
1426               gimple_call_set_arg (stmt1, 1, new_str_cst);
1427               gimple_call_set_arg (stmt1, 2,
1428                                    build_int_cst (TREE_TYPE (len1), src_len));
1429               update_stmt (stmt1);
1430               unlink_stmt_vdef (stmt2);
1431               gsi_remove (gsi_p, true);
1432               fwprop_invalidate_lattice (gimple_get_lhs (stmt2));
1433               release_defs (stmt2);
1434               if (lhs1 && DECL_FUNCTION_CODE (callee1) == BUILT_IN_MEMPCPY)
1435                 {
1436                   fwprop_invalidate_lattice (lhs1);
1437                   release_ssa_name (lhs1);
1438                 }
1439               return true;
1440             }
1441           else
1442             {
1443               /* Otherwise, if STMT1 is length 1 memcpy optimized into
1444                  assignment, remove STMT1 and change memset call into
1445                  memcpy call.  */
1446               gimple_stmt_iterator gsi = gsi_for_stmt (stmt1);
1447
1448               if (!is_gimple_val (ptr1))
1449                 ptr1 = force_gimple_operand_gsi (gsi_p, ptr1, true, NULL_TREE,
1450                                                  true, GSI_SAME_STMT);
1451               gimple_call_set_fndecl (stmt2,
1452                                       builtin_decl_explicit (BUILT_IN_MEMCPY));
1453               gimple_call_set_arg (stmt2, 0, ptr1);
1454               gimple_call_set_arg (stmt2, 1, new_str_cst);
1455               gimple_call_set_arg (stmt2, 2,
1456                                    build_int_cst (TREE_TYPE (len2), src_len));
1457               unlink_stmt_vdef (stmt1);
1458               gsi_remove (&gsi, true);
1459               fwprop_invalidate_lattice (gimple_get_lhs (stmt1));
1460               release_defs (stmt1);
1461               update_stmt (stmt2);
1462               return false;
1463             }
1464         }
1465       break;
1466     default:
1467       break;
1468     }
1469   return false;
1470 }
1471
1472 /* Given a ssa_name in NAME see if it was defined by an assignment and
1473    set CODE to be the code and ARG1 to the first operand on the rhs and ARG2
1474    to the second operand on the rhs. */
1475
1476 static inline void
1477 defcodefor_name (tree name, enum tree_code *code, tree *arg1, tree *arg2)
1478 {
1479   gimple def;
1480   enum tree_code code1;
1481   tree arg11;
1482   tree arg21;
1483   tree arg31;
1484   enum gimple_rhs_class grhs_class;
1485
1486   code1 = TREE_CODE (name);
1487   arg11 = name;
1488   arg21 = NULL_TREE;
1489   grhs_class = get_gimple_rhs_class (code1);
1490
1491   if (code1 == SSA_NAME)
1492     {
1493       def = SSA_NAME_DEF_STMT (name);
1494       
1495       if (def && is_gimple_assign (def)
1496           && can_propagate_from (def))
1497         {
1498           code1 = gimple_assign_rhs_code (def);
1499           arg11 = gimple_assign_rhs1 (def);
1500           arg21 = gimple_assign_rhs2 (def);
1501           arg31 = gimple_assign_rhs2 (def);
1502         }
1503     }
1504   else if (grhs_class == GIMPLE_TERNARY_RHS
1505            || GIMPLE_BINARY_RHS
1506            || GIMPLE_UNARY_RHS
1507            || GIMPLE_SINGLE_RHS)
1508     extract_ops_from_tree_1 (name, &code1, &arg11, &arg21, &arg31);
1509
1510   *code = code1;
1511   *arg1 = arg11;
1512   if (arg2)
1513     *arg2 = arg21;
1514   /* Ignore arg3 currently. */
1515 }
1516
1517
1518 /* Recognize rotation patterns.  Return true if a transformation
1519    applied, otherwise return false.
1520
1521    We are looking for X with unsigned type T with bitsize B, OP being
1522    +, | or ^, some type T2 wider than T and
1523    (X << CNT1) OP (X >> CNT2)                           iff CNT1 + CNT2 == B
1524    ((T) ((T2) X << CNT1)) OP ((T) ((T2) X >> CNT2))     iff CNT1 + CNT2 == B
1525    (X << Y) OP (X >> (B - Y))
1526    (X << (int) Y) OP (X >> (int) (B - Y))
1527    ((T) ((T2) X << Y)) OP ((T) ((T2) X >> (B - Y)))
1528    ((T) ((T2) X << (int) Y)) OP ((T) ((T2) X >> (int) (B - Y)))
1529    (X << Y) | (X >> ((-Y) & (B - 1)))
1530    (X << (int) Y) | (X >> (int) ((-Y) & (B - 1)))
1531    ((T) ((T2) X << Y)) | ((T) ((T2) X >> ((-Y) & (B - 1))))
1532    ((T) ((T2) X << (int) Y)) | ((T) ((T2) X >> (int) ((-Y) & (B - 1))))
1533
1534    and transform these into:
1535    X r<< CNT1
1536    X r<< Y
1537
1538    Note, in the patterns with T2 type, the type of OP operands
1539    might be even a signed type, but should have precision B.  */
1540
1541 static bool
1542 simplify_rotate (gimple_stmt_iterator *gsi)
1543 {
1544   gimple stmt = gsi_stmt (*gsi);
1545   tree arg[2], rtype, rotcnt = NULL_TREE;
1546   tree def_arg1[2], def_arg2[2];
1547   enum tree_code def_code[2];
1548   tree lhs;
1549   int i;
1550   bool swapped_p = false;
1551   gimple g;
1552
1553   arg[0] = gimple_assign_rhs1 (stmt);
1554   arg[1] = gimple_assign_rhs2 (stmt);
1555   rtype = TREE_TYPE (arg[0]);
1556
1557   /* Only create rotates in complete modes.  Other cases are not
1558      expanded properly.  */
1559   if (!INTEGRAL_TYPE_P (rtype)
1560       || TYPE_PRECISION (rtype) != GET_MODE_PRECISION (TYPE_MODE (rtype)))
1561     return false;
1562
1563   for (i = 0; i < 2; i++)
1564     defcodefor_name (arg[i], &def_code[i], &def_arg1[i], &def_arg2[i]);
1565
1566   /* Look through narrowing conversions.  */
1567   if (CONVERT_EXPR_CODE_P (def_code[0])
1568       && CONVERT_EXPR_CODE_P (def_code[1])
1569       && INTEGRAL_TYPE_P (TREE_TYPE (def_arg1[0]))
1570       && INTEGRAL_TYPE_P (TREE_TYPE (def_arg1[1]))
1571       && TYPE_PRECISION (TREE_TYPE (def_arg1[0]))
1572          == TYPE_PRECISION (TREE_TYPE (def_arg1[1]))
1573       && TYPE_PRECISION (TREE_TYPE (def_arg1[0])) > TYPE_PRECISION (rtype)
1574       && has_single_use (arg[0])
1575       && has_single_use (arg[1]))
1576     {
1577       for (i = 0; i < 2; i++)
1578         {
1579           arg[i] = def_arg1[i];
1580           defcodefor_name (arg[i], &def_code[i], &def_arg1[i], &def_arg2[i]);
1581         }
1582     }
1583
1584   /* One operand has to be LSHIFT_EXPR and one RSHIFT_EXPR.  */
1585   for (i = 0; i < 2; i++)
1586     if (def_code[i] != LSHIFT_EXPR && def_code[i] != RSHIFT_EXPR)
1587       return false;
1588     else if (!has_single_use (arg[i]))
1589       return false;
1590   if (def_code[0] == def_code[1])
1591     return false;
1592
1593   /* If we've looked through narrowing conversions before, look through
1594      widening conversions from unsigned type with the same precision
1595      as rtype here.  */
1596   if (TYPE_PRECISION (TREE_TYPE (def_arg1[0])) != TYPE_PRECISION (rtype))
1597     for (i = 0; i < 2; i++)
1598       {
1599         tree tem;
1600         enum tree_code code;
1601         defcodefor_name (def_arg1[i], &code, &tem, NULL);
1602         if (!CONVERT_EXPR_CODE_P (code)
1603             || !INTEGRAL_TYPE_P (TREE_TYPE (tem))
1604             || TYPE_PRECISION (TREE_TYPE (tem)) != TYPE_PRECISION (rtype))
1605           return false;
1606         def_arg1[i] = tem;
1607       }
1608   /* Both shifts have to use the same first operand.  */
1609   if (TREE_CODE (def_arg1[0]) != SSA_NAME || def_arg1[0] != def_arg1[1])
1610     return false;
1611   if (!TYPE_UNSIGNED (TREE_TYPE (def_arg1[0])))
1612     return false;
1613
1614   /* CNT1 + CNT2 == B case above.  */
1615   if (tree_fits_uhwi_p (def_arg2[0])
1616       && tree_fits_uhwi_p (def_arg2[1])
1617       && tree_to_uhwi (def_arg2[0])
1618          + tree_to_uhwi (def_arg2[1]) == TYPE_PRECISION (rtype))
1619     rotcnt = def_arg2[0];
1620   else if (TREE_CODE (def_arg2[0]) != SSA_NAME
1621            || TREE_CODE (def_arg2[1]) != SSA_NAME)
1622     return false;
1623   else
1624     {
1625       tree cdef_arg1[2], cdef_arg2[2], def_arg2_alt[2];
1626       enum tree_code cdef_code[2];
1627       /* Look through conversion of the shift count argument.
1628          The C/C++ FE cast any shift count argument to integer_type_node.
1629          The only problem might be if the shift count type maximum value
1630          is equal or smaller than number of bits in rtype.  */
1631       for (i = 0; i < 2; i++)
1632         {
1633           def_arg2_alt[i] = def_arg2[i];
1634           defcodefor_name (def_arg2[i], &cdef_code[i],
1635                            &cdef_arg1[i], &cdef_arg2[i]);
1636           if (CONVERT_EXPR_CODE_P (cdef_code[i])
1637               && INTEGRAL_TYPE_P (TREE_TYPE (cdef_arg1[i]))
1638               && TYPE_PRECISION (TREE_TYPE (cdef_arg1[i]))
1639                  > floor_log2 (TYPE_PRECISION (rtype))
1640               && TYPE_PRECISION (TREE_TYPE (cdef_arg1[i]))
1641                  == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (cdef_arg1[i]))))
1642             {
1643               def_arg2_alt[i] = cdef_arg1[i];
1644               defcodefor_name (def_arg2_alt[i], &cdef_code[i],
1645                                &cdef_arg1[i], &cdef_arg2[i]);
1646             }
1647         }
1648       for (i = 0; i < 2; i++)
1649         /* Check for one shift count being Y and the other B - Y,
1650            with optional casts.  */
1651         if (cdef_code[i] == MINUS_EXPR
1652             && tree_fits_shwi_p (cdef_arg1[i])
1653             && tree_to_shwi (cdef_arg1[i]) == TYPE_PRECISION (rtype)
1654             && TREE_CODE (cdef_arg2[i]) == SSA_NAME)
1655           {
1656             tree tem;
1657             enum tree_code code;
1658
1659             if (cdef_arg2[i] == def_arg2[1 - i]
1660                 || cdef_arg2[i] == def_arg2_alt[1 - i])
1661               {
1662                 rotcnt = cdef_arg2[i];
1663                 break;
1664               }
1665             defcodefor_name (cdef_arg2[i], &code, &tem, NULL);
1666             if (CONVERT_EXPR_CODE_P (code)
1667                 && INTEGRAL_TYPE_P (TREE_TYPE (tem))
1668                 && TYPE_PRECISION (TREE_TYPE (tem))
1669                  > floor_log2 (TYPE_PRECISION (rtype))
1670                 && TYPE_PRECISION (TREE_TYPE (tem))
1671                  == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (tem)))
1672                 && (tem == def_arg2[1 - i]
1673                     || tem == def_arg2_alt[1 - i]))
1674               {
1675                 rotcnt = tem;
1676                 break;
1677               }
1678           }
1679         /* The above sequence isn't safe for Y being 0,
1680            because then one of the shifts triggers undefined behavior.
1681            This alternative is safe even for rotation count of 0.
1682            One shift count is Y and the other (-Y) & (B - 1).  */
1683         else if (cdef_code[i] == BIT_AND_EXPR
1684                  && tree_fits_shwi_p (cdef_arg2[i])
1685                  && tree_to_shwi (cdef_arg2[i])
1686                     == TYPE_PRECISION (rtype) - 1
1687                  && TREE_CODE (cdef_arg1[i]) == SSA_NAME
1688                  && gimple_assign_rhs_code (stmt) == BIT_IOR_EXPR)
1689           {
1690             tree tem;
1691             enum tree_code code;
1692
1693             defcodefor_name (cdef_arg1[i], &code, &tem, NULL);
1694             if (CONVERT_EXPR_CODE_P (code)
1695                 && INTEGRAL_TYPE_P (TREE_TYPE (tem))
1696                 && TYPE_PRECISION (TREE_TYPE (tem))
1697                  > floor_log2 (TYPE_PRECISION (rtype))
1698                 && TYPE_PRECISION (TREE_TYPE (tem))
1699                  == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (tem))))
1700               defcodefor_name (tem, &code, &tem, NULL);
1701
1702             if (code == NEGATE_EXPR)
1703               {
1704                 if (tem == def_arg2[1 - i] || tem == def_arg2_alt[1 - i])
1705                   {
1706                     rotcnt = tem;
1707                     break;
1708                   }
1709                 defcodefor_name (tem, &code, &tem, NULL);
1710                 if (CONVERT_EXPR_CODE_P (code)
1711                     && INTEGRAL_TYPE_P (TREE_TYPE (tem))
1712                     && TYPE_PRECISION (TREE_TYPE (tem))
1713                        > floor_log2 (TYPE_PRECISION (rtype))
1714                     && TYPE_PRECISION (TREE_TYPE (tem))
1715                        == GET_MODE_PRECISION (TYPE_MODE (TREE_TYPE (tem)))
1716                     && (tem == def_arg2[1 - i]
1717                         || tem == def_arg2_alt[1 - i]))
1718                   {
1719                     rotcnt = tem;
1720                     break;
1721                   }
1722               }
1723           }
1724       if (rotcnt == NULL_TREE)
1725         return false;
1726       swapped_p = i != 1;
1727     }
1728
1729   if (!useless_type_conversion_p (TREE_TYPE (def_arg2[0]),
1730                                   TREE_TYPE (rotcnt)))
1731     {
1732       g = gimple_build_assign (make_ssa_name (TREE_TYPE (def_arg2[0])),
1733                                NOP_EXPR, rotcnt);
1734       gsi_insert_before (gsi, g, GSI_SAME_STMT);
1735       rotcnt = gimple_assign_lhs (g);
1736     }
1737   lhs = gimple_assign_lhs (stmt);
1738   if (!useless_type_conversion_p (rtype, TREE_TYPE (def_arg1[0])))
1739     lhs = make_ssa_name (TREE_TYPE (def_arg1[0]));
1740   g = gimple_build_assign (lhs,
1741                            ((def_code[0] == LSHIFT_EXPR) ^ swapped_p)
1742                            ? LROTATE_EXPR : RROTATE_EXPR, def_arg1[0], rotcnt);
1743   if (!useless_type_conversion_p (rtype, TREE_TYPE (def_arg1[0])))
1744     {
1745       gsi_insert_before (gsi, g, GSI_SAME_STMT);
1746       g = gimple_build_assign (gimple_assign_lhs (stmt), NOP_EXPR, lhs);
1747     }
1748   gsi_replace (gsi, g, false);
1749   return true;
1750 }
1751
1752 /* Combine an element access with a shuffle.  Returns true if there were
1753    any changes made, else it returns false.  */
1754  
1755 static bool
1756 simplify_bitfield_ref (gimple_stmt_iterator *gsi)
1757 {
1758   gimple stmt = gsi_stmt (*gsi);
1759   gimple def_stmt;
1760   tree op, op0, op1, op2;
1761   tree elem_type;
1762   unsigned idx, n, size;
1763   enum tree_code code;
1764
1765   op = gimple_assign_rhs1 (stmt);
1766   gcc_checking_assert (TREE_CODE (op) == BIT_FIELD_REF);
1767
1768   op0 = TREE_OPERAND (op, 0);
1769   if (TREE_CODE (op0) != SSA_NAME
1770       || TREE_CODE (TREE_TYPE (op0)) != VECTOR_TYPE)
1771     return false;
1772
1773   def_stmt = get_prop_source_stmt (op0, false, NULL);
1774   if (!def_stmt || !can_propagate_from (def_stmt))
1775     return false;
1776
1777   op1 = TREE_OPERAND (op, 1);
1778   op2 = TREE_OPERAND (op, 2);
1779   code = gimple_assign_rhs_code (def_stmt);
1780
1781   if (code == CONSTRUCTOR)
1782     {
1783       tree tem = fold_ternary (BIT_FIELD_REF, TREE_TYPE (op),
1784                                gimple_assign_rhs1 (def_stmt), op1, op2);
1785       if (!tem || !valid_gimple_rhs_p (tem))
1786         return false;
1787       gimple_assign_set_rhs_from_tree (gsi, tem);
1788       update_stmt (gsi_stmt (*gsi));
1789       return true;
1790     }
1791
1792   elem_type = TREE_TYPE (TREE_TYPE (op0));
1793   if (TREE_TYPE (op) != elem_type)
1794     return false;
1795
1796   size = TREE_INT_CST_LOW (TYPE_SIZE (elem_type));
1797   n = TREE_INT_CST_LOW (op1) / size;
1798   if (n != 1)
1799     return false;
1800   idx = TREE_INT_CST_LOW (op2) / size;
1801
1802   if (code == VEC_PERM_EXPR)
1803     {
1804       tree p, m, index, tem;
1805       unsigned nelts;
1806       m = gimple_assign_rhs3 (def_stmt);
1807       if (TREE_CODE (m) != VECTOR_CST)
1808         return false;
1809       nelts = VECTOR_CST_NELTS (m);
1810       idx = TREE_INT_CST_LOW (VECTOR_CST_ELT (m, idx));
1811       idx %= 2 * nelts;
1812       if (idx < nelts)
1813         {
1814           p = gimple_assign_rhs1 (def_stmt);
1815         }
1816       else
1817         {
1818           p = gimple_assign_rhs2 (def_stmt);
1819           idx -= nelts;
1820         }
1821       index = build_int_cst (TREE_TYPE (TREE_TYPE (m)), idx * size);
1822       tem = build3 (BIT_FIELD_REF, TREE_TYPE (op),
1823                     unshare_expr (p), op1, index);
1824       gimple_assign_set_rhs1 (stmt, tem);
1825       fold_stmt (gsi);
1826       update_stmt (gsi_stmt (*gsi));
1827       return true;
1828     }
1829
1830   return false;
1831 }
1832
1833 /* Determine whether applying the 2 permutations (mask1 then mask2)
1834    gives back one of the input.  */
1835
1836 static int
1837 is_combined_permutation_identity (tree mask1, tree mask2)
1838 {
1839   tree mask;
1840   unsigned int nelts, i, j;
1841   bool maybe_identity1 = true;
1842   bool maybe_identity2 = true;
1843
1844   gcc_checking_assert (TREE_CODE (mask1) == VECTOR_CST
1845                        && TREE_CODE (mask2) == VECTOR_CST);
1846   mask = fold_ternary (VEC_PERM_EXPR, TREE_TYPE (mask1), mask1, mask1, mask2);
1847   gcc_assert (TREE_CODE (mask) == VECTOR_CST);
1848
1849   nelts = VECTOR_CST_NELTS (mask);
1850   for (i = 0; i < nelts; i++)
1851     {
1852       tree val = VECTOR_CST_ELT (mask, i);
1853       gcc_assert (TREE_CODE (val) == INTEGER_CST);
1854       j = TREE_INT_CST_LOW (val) & (2 * nelts - 1);
1855       if (j == i)
1856         maybe_identity2 = false;
1857       else if (j == i + nelts)
1858         maybe_identity1 = false;
1859       else
1860         return 0;
1861     }
1862   return maybe_identity1 ? 1 : maybe_identity2 ? 2 : 0;
1863 }
1864
1865 /* Combine a shuffle with its arguments.  Returns 1 if there were any
1866    changes made, 2 if cfg-cleanup needs to run.  Else it returns 0.  */
1867  
1868 static int
1869 simplify_permutation (gimple_stmt_iterator *gsi)
1870 {
1871   gimple stmt = gsi_stmt (*gsi);
1872   gimple def_stmt;
1873   tree op0, op1, op2, op3, arg0, arg1;
1874   enum tree_code code;
1875   bool single_use_op0 = false;
1876
1877   gcc_checking_assert (gimple_assign_rhs_code (stmt) == VEC_PERM_EXPR);
1878
1879   op0 = gimple_assign_rhs1 (stmt);
1880   op1 = gimple_assign_rhs2 (stmt);
1881   op2 = gimple_assign_rhs3 (stmt);
1882
1883   if (TREE_CODE (op2) != VECTOR_CST)
1884     return 0;
1885
1886   if (TREE_CODE (op0) == VECTOR_CST)
1887     {
1888       code = VECTOR_CST;
1889       arg0 = op0;
1890     }
1891   else if (TREE_CODE (op0) == SSA_NAME)
1892     {
1893       def_stmt = get_prop_source_stmt (op0, false, &single_use_op0);
1894       if (!def_stmt || !can_propagate_from (def_stmt))
1895         return 0;
1896
1897       code = gimple_assign_rhs_code (def_stmt);
1898       arg0 = gimple_assign_rhs1 (def_stmt);
1899     }
1900   else
1901     return 0;
1902
1903   /* Two consecutive shuffles.  */
1904   if (code == VEC_PERM_EXPR)
1905     {
1906       tree orig;
1907       int ident;
1908
1909       if (op0 != op1)
1910         return 0;
1911       op3 = gimple_assign_rhs3 (def_stmt);
1912       if (TREE_CODE (op3) != VECTOR_CST)
1913         return 0;
1914       ident = is_combined_permutation_identity (op3, op2);
1915       if (!ident)
1916         return 0;
1917       orig = (ident == 1) ? gimple_assign_rhs1 (def_stmt)
1918                           : gimple_assign_rhs2 (def_stmt);
1919       gimple_assign_set_rhs1 (stmt, unshare_expr (orig));
1920       gimple_assign_set_rhs_code (stmt, TREE_CODE (orig));
1921       gimple_set_num_ops (stmt, 2);
1922       update_stmt (stmt);
1923       return remove_prop_source_from_use (op0) ? 2 : 1;
1924     }
1925
1926   /* Shuffle of a constructor.  */
1927   else if (code == CONSTRUCTOR || code == VECTOR_CST)
1928     {
1929       tree opt;
1930       bool ret = false;
1931       if (op0 != op1)
1932         {
1933           if (TREE_CODE (op0) == SSA_NAME && !single_use_op0)
1934             return 0;
1935
1936           if (TREE_CODE (op1) == VECTOR_CST)
1937             arg1 = op1;
1938           else if (TREE_CODE (op1) == SSA_NAME)
1939             {
1940               enum tree_code code2;
1941
1942               gimple def_stmt2 = get_prop_source_stmt (op1, true, NULL);
1943               if (!def_stmt2 || !can_propagate_from (def_stmt2))
1944                 return 0;
1945
1946               code2 = gimple_assign_rhs_code (def_stmt2);
1947               if (code2 != CONSTRUCTOR && code2 != VECTOR_CST)
1948                 return 0;
1949               arg1 = gimple_assign_rhs1 (def_stmt2);
1950             }
1951           else
1952             return 0;
1953         }
1954       else
1955         {
1956           /* Already used twice in this statement.  */
1957           if (TREE_CODE (op0) == SSA_NAME && num_imm_uses (op0) > 2)
1958             return 0;
1959           arg1 = arg0;
1960         }
1961       opt = fold_ternary (VEC_PERM_EXPR, TREE_TYPE (op0), arg0, arg1, op2);
1962       if (!opt
1963           || (TREE_CODE (opt) != CONSTRUCTOR && TREE_CODE (opt) != VECTOR_CST))
1964         return 0;
1965       gimple_assign_set_rhs_from_tree (gsi, opt);
1966       update_stmt (gsi_stmt (*gsi));
1967       if (TREE_CODE (op0) == SSA_NAME)
1968         ret = remove_prop_source_from_use (op0);
1969       if (op0 != op1 && TREE_CODE (op1) == SSA_NAME)
1970         ret |= remove_prop_source_from_use (op1);
1971       return ret ? 2 : 1;
1972     }
1973
1974   return 0;
1975 }
1976
1977 /* Recognize a VEC_PERM_EXPR.  Returns true if there were any changes.  */
1978
1979 static bool
1980 simplify_vector_constructor (gimple_stmt_iterator *gsi)
1981 {
1982   gimple stmt = gsi_stmt (*gsi);
1983   gimple def_stmt;
1984   tree op, op2, orig, type, elem_type;
1985   unsigned elem_size, nelts, i;
1986   enum tree_code code;
1987   constructor_elt *elt;
1988   unsigned char *sel;
1989   bool maybe_ident;
1990
1991   gcc_checking_assert (gimple_assign_rhs_code (stmt) == CONSTRUCTOR);
1992
1993   op = gimple_assign_rhs1 (stmt);
1994   type = TREE_TYPE (op);
1995   gcc_checking_assert (TREE_CODE (type) == VECTOR_TYPE);
1996
1997   nelts = TYPE_VECTOR_SUBPARTS (type);
1998   elem_type = TREE_TYPE (type);
1999   elem_size = TREE_INT_CST_LOW (TYPE_SIZE (elem_type));
2000
2001   sel = XALLOCAVEC (unsigned char, nelts);
2002   orig = NULL;
2003   maybe_ident = true;
2004   FOR_EACH_VEC_SAFE_ELT (CONSTRUCTOR_ELTS (op), i, elt)
2005     {
2006       tree ref, op1;
2007
2008       if (i >= nelts)
2009         return false;
2010
2011       if (TREE_CODE (elt->value) != SSA_NAME)
2012         return false;
2013       def_stmt = get_prop_source_stmt (elt->value, false, NULL);
2014       if (!def_stmt)
2015         return false;
2016       code = gimple_assign_rhs_code (def_stmt);
2017       if (code != BIT_FIELD_REF)
2018         return false;
2019       op1 = gimple_assign_rhs1 (def_stmt);
2020       ref = TREE_OPERAND (op1, 0);
2021       if (orig)
2022         {
2023           if (ref != orig)
2024             return false;
2025         }
2026       else
2027         {
2028           if (TREE_CODE (ref) != SSA_NAME)
2029             return false;
2030           if (!useless_type_conversion_p (type, TREE_TYPE (ref)))
2031             return false;
2032           orig = ref;
2033         }
2034       if (TREE_INT_CST_LOW (TREE_OPERAND (op1, 1)) != elem_size)
2035         return false;
2036       sel[i] = TREE_INT_CST_LOW (TREE_OPERAND (op1, 2)) / elem_size;
2037       if (sel[i] != i) maybe_ident = false;
2038     }
2039   if (i < nelts)
2040     return false;
2041
2042   if (maybe_ident)
2043     gimple_assign_set_rhs_from_tree (gsi, orig);
2044   else
2045     {
2046       tree mask_type, *mask_elts;
2047
2048       if (!can_vec_perm_p (TYPE_MODE (type), false, sel))
2049         return false;
2050       mask_type
2051         = build_vector_type (build_nonstandard_integer_type (elem_size, 1),
2052                              nelts);
2053       if (GET_MODE_CLASS (TYPE_MODE (mask_type)) != MODE_VECTOR_INT
2054           || GET_MODE_SIZE (TYPE_MODE (mask_type))
2055              != GET_MODE_SIZE (TYPE_MODE (type)))
2056         return false;
2057       mask_elts = XALLOCAVEC (tree, nelts);
2058       for (i = 0; i < nelts; i++)
2059         mask_elts[i] = build_int_cst (TREE_TYPE (mask_type), sel[i]);
2060       op2 = build_vector (mask_type, mask_elts);
2061       gimple_assign_set_rhs_with_ops (gsi, VEC_PERM_EXPR, orig, orig, op2);
2062     }
2063   update_stmt (gsi_stmt (*gsi));
2064   return true;
2065 }
2066
2067
2068 /* Primitive "lattice" function for gimple_simplify.  */
2069
2070 static tree
2071 fwprop_ssa_val (tree name)
2072 {
2073   /* First valueize NAME.  */
2074   if (TREE_CODE (name) == SSA_NAME
2075       && SSA_NAME_VERSION (name) < lattice.length ())
2076     {
2077       tree val = lattice[SSA_NAME_VERSION (name)];
2078       if (val)
2079         name = val;
2080     }
2081   /* We continue matching along SSA use-def edges for SSA names
2082      that are not single-use.  Currently there are no patterns
2083      that would cause any issues with that.  */
2084   return name;
2085 }
2086
2087 /* Main entry point for the forward propagation and statement combine
2088    optimizer.  */
2089
2090 namespace {
2091
2092 const pass_data pass_data_forwprop =
2093 {
2094   GIMPLE_PASS, /* type */
2095   "forwprop", /* name */
2096   OPTGROUP_NONE, /* optinfo_flags */
2097   TV_TREE_FORWPROP, /* tv_id */
2098   ( PROP_cfg | PROP_ssa ), /* properties_required */
2099   0, /* properties_provided */
2100   0, /* properties_destroyed */
2101   0, /* todo_flags_start */
2102   TODO_update_ssa, /* todo_flags_finish */
2103 };
2104
2105 class pass_forwprop : public gimple_opt_pass
2106 {
2107 public:
2108   pass_forwprop (gcc::context *ctxt)
2109     : gimple_opt_pass (pass_data_forwprop, ctxt)
2110   {}
2111
2112   /* opt_pass methods: */
2113   opt_pass * clone () { return new pass_forwprop (m_ctxt); }
2114   virtual bool gate (function *) { return flag_tree_forwprop; }
2115   virtual unsigned int execute (function *);
2116
2117 }; // class pass_forwprop
2118
2119 unsigned int
2120 pass_forwprop::execute (function *fun)
2121 {
2122   unsigned int todoflags = 0;
2123
2124   cfg_changed = false;
2125
2126   /* Combine stmts with the stmts defining their operands.  Do that
2127      in an order that guarantees visiting SSA defs before SSA uses.  */
2128   lattice.create (num_ssa_names);
2129   lattice.quick_grow_cleared (num_ssa_names);
2130   int *postorder = XNEWVEC (int, n_basic_blocks_for_fn (fun));
2131   int postorder_num = inverted_post_order_compute (postorder);
2132   auto_vec<gimple, 4> to_fixup;
2133   to_purge = BITMAP_ALLOC (NULL);
2134   for (int i = 0; i < postorder_num; ++i)
2135     {
2136       gimple_stmt_iterator gsi;
2137       basic_block bb = BASIC_BLOCK_FOR_FN (fun, postorder[i]);
2138
2139       /* Apply forward propagation to all stmts in the basic-block.
2140          Note we update GSI within the loop as necessary.  */
2141       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); )
2142         {
2143           gimple stmt = gsi_stmt (gsi);
2144           tree lhs, rhs;
2145           enum tree_code code;
2146
2147           if (!is_gimple_assign (stmt))
2148             {
2149               gsi_next (&gsi);
2150               continue;
2151             }
2152
2153           lhs = gimple_assign_lhs (stmt);
2154           rhs = gimple_assign_rhs1 (stmt);
2155           code = gimple_assign_rhs_code (stmt);
2156           if (TREE_CODE (lhs) != SSA_NAME
2157               || has_zero_uses (lhs))
2158             {
2159               gsi_next (&gsi);
2160               continue;
2161             }
2162
2163           /* If this statement sets an SSA_NAME to an address,
2164              try to propagate the address into the uses of the SSA_NAME.  */
2165           if (code == ADDR_EXPR
2166               /* Handle pointer conversions on invariant addresses
2167                  as well, as this is valid gimple.  */
2168               || (CONVERT_EXPR_CODE_P (code)
2169                   && TREE_CODE (rhs) == ADDR_EXPR
2170                   && POINTER_TYPE_P (TREE_TYPE (lhs))))
2171             {
2172               tree base = get_base_address (TREE_OPERAND (rhs, 0));
2173               if ((!base
2174                    || !DECL_P (base)
2175                    || decl_address_invariant_p (base))
2176                   && !stmt_references_abnormal_ssa_name (stmt)
2177                   && forward_propagate_addr_expr (lhs, rhs, true))
2178                 {
2179                   fwprop_invalidate_lattice (gimple_get_lhs (stmt));
2180                   release_defs (stmt);
2181                   gsi_remove (&gsi, true);
2182                 }
2183               else
2184                 gsi_next (&gsi);
2185             }
2186           else if (code == POINTER_PLUS_EXPR)
2187             {
2188               tree off = gimple_assign_rhs2 (stmt);
2189               if (TREE_CODE (off) == INTEGER_CST
2190                   && can_propagate_from (stmt)
2191                   && !simple_iv_increment_p (stmt)
2192                   /* ???  Better adjust the interface to that function
2193                      instead of building new trees here.  */
2194                   && forward_propagate_addr_expr
2195                        (lhs,
2196                         build1_loc (gimple_location (stmt),
2197                                     ADDR_EXPR, TREE_TYPE (rhs),
2198                                     fold_build2 (MEM_REF,
2199                                                  TREE_TYPE (TREE_TYPE (rhs)),
2200                                                  rhs,
2201                                                  fold_convert (ptr_type_node,
2202                                                                off))), true))
2203                 {
2204                   fwprop_invalidate_lattice (gimple_get_lhs (stmt));
2205                   release_defs (stmt);
2206                   gsi_remove (&gsi, true);
2207                 }
2208               else if (is_gimple_min_invariant (rhs))
2209                 {
2210                   /* Make sure to fold &a[0] + off_1 here.  */
2211                   fold_stmt_inplace (&gsi);
2212                   update_stmt (stmt);
2213                   if (gimple_assign_rhs_code (stmt) == POINTER_PLUS_EXPR)
2214                     gsi_next (&gsi);
2215                 }
2216               else
2217                 gsi_next (&gsi);
2218             }
2219           else if (TREE_CODE (TREE_TYPE (lhs)) == COMPLEX_TYPE
2220                    && gimple_assign_load_p (stmt)
2221                    && !gimple_has_volatile_ops (stmt)
2222                    && (TREE_CODE (gimple_assign_rhs1 (stmt))
2223                        != TARGET_MEM_REF)
2224                    && !stmt_can_throw_internal (stmt))
2225             {
2226               /* Rewrite loads used only in real/imagpart extractions to
2227                  component-wise loads.  */
2228               use_operand_p use_p;
2229               imm_use_iterator iter;
2230               bool rewrite = true;
2231               FOR_EACH_IMM_USE_FAST (use_p, iter, lhs)
2232                 {
2233                   gimple use_stmt = USE_STMT (use_p);
2234                   if (is_gimple_debug (use_stmt))
2235                     continue;
2236                   if (!is_gimple_assign (use_stmt)
2237                       || (gimple_assign_rhs_code (use_stmt) != REALPART_EXPR
2238                           && gimple_assign_rhs_code (use_stmt) != IMAGPART_EXPR))
2239                     {
2240                       rewrite = false;
2241                       break;
2242                     }
2243                 }
2244               if (rewrite)
2245                 {
2246                   gimple use_stmt;
2247                   FOR_EACH_IMM_USE_STMT (use_stmt, iter, lhs)
2248                     {
2249                       if (is_gimple_debug (use_stmt))
2250                         {
2251                           if (gimple_debug_bind_p (use_stmt))
2252                             {
2253                               gimple_debug_bind_reset_value (use_stmt);
2254                               update_stmt (use_stmt);
2255                             }
2256                           continue;
2257                         }
2258
2259                       tree new_rhs = build1 (gimple_assign_rhs_code (use_stmt),
2260                                              TREE_TYPE (TREE_TYPE (rhs)),
2261                                              unshare_expr (rhs));
2262                       gimple new_stmt
2263                         = gimple_build_assign (gimple_assign_lhs (use_stmt),
2264                                                new_rhs);
2265
2266                       location_t loc = gimple_location (use_stmt);
2267                       gimple_set_location (new_stmt, loc);
2268                       gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
2269                       unlink_stmt_vdef (use_stmt);
2270                       gsi_remove (&gsi2, true);
2271
2272                       gsi_insert_before (&gsi, new_stmt, GSI_SAME_STMT);
2273                     }
2274
2275                   release_defs (stmt);
2276                   gsi_remove (&gsi, true);
2277                 }
2278               else
2279                 gsi_next (&gsi);
2280             }
2281           else if (code == COMPLEX_EXPR)
2282             {
2283               /* Rewrite stores of a single-use complex build expression
2284                  to component-wise stores.  */
2285               use_operand_p use_p;
2286               gimple use_stmt;
2287               if (single_imm_use (lhs, &use_p, &use_stmt)
2288                   && gimple_store_p (use_stmt)
2289                   && !gimple_has_volatile_ops (use_stmt)
2290                   && is_gimple_assign (use_stmt)
2291                   && (TREE_CODE (gimple_assign_lhs (use_stmt))
2292                       != TARGET_MEM_REF))
2293                 {
2294                   tree use_lhs = gimple_assign_lhs (use_stmt);
2295                   tree new_lhs = build1 (REALPART_EXPR,
2296                                          TREE_TYPE (TREE_TYPE (use_lhs)),
2297                                          unshare_expr (use_lhs));
2298                   gimple new_stmt = gimple_build_assign (new_lhs, rhs);
2299                   location_t loc = gimple_location (use_stmt);
2300                   gimple_set_location (new_stmt, loc);
2301                   gimple_set_vuse (new_stmt, gimple_vuse (use_stmt));
2302                   gimple_set_vdef (new_stmt, make_ssa_name (gimple_vop (cfun)));
2303                   SSA_NAME_DEF_STMT (gimple_vdef (new_stmt)) = new_stmt;
2304                   gimple_set_vuse (use_stmt, gimple_vdef (new_stmt));
2305                   gimple_stmt_iterator gsi2 = gsi_for_stmt (use_stmt);
2306                   gsi_insert_before (&gsi2, new_stmt, GSI_SAME_STMT);
2307
2308                   new_lhs = build1 (IMAGPART_EXPR,
2309                                     TREE_TYPE (TREE_TYPE (use_lhs)),
2310                                     unshare_expr (use_lhs));
2311                   gimple_assign_set_lhs (use_stmt, new_lhs);
2312                   gimple_assign_set_rhs1 (use_stmt, gimple_assign_rhs2 (stmt));
2313                   update_stmt (use_stmt);
2314
2315                   release_defs (stmt);
2316                   gsi_remove (&gsi, true);
2317                 }
2318               else
2319                 gsi_next (&gsi);
2320             }
2321           else
2322             gsi_next (&gsi);
2323         }
2324
2325       /* Combine stmts with the stmts defining their operands.
2326          Note we update GSI within the loop as necessary.  */
2327       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
2328         {
2329           gimple stmt = gsi_stmt (gsi);
2330           gimple orig_stmt = stmt;
2331           bool changed = false;
2332           bool was_noreturn = (is_gimple_call (stmt)
2333                                && gimple_call_noreturn_p (stmt));
2334
2335           /* Mark stmt as potentially needing revisiting.  */
2336           gimple_set_plf (stmt, GF_PLF_1, false);
2337
2338           if (fold_stmt (&gsi, fwprop_ssa_val))
2339             {
2340               changed = true;
2341               stmt = gsi_stmt (gsi);
2342               if (maybe_clean_or_replace_eh_stmt (orig_stmt, stmt))
2343                 bitmap_set_bit (to_purge, bb->index);
2344               if (!was_noreturn
2345                   && is_gimple_call (stmt) && gimple_call_noreturn_p (stmt))
2346                 to_fixup.safe_push (stmt);
2347               /* Cleanup the CFG if we simplified a condition to
2348                  true or false.  */
2349               if (gcond *cond = dyn_cast <gcond *> (stmt))
2350                 if (gimple_cond_true_p (cond)
2351                     || gimple_cond_false_p (cond))
2352                   cfg_changed = true;
2353               update_stmt (stmt);
2354             }
2355
2356           switch (gimple_code (stmt))
2357             {
2358             case GIMPLE_ASSIGN:
2359               {
2360                 tree rhs1 = gimple_assign_rhs1 (stmt);
2361                 enum tree_code code = gimple_assign_rhs_code (stmt);
2362
2363                 if (code == COND_EXPR
2364                     || code == VEC_COND_EXPR)
2365                   {
2366                     /* In this case the entire COND_EXPR is in rhs1. */
2367                     if (forward_propagate_into_cond (&gsi))
2368                       {
2369                         changed = true;
2370                         stmt = gsi_stmt (gsi);
2371                       }
2372                   }
2373                 else if (TREE_CODE_CLASS (code) == tcc_comparison)
2374                   {
2375                     int did_something;
2376                     did_something = forward_propagate_into_comparison (&gsi);
2377                     if (did_something == 2)
2378                       cfg_changed = true;
2379                     changed = did_something != 0;
2380                   }
2381                 else if ((code == PLUS_EXPR
2382                           || code == BIT_IOR_EXPR
2383                           || code == BIT_XOR_EXPR)
2384                          && simplify_rotate (&gsi))
2385                   changed = true;
2386                 else if (code == VEC_PERM_EXPR)
2387                   {
2388                     int did_something = simplify_permutation (&gsi);
2389                     if (did_something == 2)
2390                       cfg_changed = true;
2391                     changed = did_something != 0;
2392                   }
2393                 else if (code == BIT_FIELD_REF)
2394                   changed = simplify_bitfield_ref (&gsi);
2395                 else if (code == CONSTRUCTOR
2396                          && TREE_CODE (TREE_TYPE (rhs1)) == VECTOR_TYPE)
2397                   changed = simplify_vector_constructor (&gsi);
2398                 break;
2399               }
2400
2401             case GIMPLE_SWITCH:
2402               changed = simplify_gimple_switch (as_a <gswitch *> (stmt));
2403               break;
2404
2405             case GIMPLE_COND:
2406               {
2407                 int did_something
2408                   = forward_propagate_into_gimple_cond (as_a <gcond *> (stmt));
2409                 if (did_something == 2)
2410                   cfg_changed = true;
2411                 changed = did_something != 0;
2412                 break;
2413               }
2414
2415             case GIMPLE_CALL:
2416               {
2417                 tree callee = gimple_call_fndecl (stmt);
2418                 if (callee != NULL_TREE
2419                     && DECL_BUILT_IN_CLASS (callee) == BUILT_IN_NORMAL)
2420                   changed = simplify_builtin_call (&gsi, callee);
2421                 break;
2422               }
2423
2424             default:;
2425             }
2426
2427           if (changed)
2428             {
2429               /* If the stmt changed then re-visit it and the statements
2430                  inserted before it.  */
2431               for (; !gsi_end_p (gsi); gsi_prev (&gsi))
2432                 if (gimple_plf (gsi_stmt (gsi), GF_PLF_1))
2433                   break;
2434               if (gsi_end_p (gsi))
2435                 gsi = gsi_start_bb (bb);
2436               else
2437                 gsi_next (&gsi);
2438             }
2439           else
2440             {
2441               /* Stmt no longer needs to be revisited.  */
2442               gimple_set_plf (stmt, GF_PLF_1, true);
2443
2444               /* Fill up the lattice.  */
2445               if (gimple_assign_single_p (stmt))
2446                 {
2447                   tree lhs = gimple_assign_lhs (stmt);
2448                   tree rhs = gimple_assign_rhs1 (stmt);
2449                   if (TREE_CODE (lhs) == SSA_NAME)
2450                     {
2451                       tree val = lhs;
2452                       if (TREE_CODE (rhs) == SSA_NAME)
2453                         val = fwprop_ssa_val (rhs);
2454                       else if (is_gimple_min_invariant (rhs))
2455                         val = rhs;
2456                       fwprop_set_lattice_val (lhs, val);
2457                     }
2458                 }
2459
2460               gsi_next (&gsi);
2461             }
2462         }
2463     }
2464   free (postorder);
2465   lattice.release ();
2466
2467   /* Fixup stmts that became noreturn calls.  This may require splitting
2468      blocks and thus isn't possible during the walk.  Do this
2469      in reverse order so we don't inadvertedly remove a stmt we want to
2470      fixup by visiting a dominating now noreturn call first.  */
2471   while (!to_fixup.is_empty ())
2472     {
2473       gimple stmt = to_fixup.pop ();
2474       if (dump_file && dump_flags & TDF_DETAILS)
2475         {
2476           fprintf (dump_file, "Fixing up noreturn call ");
2477           print_gimple_stmt (dump_file, stmt, 0, 0);
2478           fprintf (dump_file, "\n");
2479         }
2480       cfg_changed |= fixup_noreturn_call (stmt);
2481     }
2482
2483   cfg_changed |= gimple_purge_all_dead_eh_edges (to_purge);
2484   BITMAP_FREE (to_purge);
2485
2486   if (cfg_changed)
2487     todoflags |= TODO_cleanup_cfg;
2488
2489   return todoflags;
2490 }
2491
2492 } // anon namespace
2493
2494 gimple_opt_pass *
2495 make_pass_forwprop (gcc::context *ctxt)
2496 {
2497   return new pass_forwprop (ctxt);
2498 }