[RTL-ifcvt] Make non-conditional execution if-conversion more aggressive
[platform/upstream/gcc.git] / gcc / ifcvt.c
1 /* If-conversion support.
2    Copyright (C) 2000-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 it
7    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, but WITHOUT
12    ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
13    or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public
14    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 "backend.h"
24 #include "cfghooks.h"
25 #include "tree.h"
26 #include "rtl.h"
27 #include "df.h"
28
29 #include "regs.h"
30 #include "flags.h"
31 #include "insn-config.h"
32 #include "recog.h"
33 #include "except.h"
34 #include "cfgrtl.h"
35 #include "cfganal.h"
36 #include "cfgcleanup.h"
37 #include "alias.h"
38 #include "expmed.h"
39 #include "dojump.h"
40 #include "explow.h"
41 #include "calls.h"
42 #include "emit-rtl.h"
43 #include "varasm.h"
44 #include "stmt.h"
45 #include "expr.h"
46 #include "output.h"
47 #include "insn-codes.h"
48 #include "optabs.h"
49 #include "diagnostic-core.h"
50 #include "tm_p.h"
51 #include "cfgloop.h"
52 #include "target.h"
53 #include "tree-pass.h"
54 #include "dbgcnt.h"
55 #include "shrink-wrap.h"
56 #include "rtl-iter.h"
57 #include "ifcvt.h"
58
59 #ifndef MAX_CONDITIONAL_EXECUTE
60 #define MAX_CONDITIONAL_EXECUTE \
61   (BRANCH_COST (optimize_function_for_speed_p (cfun), false) \
62    + 1)
63 #endif
64
65 #define IFCVT_MULTIPLE_DUMPS 1
66
67 #define NULL_BLOCK      ((basic_block) NULL)
68
69 /* True if after combine pass.  */
70 static bool ifcvt_after_combine;
71
72 /* True if the target has the cbranchcc4 optab.  */
73 static bool have_cbranchcc4;
74
75 /* # of IF-THEN or IF-THEN-ELSE blocks we looked at  */
76 static int num_possible_if_blocks;
77
78 /* # of IF-THEN or IF-THEN-ELSE blocks were converted to conditional
79    execution.  */
80 static int num_updated_if_blocks;
81
82 /* # of changes made.  */
83 static int num_true_changes;
84
85 /* Whether conditional execution changes were made.  */
86 static int cond_exec_changed_p;
87
88 /* Forward references.  */
89 static int count_bb_insns (const_basic_block);
90 static bool cheap_bb_rtx_cost_p (const_basic_block, int, int);
91 static rtx_insn *first_active_insn (basic_block);
92 static rtx_insn *last_active_insn (basic_block, int);
93 static rtx_insn *find_active_insn_before (basic_block, rtx_insn *);
94 static rtx_insn *find_active_insn_after (basic_block, rtx_insn *);
95 static basic_block block_fallthru (basic_block);
96 static int cond_exec_process_insns (ce_if_block *, rtx_insn *, rtx, rtx, int,
97                                     int);
98 static rtx cond_exec_get_condition (rtx_insn *);
99 static rtx noce_get_condition (rtx_insn *, rtx_insn **, bool);
100 static int noce_operand_ok (const_rtx);
101 static void merge_if_block (ce_if_block *);
102 static int find_cond_trap (basic_block, edge, edge);
103 static basic_block find_if_header (basic_block, int);
104 static int block_jumps_and_fallthru_p (basic_block, basic_block);
105 static int noce_find_if_block (basic_block, edge, edge, int);
106 static int cond_exec_find_if_block (ce_if_block *);
107 static int find_if_case_1 (basic_block, edge, edge);
108 static int find_if_case_2 (basic_block, edge, edge);
109 static int dead_or_predicable (basic_block, basic_block, basic_block,
110                                edge, int);
111 static void noce_emit_move_insn (rtx, rtx);
112 static rtx_insn *block_has_only_trap (basic_block);
113 \f
114 /* Count the number of non-jump active insns in BB.  */
115
116 static int
117 count_bb_insns (const_basic_block bb)
118 {
119   int count = 0;
120   rtx_insn *insn = BB_HEAD (bb);
121
122   while (1)
123     {
124       if (active_insn_p (insn) && !JUMP_P (insn))
125         count++;
126
127       if (insn == BB_END (bb))
128         break;
129       insn = NEXT_INSN (insn);
130     }
131
132   return count;
133 }
134
135 /* Determine whether the total insn_rtx_cost on non-jump insns in
136    basic block BB is less than MAX_COST.  This function returns
137    false if the cost of any instruction could not be estimated. 
138
139    The cost of the non-jump insns in BB is scaled by REG_BR_PROB_BASE
140    as those insns are being speculated.  MAX_COST is scaled with SCALE
141    plus a small fudge factor.  */
142
143 static bool
144 cheap_bb_rtx_cost_p (const_basic_block bb, int scale, int max_cost)
145 {
146   int count = 0;
147   rtx_insn *insn = BB_HEAD (bb);
148   bool speed = optimize_bb_for_speed_p (bb);
149
150   /* Set scale to REG_BR_PROB_BASE to void the identical scaling
151      applied to insn_rtx_cost when optimizing for size.  Only do
152      this after combine because if-conversion might interfere with
153      passes before combine.
154
155      Use optimize_function_for_speed_p instead of the pre-defined
156      variable speed to make sure it is set to same value for all
157      basic blocks in one if-conversion transformation.  */
158   if (!optimize_function_for_speed_p (cfun) && ifcvt_after_combine)
159     scale = REG_BR_PROB_BASE;
160   /* Our branch probability/scaling factors are just estimates and don't
161      account for cases where we can get speculation for free and other
162      secondary benefits.  So we fudge the scale factor to make speculating
163      appear a little more profitable when optimizing for performance.  */
164   else
165     scale += REG_BR_PROB_BASE / 8;
166
167
168   max_cost *= scale;
169
170   while (1)
171     {
172       if (NONJUMP_INSN_P (insn))
173         {
174           int cost = insn_rtx_cost (PATTERN (insn), speed) * REG_BR_PROB_BASE;
175           if (cost == 0)
176             return false;
177
178           /* If this instruction is the load or set of a "stack" register,
179              such as a floating point register on x87, then the cost of
180              speculatively executing this insn may need to include
181              the additional cost of popping its result off of the
182              register stack.  Unfortunately, correctly recognizing and
183              accounting for this additional overhead is tricky, so for
184              now we simply prohibit such speculative execution.  */
185 #ifdef STACK_REGS
186           {
187             rtx set = single_set (insn);
188             if (set && STACK_REG_P (SET_DEST (set)))
189               return false;
190           }
191 #endif
192
193           count += cost;
194           if (count >= max_cost)
195             return false;
196         }
197       else if (CALL_P (insn))
198         return false;
199
200       if (insn == BB_END (bb))
201         break;
202       insn = NEXT_INSN (insn);
203     }
204
205   return true;
206 }
207
208 /* Return the first non-jump active insn in the basic block.  */
209
210 static rtx_insn *
211 first_active_insn (basic_block bb)
212 {
213   rtx_insn *insn = BB_HEAD (bb);
214
215   if (LABEL_P (insn))
216     {
217       if (insn == BB_END (bb))
218         return NULL;
219       insn = NEXT_INSN (insn);
220     }
221
222   while (NOTE_P (insn) || DEBUG_INSN_P (insn))
223     {
224       if (insn == BB_END (bb))
225         return NULL;
226       insn = NEXT_INSN (insn);
227     }
228
229   if (JUMP_P (insn))
230     return NULL;
231
232   return insn;
233 }
234
235 /* Return the last non-jump active (non-jump) insn in the basic block.  */
236
237 static rtx_insn *
238 last_active_insn (basic_block bb, int skip_use_p)
239 {
240   rtx_insn *insn = BB_END (bb);
241   rtx_insn *head = BB_HEAD (bb);
242
243   while (NOTE_P (insn)
244          || JUMP_P (insn)
245          || DEBUG_INSN_P (insn)
246          || (skip_use_p
247              && NONJUMP_INSN_P (insn)
248              && GET_CODE (PATTERN (insn)) == USE))
249     {
250       if (insn == head)
251         return NULL;
252       insn = PREV_INSN (insn);
253     }
254
255   if (LABEL_P (insn))
256     return NULL;
257
258   return insn;
259 }
260
261 /* Return the active insn before INSN inside basic block CURR_BB. */
262
263 static rtx_insn *
264 find_active_insn_before (basic_block curr_bb, rtx_insn *insn)
265 {
266   if (!insn || insn == BB_HEAD (curr_bb))
267     return NULL;
268
269   while ((insn = PREV_INSN (insn)) != NULL_RTX)
270     {
271       if (NONJUMP_INSN_P (insn) || JUMP_P (insn) || CALL_P (insn))
272         break;
273
274       /* No other active insn all the way to the start of the basic block. */
275       if (insn == BB_HEAD (curr_bb))
276         return NULL;
277     }
278
279   return insn;
280 }
281
282 /* Return the active insn after INSN inside basic block CURR_BB. */
283
284 static rtx_insn *
285 find_active_insn_after (basic_block curr_bb, rtx_insn *insn)
286 {
287   if (!insn || insn == BB_END (curr_bb))
288     return NULL;
289
290   while ((insn = NEXT_INSN (insn)) != NULL_RTX)
291     {
292       if (NONJUMP_INSN_P (insn) || JUMP_P (insn) || CALL_P (insn))
293         break;
294
295       /* No other active insn all the way to the end of the basic block. */
296       if (insn == BB_END (curr_bb))
297         return NULL;
298     }
299
300   return insn;
301 }
302
303 /* Return the basic block reached by falling though the basic block BB.  */
304
305 static basic_block
306 block_fallthru (basic_block bb)
307 {
308   edge e = find_fallthru_edge (bb->succs);
309
310   return (e) ? e->dest : NULL_BLOCK;
311 }
312
313 /* Return true if RTXs A and B can be safely interchanged.  */
314
315 static bool
316 rtx_interchangeable_p (const_rtx a, const_rtx b)
317 {
318   if (!rtx_equal_p (a, b))
319     return false;
320
321   if (GET_CODE (a) != MEM)
322     return true;
323
324   /* A dead type-unsafe memory reference is legal, but a live type-unsafe memory
325      reference is not.  Interchanging a dead type-unsafe memory reference with
326      a live type-safe one creates a live type-unsafe memory reference, in other
327      words, it makes the program illegal.
328      We check here conservatively whether the two memory references have equal
329      memory attributes.  */
330
331   return mem_attrs_eq_p (get_mem_attrs (a), get_mem_attrs (b));
332 }
333
334 \f
335 /* Go through a bunch of insns, converting them to conditional
336    execution format if possible.  Return TRUE if all of the non-note
337    insns were processed.  */
338
339 static int
340 cond_exec_process_insns (ce_if_block *ce_info ATTRIBUTE_UNUSED,
341                          /* if block information */rtx_insn *start,
342                          /* first insn to look at */rtx end,
343                          /* last insn to look at */rtx test,
344                          /* conditional execution test */int prob_val,
345                          /* probability of branch taken. */int mod_ok)
346 {
347   int must_be_last = FALSE;
348   rtx_insn *insn;
349   rtx xtest;
350   rtx pattern;
351
352   if (!start || !end)
353     return FALSE;
354
355   for (insn = start; ; insn = NEXT_INSN (insn))
356     {
357       /* dwarf2out can't cope with conditional prologues.  */
358       if (NOTE_P (insn) && NOTE_KIND (insn) == NOTE_INSN_PROLOGUE_END)
359         return FALSE;
360
361       if (NOTE_P (insn) || DEBUG_INSN_P (insn))
362         goto insn_done;
363
364       gcc_assert (NONJUMP_INSN_P (insn) || CALL_P (insn));
365
366       /* dwarf2out can't cope with conditional unwind info.  */
367       if (RTX_FRAME_RELATED_P (insn))
368         return FALSE;
369
370       /* Remove USE insns that get in the way.  */
371       if (reload_completed && GET_CODE (PATTERN (insn)) == USE)
372         {
373           /* ??? Ug.  Actually unlinking the thing is problematic,
374              given what we'd have to coordinate with our callers.  */
375           SET_INSN_DELETED (insn);
376           goto insn_done;
377         }
378
379       /* Last insn wasn't last?  */
380       if (must_be_last)
381         return FALSE;
382
383       if (modified_in_p (test, insn))
384         {
385           if (!mod_ok)
386             return FALSE;
387           must_be_last = TRUE;
388         }
389
390       /* Now build the conditional form of the instruction.  */
391       pattern = PATTERN (insn);
392       xtest = copy_rtx (test);
393
394       /* If this is already a COND_EXEC, rewrite the test to be an AND of the
395          two conditions.  */
396       if (GET_CODE (pattern) == COND_EXEC)
397         {
398           if (GET_MODE (xtest) != GET_MODE (COND_EXEC_TEST (pattern)))
399             return FALSE;
400
401           xtest = gen_rtx_AND (GET_MODE (xtest), xtest,
402                                COND_EXEC_TEST (pattern));
403           pattern = COND_EXEC_CODE (pattern);
404         }
405
406       pattern = gen_rtx_COND_EXEC (VOIDmode, xtest, pattern);
407
408       /* If the machine needs to modify the insn being conditionally executed,
409          say for example to force a constant integer operand into a temp
410          register, do so here.  */
411 #ifdef IFCVT_MODIFY_INSN
412       IFCVT_MODIFY_INSN (ce_info, pattern, insn);
413       if (! pattern)
414         return FALSE;
415 #endif
416
417       validate_change (insn, &PATTERN (insn), pattern, 1);
418
419       if (CALL_P (insn) && prob_val >= 0)
420         validate_change (insn, &REG_NOTES (insn),
421                          gen_rtx_INT_LIST ((machine_mode) REG_BR_PROB,
422                                            prob_val, REG_NOTES (insn)), 1);
423
424     insn_done:
425       if (insn == end)
426         break;
427     }
428
429   return TRUE;
430 }
431
432 /* Return the condition for a jump.  Do not do any special processing.  */
433
434 static rtx
435 cond_exec_get_condition (rtx_insn *jump)
436 {
437   rtx test_if, cond;
438
439   if (any_condjump_p (jump))
440     test_if = SET_SRC (pc_set (jump));
441   else
442     return NULL_RTX;
443   cond = XEXP (test_if, 0);
444
445   /* If this branches to JUMP_LABEL when the condition is false,
446      reverse the condition.  */
447   if (GET_CODE (XEXP (test_if, 2)) == LABEL_REF
448       && LABEL_REF_LABEL (XEXP (test_if, 2)) == JUMP_LABEL (jump))
449     {
450       enum rtx_code rev = reversed_comparison_code (cond, jump);
451       if (rev == UNKNOWN)
452         return NULL_RTX;
453
454       cond = gen_rtx_fmt_ee (rev, GET_MODE (cond), XEXP (cond, 0),
455                              XEXP (cond, 1));
456     }
457
458   return cond;
459 }
460
461 /* Given a simple IF-THEN or IF-THEN-ELSE block, attempt to convert it
462    to conditional execution.  Return TRUE if we were successful at
463    converting the block.  */
464
465 static int
466 cond_exec_process_if_block (ce_if_block * ce_info,
467                             /* if block information */int do_multiple_p)
468 {
469   basic_block test_bb = ce_info->test_bb;       /* last test block */
470   basic_block then_bb = ce_info->then_bb;       /* THEN */
471   basic_block else_bb = ce_info->else_bb;       /* ELSE or NULL */
472   rtx test_expr;                /* expression in IF_THEN_ELSE that is tested */
473   rtx_insn *then_start;         /* first insn in THEN block */
474   rtx_insn *then_end;           /* last insn + 1 in THEN block */
475   rtx_insn *else_start = NULL;  /* first insn in ELSE block or NULL */
476   rtx_insn *else_end = NULL;    /* last insn + 1 in ELSE block */
477   int max;                      /* max # of insns to convert.  */
478   int then_mod_ok;              /* whether conditional mods are ok in THEN */
479   rtx true_expr;                /* test for else block insns */
480   rtx false_expr;               /* test for then block insns */
481   int true_prob_val;            /* probability of else block */
482   int false_prob_val;           /* probability of then block */
483   rtx_insn *then_last_head = NULL;      /* Last match at the head of THEN */
484   rtx_insn *else_last_head = NULL;      /* Last match at the head of ELSE */
485   rtx_insn *then_first_tail = NULL;     /* First match at the tail of THEN */
486   rtx_insn *else_first_tail = NULL;     /* First match at the tail of ELSE */
487   int then_n_insns, else_n_insns, n_insns;
488   enum rtx_code false_code;
489   rtx note;
490
491   /* If test is comprised of && or || elements, and we've failed at handling
492      all of them together, just use the last test if it is the special case of
493      && elements without an ELSE block.  */
494   if (!do_multiple_p && ce_info->num_multiple_test_blocks)
495     {
496       if (else_bb || ! ce_info->and_and_p)
497         return FALSE;
498
499       ce_info->test_bb = test_bb = ce_info->last_test_bb;
500       ce_info->num_multiple_test_blocks = 0;
501       ce_info->num_and_and_blocks = 0;
502       ce_info->num_or_or_blocks = 0;
503     }
504
505   /* Find the conditional jump to the ELSE or JOIN part, and isolate
506      the test.  */
507   test_expr = cond_exec_get_condition (BB_END (test_bb));
508   if (! test_expr)
509     return FALSE;
510
511   /* If the conditional jump is more than just a conditional jump,
512      then we can not do conditional execution conversion on this block.  */
513   if (! onlyjump_p (BB_END (test_bb)))
514     return FALSE;
515
516   /* Collect the bounds of where we're to search, skipping any labels, jumps
517      and notes at the beginning and end of the block.  Then count the total
518      number of insns and see if it is small enough to convert.  */
519   then_start = first_active_insn (then_bb);
520   then_end = last_active_insn (then_bb, TRUE);
521   then_n_insns = ce_info->num_then_insns = count_bb_insns (then_bb);
522   n_insns = then_n_insns;
523   max = MAX_CONDITIONAL_EXECUTE;
524
525   if (else_bb)
526     {
527       int n_matching;
528
529       max *= 2;
530       else_start = first_active_insn (else_bb);
531       else_end = last_active_insn (else_bb, TRUE);
532       else_n_insns = ce_info->num_else_insns = count_bb_insns (else_bb);
533       n_insns += else_n_insns;
534
535       /* Look for matching sequences at the head and tail of the two blocks,
536          and limit the range of insns to be converted if possible.  */
537       n_matching = flow_find_cross_jump (then_bb, else_bb,
538                                          &then_first_tail, &else_first_tail,
539                                          NULL);
540       if (then_first_tail == BB_HEAD (then_bb))
541         then_start = then_end = NULL;
542       if (else_first_tail == BB_HEAD (else_bb))
543         else_start = else_end = NULL;
544
545       if (n_matching > 0)
546         {
547           if (then_end)
548             then_end = find_active_insn_before (then_bb, then_first_tail);
549           if (else_end)
550             else_end = find_active_insn_before (else_bb, else_first_tail);
551           n_insns -= 2 * n_matching;
552         }
553
554       if (then_start
555           && else_start
556           && then_n_insns > n_matching
557           && else_n_insns > n_matching)
558         {
559           int longest_match = MIN (then_n_insns - n_matching,
560                                    else_n_insns - n_matching);
561           n_matching
562             = flow_find_head_matching_sequence (then_bb, else_bb,
563                                                 &then_last_head,
564                                                 &else_last_head,
565                                                 longest_match);
566
567           if (n_matching > 0)
568             {
569               rtx_insn *insn;
570
571               /* We won't pass the insns in the head sequence to
572                  cond_exec_process_insns, so we need to test them here
573                  to make sure that they don't clobber the condition.  */
574               for (insn = BB_HEAD (then_bb);
575                    insn != NEXT_INSN (then_last_head);
576                    insn = NEXT_INSN (insn))
577                 if (!LABEL_P (insn) && !NOTE_P (insn)
578                     && !DEBUG_INSN_P (insn)
579                     && modified_in_p (test_expr, insn))
580                   return FALSE;
581             }
582
583           if (then_last_head == then_end)
584             then_start = then_end = NULL;
585           if (else_last_head == else_end)
586             else_start = else_end = NULL;
587
588           if (n_matching > 0)
589             {
590               if (then_start)
591                 then_start = find_active_insn_after (then_bb, then_last_head);
592               if (else_start)
593                 else_start = find_active_insn_after (else_bb, else_last_head);
594               n_insns -= 2 * n_matching;
595             }
596         }
597     }
598
599   if (n_insns > max)
600     return FALSE;
601
602   /* Map test_expr/test_jump into the appropriate MD tests to use on
603      the conditionally executed code.  */
604
605   true_expr = test_expr;
606
607   false_code = reversed_comparison_code (true_expr, BB_END (test_bb));
608   if (false_code != UNKNOWN)
609     false_expr = gen_rtx_fmt_ee (false_code, GET_MODE (true_expr),
610                                  XEXP (true_expr, 0), XEXP (true_expr, 1));
611   else
612     false_expr = NULL_RTX;
613
614 #ifdef IFCVT_MODIFY_TESTS
615   /* If the machine description needs to modify the tests, such as setting a
616      conditional execution register from a comparison, it can do so here.  */
617   IFCVT_MODIFY_TESTS (ce_info, true_expr, false_expr);
618
619   /* See if the conversion failed.  */
620   if (!true_expr || !false_expr)
621     goto fail;
622 #endif
623
624   note = find_reg_note (BB_END (test_bb), REG_BR_PROB, NULL_RTX);
625   if (note)
626     {
627       true_prob_val = XINT (note, 0);
628       false_prob_val = REG_BR_PROB_BASE - true_prob_val;
629     }
630   else
631     {
632       true_prob_val = -1;
633       false_prob_val = -1;
634     }
635
636   /* If we have && or || tests, do them here.  These tests are in the adjacent
637      blocks after the first block containing the test.  */
638   if (ce_info->num_multiple_test_blocks > 0)
639     {
640       basic_block bb = test_bb;
641       basic_block last_test_bb = ce_info->last_test_bb;
642
643       if (! false_expr)
644         goto fail;
645
646       do
647         {
648           rtx_insn *start, *end;
649           rtx t, f;
650           enum rtx_code f_code;
651
652           bb = block_fallthru (bb);
653           start = first_active_insn (bb);
654           end = last_active_insn (bb, TRUE);
655           if (start
656               && ! cond_exec_process_insns (ce_info, start, end, false_expr,
657                                             false_prob_val, FALSE))
658             goto fail;
659
660           /* If the conditional jump is more than just a conditional jump, then
661              we can not do conditional execution conversion on this block.  */
662           if (! onlyjump_p (BB_END (bb)))
663             goto fail;
664
665           /* Find the conditional jump and isolate the test.  */
666           t = cond_exec_get_condition (BB_END (bb));
667           if (! t)
668             goto fail;
669
670           f_code = reversed_comparison_code (t, BB_END (bb));
671           if (f_code == UNKNOWN)
672             goto fail;
673
674           f = gen_rtx_fmt_ee (f_code, GET_MODE (t), XEXP (t, 0), XEXP (t, 1));
675           if (ce_info->and_and_p)
676             {
677               t = gen_rtx_AND (GET_MODE (t), true_expr, t);
678               f = gen_rtx_IOR (GET_MODE (t), false_expr, f);
679             }
680           else
681             {
682               t = gen_rtx_IOR (GET_MODE (t), true_expr, t);
683               f = gen_rtx_AND (GET_MODE (t), false_expr, f);
684             }
685
686           /* If the machine description needs to modify the tests, such as
687              setting a conditional execution register from a comparison, it can
688              do so here.  */
689 #ifdef IFCVT_MODIFY_MULTIPLE_TESTS
690           IFCVT_MODIFY_MULTIPLE_TESTS (ce_info, bb, t, f);
691
692           /* See if the conversion failed.  */
693           if (!t || !f)
694             goto fail;
695 #endif
696
697           true_expr = t;
698           false_expr = f;
699         }
700       while (bb != last_test_bb);
701     }
702
703   /* For IF-THEN-ELSE blocks, we don't allow modifications of the test
704      on then THEN block.  */
705   then_mod_ok = (else_bb == NULL_BLOCK);
706
707   /* Go through the THEN and ELSE blocks converting the insns if possible
708      to conditional execution.  */
709
710   if (then_end
711       && (! false_expr
712           || ! cond_exec_process_insns (ce_info, then_start, then_end,
713                                         false_expr, false_prob_val,
714                                         then_mod_ok)))
715     goto fail;
716
717   if (else_bb && else_end
718       && ! cond_exec_process_insns (ce_info, else_start, else_end,
719                                     true_expr, true_prob_val, TRUE))
720     goto fail;
721
722   /* If we cannot apply the changes, fail.  Do not go through the normal fail
723      processing, since apply_change_group will call cancel_changes.  */
724   if (! apply_change_group ())
725     {
726 #ifdef IFCVT_MODIFY_CANCEL
727       /* Cancel any machine dependent changes.  */
728       IFCVT_MODIFY_CANCEL (ce_info);
729 #endif
730       return FALSE;
731     }
732
733 #ifdef IFCVT_MODIFY_FINAL
734   /* Do any machine dependent final modifications.  */
735   IFCVT_MODIFY_FINAL (ce_info);
736 #endif
737
738   /* Conversion succeeded.  */
739   if (dump_file)
740     fprintf (dump_file, "%d insn%s converted to conditional execution.\n",
741              n_insns, (n_insns == 1) ? " was" : "s were");
742
743   /* Merge the blocks!  If we had matching sequences, make sure to delete one
744      copy at the appropriate location first: delete the copy in the THEN branch
745      for a tail sequence so that the remaining one is executed last for both
746      branches, and delete the copy in the ELSE branch for a head sequence so
747      that the remaining one is executed first for both branches.  */
748   if (then_first_tail)
749     {
750       rtx_insn *from = then_first_tail;
751       if (!INSN_P (from))
752         from = find_active_insn_after (then_bb, from);
753       delete_insn_chain (from, BB_END (then_bb), false);
754     }
755   if (else_last_head)
756     delete_insn_chain (first_active_insn (else_bb), else_last_head, false);
757
758   merge_if_block (ce_info);
759   cond_exec_changed_p = TRUE;
760   return TRUE;
761
762  fail:
763 #ifdef IFCVT_MODIFY_CANCEL
764   /* Cancel any machine dependent changes.  */
765   IFCVT_MODIFY_CANCEL (ce_info);
766 #endif
767
768   cancel_changes (0);
769   return FALSE;
770 }
771 \f
772 /* Used by noce_process_if_block to communicate with its subroutines.
773
774    The subroutines know that A and B may be evaluated freely.  They
775    know that X is a register.  They should insert new instructions
776    before cond_earliest.  */
777
778 struct noce_if_info
779 {
780   /* The basic blocks that make up the IF-THEN-{ELSE-,}JOIN block.  */
781   basic_block test_bb, then_bb, else_bb, join_bb;
782
783   /* The jump that ends TEST_BB.  */
784   rtx_insn *jump;
785
786   /* The jump condition.  */
787   rtx cond;
788
789   /* New insns should be inserted before this one.  */
790   rtx_insn *cond_earliest;
791
792   /* Insns in the THEN and ELSE block.  There is always just this
793      one insns in those blocks.  The insns are single_set insns.
794      If there was no ELSE block, INSN_B is the last insn before
795      COND_EARLIEST, or NULL_RTX.  In the former case, the insn
796      operands are still valid, as if INSN_B was moved down below
797      the jump.  */
798   rtx_insn *insn_a, *insn_b;
799
800   /* The SET_SRC of INSN_A and INSN_B.  */
801   rtx a, b;
802
803   /* The SET_DEST of INSN_A.  */
804   rtx x;
805
806   /* True if this if block is not canonical.  In the canonical form of
807      if blocks, the THEN_BB is the block reached via the fallthru edge
808      from TEST_BB.  For the noce transformations, we allow the symmetric
809      form as well.  */
810   bool then_else_reversed;
811
812   /* True if the contents of then_bb and else_bb are a
813      simple single set instruction.  */
814   bool then_simple;
815   bool else_simple;
816
817   /* The total rtx cost of the instructions in then_bb and else_bb.  */
818   unsigned int then_cost;
819   unsigned int else_cost;
820
821   /* Estimated cost of the particular branch instruction.  */
822   unsigned int branch_cost;
823 };
824
825 static rtx noce_emit_store_flag (struct noce_if_info *, rtx, int, int);
826 static int noce_try_move (struct noce_if_info *);
827 static int noce_try_store_flag (struct noce_if_info *);
828 static int noce_try_addcc (struct noce_if_info *);
829 static int noce_try_store_flag_constants (struct noce_if_info *);
830 static int noce_try_store_flag_mask (struct noce_if_info *);
831 static rtx noce_emit_cmove (struct noce_if_info *, rtx, enum rtx_code, rtx,
832                             rtx, rtx, rtx);
833 static int noce_try_cmove (struct noce_if_info *);
834 static int noce_try_cmove_arith (struct noce_if_info *);
835 static rtx noce_get_alt_condition (struct noce_if_info *, rtx, rtx_insn **);
836 static int noce_try_minmax (struct noce_if_info *);
837 static int noce_try_abs (struct noce_if_info *);
838 static int noce_try_sign_mask (struct noce_if_info *);
839
840 /* Helper function for noce_try_store_flag*.  */
841
842 static rtx
843 noce_emit_store_flag (struct noce_if_info *if_info, rtx x, int reversep,
844                       int normalize)
845 {
846   rtx cond = if_info->cond;
847   int cond_complex;
848   enum rtx_code code;
849
850   cond_complex = (! general_operand (XEXP (cond, 0), VOIDmode)
851                   || ! general_operand (XEXP (cond, 1), VOIDmode));
852
853   /* If earliest == jump, or when the condition is complex, try to
854      build the store_flag insn directly.  */
855
856   if (cond_complex)
857     {
858       rtx set = pc_set (if_info->jump);
859       cond = XEXP (SET_SRC (set), 0);
860       if (GET_CODE (XEXP (SET_SRC (set), 2)) == LABEL_REF
861           && LABEL_REF_LABEL (XEXP (SET_SRC (set), 2)) == JUMP_LABEL (if_info->jump))
862         reversep = !reversep;
863       if (if_info->then_else_reversed)
864         reversep = !reversep;
865     }
866
867   if (reversep)
868     code = reversed_comparison_code (cond, if_info->jump);
869   else
870     code = GET_CODE (cond);
871
872   if ((if_info->cond_earliest == if_info->jump || cond_complex)
873       && (normalize == 0 || STORE_FLAG_VALUE == normalize))
874     {
875       rtx src = gen_rtx_fmt_ee (code, GET_MODE (x), XEXP (cond, 0),
876                             XEXP (cond, 1));
877       rtx set = gen_rtx_SET (x, src);
878
879       start_sequence ();
880       rtx_insn *insn = emit_insn (set);
881
882       if (recog_memoized (insn) >= 0)
883         {
884           rtx_insn *seq = get_insns ();
885           end_sequence ();
886           emit_insn (seq);
887
888           if_info->cond_earliest = if_info->jump;
889
890           return x;
891         }
892
893       end_sequence ();
894     }
895
896   /* Don't even try if the comparison operands or the mode of X are weird.  */
897   if (cond_complex || !SCALAR_INT_MODE_P (GET_MODE (x)))
898     return NULL_RTX;
899
900   return emit_store_flag (x, code, XEXP (cond, 0),
901                           XEXP (cond, 1), VOIDmode,
902                           (code == LTU || code == LEU
903                            || code == GEU || code == GTU), normalize);
904 }
905
906 /* Emit instruction to move an rtx, possibly into STRICT_LOW_PART.
907    X is the destination/target and Y is the value to copy.  */
908
909 static void
910 noce_emit_move_insn (rtx x, rtx y)
911 {
912   machine_mode outmode;
913   rtx outer, inner;
914   int bitpos;
915
916   if (GET_CODE (x) != STRICT_LOW_PART)
917     {
918       rtx_insn *seq, *insn;
919       rtx target;
920       optab ot;
921
922       start_sequence ();
923       /* Check that the SET_SRC is reasonable before calling emit_move_insn,
924          otherwise construct a suitable SET pattern ourselves.  */
925       insn = (OBJECT_P (y) || CONSTANT_P (y) || GET_CODE (y) == SUBREG)
926              ? emit_move_insn (x, y)
927              : emit_insn (gen_rtx_SET (x, y));
928       seq = get_insns ();
929       end_sequence ();
930
931       if (recog_memoized (insn) <= 0)
932         {
933           if (GET_CODE (x) == ZERO_EXTRACT)
934             {
935               rtx op = XEXP (x, 0);
936               unsigned HOST_WIDE_INT size = INTVAL (XEXP (x, 1));
937               unsigned HOST_WIDE_INT start = INTVAL (XEXP (x, 2));
938
939               /* store_bit_field expects START to be relative to
940                  BYTES_BIG_ENDIAN and adjusts this value for machines with
941                  BITS_BIG_ENDIAN != BYTES_BIG_ENDIAN.  In order to be able to
942                  invoke store_bit_field again it is necessary to have the START
943                  value from the first call.  */
944               if (BITS_BIG_ENDIAN != BYTES_BIG_ENDIAN)
945                 {
946                   if (MEM_P (op))
947                     start = BITS_PER_UNIT - start - size;
948                   else
949                     {
950                       gcc_assert (REG_P (op));
951                       start = BITS_PER_WORD - start - size;
952                     }
953                 }
954
955               gcc_assert (start < (MEM_P (op) ? BITS_PER_UNIT : BITS_PER_WORD));
956               store_bit_field (op, size, start, 0, 0, GET_MODE (x), y);
957               return;
958             }
959
960           switch (GET_RTX_CLASS (GET_CODE (y)))
961             {
962             case RTX_UNARY:
963               ot = code_to_optab (GET_CODE (y));
964               if (ot)
965                 {
966                   start_sequence ();
967                   target = expand_unop (GET_MODE (y), ot, XEXP (y, 0), x, 0);
968                   if (target != NULL_RTX)
969                     {
970                       if (target != x)
971                         emit_move_insn (x, target);
972                       seq = get_insns ();
973                     }
974                   end_sequence ();
975                 }
976               break;
977
978             case RTX_BIN_ARITH:
979             case RTX_COMM_ARITH:
980               ot = code_to_optab (GET_CODE (y));
981               if (ot)
982                 {
983                   start_sequence ();
984                   target = expand_binop (GET_MODE (y), ot,
985                                          XEXP (y, 0), XEXP (y, 1),
986                                          x, 0, OPTAB_DIRECT);
987                   if (target != NULL_RTX)
988                     {
989                       if (target != x)
990                           emit_move_insn (x, target);
991                       seq = get_insns ();
992                     }
993                   end_sequence ();
994                 }
995               break;
996
997             default:
998               break;
999             }
1000         }
1001
1002       emit_insn (seq);
1003       return;
1004     }
1005
1006   outer = XEXP (x, 0);
1007   inner = XEXP (outer, 0);
1008   outmode = GET_MODE (outer);
1009   bitpos = SUBREG_BYTE (outer) * BITS_PER_UNIT;
1010   store_bit_field (inner, GET_MODE_BITSIZE (outmode), bitpos,
1011                    0, 0, outmode, y);
1012 }
1013
1014 /* Return the CC reg if it is used in COND.  */
1015
1016 static rtx
1017 cc_in_cond (rtx cond)
1018 {
1019   if (have_cbranchcc4 && cond
1020       && GET_MODE_CLASS (GET_MODE (XEXP (cond, 0))) == MODE_CC)
1021     return XEXP (cond, 0);
1022
1023   return NULL_RTX;
1024 }
1025
1026 /* Return sequence of instructions generated by if conversion.  This
1027    function calls end_sequence() to end the current stream, ensures
1028    that the instructions are unshared, recognizable non-jump insns.
1029    On failure, this function returns a NULL_RTX.  */
1030
1031 static rtx_insn *
1032 end_ifcvt_sequence (struct noce_if_info *if_info)
1033 {
1034   rtx_insn *insn;
1035   rtx_insn *seq = get_insns ();
1036   rtx cc = cc_in_cond (if_info->cond);
1037
1038   set_used_flags (if_info->x);
1039   set_used_flags (if_info->cond);
1040   set_used_flags (if_info->a);
1041   set_used_flags (if_info->b);
1042
1043   for (insn = seq; insn; insn = NEXT_INSN (insn))
1044     set_used_flags (insn);
1045
1046   unshare_all_rtl_in_chain (seq);
1047   end_sequence ();
1048
1049   /* Make sure that all of the instructions emitted are recognizable,
1050      and that we haven't introduced a new jump instruction.
1051      As an exercise for the reader, build a general mechanism that
1052      allows proper placement of required clobbers.  */
1053   for (insn = seq; insn; insn = NEXT_INSN (insn))
1054     if (JUMP_P (insn)
1055         || recog_memoized (insn) == -1
1056            /* Make sure new generated code does not clobber CC.  */
1057         || (cc && set_of (cc, insn)))
1058       return NULL;
1059
1060   return seq;
1061 }
1062
1063 /* Return true iff the then and else basic block (if it exists)
1064    consist of a single simple set instruction.  */
1065
1066 static bool
1067 noce_simple_bbs (struct noce_if_info *if_info)
1068 {
1069   if (!if_info->then_simple)
1070     return false;
1071
1072   if (if_info->else_bb)
1073     return if_info->else_simple;
1074
1075   return true;
1076 }
1077
1078 /* Convert "if (a != b) x = a; else x = b" into "x = a" and
1079    "if (a == b) x = a; else x = b" into "x = b".  */
1080
1081 static int
1082 noce_try_move (struct noce_if_info *if_info)
1083 {
1084   rtx cond = if_info->cond;
1085   enum rtx_code code = GET_CODE (cond);
1086   rtx y;
1087   rtx_insn *seq;
1088
1089   if (code != NE && code != EQ)
1090     return FALSE;
1091
1092   if (!noce_simple_bbs (if_info))
1093     return FALSE;
1094
1095   /* This optimization isn't valid if either A or B could be a NaN
1096      or a signed zero.  */
1097   if (HONOR_NANS (if_info->x)
1098       || HONOR_SIGNED_ZEROS (if_info->x))
1099     return FALSE;
1100
1101   /* Check whether the operands of the comparison are A and in
1102      either order.  */
1103   if ((rtx_equal_p (if_info->a, XEXP (cond, 0))
1104        && rtx_equal_p (if_info->b, XEXP (cond, 1)))
1105       || (rtx_equal_p (if_info->a, XEXP (cond, 1))
1106           && rtx_equal_p (if_info->b, XEXP (cond, 0))))
1107     {
1108       if (!rtx_interchangeable_p (if_info->a, if_info->b))
1109         return FALSE;
1110
1111       y = (code == EQ) ? if_info->a : if_info->b;
1112
1113       /* Avoid generating the move if the source is the destination.  */
1114       if (! rtx_equal_p (if_info->x, y))
1115         {
1116           start_sequence ();
1117           noce_emit_move_insn (if_info->x, y);
1118           seq = end_ifcvt_sequence (if_info);
1119           if (!seq)
1120             return FALSE;
1121
1122           emit_insn_before_setloc (seq, if_info->jump,
1123                                    INSN_LOCATION (if_info->insn_a));
1124         }
1125       return TRUE;
1126     }
1127   return FALSE;
1128 }
1129
1130 /* Convert "if (test) x = 1; else x = 0".
1131
1132    Only try 0 and STORE_FLAG_VALUE here.  Other combinations will be
1133    tried in noce_try_store_flag_constants after noce_try_cmove has had
1134    a go at the conversion.  */
1135
1136 static int
1137 noce_try_store_flag (struct noce_if_info *if_info)
1138 {
1139   int reversep;
1140   rtx target;
1141   rtx_insn *seq;
1142
1143   if (!noce_simple_bbs (if_info))
1144     return FALSE;
1145
1146   if (CONST_INT_P (if_info->b)
1147       && INTVAL (if_info->b) == STORE_FLAG_VALUE
1148       && if_info->a == const0_rtx)
1149     reversep = 0;
1150   else if (if_info->b == const0_rtx
1151            && CONST_INT_P (if_info->a)
1152            && INTVAL (if_info->a) == STORE_FLAG_VALUE
1153            && (reversed_comparison_code (if_info->cond, if_info->jump)
1154                != UNKNOWN))
1155     reversep = 1;
1156   else
1157     return FALSE;
1158
1159   start_sequence ();
1160
1161   target = noce_emit_store_flag (if_info, if_info->x, reversep, 0);
1162   if (target)
1163     {
1164       if (target != if_info->x)
1165         noce_emit_move_insn (if_info->x, target);
1166
1167       seq = end_ifcvt_sequence (if_info);
1168       if (! seq)
1169         return FALSE;
1170
1171       emit_insn_before_setloc (seq, if_info->jump,
1172                                INSN_LOCATION (if_info->insn_a));
1173       return TRUE;
1174     }
1175   else
1176     {
1177       end_sequence ();
1178       return FALSE;
1179     }
1180 }
1181
1182 /* Convert "if (test) x = a; else x = b", for A and B constant.
1183    Also allow A = y + c1, B = y + c2, with a common y between A
1184    and B.  */
1185
1186 static int
1187 noce_try_store_flag_constants (struct noce_if_info *if_info)
1188 {
1189   rtx target;
1190   rtx_insn *seq;
1191   bool reversep;
1192   HOST_WIDE_INT itrue, ifalse, diff, tmp;
1193   int normalize;
1194   bool can_reverse;
1195   machine_mode mode = GET_MODE (if_info->x);;
1196   rtx common = NULL_RTX;
1197
1198   rtx a = if_info->a;
1199   rtx b = if_info->b;
1200
1201   /* Handle cases like x := test ? y + 3 : y + 4.  */
1202   if (GET_CODE (a) == PLUS
1203       && GET_CODE (b) == PLUS
1204       && CONST_INT_P (XEXP (a, 1))
1205       && CONST_INT_P (XEXP (b, 1))
1206       && rtx_equal_p (XEXP (a, 0), XEXP (b, 0))
1207       && noce_operand_ok (XEXP (a, 0))
1208       && if_info->branch_cost >= 2)
1209     {
1210       common = XEXP (a, 0);
1211       a = XEXP (a, 1);
1212       b = XEXP (b, 1);
1213     }
1214
1215   if (!noce_simple_bbs (if_info))
1216     return FALSE;
1217
1218   if (CONST_INT_P (a)
1219       && CONST_INT_P (b))
1220     {
1221       ifalse = INTVAL (a);
1222       itrue = INTVAL (b);
1223       bool subtract_flag_p = false;
1224
1225       diff = (unsigned HOST_WIDE_INT) itrue - ifalse;
1226       /* Make sure we can represent the difference between the two values.  */
1227       if ((diff > 0)
1228           != ((ifalse < 0) != (itrue < 0) ? ifalse < 0 : ifalse < itrue))
1229         return FALSE;
1230
1231       diff = trunc_int_for_mode (diff, mode);
1232
1233       can_reverse = (reversed_comparison_code (if_info->cond, if_info->jump)
1234                      != UNKNOWN);
1235
1236       reversep = false;
1237       if (diff == STORE_FLAG_VALUE || diff == -STORE_FLAG_VALUE)
1238         {
1239           normalize = 0;
1240           /* We could collapse these cases but it is easier to follow the
1241              diff/STORE_FLAG_VALUE combinations when they are listed
1242              explicitly.  */
1243
1244           /* test ? 3 : 4
1245              => 4 + (test != 0).  */
1246           if (diff < 0 && STORE_FLAG_VALUE < 0)
1247               reversep = false;
1248           /* test ? 4 : 3
1249              => can_reverse  | 4 + (test == 0)
1250                 !can_reverse | 3 - (test != 0).  */
1251           else if (diff > 0 && STORE_FLAG_VALUE < 0)
1252             {
1253               reversep = can_reverse;
1254               subtract_flag_p = !can_reverse;
1255               /* If we need to subtract the flag and we have PLUS-immediate
1256                  A and B then it is unlikely to be beneficial to play tricks
1257                  here.  */
1258               if (subtract_flag_p && common)
1259                 return FALSE;
1260             }
1261           /* test ? 3 : 4
1262              => can_reverse  | 3 + (test == 0)
1263                 !can_reverse | 4 - (test != 0).  */
1264           else if (diff < 0 && STORE_FLAG_VALUE > 0)
1265             {
1266               reversep = can_reverse;
1267               subtract_flag_p = !can_reverse;
1268               /* If we need to subtract the flag and we have PLUS-immediate
1269                  A and B then it is unlikely to be beneficial to play tricks
1270                  here.  */
1271               if (subtract_flag_p && common)
1272                 return FALSE;
1273             }
1274           /* test ? 4 : 3
1275              => 4 + (test != 0).  */
1276           else if (diff > 0 && STORE_FLAG_VALUE > 0)
1277             reversep = false;
1278           else
1279             gcc_unreachable ();
1280         }
1281       else if (ifalse == 0 && exact_log2 (itrue) >= 0
1282                && (STORE_FLAG_VALUE == 1
1283                    || if_info->branch_cost >= 2))
1284         normalize = 1;
1285       else if (itrue == 0 && exact_log2 (ifalse) >= 0 && can_reverse
1286                && (STORE_FLAG_VALUE == 1 || if_info->branch_cost >= 2))
1287         {
1288           normalize = 1;
1289           reversep = true;
1290         }
1291       else if (itrue == -1
1292                && (STORE_FLAG_VALUE == -1
1293                    || if_info->branch_cost >= 2))
1294         normalize = -1;
1295       else if (ifalse == -1 && can_reverse
1296                && (STORE_FLAG_VALUE == -1 || if_info->branch_cost >= 2))
1297         {
1298           normalize = -1;
1299           reversep = true;
1300         }
1301       else
1302         return FALSE;
1303
1304       if (reversep)
1305         {
1306           std::swap (itrue, ifalse);
1307           diff = trunc_int_for_mode (-(unsigned HOST_WIDE_INT) diff, mode);
1308         }
1309
1310       start_sequence ();
1311
1312       /* If we have x := test ? x + 3 : x + 4 then move the original
1313          x out of the way while we store flags.  */
1314       if (common && rtx_equal_p (common, if_info->x))
1315         {
1316           common = gen_reg_rtx (mode);
1317           noce_emit_move_insn (common, if_info->x);
1318         }
1319
1320       target = noce_emit_store_flag (if_info, if_info->x, reversep, normalize);
1321       if (! target)
1322         {
1323           end_sequence ();
1324           return FALSE;
1325         }
1326
1327       /* if (test) x = 3; else x = 4;
1328          =>   x = 3 + (test == 0);  */
1329       if (diff == STORE_FLAG_VALUE || diff == -STORE_FLAG_VALUE)
1330         {
1331           /* Add the common part now.  This may allow combine to merge this
1332              with the store flag operation earlier into some sort of conditional
1333              increment/decrement if the target allows it.  */
1334           if (common)
1335             target = expand_simple_binop (mode, PLUS,
1336                                            target, common,
1337                                            target, 0, OPTAB_WIDEN);
1338
1339           /* Always use ifalse here.  It should have been swapped with itrue
1340              when appropriate when reversep is true.  */
1341           target = expand_simple_binop (mode, subtract_flag_p ? MINUS : PLUS,
1342                                         gen_int_mode (ifalse, mode), target,
1343                                         if_info->x, 0, OPTAB_WIDEN);
1344         }
1345       /* Other cases are not beneficial when the original A and B are PLUS
1346          expressions.  */
1347       else if (common)
1348         {
1349           end_sequence ();
1350           return FALSE;
1351         }
1352       /* if (test) x = 8; else x = 0;
1353          =>   x = (test != 0) << 3;  */
1354       else if (ifalse == 0 && (tmp = exact_log2 (itrue)) >= 0)
1355         {
1356           target = expand_simple_binop (mode, ASHIFT,
1357                                         target, GEN_INT (tmp), if_info->x, 0,
1358                                         OPTAB_WIDEN);
1359         }
1360
1361       /* if (test) x = -1; else x = b;
1362          =>   x = -(test != 0) | b;  */
1363       else if (itrue == -1)
1364         {
1365           target = expand_simple_binop (mode, IOR,
1366                                         target, gen_int_mode (ifalse, mode),
1367                                         if_info->x, 0, OPTAB_WIDEN);
1368         }
1369       else
1370         {
1371           end_sequence ();
1372           return FALSE;
1373         }
1374
1375       if (! target)
1376         {
1377           end_sequence ();
1378           return FALSE;
1379         }
1380
1381       if (target != if_info->x)
1382         noce_emit_move_insn (if_info->x, target);
1383
1384       seq = end_ifcvt_sequence (if_info);
1385       if (!seq)
1386         return FALSE;
1387
1388       emit_insn_before_setloc (seq, if_info->jump,
1389                                INSN_LOCATION (if_info->insn_a));
1390       return TRUE;
1391     }
1392
1393   return FALSE;
1394 }
1395
1396 /* Convert "if (test) foo++" into "foo += (test != 0)", and
1397    similarly for "foo--".  */
1398
1399 static int
1400 noce_try_addcc (struct noce_if_info *if_info)
1401 {
1402   rtx target;
1403   rtx_insn *seq;
1404   int subtract, normalize;
1405
1406   if (!noce_simple_bbs (if_info))
1407     return FALSE;
1408
1409   if (GET_CODE (if_info->a) == PLUS
1410       && rtx_equal_p (XEXP (if_info->a, 0), if_info->b)
1411       && (reversed_comparison_code (if_info->cond, if_info->jump)
1412           != UNKNOWN))
1413     {
1414       rtx cond = if_info->cond;
1415       enum rtx_code code = reversed_comparison_code (cond, if_info->jump);
1416
1417       /* First try to use addcc pattern.  */
1418       if (general_operand (XEXP (cond, 0), VOIDmode)
1419           && general_operand (XEXP (cond, 1), VOIDmode))
1420         {
1421           start_sequence ();
1422           target = emit_conditional_add (if_info->x, code,
1423                                          XEXP (cond, 0),
1424                                          XEXP (cond, 1),
1425                                          VOIDmode,
1426                                          if_info->b,
1427                                          XEXP (if_info->a, 1),
1428                                          GET_MODE (if_info->x),
1429                                          (code == LTU || code == GEU
1430                                           || code == LEU || code == GTU));
1431           if (target)
1432             {
1433               if (target != if_info->x)
1434                 noce_emit_move_insn (if_info->x, target);
1435
1436               seq = end_ifcvt_sequence (if_info);
1437               if (!seq)
1438                 return FALSE;
1439
1440               emit_insn_before_setloc (seq, if_info->jump,
1441                                        INSN_LOCATION (if_info->insn_a));
1442               return TRUE;
1443             }
1444           end_sequence ();
1445         }
1446
1447       /* If that fails, construct conditional increment or decrement using
1448          setcc.  */
1449       if (if_info->branch_cost >= 2
1450           && (XEXP (if_info->a, 1) == const1_rtx
1451               || XEXP (if_info->a, 1) == constm1_rtx))
1452         {
1453           start_sequence ();
1454           if (STORE_FLAG_VALUE == INTVAL (XEXP (if_info->a, 1)))
1455             subtract = 0, normalize = 0;
1456           else if (-STORE_FLAG_VALUE == INTVAL (XEXP (if_info->a, 1)))
1457             subtract = 1, normalize = 0;
1458           else
1459             subtract = 0, normalize = INTVAL (XEXP (if_info->a, 1));
1460
1461
1462           target = noce_emit_store_flag (if_info,
1463                                          gen_reg_rtx (GET_MODE (if_info->x)),
1464                                          1, normalize);
1465
1466           if (target)
1467             target = expand_simple_binop (GET_MODE (if_info->x),
1468                                           subtract ? MINUS : PLUS,
1469                                           if_info->b, target, if_info->x,
1470                                           0, OPTAB_WIDEN);
1471           if (target)
1472             {
1473               if (target != if_info->x)
1474                 noce_emit_move_insn (if_info->x, target);
1475
1476               seq = end_ifcvt_sequence (if_info);
1477               if (!seq)
1478                 return FALSE;
1479
1480               emit_insn_before_setloc (seq, if_info->jump,
1481                                        INSN_LOCATION (if_info->insn_a));
1482               return TRUE;
1483             }
1484           end_sequence ();
1485         }
1486     }
1487
1488   return FALSE;
1489 }
1490
1491 /* Convert "if (test) x = 0;" to "x &= -(test == 0);"  */
1492
1493 static int
1494 noce_try_store_flag_mask (struct noce_if_info *if_info)
1495 {
1496   rtx target;
1497   rtx_insn *seq;
1498   int reversep;
1499
1500   if (!noce_simple_bbs (if_info))
1501     return FALSE;
1502
1503   reversep = 0;
1504   if ((if_info->branch_cost >= 2
1505        || STORE_FLAG_VALUE == -1)
1506       && ((if_info->a == const0_rtx
1507            && rtx_equal_p (if_info->b, if_info->x))
1508           || ((reversep = (reversed_comparison_code (if_info->cond,
1509                                                      if_info->jump)
1510                            != UNKNOWN))
1511               && if_info->b == const0_rtx
1512               && rtx_equal_p (if_info->a, if_info->x))))
1513     {
1514       start_sequence ();
1515       target = noce_emit_store_flag (if_info,
1516                                      gen_reg_rtx (GET_MODE (if_info->x)),
1517                                      reversep, -1);
1518       if (target)
1519         target = expand_simple_binop (GET_MODE (if_info->x), AND,
1520                                       if_info->x,
1521                                       target, if_info->x, 0,
1522                                       OPTAB_WIDEN);
1523
1524       if (target)
1525         {
1526           int old_cost, new_cost, insn_cost;
1527           int speed_p;
1528
1529           if (target != if_info->x)
1530             noce_emit_move_insn (if_info->x, target);
1531
1532           seq = end_ifcvt_sequence (if_info);
1533           if (!seq)
1534             return FALSE;
1535
1536           speed_p = optimize_bb_for_speed_p (BLOCK_FOR_INSN (if_info->insn_a));
1537           insn_cost = insn_rtx_cost (PATTERN (if_info->insn_a), speed_p);
1538           old_cost = COSTS_N_INSNS (if_info->branch_cost) + insn_cost;
1539           new_cost = seq_cost (seq, speed_p);
1540
1541           if (new_cost > old_cost)
1542             return FALSE;
1543
1544           emit_insn_before_setloc (seq, if_info->jump,
1545                                    INSN_LOCATION (if_info->insn_a));
1546           return TRUE;
1547         }
1548
1549       end_sequence ();
1550     }
1551
1552   return FALSE;
1553 }
1554
1555 /* Helper function for noce_try_cmove and noce_try_cmove_arith.  */
1556
1557 static rtx
1558 noce_emit_cmove (struct noce_if_info *if_info, rtx x, enum rtx_code code,
1559                  rtx cmp_a, rtx cmp_b, rtx vfalse, rtx vtrue)
1560 {
1561   rtx target ATTRIBUTE_UNUSED;
1562   int unsignedp ATTRIBUTE_UNUSED;
1563
1564   /* If earliest == jump, try to build the cmove insn directly.
1565      This is helpful when combine has created some complex condition
1566      (like for alpha's cmovlbs) that we can't hope to regenerate
1567      through the normal interface.  */
1568
1569   if (if_info->cond_earliest == if_info->jump)
1570     {
1571       rtx cond = gen_rtx_fmt_ee (code, GET_MODE (if_info->cond), cmp_a, cmp_b);
1572       rtx if_then_else = gen_rtx_IF_THEN_ELSE (GET_MODE (x),
1573                                                cond, vtrue, vfalse);
1574       rtx set = gen_rtx_SET (x, if_then_else);
1575
1576       start_sequence ();
1577       rtx_insn *insn = emit_insn (set);
1578
1579       if (recog_memoized (insn) >= 0)
1580         {
1581           rtx_insn *seq = get_insns ();
1582           end_sequence ();
1583           emit_insn (seq);
1584
1585           return x;
1586         }
1587
1588       end_sequence ();
1589     }
1590
1591   /* Don't even try if the comparison operands are weird
1592      except that the target supports cbranchcc4.  */
1593   if (! general_operand (cmp_a, GET_MODE (cmp_a))
1594       || ! general_operand (cmp_b, GET_MODE (cmp_b)))
1595     {
1596       if (!have_cbranchcc4
1597           || GET_MODE_CLASS (GET_MODE (cmp_a)) != MODE_CC
1598           || cmp_b != const0_rtx)
1599         return NULL_RTX;
1600     }
1601
1602   unsignedp = (code == LTU || code == GEU
1603                || code == LEU || code == GTU);
1604
1605   target = emit_conditional_move (x, code, cmp_a, cmp_b, VOIDmode,
1606                                   vtrue, vfalse, GET_MODE (x),
1607                                   unsignedp);
1608   if (target)
1609     return target;
1610
1611   /* We might be faced with a situation like:
1612
1613      x = (reg:M TARGET)
1614      vtrue = (subreg:M (reg:N VTRUE) BYTE)
1615      vfalse = (subreg:M (reg:N VFALSE) BYTE)
1616
1617      We can't do a conditional move in mode M, but it's possible that we
1618      could do a conditional move in mode N instead and take a subreg of
1619      the result.
1620
1621      If we can't create new pseudos, though, don't bother.  */
1622   if (reload_completed)
1623     return NULL_RTX;
1624
1625   if (GET_CODE (vtrue) == SUBREG && GET_CODE (vfalse) == SUBREG)
1626     {
1627       rtx reg_vtrue = SUBREG_REG (vtrue);
1628       rtx reg_vfalse = SUBREG_REG (vfalse);
1629       unsigned int byte_vtrue = SUBREG_BYTE (vtrue);
1630       unsigned int byte_vfalse = SUBREG_BYTE (vfalse);
1631       rtx promoted_target;
1632
1633       if (GET_MODE (reg_vtrue) != GET_MODE (reg_vfalse)
1634           || byte_vtrue != byte_vfalse
1635           || (SUBREG_PROMOTED_VAR_P (vtrue)
1636               != SUBREG_PROMOTED_VAR_P (vfalse))
1637           || (SUBREG_PROMOTED_GET (vtrue)
1638               != SUBREG_PROMOTED_GET (vfalse)))
1639         return NULL_RTX;
1640
1641       promoted_target = gen_reg_rtx (GET_MODE (reg_vtrue));
1642
1643       target = emit_conditional_move (promoted_target, code, cmp_a, cmp_b,
1644                                       VOIDmode, reg_vtrue, reg_vfalse,
1645                                       GET_MODE (reg_vtrue), unsignedp);
1646       /* Nope, couldn't do it in that mode either.  */
1647       if (!target)
1648         return NULL_RTX;
1649
1650       target = gen_rtx_SUBREG (GET_MODE (vtrue), promoted_target, byte_vtrue);
1651       SUBREG_PROMOTED_VAR_P (target) = SUBREG_PROMOTED_VAR_P (vtrue);
1652       SUBREG_PROMOTED_SET (target, SUBREG_PROMOTED_GET (vtrue));
1653       emit_move_insn (x, target);
1654       return x;
1655     }
1656   else
1657     return NULL_RTX;
1658 }
1659
1660 /* Try only simple constants and registers here.  More complex cases
1661    are handled in noce_try_cmove_arith after noce_try_store_flag_arith
1662    has had a go at it.  */
1663
1664 static int
1665 noce_try_cmove (struct noce_if_info *if_info)
1666 {
1667   enum rtx_code code;
1668   rtx target;
1669   rtx_insn *seq;
1670
1671   if (!noce_simple_bbs (if_info))
1672     return FALSE;
1673
1674   if ((CONSTANT_P (if_info->a) || register_operand (if_info->a, VOIDmode))
1675       && (CONSTANT_P (if_info->b) || register_operand (if_info->b, VOIDmode)))
1676     {
1677       start_sequence ();
1678
1679       code = GET_CODE (if_info->cond);
1680       target = noce_emit_cmove (if_info, if_info->x, code,
1681                                 XEXP (if_info->cond, 0),
1682                                 XEXP (if_info->cond, 1),
1683                                 if_info->a, if_info->b);
1684
1685       if (target)
1686         {
1687           if (target != if_info->x)
1688             noce_emit_move_insn (if_info->x, target);
1689
1690           seq = end_ifcvt_sequence (if_info);
1691           if (!seq)
1692             return FALSE;
1693
1694           emit_insn_before_setloc (seq, if_info->jump,
1695                                    INSN_LOCATION (if_info->insn_a));
1696           return TRUE;
1697         }
1698       /* If both a and b are constants try a last-ditch transformation:
1699          if (test) x = a; else x = b;
1700          =>   x = (-(test != 0) & (b - a)) + a;
1701          Try this only if the target-specific expansion above has failed.
1702          The target-specific expander may want to generate sequences that
1703          we don't know about, so give them a chance before trying this
1704          approach.  */
1705       else if (!targetm.have_conditional_execution ()
1706                 && CONST_INT_P (if_info->a) && CONST_INT_P (if_info->b)
1707                 && ((if_info->branch_cost >= 2 && STORE_FLAG_VALUE == -1)
1708                     || if_info->branch_cost >= 3))
1709         {
1710           machine_mode mode = GET_MODE (if_info->x);
1711           HOST_WIDE_INT ifalse = INTVAL (if_info->a);
1712           HOST_WIDE_INT itrue = INTVAL (if_info->b);
1713           rtx target = noce_emit_store_flag (if_info, if_info->x, false, -1);
1714           if (!target)
1715             {
1716               end_sequence ();
1717               return FALSE;
1718             }
1719
1720           HOST_WIDE_INT diff = (unsigned HOST_WIDE_INT) itrue - ifalse;
1721           /* Make sure we can represent the difference
1722              between the two values.  */
1723           if ((diff > 0)
1724               != ((ifalse < 0) != (itrue < 0) ? ifalse < 0 : ifalse < itrue))
1725             {
1726               end_sequence ();
1727               return FALSE;
1728             }
1729
1730           diff = trunc_int_for_mode (diff, mode);
1731           target = expand_simple_binop (mode, AND,
1732                                         target, gen_int_mode (diff, mode),
1733                                         if_info->x, 0, OPTAB_WIDEN);
1734           if (target)
1735             target = expand_simple_binop (mode, PLUS,
1736                                           target, gen_int_mode (ifalse, mode),
1737                                           if_info->x, 0, OPTAB_WIDEN);
1738           if (target)
1739             {
1740               if (target != if_info->x)
1741                 noce_emit_move_insn (if_info->x, target);
1742
1743               seq = end_ifcvt_sequence (if_info);
1744               if (!seq)
1745                 return FALSE;
1746
1747               emit_insn_before_setloc (seq, if_info->jump,
1748                                    INSN_LOCATION (if_info->insn_a));
1749               return TRUE;
1750             }
1751           else
1752             {
1753               end_sequence ();
1754               return FALSE;
1755             }
1756         }
1757       else
1758         end_sequence ();
1759     }
1760
1761   return FALSE;
1762 }
1763
1764 /* Helper for bb_valid_for_noce_process_p.  Validate that
1765    the rtx insn INSN is a single set that does not set
1766    the conditional register CC and is in general valid for
1767    if-conversion.  */
1768
1769 static bool
1770 insn_valid_noce_process_p (rtx_insn *insn, rtx cc)
1771 {
1772   if (!insn
1773       || !NONJUMP_INSN_P (insn)
1774       || (cc && set_of (cc, insn)))
1775       return false;
1776
1777   rtx sset = single_set (insn);
1778
1779   /* Currently support only simple single sets in test_bb.  */
1780   if (!sset
1781       || !noce_operand_ok (SET_DEST (sset))
1782       || !noce_operand_ok (SET_SRC (sset)))
1783     return false;
1784
1785   return true;
1786 }
1787
1788
1789 /* Return true iff the registers that the insns in BB_A set do not
1790    get used in BB_B.  */
1791
1792 static bool
1793 bbs_ok_for_cmove_arith (basic_block bb_a, basic_block bb_b)
1794 {
1795   rtx_insn *a_insn;
1796   bitmap bba_sets = BITMAP_ALLOC (&reg_obstack);
1797
1798   df_ref def;
1799   df_ref use;
1800
1801   FOR_BB_INSNS (bb_a, a_insn)
1802     {
1803       if (!active_insn_p (a_insn))
1804         continue;
1805
1806       rtx sset_a = single_set (a_insn);
1807
1808       if (!sset_a)
1809         {
1810           BITMAP_FREE (bba_sets);
1811           return false;
1812         }
1813
1814       /* Record all registers that BB_A sets.  */
1815       FOR_EACH_INSN_DEF (def, a_insn)
1816         bitmap_set_bit (bba_sets, DF_REF_REGNO (def));
1817     }
1818
1819   rtx_insn *b_insn;
1820
1821   FOR_BB_INSNS (bb_b, b_insn)
1822     {
1823       if (!active_insn_p (b_insn))
1824         continue;
1825
1826       rtx sset_b = single_set (b_insn);
1827
1828       if (!sset_b)
1829         {
1830           BITMAP_FREE (bba_sets);
1831           return false;
1832         }
1833
1834       /* Make sure this is a REG and not some instance
1835          of ZERO_EXTRACT or SUBREG or other dangerous stuff.  */
1836       if (!REG_P (SET_DEST (sset_b)))
1837         {
1838           BITMAP_FREE (bba_sets);
1839           return false;
1840         }
1841
1842       /* If the insn uses a reg set in BB_A return false.  */
1843       FOR_EACH_INSN_USE (use, b_insn)
1844         {
1845           if (bitmap_bit_p (bba_sets, DF_REF_REGNO (use)))
1846             {
1847               BITMAP_FREE (bba_sets);
1848               return false;
1849             }
1850         }
1851
1852     }
1853
1854   BITMAP_FREE (bba_sets);
1855   return true;
1856 }
1857
1858 /* Emit copies of all the active instructions in BB except the last.
1859    This is a helper for noce_try_cmove_arith.  */
1860
1861 static void
1862 noce_emit_all_but_last (basic_block bb)
1863 {
1864   rtx_insn *last = last_active_insn (bb, FALSE);
1865   rtx_insn *insn;
1866   FOR_BB_INSNS (bb, insn)
1867     {
1868       if (insn != last && active_insn_p (insn))
1869         {
1870           rtx_insn *to_emit = as_a <rtx_insn *> (copy_rtx (insn));
1871
1872           emit_insn (PATTERN (to_emit));
1873         }
1874     }
1875 }
1876
1877 /* Helper for noce_try_cmove_arith.  Emit the pattern TO_EMIT and return
1878    the resulting insn or NULL if it's not a valid insn.  */
1879
1880 static rtx_insn *
1881 noce_emit_insn (rtx to_emit)
1882 {
1883   gcc_assert (to_emit);
1884   rtx_insn *insn = emit_insn (to_emit);
1885
1886   if (recog_memoized (insn) < 0)
1887     return NULL;
1888
1889   return insn;
1890 }
1891
1892 /* Helper for noce_try_cmove_arith.  Emit a copy of the insns up to
1893    and including the penultimate one in BB if it is not simple
1894    (as indicated by SIMPLE).  Then emit LAST_INSN as the last
1895    insn in the block.  The reason for that is that LAST_INSN may
1896    have been modified by the preparation in noce_try_cmove_arith.  */
1897
1898 static bool
1899 noce_emit_bb (rtx last_insn, basic_block bb, bool simple)
1900 {
1901   if (bb && !simple)
1902     noce_emit_all_but_last (bb);
1903
1904   if (last_insn && !noce_emit_insn (last_insn))
1905     return false;
1906
1907   return true;
1908 }
1909
1910 /* Try more complex cases involving conditional_move.  */
1911
1912 static int
1913 noce_try_cmove_arith (struct noce_if_info *if_info)
1914 {
1915   rtx a = if_info->a;
1916   rtx b = if_info->b;
1917   rtx x = if_info->x;
1918   rtx orig_a, orig_b;
1919   rtx_insn *insn_a, *insn_b;
1920   bool a_simple = if_info->then_simple;
1921   bool b_simple = if_info->else_simple;
1922   basic_block then_bb = if_info->then_bb;
1923   basic_block else_bb = if_info->else_bb;
1924   rtx target;
1925   int is_mem = 0;
1926   enum rtx_code code;
1927   rtx_insn *ifcvt_seq;
1928
1929   /* A conditional move from two memory sources is equivalent to a
1930      conditional on their addresses followed by a load.  Don't do this
1931      early because it'll screw alias analysis.  Note that we've
1932      already checked for no side effects.  */
1933   /* ??? FIXME: Magic number 5.  */
1934   if (cse_not_expected
1935       && MEM_P (a) && MEM_P (b)
1936       && MEM_ADDR_SPACE (a) == MEM_ADDR_SPACE (b)
1937       && if_info->branch_cost >= 5)
1938     {
1939       machine_mode address_mode = get_address_mode (a);
1940
1941       a = XEXP (a, 0);
1942       b = XEXP (b, 0);
1943       x = gen_reg_rtx (address_mode);
1944       is_mem = 1;
1945     }
1946
1947   /* ??? We could handle this if we knew that a load from A or B could
1948      not trap or fault.  This is also true if we've already loaded
1949      from the address along the path from ENTRY.  */
1950   else if (may_trap_or_fault_p (a) || may_trap_or_fault_p (b))
1951     return FALSE;
1952
1953   /* if (test) x = a + b; else x = c - d;
1954      => y = a + b;
1955         x = c - d;
1956         if (test)
1957           x = y;
1958   */
1959
1960   code = GET_CODE (if_info->cond);
1961   insn_a = if_info->insn_a;
1962   insn_b = if_info->insn_b;
1963
1964   unsigned int then_cost;
1965   unsigned int else_cost;
1966   if (insn_a)
1967     then_cost = if_info->then_cost;
1968   else
1969     then_cost = 0;
1970
1971   if (insn_b)
1972     else_cost = if_info->else_cost;
1973   else
1974     else_cost = 0;
1975
1976   /* We're going to execute one of the basic blocks anyway, so
1977      bail out if the most expensive of the two blocks is unacceptable.  */
1978   if (MAX (then_cost, else_cost) > COSTS_N_INSNS (if_info->branch_cost))
1979     return FALSE;
1980
1981   /* Possibly rearrange operands to make things come out more natural.  */
1982   if (reversed_comparison_code (if_info->cond, if_info->jump) != UNKNOWN)
1983     {
1984       int reversep = 0;
1985       if (rtx_equal_p (b, x))
1986         reversep = 1;
1987       else if (general_operand (b, GET_MODE (b)))
1988         reversep = 1;
1989
1990       if (reversep)
1991         {
1992           code = reversed_comparison_code (if_info->cond, if_info->jump);
1993           std::swap (a, b);
1994           std::swap (insn_a, insn_b);
1995           std::swap (a_simple, b_simple);
1996           std::swap (then_bb, else_bb);
1997         }
1998     }
1999
2000   if (!a_simple && then_bb && !b_simple && else_bb
2001       && (!bbs_ok_for_cmove_arith (then_bb, else_bb)
2002           || !bbs_ok_for_cmove_arith (else_bb, then_bb)))
2003     return FALSE;
2004
2005   start_sequence ();
2006
2007   orig_a = a;
2008   orig_b = b;
2009
2010   rtx emit_a = NULL_RTX;
2011   rtx emit_b = NULL_RTX;
2012
2013   /* If either operand is complex, load it into a register first.
2014      The best way to do this is to copy the original insn.  In this
2015      way we preserve any clobbers etc that the insn may have had.
2016      This is of course not possible in the IS_MEM case.  */
2017
2018   if (! general_operand (a, GET_MODE (a)))
2019     {
2020
2021       if (is_mem)
2022         {
2023           rtx reg = gen_reg_rtx (GET_MODE (a));
2024           emit_a = gen_rtx_SET (reg, a);
2025         }
2026       else if (! insn_a)
2027         goto end_seq_and_fail;
2028       else
2029         {
2030           a = gen_reg_rtx (GET_MODE (a));
2031           rtx_insn *copy_of_a = as_a <rtx_insn *> (copy_rtx (insn_a));
2032           rtx set = single_set (copy_of_a);
2033           SET_DEST (set) = a;
2034
2035           emit_a = PATTERN (copy_of_a);
2036         }
2037     }
2038
2039   if (! general_operand (b, GET_MODE (b)))
2040     {
2041       if (is_mem)
2042         {
2043           rtx reg = gen_reg_rtx (GET_MODE (b));
2044           emit_b = gen_rtx_SET (reg, b);
2045         }
2046       else if (! insn_b)
2047         goto end_seq_and_fail;
2048       else
2049         {
2050           b = gen_reg_rtx (GET_MODE (b));
2051           rtx_insn *copy_of_b = as_a <rtx_insn *> (copy_rtx (insn_b));
2052           rtx set = single_set (copy_of_b);
2053
2054           SET_DEST (set) = b;
2055           emit_b = PATTERN (copy_of_b);
2056         }
2057     }
2058
2059     /* If insn to set up A clobbers any registers B depends on, try to
2060        swap insn that sets up A with the one that sets up B.  If even
2061        that doesn't help, punt.  */
2062
2063     if (emit_a && modified_in_p (orig_b, emit_a))
2064       {
2065         if (modified_in_p (orig_a, emit_b))
2066           goto end_seq_and_fail;
2067
2068         if (else_bb && !b_simple)
2069           {
2070             if (!noce_emit_bb (emit_b, else_bb, b_simple))
2071               goto end_seq_and_fail;
2072           }
2073
2074         if (!noce_emit_bb (emit_a, then_bb, a_simple))
2075           goto end_seq_and_fail;
2076       }
2077     else
2078       {
2079         if (!noce_emit_bb (emit_a, then_bb, a_simple))
2080           goto end_seq_and_fail;
2081
2082         if (!noce_emit_bb (emit_b, else_bb, b_simple))
2083           goto end_seq_and_fail;
2084
2085       }
2086
2087   target = noce_emit_cmove (if_info, x, code, XEXP (if_info->cond, 0),
2088                             XEXP (if_info->cond, 1), a, b);
2089
2090   if (! target)
2091     goto end_seq_and_fail;
2092
2093   /* If we're handling a memory for above, emit the load now.  */
2094   if (is_mem)
2095     {
2096       rtx mem = gen_rtx_MEM (GET_MODE (if_info->x), target);
2097
2098       /* Copy over flags as appropriate.  */
2099       if (MEM_VOLATILE_P (if_info->a) || MEM_VOLATILE_P (if_info->b))
2100         MEM_VOLATILE_P (mem) = 1;
2101       if (MEM_ALIAS_SET (if_info->a) == MEM_ALIAS_SET (if_info->b))
2102         set_mem_alias_set (mem, MEM_ALIAS_SET (if_info->a));
2103       set_mem_align (mem,
2104                      MIN (MEM_ALIGN (if_info->a), MEM_ALIGN (if_info->b)));
2105
2106       gcc_assert (MEM_ADDR_SPACE (if_info->a) == MEM_ADDR_SPACE (if_info->b));
2107       set_mem_addr_space (mem, MEM_ADDR_SPACE (if_info->a));
2108
2109       noce_emit_move_insn (if_info->x, mem);
2110     }
2111   else if (target != x)
2112     noce_emit_move_insn (x, target);
2113
2114   ifcvt_seq = end_ifcvt_sequence (if_info);
2115   if (!ifcvt_seq)
2116     return FALSE;
2117
2118   emit_insn_before_setloc (ifcvt_seq, if_info->jump,
2119                            INSN_LOCATION (if_info->insn_a));
2120   return TRUE;
2121
2122  end_seq_and_fail:
2123   end_sequence ();
2124   return FALSE;
2125 }
2126
2127 /* For most cases, the simplified condition we found is the best
2128    choice, but this is not the case for the min/max/abs transforms.
2129    For these we wish to know that it is A or B in the condition.  */
2130
2131 static rtx
2132 noce_get_alt_condition (struct noce_if_info *if_info, rtx target,
2133                         rtx_insn **earliest)
2134 {
2135   rtx cond, set;
2136   rtx_insn *insn;
2137   int reverse;
2138
2139   /* If target is already mentioned in the known condition, return it.  */
2140   if (reg_mentioned_p (target, if_info->cond))
2141     {
2142       *earliest = if_info->cond_earliest;
2143       return if_info->cond;
2144     }
2145
2146   set = pc_set (if_info->jump);
2147   cond = XEXP (SET_SRC (set), 0);
2148   reverse
2149     = GET_CODE (XEXP (SET_SRC (set), 2)) == LABEL_REF
2150       && LABEL_REF_LABEL (XEXP (SET_SRC (set), 2)) == JUMP_LABEL (if_info->jump);
2151   if (if_info->then_else_reversed)
2152     reverse = !reverse;
2153
2154   /* If we're looking for a constant, try to make the conditional
2155      have that constant in it.  There are two reasons why it may
2156      not have the constant we want:
2157
2158      1. GCC may have needed to put the constant in a register, because
2159         the target can't compare directly against that constant.  For
2160         this case, we look for a SET immediately before the comparison
2161         that puts a constant in that register.
2162
2163      2. GCC may have canonicalized the conditional, for example
2164         replacing "if x < 4" with "if x <= 3".  We can undo that (or
2165         make equivalent types of changes) to get the constants we need
2166         if they're off by one in the right direction.  */
2167
2168   if (CONST_INT_P (target))
2169     {
2170       enum rtx_code code = GET_CODE (if_info->cond);
2171       rtx op_a = XEXP (if_info->cond, 0);
2172       rtx op_b = XEXP (if_info->cond, 1);
2173       rtx_insn *prev_insn;
2174
2175       /* First, look to see if we put a constant in a register.  */
2176       prev_insn = prev_nonnote_insn (if_info->cond_earliest);
2177       if (prev_insn
2178           && BLOCK_FOR_INSN (prev_insn)
2179              == BLOCK_FOR_INSN (if_info->cond_earliest)
2180           && INSN_P (prev_insn)
2181           && GET_CODE (PATTERN (prev_insn)) == SET)
2182         {
2183           rtx src = find_reg_equal_equiv_note (prev_insn);
2184           if (!src)
2185             src = SET_SRC (PATTERN (prev_insn));
2186           if (CONST_INT_P (src))
2187             {
2188               if (rtx_equal_p (op_a, SET_DEST (PATTERN (prev_insn))))
2189                 op_a = src;
2190               else if (rtx_equal_p (op_b, SET_DEST (PATTERN (prev_insn))))
2191                 op_b = src;
2192
2193               if (CONST_INT_P (op_a))
2194                 {
2195                   std::swap (op_a, op_b);
2196                   code = swap_condition (code);
2197                 }
2198             }
2199         }
2200
2201       /* Now, look to see if we can get the right constant by
2202          adjusting the conditional.  */
2203       if (CONST_INT_P (op_b))
2204         {
2205           HOST_WIDE_INT desired_val = INTVAL (target);
2206           HOST_WIDE_INT actual_val = INTVAL (op_b);
2207
2208           switch (code)
2209             {
2210             case LT:
2211               if (actual_val == desired_val + 1)
2212                 {
2213                   code = LE;
2214                   op_b = GEN_INT (desired_val);
2215                 }
2216               break;
2217             case LE:
2218               if (actual_val == desired_val - 1)
2219                 {
2220                   code = LT;
2221                   op_b = GEN_INT (desired_val);
2222                 }
2223               break;
2224             case GT:
2225               if (actual_val == desired_val - 1)
2226                 {
2227                   code = GE;
2228                   op_b = GEN_INT (desired_val);
2229                 }
2230               break;
2231             case GE:
2232               if (actual_val == desired_val + 1)
2233                 {
2234                   code = GT;
2235                   op_b = GEN_INT (desired_val);
2236                 }
2237               break;
2238             default:
2239               break;
2240             }
2241         }
2242
2243       /* If we made any changes, generate a new conditional that is
2244          equivalent to what we started with, but has the right
2245          constants in it.  */
2246       if (code != GET_CODE (if_info->cond)
2247           || op_a != XEXP (if_info->cond, 0)
2248           || op_b != XEXP (if_info->cond, 1))
2249         {
2250           cond = gen_rtx_fmt_ee (code, GET_MODE (cond), op_a, op_b);
2251           *earliest = if_info->cond_earliest;
2252           return cond;
2253         }
2254     }
2255
2256   cond = canonicalize_condition (if_info->jump, cond, reverse,
2257                                  earliest, target, have_cbranchcc4, true);
2258   if (! cond || ! reg_mentioned_p (target, cond))
2259     return NULL;
2260
2261   /* We almost certainly searched back to a different place.
2262      Need to re-verify correct lifetimes.  */
2263
2264   /* X may not be mentioned in the range (cond_earliest, jump].  */
2265   for (insn = if_info->jump; insn != *earliest; insn = PREV_INSN (insn))
2266     if (INSN_P (insn) && reg_overlap_mentioned_p (if_info->x, PATTERN (insn)))
2267       return NULL;
2268
2269   /* A and B may not be modified in the range [cond_earliest, jump).  */
2270   for (insn = *earliest; insn != if_info->jump; insn = NEXT_INSN (insn))
2271     if (INSN_P (insn)
2272         && (modified_in_p (if_info->a, insn)
2273             || modified_in_p (if_info->b, insn)))
2274       return NULL;
2275
2276   return cond;
2277 }
2278
2279 /* Convert "if (a < b) x = a; else x = b;" to "x = min(a, b);", etc.  */
2280
2281 static int
2282 noce_try_minmax (struct noce_if_info *if_info)
2283 {
2284   rtx cond, target;
2285   rtx_insn *earliest, *seq;
2286   enum rtx_code code, op;
2287   int unsignedp;
2288
2289   if (!noce_simple_bbs (if_info))
2290     return FALSE;
2291
2292   /* ??? Reject modes with NaNs or signed zeros since we don't know how
2293      they will be resolved with an SMIN/SMAX.  It wouldn't be too hard
2294      to get the target to tell us...  */
2295   if (HONOR_SIGNED_ZEROS (if_info->x)
2296       || HONOR_NANS (if_info->x))
2297     return FALSE;
2298
2299   cond = noce_get_alt_condition (if_info, if_info->a, &earliest);
2300   if (!cond)
2301     return FALSE;
2302
2303   /* Verify the condition is of the form we expect, and canonicalize
2304      the comparison code.  */
2305   code = GET_CODE (cond);
2306   if (rtx_equal_p (XEXP (cond, 0), if_info->a))
2307     {
2308       if (! rtx_equal_p (XEXP (cond, 1), if_info->b))
2309         return FALSE;
2310     }
2311   else if (rtx_equal_p (XEXP (cond, 1), if_info->a))
2312     {
2313       if (! rtx_equal_p (XEXP (cond, 0), if_info->b))
2314         return FALSE;
2315       code = swap_condition (code);
2316     }
2317   else
2318     return FALSE;
2319
2320   /* Determine what sort of operation this is.  Note that the code is for
2321      a taken branch, so the code->operation mapping appears backwards.  */
2322   switch (code)
2323     {
2324     case LT:
2325     case LE:
2326     case UNLT:
2327     case UNLE:
2328       op = SMAX;
2329       unsignedp = 0;
2330       break;
2331     case GT:
2332     case GE:
2333     case UNGT:
2334     case UNGE:
2335       op = SMIN;
2336       unsignedp = 0;
2337       break;
2338     case LTU:
2339     case LEU:
2340       op = UMAX;
2341       unsignedp = 1;
2342       break;
2343     case GTU:
2344     case GEU:
2345       op = UMIN;
2346       unsignedp = 1;
2347       break;
2348     default:
2349       return FALSE;
2350     }
2351
2352   start_sequence ();
2353
2354   target = expand_simple_binop (GET_MODE (if_info->x), op,
2355                                 if_info->a, if_info->b,
2356                                 if_info->x, unsignedp, OPTAB_WIDEN);
2357   if (! target)
2358     {
2359       end_sequence ();
2360       return FALSE;
2361     }
2362   if (target != if_info->x)
2363     noce_emit_move_insn (if_info->x, target);
2364
2365   seq = end_ifcvt_sequence (if_info);
2366   if (!seq)
2367     return FALSE;
2368
2369   emit_insn_before_setloc (seq, if_info->jump, INSN_LOCATION (if_info->insn_a));
2370   if_info->cond = cond;
2371   if_info->cond_earliest = earliest;
2372
2373   return TRUE;
2374 }
2375
2376 /* Convert "if (a < 0) x = -a; else x = a;" to "x = abs(a);",
2377    "if (a < 0) x = ~a; else x = a;" to "x = one_cmpl_abs(a);",
2378    etc.  */
2379
2380 static int
2381 noce_try_abs (struct noce_if_info *if_info)
2382 {
2383   rtx cond, target, a, b, c;
2384   rtx_insn *earliest, *seq;
2385   int negate;
2386   bool one_cmpl = false;
2387
2388   if (!noce_simple_bbs (if_info))
2389     return FALSE;
2390
2391   /* Reject modes with signed zeros.  */
2392   if (HONOR_SIGNED_ZEROS (if_info->x))
2393     return FALSE;
2394
2395   /* Recognize A and B as constituting an ABS or NABS.  The canonical
2396      form is a branch around the negation, taken when the object is the
2397      first operand of a comparison against 0 that evaluates to true.  */
2398   a = if_info->a;
2399   b = if_info->b;
2400   if (GET_CODE (a) == NEG && rtx_equal_p (XEXP (a, 0), b))
2401     negate = 0;
2402   else if (GET_CODE (b) == NEG && rtx_equal_p (XEXP (b, 0), a))
2403     {
2404       std::swap (a, b);
2405       negate = 1;
2406     }
2407   else if (GET_CODE (a) == NOT && rtx_equal_p (XEXP (a, 0), b))
2408     {
2409       negate = 0;
2410       one_cmpl = true;
2411     }
2412   else if (GET_CODE (b) == NOT && rtx_equal_p (XEXP (b, 0), a))
2413     {
2414       std::swap (a, b);
2415       negate = 1;
2416       one_cmpl = true;
2417     }
2418   else
2419     return FALSE;
2420
2421   cond = noce_get_alt_condition (if_info, b, &earliest);
2422   if (!cond)
2423     return FALSE;
2424
2425   /* Verify the condition is of the form we expect.  */
2426   if (rtx_equal_p (XEXP (cond, 0), b))
2427     c = XEXP (cond, 1);
2428   else if (rtx_equal_p (XEXP (cond, 1), b))
2429     {
2430       c = XEXP (cond, 0);
2431       negate = !negate;
2432     }
2433   else
2434     return FALSE;
2435
2436   /* Verify that C is zero.  Search one step backward for a
2437      REG_EQUAL note or a simple source if necessary.  */
2438   if (REG_P (c))
2439     {
2440       rtx set;
2441       rtx_insn *insn = prev_nonnote_insn (earliest);
2442       if (insn
2443           && BLOCK_FOR_INSN (insn) == BLOCK_FOR_INSN (earliest)
2444           && (set = single_set (insn))
2445           && rtx_equal_p (SET_DEST (set), c))
2446         {
2447           rtx note = find_reg_equal_equiv_note (insn);
2448           if (note)
2449             c = XEXP (note, 0);
2450           else
2451             c = SET_SRC (set);
2452         }
2453       else
2454         return FALSE;
2455     }
2456   if (MEM_P (c)
2457       && GET_CODE (XEXP (c, 0)) == SYMBOL_REF
2458       && CONSTANT_POOL_ADDRESS_P (XEXP (c, 0)))
2459     c = get_pool_constant (XEXP (c, 0));
2460
2461   /* Work around funny ideas get_condition has wrt canonicalization.
2462      Note that these rtx constants are known to be CONST_INT, and
2463      therefore imply integer comparisons.  */
2464   if (c == constm1_rtx && GET_CODE (cond) == GT)
2465     ;
2466   else if (c == const1_rtx && GET_CODE (cond) == LT)
2467     ;
2468   else if (c != CONST0_RTX (GET_MODE (b)))
2469     return FALSE;
2470
2471   /* Determine what sort of operation this is.  */
2472   switch (GET_CODE (cond))
2473     {
2474     case LT:
2475     case LE:
2476     case UNLT:
2477     case UNLE:
2478       negate = !negate;
2479       break;
2480     case GT:
2481     case GE:
2482     case UNGT:
2483     case UNGE:
2484       break;
2485     default:
2486       return FALSE;
2487     }
2488
2489   start_sequence ();
2490   if (one_cmpl)
2491     target = expand_one_cmpl_abs_nojump (GET_MODE (if_info->x), b,
2492                                          if_info->x);
2493   else
2494     target = expand_abs_nojump (GET_MODE (if_info->x), b, if_info->x, 1);
2495
2496   /* ??? It's a quandary whether cmove would be better here, especially
2497      for integers.  Perhaps combine will clean things up.  */
2498   if (target && negate)
2499     {
2500       if (one_cmpl)
2501         target = expand_simple_unop (GET_MODE (target), NOT, target,
2502                                      if_info->x, 0);
2503       else
2504         target = expand_simple_unop (GET_MODE (target), NEG, target,
2505                                      if_info->x, 0);
2506     }
2507
2508   if (! target)
2509     {
2510       end_sequence ();
2511       return FALSE;
2512     }
2513
2514   if (target != if_info->x)
2515     noce_emit_move_insn (if_info->x, target);
2516
2517   seq = end_ifcvt_sequence (if_info);
2518   if (!seq)
2519     return FALSE;
2520
2521   emit_insn_before_setloc (seq, if_info->jump, INSN_LOCATION (if_info->insn_a));
2522   if_info->cond = cond;
2523   if_info->cond_earliest = earliest;
2524
2525   return TRUE;
2526 }
2527
2528 /* Convert "if (m < 0) x = b; else x = 0;" to "x = (m >> C) & b;".  */
2529
2530 static int
2531 noce_try_sign_mask (struct noce_if_info *if_info)
2532 {
2533   rtx cond, t, m, c;
2534   rtx_insn *seq;
2535   machine_mode mode;
2536   enum rtx_code code;
2537   bool t_unconditional;
2538
2539   if (!noce_simple_bbs (if_info))
2540     return FALSE;
2541
2542   cond = if_info->cond;
2543   code = GET_CODE (cond);
2544   m = XEXP (cond, 0);
2545   c = XEXP (cond, 1);
2546
2547   t = NULL_RTX;
2548   if (if_info->a == const0_rtx)
2549     {
2550       if ((code == LT && c == const0_rtx)
2551           || (code == LE && c == constm1_rtx))
2552         t = if_info->b;
2553     }
2554   else if (if_info->b == const0_rtx)
2555     {
2556       if ((code == GE && c == const0_rtx)
2557           || (code == GT && c == constm1_rtx))
2558         t = if_info->a;
2559     }
2560
2561   if (! t || side_effects_p (t))
2562     return FALSE;
2563
2564   /* We currently don't handle different modes.  */
2565   mode = GET_MODE (t);
2566   if (GET_MODE (m) != mode)
2567     return FALSE;
2568
2569   /* This is only profitable if T is unconditionally executed/evaluated in the
2570      original insn sequence or T is cheap.  The former happens if B is the
2571      non-zero (T) value and if INSN_B was taken from TEST_BB, or there was no
2572      INSN_B which can happen for e.g. conditional stores to memory.  For the
2573      cost computation use the block TEST_BB where the evaluation will end up
2574      after the transformation.  */
2575   t_unconditional =
2576     (t == if_info->b
2577      && (if_info->insn_b == NULL_RTX
2578          || BLOCK_FOR_INSN (if_info->insn_b) == if_info->test_bb));
2579   if (!(t_unconditional
2580         || (set_src_cost (t, mode, optimize_bb_for_speed_p (if_info->test_bb))
2581             < COSTS_N_INSNS (2))))
2582     return FALSE;
2583
2584   start_sequence ();
2585   /* Use emit_store_flag to generate "m < 0 ? -1 : 0" instead of expanding
2586      "(signed) m >> 31" directly.  This benefits targets with specialized
2587      insns to obtain the signmask, but still uses ashr_optab otherwise.  */
2588   m = emit_store_flag (gen_reg_rtx (mode), LT, m, const0_rtx, mode, 0, -1);
2589   t = m ? expand_binop (mode, and_optab, m, t, NULL_RTX, 0, OPTAB_DIRECT)
2590         : NULL_RTX;
2591
2592   if (!t)
2593     {
2594       end_sequence ();
2595       return FALSE;
2596     }
2597
2598   noce_emit_move_insn (if_info->x, t);
2599
2600   seq = end_ifcvt_sequence (if_info);
2601   if (!seq)
2602     return FALSE;
2603
2604   emit_insn_before_setloc (seq, if_info->jump, INSN_LOCATION (if_info->insn_a));
2605   return TRUE;
2606 }
2607
2608
2609 /* Optimize away "if (x & C) x |= C" and similar bit manipulation
2610    transformations.  */
2611
2612 static int
2613 noce_try_bitop (struct noce_if_info *if_info)
2614 {
2615   rtx cond, x, a, result;
2616   rtx_insn *seq;
2617   machine_mode mode;
2618   enum rtx_code code;
2619   int bitnum;
2620
2621   x = if_info->x;
2622   cond = if_info->cond;
2623   code = GET_CODE (cond);
2624
2625   if (!noce_simple_bbs (if_info))
2626     return FALSE;
2627
2628   /* Check for no else condition.  */
2629   if (! rtx_equal_p (x, if_info->b))
2630     return FALSE;
2631
2632   /* Check for a suitable condition.  */
2633   if (code != NE && code != EQ)
2634     return FALSE;
2635   if (XEXP (cond, 1) != const0_rtx)
2636     return FALSE;
2637   cond = XEXP (cond, 0);
2638
2639   /* ??? We could also handle AND here.  */
2640   if (GET_CODE (cond) == ZERO_EXTRACT)
2641     {
2642       if (XEXP (cond, 1) != const1_rtx
2643           || !CONST_INT_P (XEXP (cond, 2))
2644           || ! rtx_equal_p (x, XEXP (cond, 0)))
2645         return FALSE;
2646       bitnum = INTVAL (XEXP (cond, 2));
2647       mode = GET_MODE (x);
2648       if (BITS_BIG_ENDIAN)
2649         bitnum = GET_MODE_BITSIZE (mode) - 1 - bitnum;
2650       if (bitnum < 0 || bitnum >= HOST_BITS_PER_WIDE_INT)
2651         return FALSE;
2652     }
2653   else
2654     return FALSE;
2655
2656   a = if_info->a;
2657   if (GET_CODE (a) == IOR || GET_CODE (a) == XOR)
2658     {
2659       /* Check for "if (X & C) x = x op C".  */
2660       if (! rtx_equal_p (x, XEXP (a, 0))
2661           || !CONST_INT_P (XEXP (a, 1))
2662           || (INTVAL (XEXP (a, 1)) & GET_MODE_MASK (mode))
2663              != (unsigned HOST_WIDE_INT) 1 << bitnum)
2664         return FALSE;
2665
2666       /* if ((x & C) == 0) x |= C; is transformed to x |= C.   */
2667       /* if ((x & C) != 0) x |= C; is transformed to nothing.  */
2668       if (GET_CODE (a) == IOR)
2669         result = (code == NE) ? a : NULL_RTX;
2670       else if (code == NE)
2671         {
2672           /* if ((x & C) == 0) x ^= C; is transformed to x |= C.   */
2673           result = gen_int_mode ((HOST_WIDE_INT) 1 << bitnum, mode);
2674           result = simplify_gen_binary (IOR, mode, x, result);
2675         }
2676       else
2677         {
2678           /* if ((x & C) != 0) x ^= C; is transformed to x &= ~C.  */
2679           result = gen_int_mode (~((HOST_WIDE_INT) 1 << bitnum), mode);
2680           result = simplify_gen_binary (AND, mode, x, result);
2681         }
2682     }
2683   else if (GET_CODE (a) == AND)
2684     {
2685       /* Check for "if (X & C) x &= ~C".  */
2686       if (! rtx_equal_p (x, XEXP (a, 0))
2687           || !CONST_INT_P (XEXP (a, 1))
2688           || (INTVAL (XEXP (a, 1)) & GET_MODE_MASK (mode))
2689              != (~((HOST_WIDE_INT) 1 << bitnum) & GET_MODE_MASK (mode)))
2690         return FALSE;
2691
2692       /* if ((x & C) == 0) x &= ~C; is transformed to nothing.  */
2693       /* if ((x & C) != 0) x &= ~C; is transformed to x &= ~C.  */
2694       result = (code == EQ) ? a : NULL_RTX;
2695     }
2696   else
2697     return FALSE;
2698
2699   if (result)
2700     {
2701       start_sequence ();
2702       noce_emit_move_insn (x, result);
2703       seq = end_ifcvt_sequence (if_info);
2704       if (!seq)
2705         return FALSE;
2706
2707       emit_insn_before_setloc (seq, if_info->jump,
2708                                INSN_LOCATION (if_info->insn_a));
2709     }
2710   return TRUE;
2711 }
2712
2713
2714 /* Similar to get_condition, only the resulting condition must be
2715    valid at JUMP, instead of at EARLIEST.
2716
2717    If THEN_ELSE_REVERSED is true, the fallthrough does not go to the
2718    THEN block of the caller, and we have to reverse the condition.  */
2719
2720 static rtx
2721 noce_get_condition (rtx_insn *jump, rtx_insn **earliest, bool then_else_reversed)
2722 {
2723   rtx cond, set, tmp;
2724   bool reverse;
2725
2726   if (! any_condjump_p (jump))
2727     return NULL_RTX;
2728
2729   set = pc_set (jump);
2730
2731   /* If this branches to JUMP_LABEL when the condition is false,
2732      reverse the condition.  */
2733   reverse = (GET_CODE (XEXP (SET_SRC (set), 2)) == LABEL_REF
2734              && LABEL_REF_LABEL (XEXP (SET_SRC (set), 2)) == JUMP_LABEL (jump));
2735
2736   /* We may have to reverse because the caller's if block is not canonical,
2737      i.e. the THEN block isn't the fallthrough block for the TEST block
2738      (see find_if_header).  */
2739   if (then_else_reversed)
2740     reverse = !reverse;
2741
2742   /* If the condition variable is a register and is MODE_INT, accept it.  */
2743
2744   cond = XEXP (SET_SRC (set), 0);
2745   tmp = XEXP (cond, 0);
2746   if (REG_P (tmp) && GET_MODE_CLASS (GET_MODE (tmp)) == MODE_INT
2747       && (GET_MODE (tmp) != BImode
2748           || !targetm.small_register_classes_for_mode_p (BImode)))
2749     {
2750       *earliest = jump;
2751
2752       if (reverse)
2753         cond = gen_rtx_fmt_ee (reverse_condition (GET_CODE (cond)),
2754                                GET_MODE (cond), tmp, XEXP (cond, 1));
2755       return cond;
2756     }
2757
2758   /* Otherwise, fall back on canonicalize_condition to do the dirty
2759      work of manipulating MODE_CC values and COMPARE rtx codes.  */
2760   tmp = canonicalize_condition (jump, cond, reverse, earliest,
2761                                 NULL_RTX, have_cbranchcc4, true);
2762
2763   /* We don't handle side-effects in the condition, like handling
2764      REG_INC notes and making sure no duplicate conditions are emitted.  */
2765   if (tmp != NULL_RTX && side_effects_p (tmp))
2766     return NULL_RTX;
2767
2768   return tmp;
2769 }
2770
2771 /* Return true if OP is ok for if-then-else processing.  */
2772
2773 static int
2774 noce_operand_ok (const_rtx op)
2775 {
2776   if (side_effects_p (op))
2777     return FALSE;
2778
2779   /* We special-case memories, so handle any of them with
2780      no address side effects.  */
2781   if (MEM_P (op))
2782     return ! side_effects_p (XEXP (op, 0));
2783
2784   return ! may_trap_p (op);
2785 }
2786
2787 /* Return true if a write into MEM may trap or fault.  */
2788
2789 static bool
2790 noce_mem_write_may_trap_or_fault_p (const_rtx mem)
2791 {
2792   rtx addr;
2793
2794   if (MEM_READONLY_P (mem))
2795     return true;
2796
2797   if (may_trap_or_fault_p (mem))
2798     return true;
2799
2800   addr = XEXP (mem, 0);
2801
2802   /* Call target hook to avoid the effects of -fpic etc....  */
2803   addr = targetm.delegitimize_address (addr);
2804
2805   while (addr)
2806     switch (GET_CODE (addr))
2807       {
2808       case CONST:
2809       case PRE_DEC:
2810       case PRE_INC:
2811       case POST_DEC:
2812       case POST_INC:
2813       case POST_MODIFY:
2814         addr = XEXP (addr, 0);
2815         break;
2816       case LO_SUM:
2817       case PRE_MODIFY:
2818         addr = XEXP (addr, 1);
2819         break;
2820       case PLUS:
2821         if (CONST_INT_P (XEXP (addr, 1)))
2822           addr = XEXP (addr, 0);
2823         else
2824           return false;
2825         break;
2826       case LABEL_REF:
2827         return true;
2828       case SYMBOL_REF:
2829         if (SYMBOL_REF_DECL (addr)
2830             && decl_readonly_section (SYMBOL_REF_DECL (addr), 0))
2831           return true;
2832         return false;
2833       default:
2834         return false;
2835       }
2836
2837   return false;
2838 }
2839
2840 /* Return whether we can use store speculation for MEM.  TOP_BB is the
2841    basic block above the conditional block where we are considering
2842    doing the speculative store.  We look for whether MEM is set
2843    unconditionally later in the function.  */
2844
2845 static bool
2846 noce_can_store_speculate_p (basic_block top_bb, const_rtx mem)
2847 {
2848   basic_block dominator;
2849
2850   for (dominator = get_immediate_dominator (CDI_POST_DOMINATORS, top_bb);
2851        dominator != NULL;
2852        dominator = get_immediate_dominator (CDI_POST_DOMINATORS, dominator))
2853     {
2854       rtx_insn *insn;
2855
2856       FOR_BB_INSNS (dominator, insn)
2857         {
2858           /* If we see something that might be a memory barrier, we
2859              have to stop looking.  Even if the MEM is set later in
2860              the function, we still don't want to set it
2861              unconditionally before the barrier.  */
2862           if (INSN_P (insn)
2863               && (volatile_insn_p (PATTERN (insn))
2864                   || (CALL_P (insn) && (!RTL_CONST_CALL_P (insn)))))
2865             return false;
2866
2867           if (memory_must_be_modified_in_insn_p (mem, insn))
2868             return true;
2869           if (modified_in_p (XEXP (mem, 0), insn))
2870             return false;
2871
2872         }
2873     }
2874
2875   return false;
2876 }
2877
2878 /* Return true if X contains a MEM subrtx.  */
2879
2880 static bool
2881 contains_mem_rtx_p (rtx x)
2882 {
2883   subrtx_iterator::array_type array;
2884   FOR_EACH_SUBRTX (iter, array, x, ALL)
2885     if (MEM_P (*iter))
2886       return true;
2887
2888   return false;
2889 }
2890
2891 /* Return true iff basic block TEST_BB is valid for noce if-conversion.
2892    The condition used in this if-conversion is in COND.
2893    In practice, check that TEST_BB ends with a single set
2894    x := a and all previous computations
2895    in TEST_BB don't produce any values that are live after TEST_BB.
2896    In other words, all the insns in TEST_BB are there only
2897    to compute a value for x.  Put the rtx cost of the insns
2898    in TEST_BB into COST.  Record whether TEST_BB is a single simple
2899    set instruction in SIMPLE_P.  */
2900
2901 static bool
2902 bb_valid_for_noce_process_p (basic_block test_bb, rtx cond,
2903                               unsigned int *cost, bool *simple_p)
2904 {
2905   if (!test_bb)
2906     return false;
2907
2908   rtx_insn *last_insn = last_active_insn (test_bb, FALSE);
2909   rtx last_set = NULL_RTX;
2910
2911   rtx cc = cc_in_cond (cond);
2912
2913   if (!insn_valid_noce_process_p (last_insn, cc))
2914     return false;
2915   last_set = single_set (last_insn);
2916
2917   rtx x = SET_DEST (last_set);
2918   rtx_insn *first_insn = first_active_insn (test_bb);
2919   rtx first_set = single_set (first_insn);
2920
2921   if (!first_set)
2922     return false;
2923
2924   /* We have a single simple set, that's okay.  */
2925   bool speed_p = optimize_bb_for_speed_p (test_bb);
2926
2927   if (first_insn == last_insn)
2928     {
2929       *simple_p = noce_operand_ok (SET_DEST (first_set));
2930       *cost = insn_rtx_cost (first_set, speed_p);
2931       return *simple_p;
2932     }
2933
2934   rtx_insn *prev_last_insn = PREV_INSN (last_insn);
2935   gcc_assert (prev_last_insn);
2936
2937   /* For now, disallow setting x multiple times in test_bb.  */
2938   if (REG_P (x) && reg_set_between_p (x, first_insn, prev_last_insn))
2939     return false;
2940
2941   bitmap test_bb_temps = BITMAP_ALLOC (&reg_obstack);
2942
2943   /* The regs that are live out of test_bb.  */
2944   bitmap test_bb_live_out = df_get_live_out (test_bb);
2945
2946   int potential_cost = insn_rtx_cost (last_set, speed_p);
2947   rtx_insn *insn;
2948   FOR_BB_INSNS (test_bb, insn)
2949     {
2950       if (insn != last_insn)
2951         {
2952           if (!active_insn_p (insn))
2953             continue;
2954
2955           if (!insn_valid_noce_process_p (insn, cc))
2956             goto free_bitmap_and_fail;
2957
2958           rtx sset = single_set (insn);
2959           gcc_assert (sset);
2960
2961           if (contains_mem_rtx_p (SET_SRC (sset))
2962               || !REG_P (SET_DEST (sset)))
2963             goto free_bitmap_and_fail;
2964
2965           potential_cost += insn_rtx_cost (sset, speed_p);
2966           bitmap_set_bit (test_bb_temps, REGNO (SET_DEST (sset)));
2967         }
2968     }
2969
2970   /* If any of the intermediate results in test_bb are live after test_bb
2971      then fail.  */
2972   if (bitmap_intersect_p (test_bb_live_out, test_bb_temps))
2973     goto free_bitmap_and_fail;
2974
2975   BITMAP_FREE (test_bb_temps);
2976   *cost = potential_cost;
2977   *simple_p = false;
2978   return true;
2979
2980  free_bitmap_and_fail:
2981   BITMAP_FREE (test_bb_temps);
2982   return false;
2983 }
2984
2985 /* Given a simple IF-THEN-JOIN or IF-THEN-ELSE-JOIN block, attempt to convert
2986    it without using conditional execution.  Return TRUE if we were successful
2987    at converting the block.  */
2988
2989 static int
2990 noce_process_if_block (struct noce_if_info *if_info)
2991 {
2992   basic_block test_bb = if_info->test_bb;       /* test block */
2993   basic_block then_bb = if_info->then_bb;       /* THEN */
2994   basic_block else_bb = if_info->else_bb;       /* ELSE or NULL */
2995   basic_block join_bb = if_info->join_bb;       /* JOIN */
2996   rtx_insn *jump = if_info->jump;
2997   rtx cond = if_info->cond;
2998   rtx_insn *insn_a, *insn_b;
2999   rtx set_a, set_b;
3000   rtx orig_x, x, a, b;
3001
3002   /* We're looking for patterns of the form
3003
3004      (1) if (...) x = a; else x = b;
3005      (2) x = b; if (...) x = a;
3006      (3) if (...) x = a;   // as if with an initial x = x.
3007
3008      The later patterns require jumps to be more expensive.
3009      For the if (...) x = a; else x = b; case we allow multiple insns
3010      inside the then and else blocks as long as their only effect is
3011      to calculate a value for x.
3012      ??? For future expansion, look for multiple X in such patterns.  */
3013
3014   if (! bb_valid_for_noce_process_p (then_bb, cond, &if_info->then_cost,
3015                                     &if_info->then_simple))
3016     return false;
3017
3018   if (else_bb
3019       && ! bb_valid_for_noce_process_p (else_bb, cond, &if_info->else_cost,
3020                                       &if_info->else_simple))
3021     return false;
3022
3023   insn_a = last_active_insn (then_bb, FALSE);
3024   set_a = single_set (insn_a);
3025   gcc_assert (set_a);
3026
3027   x = SET_DEST (set_a);
3028   a = SET_SRC (set_a);
3029
3030   /* Look for the other potential set.  Make sure we've got equivalent
3031      destinations.  */
3032   /* ??? This is overconservative.  Storing to two different mems is
3033      as easy as conditionally computing the address.  Storing to a
3034      single mem merely requires a scratch memory to use as one of the
3035      destination addresses; often the memory immediately below the
3036      stack pointer is available for this.  */
3037   set_b = NULL_RTX;
3038   if (else_bb)
3039     {
3040       insn_b = last_active_insn (else_bb, FALSE);
3041       set_b = single_set (insn_b);
3042       gcc_assert (set_b);
3043
3044       if (!rtx_interchangeable_p (x, SET_DEST (set_b)))
3045         return FALSE;
3046     }
3047   else
3048     {
3049       insn_b = prev_nonnote_nondebug_insn (if_info->cond_earliest);
3050       /* We're going to be moving the evaluation of B down from above
3051          COND_EARLIEST to JUMP.  Make sure the relevant data is still
3052          intact.  */
3053       if (! insn_b
3054           || BLOCK_FOR_INSN (insn_b) != BLOCK_FOR_INSN (if_info->cond_earliest)
3055           || !NONJUMP_INSN_P (insn_b)
3056           || (set_b = single_set (insn_b)) == NULL_RTX
3057           || ! rtx_interchangeable_p (x, SET_DEST (set_b))
3058           || ! noce_operand_ok (SET_SRC (set_b))
3059           || reg_overlap_mentioned_p (x, SET_SRC (set_b))
3060           || modified_between_p (SET_SRC (set_b), insn_b, jump)
3061           /* Avoid extending the lifetime of hard registers on small
3062              register class machines.  */
3063           || (REG_P (SET_SRC (set_b))
3064               && HARD_REGISTER_P (SET_SRC (set_b))
3065               && targetm.small_register_classes_for_mode_p
3066                    (GET_MODE (SET_SRC (set_b))))
3067           /* Likewise with X.  In particular this can happen when
3068              noce_get_condition looks farther back in the instruction
3069              stream than one might expect.  */
3070           || reg_overlap_mentioned_p (x, cond)
3071           || reg_overlap_mentioned_p (x, a)
3072           || modified_between_p (x, insn_b, jump))
3073         {
3074           insn_b = NULL;
3075           set_b = NULL_RTX;
3076         }
3077     }
3078
3079   /* If x has side effects then only the if-then-else form is safe to
3080      convert.  But even in that case we would need to restore any notes
3081      (such as REG_INC) at then end.  That can be tricky if
3082      noce_emit_move_insn expands to more than one insn, so disable the
3083      optimization entirely for now if there are side effects.  */
3084   if (side_effects_p (x))
3085     return FALSE;
3086
3087   b = (set_b ? SET_SRC (set_b) : x);
3088
3089   /* Only operate on register destinations, and even then avoid extending
3090      the lifetime of hard registers on small register class machines.  */
3091   orig_x = x;
3092   if (!REG_P (x)
3093       || (HARD_REGISTER_P (x)
3094           && targetm.small_register_classes_for_mode_p (GET_MODE (x))))
3095     {
3096       if (GET_MODE (x) == BLKmode)
3097         return FALSE;
3098
3099       if (GET_CODE (x) == ZERO_EXTRACT
3100           && (!CONST_INT_P (XEXP (x, 1))
3101               || !CONST_INT_P (XEXP (x, 2))))
3102         return FALSE;
3103
3104       x = gen_reg_rtx (GET_MODE (GET_CODE (x) == STRICT_LOW_PART
3105                                  ? XEXP (x, 0) : x));
3106     }
3107
3108   /* Don't operate on sources that may trap or are volatile.  */
3109   if (! noce_operand_ok (a) || ! noce_operand_ok (b))
3110     return FALSE;
3111
3112  retry:
3113   /* Set up the info block for our subroutines.  */
3114   if_info->insn_a = insn_a;
3115   if_info->insn_b = insn_b;
3116   if_info->x = x;
3117   if_info->a = a;
3118   if_info->b = b;
3119
3120   /* Try optimizations in some approximation of a useful order.  */
3121   /* ??? Should first look to see if X is live incoming at all.  If it
3122      isn't, we don't need anything but an unconditional set.  */
3123
3124   /* Look and see if A and B are really the same.  Avoid creating silly
3125      cmove constructs that no one will fix up later.  */
3126   if (noce_simple_bbs (if_info)
3127       && rtx_interchangeable_p (a, b))
3128     {
3129       /* If we have an INSN_B, we don't have to create any new rtl.  Just
3130          move the instruction that we already have.  If we don't have an
3131          INSN_B, that means that A == X, and we've got a noop move.  In
3132          that case don't do anything and let the code below delete INSN_A.  */
3133       if (insn_b && else_bb)
3134         {
3135           rtx note;
3136
3137           if (else_bb && insn_b == BB_END (else_bb))
3138             BB_END (else_bb) = PREV_INSN (insn_b);
3139           reorder_insns (insn_b, insn_b, PREV_INSN (jump));
3140
3141           /* If there was a REG_EQUAL note, delete it since it may have been
3142              true due to this insn being after a jump.  */
3143           if ((note = find_reg_note (insn_b, REG_EQUAL, NULL_RTX)) != 0)
3144             remove_note (insn_b, note);
3145
3146           insn_b = NULL;
3147         }
3148       /* If we have "x = b; if (...) x = a;", and x has side-effects, then
3149          x must be executed twice.  */
3150       else if (insn_b && side_effects_p (orig_x))
3151         return FALSE;
3152
3153       x = orig_x;
3154       goto success;
3155     }
3156
3157   if (!set_b && MEM_P (orig_x))
3158     {
3159       /* Disallow the "if (...) x = a;" form (implicit "else x = x;")
3160          for optimizations if writing to x may trap or fault,
3161          i.e. it's a memory other than a static var or a stack slot,
3162          is misaligned on strict aligned machines or is read-only.  If
3163          x is a read-only memory, then the program is valid only if we
3164          avoid the store into it.  If there are stores on both the
3165          THEN and ELSE arms, then we can go ahead with the conversion;
3166          either the program is broken, or the condition is always
3167          false such that the other memory is selected.  */
3168       if (noce_mem_write_may_trap_or_fault_p (orig_x))
3169         return FALSE;
3170
3171       /* Avoid store speculation: given "if (...) x = a" where x is a
3172          MEM, we only want to do the store if x is always set
3173          somewhere in the function.  This avoids cases like
3174            if (pthread_mutex_trylock(mutex))
3175              ++global_variable;
3176          where we only want global_variable to be changed if the mutex
3177          is held.  FIXME: This should ideally be expressed directly in
3178          RTL somehow.  */
3179       if (!noce_can_store_speculate_p (test_bb, orig_x))
3180         return FALSE;
3181     }
3182
3183   if (noce_try_move (if_info))
3184     goto success;
3185   if (noce_try_store_flag (if_info))
3186     goto success;
3187   if (noce_try_bitop (if_info))
3188     goto success;
3189   if (noce_try_minmax (if_info))
3190     goto success;
3191   if (noce_try_abs (if_info))
3192     goto success;
3193   if (!targetm.have_conditional_execution ()
3194       && noce_try_store_flag_constants (if_info))
3195     goto success;
3196   if (HAVE_conditional_move
3197       && noce_try_cmove (if_info))
3198     goto success;
3199   if (! targetm.have_conditional_execution ())
3200     {
3201       if (noce_try_addcc (if_info))
3202         goto success;
3203       if (noce_try_store_flag_mask (if_info))
3204         goto success;
3205       if (HAVE_conditional_move
3206           && noce_try_cmove_arith (if_info))
3207         goto success;
3208       if (noce_try_sign_mask (if_info))
3209         goto success;
3210     }
3211
3212   if (!else_bb && set_b)
3213     {
3214       insn_b = NULL;
3215       set_b = NULL_RTX;
3216       b = orig_x;
3217       goto retry;
3218     }
3219
3220   return FALSE;
3221
3222  success:
3223
3224   /* If we used a temporary, fix it up now.  */
3225   if (orig_x != x)
3226     {
3227       rtx_insn *seq;
3228
3229       start_sequence ();
3230       noce_emit_move_insn (orig_x, x);
3231       seq = get_insns ();
3232       set_used_flags (orig_x);
3233       unshare_all_rtl_in_chain (seq);
3234       end_sequence ();
3235
3236       emit_insn_before_setloc (seq, BB_END (test_bb), INSN_LOCATION (insn_a));
3237     }
3238
3239   /* The original THEN and ELSE blocks may now be removed.  The test block
3240      must now jump to the join block.  If the test block and the join block
3241      can be merged, do so.  */
3242   if (else_bb)
3243     {
3244       delete_basic_block (else_bb);
3245       num_true_changes++;
3246     }
3247   else
3248     remove_edge (find_edge (test_bb, join_bb));
3249
3250   remove_edge (find_edge (then_bb, join_bb));
3251   redirect_edge_and_branch_force (single_succ_edge (test_bb), join_bb);
3252   delete_basic_block (then_bb);
3253   num_true_changes++;
3254
3255   if (can_merge_blocks_p (test_bb, join_bb))
3256     {
3257       merge_blocks (test_bb, join_bb);
3258       num_true_changes++;
3259     }
3260
3261   num_updated_if_blocks++;
3262   return TRUE;
3263 }
3264
3265 /* Check whether a block is suitable for conditional move conversion.
3266    Every insn must be a simple set of a register to a constant or a
3267    register.  For each assignment, store the value in the pointer map
3268    VALS, keyed indexed by register pointer, then store the register
3269    pointer in REGS.  COND is the condition we will test.  */
3270
3271 static int
3272 check_cond_move_block (basic_block bb,
3273                        hash_map<rtx, rtx> *vals,
3274                        vec<rtx> *regs,
3275                        rtx cond)
3276 {
3277   rtx_insn *insn;
3278   rtx cc = cc_in_cond (cond);
3279
3280    /* We can only handle simple jumps at the end of the basic block.
3281       It is almost impossible to update the CFG otherwise.  */
3282   insn = BB_END (bb);
3283   if (JUMP_P (insn) && !onlyjump_p (insn))
3284     return FALSE;
3285
3286   FOR_BB_INSNS (bb, insn)
3287     {
3288       rtx set, dest, src;
3289
3290       if (!NONDEBUG_INSN_P (insn) || JUMP_P (insn))
3291         continue;
3292       set = single_set (insn);
3293       if (!set)
3294         return FALSE;
3295
3296       dest = SET_DEST (set);
3297       src = SET_SRC (set);
3298       if (!REG_P (dest)
3299           || (HARD_REGISTER_P (dest)
3300               && targetm.small_register_classes_for_mode_p (GET_MODE (dest))))
3301         return FALSE;
3302
3303       if (!CONSTANT_P (src) && !register_operand (src, VOIDmode))
3304         return FALSE;
3305
3306       if (side_effects_p (src) || side_effects_p (dest))
3307         return FALSE;
3308
3309       if (may_trap_p (src) || may_trap_p (dest))
3310         return FALSE;
3311
3312       /* Don't try to handle this if the source register was
3313          modified earlier in the block.  */
3314       if ((REG_P (src)
3315            && vals->get (src))
3316           || (GET_CODE (src) == SUBREG && REG_P (SUBREG_REG (src))
3317               && vals->get (SUBREG_REG (src))))
3318         return FALSE;
3319
3320       /* Don't try to handle this if the destination register was
3321          modified earlier in the block.  */
3322       if (vals->get (dest))
3323         return FALSE;
3324
3325       /* Don't try to handle this if the condition uses the
3326          destination register.  */
3327       if (reg_overlap_mentioned_p (dest, cond))
3328         return FALSE;
3329
3330       /* Don't try to handle this if the source register is modified
3331          later in the block.  */
3332       if (!CONSTANT_P (src)
3333           && modified_between_p (src, insn, NEXT_INSN (BB_END (bb))))
3334         return FALSE;
3335
3336       /* Skip it if the instruction to be moved might clobber CC.  */
3337       if (cc && set_of (cc, insn))
3338         return FALSE;
3339
3340       vals->put (dest, src);
3341
3342       regs->safe_push (dest);
3343     }
3344
3345   return TRUE;
3346 }
3347
3348 /* Given a basic block BB suitable for conditional move conversion,
3349    a condition COND, and pointer maps THEN_VALS and ELSE_VALS containing
3350    the register values depending on COND, emit the insns in the block as
3351    conditional moves.  If ELSE_BLOCK is true, THEN_BB was already
3352    processed.  The caller has started a sequence for the conversion.
3353    Return true if successful, false if something goes wrong.  */
3354
3355 static bool
3356 cond_move_convert_if_block (struct noce_if_info *if_infop,
3357                             basic_block bb, rtx cond,
3358                             hash_map<rtx, rtx> *then_vals,
3359                             hash_map<rtx, rtx> *else_vals,
3360                             bool else_block_p)
3361 {
3362   enum rtx_code code;
3363   rtx_insn *insn;
3364   rtx cond_arg0, cond_arg1;
3365
3366   code = GET_CODE (cond);
3367   cond_arg0 = XEXP (cond, 0);
3368   cond_arg1 = XEXP (cond, 1);
3369
3370   FOR_BB_INSNS (bb, insn)
3371     {
3372       rtx set, target, dest, t, e;
3373
3374       /* ??? Maybe emit conditional debug insn?  */
3375       if (!NONDEBUG_INSN_P (insn) || JUMP_P (insn))
3376         continue;
3377       set = single_set (insn);
3378       gcc_assert (set && REG_P (SET_DEST (set)));
3379
3380       dest = SET_DEST (set);
3381
3382       rtx *then_slot = then_vals->get (dest);
3383       rtx *else_slot = else_vals->get (dest);
3384       t = then_slot ? *then_slot : NULL_RTX;
3385       e = else_slot ? *else_slot : NULL_RTX;
3386
3387       if (else_block_p)
3388         {
3389           /* If this register was set in the then block, we already
3390              handled this case there.  */
3391           if (t)
3392             continue;
3393           t = dest;
3394           gcc_assert (e);
3395         }
3396       else
3397         {
3398           gcc_assert (t);
3399           if (!e)
3400             e = dest;
3401         }
3402
3403       target = noce_emit_cmove (if_infop, dest, code, cond_arg0, cond_arg1,
3404                                 t, e);
3405       if (!target)
3406         return false;
3407
3408       if (target != dest)
3409         noce_emit_move_insn (dest, target);
3410     }
3411
3412   return true;
3413 }
3414
3415 /* Given a simple IF-THEN-JOIN or IF-THEN-ELSE-JOIN block, attempt to convert
3416    it using only conditional moves.  Return TRUE if we were successful at
3417    converting the block.  */
3418
3419 static int
3420 cond_move_process_if_block (struct noce_if_info *if_info)
3421 {
3422   basic_block test_bb = if_info->test_bb;
3423   basic_block then_bb = if_info->then_bb;
3424   basic_block else_bb = if_info->else_bb;
3425   basic_block join_bb = if_info->join_bb;
3426   rtx_insn *jump = if_info->jump;
3427   rtx cond = if_info->cond;
3428   rtx_insn *seq, *loc_insn;
3429   rtx reg;
3430   int c;
3431   vec<rtx> then_regs = vNULL;
3432   vec<rtx> else_regs = vNULL;
3433   unsigned int i;
3434   int success_p = FALSE;
3435
3436   /* Build a mapping for each block to the value used for each
3437      register.  */
3438   hash_map<rtx, rtx> then_vals;
3439   hash_map<rtx, rtx> else_vals;
3440
3441   /* Make sure the blocks are suitable.  */
3442   if (!check_cond_move_block (then_bb, &then_vals, &then_regs, cond)
3443       || (else_bb
3444           && !check_cond_move_block (else_bb, &else_vals, &else_regs, cond)))
3445     goto done;
3446
3447   /* Make sure the blocks can be used together.  If the same register
3448      is set in both blocks, and is not set to a constant in both
3449      cases, then both blocks must set it to the same register.  We
3450      have already verified that if it is set to a register, that the
3451      source register does not change after the assignment.  Also count
3452      the number of registers set in only one of the blocks.  */
3453   c = 0;
3454   FOR_EACH_VEC_ELT (then_regs, i, reg)
3455     {
3456       rtx *then_slot = then_vals.get (reg);
3457       rtx *else_slot = else_vals.get (reg);
3458
3459       gcc_checking_assert (then_slot);
3460       if (!else_slot)
3461         ++c;
3462       else
3463         {
3464           rtx then_val = *then_slot;
3465           rtx else_val = *else_slot;
3466           if (!CONSTANT_P (then_val) && !CONSTANT_P (else_val)
3467               && !rtx_equal_p (then_val, else_val))
3468             goto done;
3469         }
3470     }
3471
3472   /* Finish off c for MAX_CONDITIONAL_EXECUTE.  */
3473   FOR_EACH_VEC_ELT (else_regs, i, reg)
3474     {
3475       gcc_checking_assert (else_vals.get (reg));
3476       if (!then_vals.get (reg))
3477         ++c;
3478     }
3479
3480   /* Make sure it is reasonable to convert this block.  What matters
3481      is the number of assignments currently made in only one of the
3482      branches, since if we convert we are going to always execute
3483      them.  */
3484   if (c > MAX_CONDITIONAL_EXECUTE)
3485     goto done;
3486
3487   /* Try to emit the conditional moves.  First do the then block,
3488      then do anything left in the else blocks.  */
3489   start_sequence ();
3490   if (!cond_move_convert_if_block (if_info, then_bb, cond,
3491                                    &then_vals, &else_vals, false)
3492       || (else_bb
3493           && !cond_move_convert_if_block (if_info, else_bb, cond,
3494                                           &then_vals, &else_vals, true)))
3495     {
3496       end_sequence ();
3497       goto done;
3498     }
3499   seq = end_ifcvt_sequence (if_info);
3500   if (!seq)
3501     goto done;
3502
3503   loc_insn = first_active_insn (then_bb);
3504   if (!loc_insn)
3505     {
3506       loc_insn = first_active_insn (else_bb);
3507       gcc_assert (loc_insn);
3508     }
3509   emit_insn_before_setloc (seq, jump, INSN_LOCATION (loc_insn));
3510
3511   if (else_bb)
3512     {
3513       delete_basic_block (else_bb);
3514       num_true_changes++;
3515     }
3516   else
3517     remove_edge (find_edge (test_bb, join_bb));
3518
3519   remove_edge (find_edge (then_bb, join_bb));
3520   redirect_edge_and_branch_force (single_succ_edge (test_bb), join_bb);
3521   delete_basic_block (then_bb);
3522   num_true_changes++;
3523
3524   if (can_merge_blocks_p (test_bb, join_bb))
3525     {
3526       merge_blocks (test_bb, join_bb);
3527       num_true_changes++;
3528     }
3529
3530   num_updated_if_blocks++;
3531
3532   success_p = TRUE;
3533
3534 done:
3535   then_regs.release ();
3536   else_regs.release ();
3537   return success_p;
3538 }
3539
3540 \f
3541 /* Determine if a given basic block heads a simple IF-THEN-JOIN or an
3542    IF-THEN-ELSE-JOIN block.
3543
3544    If so, we'll try to convert the insns to not require the branch,
3545    using only transformations that do not require conditional execution.
3546
3547    Return TRUE if we were successful at converting the block.  */
3548
3549 static int
3550 noce_find_if_block (basic_block test_bb, edge then_edge, edge else_edge,
3551                     int pass)
3552 {
3553   basic_block then_bb, else_bb, join_bb;
3554   bool then_else_reversed = false;
3555   rtx_insn *jump;
3556   rtx cond;
3557   rtx_insn *cond_earliest;
3558   struct noce_if_info if_info;
3559
3560   /* We only ever should get here before reload.  */
3561   gcc_assert (!reload_completed);
3562
3563   /* Recognize an IF-THEN-ELSE-JOIN block.  */
3564   if (single_pred_p (then_edge->dest)
3565       && single_succ_p (then_edge->dest)
3566       && single_pred_p (else_edge->dest)
3567       && single_succ_p (else_edge->dest)
3568       && single_succ (then_edge->dest) == single_succ (else_edge->dest))
3569     {
3570       then_bb = then_edge->dest;
3571       else_bb = else_edge->dest;
3572       join_bb = single_succ (then_bb);
3573     }
3574   /* Recognize an IF-THEN-JOIN block.  */
3575   else if (single_pred_p (then_edge->dest)
3576            && single_succ_p (then_edge->dest)
3577            && single_succ (then_edge->dest) == else_edge->dest)
3578     {
3579       then_bb = then_edge->dest;
3580       else_bb = NULL_BLOCK;
3581       join_bb = else_edge->dest;
3582     }
3583   /* Recognize an IF-ELSE-JOIN block.  We can have those because the order
3584      of basic blocks in cfglayout mode does not matter, so the fallthrough
3585      edge can go to any basic block (and not just to bb->next_bb, like in
3586      cfgrtl mode).  */
3587   else if (single_pred_p (else_edge->dest)
3588            && single_succ_p (else_edge->dest)
3589            && single_succ (else_edge->dest) == then_edge->dest)
3590     {
3591       /* The noce transformations do not apply to IF-ELSE-JOIN blocks.
3592          To make this work, we have to invert the THEN and ELSE blocks
3593          and reverse the jump condition.  */
3594       then_bb = else_edge->dest;
3595       else_bb = NULL_BLOCK;
3596       join_bb = single_succ (then_bb);
3597       then_else_reversed = true;
3598     }
3599   else
3600     /* Not a form we can handle.  */
3601     return FALSE;
3602
3603   /* The edges of the THEN and ELSE blocks cannot have complex edges.  */
3604   if (single_succ_edge (then_bb)->flags & EDGE_COMPLEX)
3605     return FALSE;
3606   if (else_bb
3607       && single_succ_edge (else_bb)->flags & EDGE_COMPLEX)
3608     return FALSE;
3609
3610   num_possible_if_blocks++;
3611
3612   if (dump_file)
3613     {
3614       fprintf (dump_file,
3615                "\nIF-THEN%s-JOIN block found, pass %d, test %d, then %d",
3616                (else_bb) ? "-ELSE" : "",
3617                pass, test_bb->index, then_bb->index);
3618
3619       if (else_bb)
3620         fprintf (dump_file, ", else %d", else_bb->index);
3621
3622       fprintf (dump_file, ", join %d\n", join_bb->index);
3623     }
3624
3625   /* If the conditional jump is more than just a conditional
3626      jump, then we can not do if-conversion on this block.  */
3627   jump = BB_END (test_bb);
3628   if (! onlyjump_p (jump))
3629     return FALSE;
3630
3631   /* If this is not a standard conditional jump, we can't parse it.  */
3632   cond = noce_get_condition (jump, &cond_earliest, then_else_reversed);
3633   if (!cond)
3634     return FALSE;
3635
3636   /* We must be comparing objects whose modes imply the size.  */
3637   if (GET_MODE (XEXP (cond, 0)) == BLKmode)
3638     return FALSE;
3639
3640   /* Initialize an IF_INFO struct to pass around.  */
3641   memset (&if_info, 0, sizeof if_info);
3642   if_info.test_bb = test_bb;
3643   if_info.then_bb = then_bb;
3644   if_info.else_bb = else_bb;
3645   if_info.join_bb = join_bb;
3646   if_info.cond = cond;
3647   if_info.cond_earliest = cond_earliest;
3648   if_info.jump = jump;
3649   if_info.then_else_reversed = then_else_reversed;
3650   if_info.branch_cost = BRANCH_COST (optimize_bb_for_speed_p (test_bb),
3651                                      predictable_edge_p (then_edge));
3652
3653   /* Do the real work.  */
3654
3655   if (noce_process_if_block (&if_info))
3656     return TRUE;
3657
3658   if (HAVE_conditional_move
3659       && cond_move_process_if_block (&if_info))
3660     return TRUE;
3661
3662   return FALSE;
3663 }
3664 \f
3665
3666 /* Merge the blocks and mark for local life update.  */
3667
3668 static void
3669 merge_if_block (struct ce_if_block * ce_info)
3670 {
3671   basic_block test_bb = ce_info->test_bb;       /* last test block */
3672   basic_block then_bb = ce_info->then_bb;       /* THEN */
3673   basic_block else_bb = ce_info->else_bb;       /* ELSE or NULL */
3674   basic_block join_bb = ce_info->join_bb;       /* join block */
3675   basic_block combo_bb;
3676
3677   /* All block merging is done into the lower block numbers.  */
3678
3679   combo_bb = test_bb;
3680   df_set_bb_dirty (test_bb);
3681
3682   /* Merge any basic blocks to handle && and || subtests.  Each of
3683      the blocks are on the fallthru path from the predecessor block.  */
3684   if (ce_info->num_multiple_test_blocks > 0)
3685     {
3686       basic_block bb = test_bb;
3687       basic_block last_test_bb = ce_info->last_test_bb;
3688       basic_block fallthru = block_fallthru (bb);
3689
3690       do
3691         {
3692           bb = fallthru;
3693           fallthru = block_fallthru (bb);
3694           merge_blocks (combo_bb, bb);
3695           num_true_changes++;
3696         }
3697       while (bb != last_test_bb);
3698     }
3699
3700   /* Merge TEST block into THEN block.  Normally the THEN block won't have a
3701      label, but it might if there were || tests.  That label's count should be
3702      zero, and it normally should be removed.  */
3703
3704   if (then_bb)
3705     {
3706       /* If THEN_BB has no successors, then there's a BARRIER after it.
3707          If COMBO_BB has more than one successor (THEN_BB), then that BARRIER
3708          is no longer needed, and in fact it is incorrect to leave it in
3709          the insn stream.  */
3710       if (EDGE_COUNT (then_bb->succs) == 0
3711           && EDGE_COUNT (combo_bb->succs) > 1)
3712         {
3713           rtx_insn *end = NEXT_INSN (BB_END (then_bb));
3714           while (end && NOTE_P (end) && !NOTE_INSN_BASIC_BLOCK_P (end))
3715             end = NEXT_INSN (end);
3716
3717           if (end && BARRIER_P (end))
3718             delete_insn (end);
3719         }
3720       merge_blocks (combo_bb, then_bb);
3721       num_true_changes++;
3722     }
3723
3724   /* The ELSE block, if it existed, had a label.  That label count
3725      will almost always be zero, but odd things can happen when labels
3726      get their addresses taken.  */
3727   if (else_bb)
3728     {
3729       /* If ELSE_BB has no successors, then there's a BARRIER after it.
3730          If COMBO_BB has more than one successor (ELSE_BB), then that BARRIER
3731          is no longer needed, and in fact it is incorrect to leave it in
3732          the insn stream.  */
3733       if (EDGE_COUNT (else_bb->succs) == 0
3734           && EDGE_COUNT (combo_bb->succs) > 1)
3735         {
3736           rtx_insn *end = NEXT_INSN (BB_END (else_bb));
3737           while (end && NOTE_P (end) && !NOTE_INSN_BASIC_BLOCK_P (end))
3738             end = NEXT_INSN (end);
3739
3740           if (end && BARRIER_P (end))
3741             delete_insn (end);
3742         }
3743       merge_blocks (combo_bb, else_bb);
3744       num_true_changes++;
3745     }
3746
3747   /* If there was no join block reported, that means it was not adjacent
3748      to the others, and so we cannot merge them.  */
3749
3750   if (! join_bb)
3751     {
3752       rtx_insn *last = BB_END (combo_bb);
3753
3754       /* The outgoing edge for the current COMBO block should already
3755          be correct.  Verify this.  */
3756       if (EDGE_COUNT (combo_bb->succs) == 0)
3757         gcc_assert (find_reg_note (last, REG_NORETURN, NULL)
3758                     || (NONJUMP_INSN_P (last)
3759                         && GET_CODE (PATTERN (last)) == TRAP_IF
3760                         && (TRAP_CONDITION (PATTERN (last))
3761                             == const_true_rtx)));
3762
3763       else
3764       /* There should still be something at the end of the THEN or ELSE
3765          blocks taking us to our final destination.  */
3766         gcc_assert (JUMP_P (last)
3767                     || (EDGE_SUCC (combo_bb, 0)->dest
3768                         == EXIT_BLOCK_PTR_FOR_FN (cfun)
3769                         && CALL_P (last)
3770                         && SIBLING_CALL_P (last))
3771                     || ((EDGE_SUCC (combo_bb, 0)->flags & EDGE_EH)
3772                         && can_throw_internal (last)));
3773     }
3774
3775   /* The JOIN block may have had quite a number of other predecessors too.
3776      Since we've already merged the TEST, THEN and ELSE blocks, we should
3777      have only one remaining edge from our if-then-else diamond.  If there
3778      is more than one remaining edge, it must come from elsewhere.  There
3779      may be zero incoming edges if the THEN block didn't actually join
3780      back up (as with a call to a non-return function).  */
3781   else if (EDGE_COUNT (join_bb->preds) < 2
3782            && join_bb != EXIT_BLOCK_PTR_FOR_FN (cfun))
3783     {
3784       /* We can merge the JOIN cleanly and update the dataflow try
3785          again on this pass.*/
3786       merge_blocks (combo_bb, join_bb);
3787       num_true_changes++;
3788     }
3789   else
3790     {
3791       /* We cannot merge the JOIN.  */
3792
3793       /* The outgoing edge for the current COMBO block should already
3794          be correct.  Verify this.  */
3795       gcc_assert (single_succ_p (combo_bb)
3796                   && single_succ (combo_bb) == join_bb);
3797
3798       /* Remove the jump and cruft from the end of the COMBO block.  */
3799       if (join_bb != EXIT_BLOCK_PTR_FOR_FN (cfun))
3800         tidy_fallthru_edge (single_succ_edge (combo_bb));
3801     }
3802
3803   num_updated_if_blocks++;
3804 }
3805 \f
3806 /* Find a block ending in a simple IF condition and try to transform it
3807    in some way.  When converting a multi-block condition, put the new code
3808    in the first such block and delete the rest.  Return a pointer to this
3809    first block if some transformation was done.  Return NULL otherwise.  */
3810
3811 static basic_block
3812 find_if_header (basic_block test_bb, int pass)
3813 {
3814   ce_if_block ce_info;
3815   edge then_edge;
3816   edge else_edge;
3817
3818   /* The kind of block we're looking for has exactly two successors.  */
3819   if (EDGE_COUNT (test_bb->succs) != 2)
3820     return NULL;
3821
3822   then_edge = EDGE_SUCC (test_bb, 0);
3823   else_edge = EDGE_SUCC (test_bb, 1);
3824
3825   if (df_get_bb_dirty (then_edge->dest))
3826     return NULL;
3827   if (df_get_bb_dirty (else_edge->dest))
3828     return NULL;
3829
3830   /* Neither edge should be abnormal.  */
3831   if ((then_edge->flags & EDGE_COMPLEX)
3832       || (else_edge->flags & EDGE_COMPLEX))
3833     return NULL;
3834
3835   /* Nor exit the loop.  */
3836   if ((then_edge->flags & EDGE_LOOP_EXIT)
3837       || (else_edge->flags & EDGE_LOOP_EXIT))
3838     return NULL;
3839
3840   /* The THEN edge is canonically the one that falls through.  */
3841   if (then_edge->flags & EDGE_FALLTHRU)
3842     ;
3843   else if (else_edge->flags & EDGE_FALLTHRU)
3844     std::swap (then_edge, else_edge);
3845   else
3846     /* Otherwise this must be a multiway branch of some sort.  */
3847     return NULL;
3848
3849   memset (&ce_info, 0, sizeof (ce_info));
3850   ce_info.test_bb = test_bb;
3851   ce_info.then_bb = then_edge->dest;
3852   ce_info.else_bb = else_edge->dest;
3853   ce_info.pass = pass;
3854
3855 #ifdef IFCVT_MACHDEP_INIT
3856   IFCVT_MACHDEP_INIT (&ce_info);
3857 #endif
3858
3859   if (!reload_completed
3860       && noce_find_if_block (test_bb, then_edge, else_edge, pass))
3861     goto success;
3862
3863   if (reload_completed
3864       && targetm.have_conditional_execution ()
3865       && cond_exec_find_if_block (&ce_info))
3866     goto success;
3867
3868   if (targetm.have_trap ()
3869       && optab_handler (ctrap_optab, word_mode) != CODE_FOR_nothing
3870       && find_cond_trap (test_bb, then_edge, else_edge))
3871     goto success;
3872
3873   if (dom_info_state (CDI_POST_DOMINATORS) >= DOM_NO_FAST_QUERY
3874       && (reload_completed || !targetm.have_conditional_execution ()))
3875     {
3876       if (find_if_case_1 (test_bb, then_edge, else_edge))
3877         goto success;
3878       if (find_if_case_2 (test_bb, then_edge, else_edge))
3879         goto success;
3880     }
3881
3882   return NULL;
3883
3884  success:
3885   if (dump_file)
3886     fprintf (dump_file, "Conversion succeeded on pass %d.\n", pass);
3887   /* Set this so we continue looking.  */
3888   cond_exec_changed_p = TRUE;
3889   return ce_info.test_bb;
3890 }
3891
3892 /* Return true if a block has two edges, one of which falls through to the next
3893    block, and the other jumps to a specific block, so that we can tell if the
3894    block is part of an && test or an || test.  Returns either -1 or the number
3895    of non-note, non-jump, non-USE/CLOBBER insns in the block.  */
3896
3897 static int
3898 block_jumps_and_fallthru_p (basic_block cur_bb, basic_block target_bb)
3899 {
3900   edge cur_edge;
3901   int fallthru_p = FALSE;
3902   int jump_p = FALSE;
3903   rtx_insn *insn;
3904   rtx_insn *end;
3905   int n_insns = 0;
3906   edge_iterator ei;
3907
3908   if (!cur_bb || !target_bb)
3909     return -1;
3910
3911   /* If no edges, obviously it doesn't jump or fallthru.  */
3912   if (EDGE_COUNT (cur_bb->succs) == 0)
3913     return FALSE;
3914
3915   FOR_EACH_EDGE (cur_edge, ei, cur_bb->succs)
3916     {
3917       if (cur_edge->flags & EDGE_COMPLEX)
3918         /* Anything complex isn't what we want.  */
3919         return -1;
3920
3921       else if (cur_edge->flags & EDGE_FALLTHRU)
3922         fallthru_p = TRUE;
3923
3924       else if (cur_edge->dest == target_bb)
3925         jump_p = TRUE;
3926
3927       else
3928         return -1;
3929     }
3930
3931   if ((jump_p & fallthru_p) == 0)
3932     return -1;
3933
3934   /* Don't allow calls in the block, since this is used to group && and ||
3935      together for conditional execution support.  ??? we should support
3936      conditional execution support across calls for IA-64 some day, but
3937      for now it makes the code simpler.  */
3938   end = BB_END (cur_bb);
3939   insn = BB_HEAD (cur_bb);
3940
3941   while (insn != NULL_RTX)
3942     {
3943       if (CALL_P (insn))
3944         return -1;
3945
3946       if (INSN_P (insn)
3947           && !JUMP_P (insn)
3948           && !DEBUG_INSN_P (insn)
3949           && GET_CODE (PATTERN (insn)) != USE
3950           && GET_CODE (PATTERN (insn)) != CLOBBER)
3951         n_insns++;
3952
3953       if (insn == end)
3954         break;
3955
3956       insn = NEXT_INSN (insn);
3957     }
3958
3959   return n_insns;
3960 }
3961
3962 /* Determine if a given basic block heads a simple IF-THEN or IF-THEN-ELSE
3963    block.  If so, we'll try to convert the insns to not require the branch.
3964    Return TRUE if we were successful at converting the block.  */
3965
3966 static int
3967 cond_exec_find_if_block (struct ce_if_block * ce_info)
3968 {
3969   basic_block test_bb = ce_info->test_bb;
3970   basic_block then_bb = ce_info->then_bb;
3971   basic_block else_bb = ce_info->else_bb;
3972   basic_block join_bb = NULL_BLOCK;
3973   edge cur_edge;
3974   basic_block next;
3975   edge_iterator ei;
3976
3977   ce_info->last_test_bb = test_bb;
3978
3979   /* We only ever should get here after reload,
3980      and if we have conditional execution.  */
3981   gcc_assert (reload_completed && targetm.have_conditional_execution ());
3982
3983   /* Discover if any fall through predecessors of the current test basic block
3984      were && tests (which jump to the else block) or || tests (which jump to
3985      the then block).  */
3986   if (single_pred_p (test_bb)
3987       && single_pred_edge (test_bb)->flags == EDGE_FALLTHRU)
3988     {
3989       basic_block bb = single_pred (test_bb);
3990       basic_block target_bb;
3991       int max_insns = MAX_CONDITIONAL_EXECUTE;
3992       int n_insns;
3993
3994       /* Determine if the preceding block is an && or || block.  */
3995       if ((n_insns = block_jumps_and_fallthru_p (bb, else_bb)) >= 0)
3996         {
3997           ce_info->and_and_p = TRUE;
3998           target_bb = else_bb;
3999         }
4000       else if ((n_insns = block_jumps_and_fallthru_p (bb, then_bb)) >= 0)
4001         {
4002           ce_info->and_and_p = FALSE;
4003           target_bb = then_bb;
4004         }
4005       else
4006         target_bb = NULL_BLOCK;
4007
4008       if (target_bb && n_insns <= max_insns)
4009         {
4010           int total_insns = 0;
4011           int blocks = 0;
4012
4013           ce_info->last_test_bb = test_bb;
4014
4015           /* Found at least one && or || block, look for more.  */
4016           do
4017             {
4018               ce_info->test_bb = test_bb = bb;
4019               total_insns += n_insns;
4020               blocks++;
4021
4022               if (!single_pred_p (bb))
4023                 break;
4024
4025               bb = single_pred (bb);
4026               n_insns = block_jumps_and_fallthru_p (bb, target_bb);
4027             }
4028           while (n_insns >= 0 && (total_insns + n_insns) <= max_insns);
4029
4030           ce_info->num_multiple_test_blocks = blocks;
4031           ce_info->num_multiple_test_insns = total_insns;
4032
4033           if (ce_info->and_and_p)
4034             ce_info->num_and_and_blocks = blocks;
4035           else
4036             ce_info->num_or_or_blocks = blocks;
4037         }
4038     }
4039
4040   /* The THEN block of an IF-THEN combo must have exactly one predecessor,
4041      other than any || blocks which jump to the THEN block.  */
4042   if ((EDGE_COUNT (then_bb->preds) - ce_info->num_or_or_blocks) != 1)
4043     return FALSE;
4044
4045   /* The edges of the THEN and ELSE blocks cannot have complex edges.  */
4046   FOR_EACH_EDGE (cur_edge, ei, then_bb->preds)
4047     {
4048       if (cur_edge->flags & EDGE_COMPLEX)
4049         return FALSE;
4050     }
4051
4052   FOR_EACH_EDGE (cur_edge, ei, else_bb->preds)
4053     {
4054       if (cur_edge->flags & EDGE_COMPLEX)
4055         return FALSE;
4056     }
4057
4058   /* The THEN block of an IF-THEN combo must have zero or one successors.  */
4059   if (EDGE_COUNT (then_bb->succs) > 0
4060       && (!single_succ_p (then_bb)
4061           || (single_succ_edge (then_bb)->flags & EDGE_COMPLEX)
4062           || (epilogue_completed
4063               && tablejump_p (BB_END (then_bb), NULL, NULL))))
4064     return FALSE;
4065
4066   /* If the THEN block has no successors, conditional execution can still
4067      make a conditional call.  Don't do this unless the ELSE block has
4068      only one incoming edge -- the CFG manipulation is too ugly otherwise.
4069      Check for the last insn of the THEN block being an indirect jump, which
4070      is listed as not having any successors, but confuses the rest of the CE
4071      code processing.  ??? we should fix this in the future.  */
4072   if (EDGE_COUNT (then_bb->succs) == 0)
4073     {
4074       if (single_pred_p (else_bb) && else_bb != EXIT_BLOCK_PTR_FOR_FN (cfun))
4075         {
4076           rtx_insn *last_insn = BB_END (then_bb);
4077
4078           while (last_insn
4079                  && NOTE_P (last_insn)
4080                  && last_insn != BB_HEAD (then_bb))
4081             last_insn = PREV_INSN (last_insn);
4082
4083           if (last_insn
4084               && JUMP_P (last_insn)
4085               && ! simplejump_p (last_insn))
4086             return FALSE;
4087
4088           join_bb = else_bb;
4089           else_bb = NULL_BLOCK;
4090         }
4091       else
4092         return FALSE;
4093     }
4094
4095   /* If the THEN block's successor is the other edge out of the TEST block,
4096      then we have an IF-THEN combo without an ELSE.  */
4097   else if (single_succ (then_bb) == else_bb)
4098     {
4099       join_bb = else_bb;
4100       else_bb = NULL_BLOCK;
4101     }
4102
4103   /* If the THEN and ELSE block meet in a subsequent block, and the ELSE
4104      has exactly one predecessor and one successor, and the outgoing edge
4105      is not complex, then we have an IF-THEN-ELSE combo.  */
4106   else if (single_succ_p (else_bb)
4107            && single_succ (then_bb) == single_succ (else_bb)
4108            && single_pred_p (else_bb)
4109            && !(single_succ_edge (else_bb)->flags & EDGE_COMPLEX)
4110            && !(epilogue_completed
4111                 && tablejump_p (BB_END (else_bb), NULL, NULL)))
4112     join_bb = single_succ (else_bb);
4113
4114   /* Otherwise it is not an IF-THEN or IF-THEN-ELSE combination.  */
4115   else
4116     return FALSE;
4117
4118   num_possible_if_blocks++;
4119
4120   if (dump_file)
4121     {
4122       fprintf (dump_file,
4123                "\nIF-THEN%s block found, pass %d, start block %d "
4124                "[insn %d], then %d [%d]",
4125                (else_bb) ? "-ELSE" : "",
4126                ce_info->pass,
4127                test_bb->index,
4128                BB_HEAD (test_bb) ? (int)INSN_UID (BB_HEAD (test_bb)) : -1,
4129                then_bb->index,
4130                BB_HEAD (then_bb) ? (int)INSN_UID (BB_HEAD (then_bb)) : -1);
4131
4132       if (else_bb)
4133         fprintf (dump_file, ", else %d [%d]",
4134                  else_bb->index,
4135                  BB_HEAD (else_bb) ? (int)INSN_UID (BB_HEAD (else_bb)) : -1);
4136
4137       fprintf (dump_file, ", join %d [%d]",
4138                join_bb->index,
4139                BB_HEAD (join_bb) ? (int)INSN_UID (BB_HEAD (join_bb)) : -1);
4140
4141       if (ce_info->num_multiple_test_blocks > 0)
4142         fprintf (dump_file, ", %d %s block%s last test %d [%d]",
4143                  ce_info->num_multiple_test_blocks,
4144                  (ce_info->and_and_p) ? "&&" : "||",
4145                  (ce_info->num_multiple_test_blocks == 1) ? "" : "s",
4146                  ce_info->last_test_bb->index,
4147                  ((BB_HEAD (ce_info->last_test_bb))
4148                   ? (int)INSN_UID (BB_HEAD (ce_info->last_test_bb))
4149                   : -1));
4150
4151       fputc ('\n', dump_file);
4152     }
4153
4154   /* Make sure IF, THEN, and ELSE, blocks are adjacent.  Actually, we get the
4155      first condition for free, since we've already asserted that there's a
4156      fallthru edge from IF to THEN.  Likewise for the && and || blocks, since
4157      we checked the FALLTHRU flag, those are already adjacent to the last IF
4158      block.  */
4159   /* ??? As an enhancement, move the ELSE block.  Have to deal with
4160      BLOCK notes, if by no other means than backing out the merge if they
4161      exist.  Sticky enough I don't want to think about it now.  */
4162   next = then_bb;
4163   if (else_bb && (next = next->next_bb) != else_bb)
4164     return FALSE;
4165   if ((next = next->next_bb) != join_bb
4166       && join_bb != EXIT_BLOCK_PTR_FOR_FN (cfun))
4167     {
4168       if (else_bb)
4169         join_bb = NULL;
4170       else
4171         return FALSE;
4172     }
4173
4174   /* Do the real work.  */
4175
4176   ce_info->else_bb = else_bb;
4177   ce_info->join_bb = join_bb;
4178
4179   /* If we have && and || tests, try to first handle combining the && and ||
4180      tests into the conditional code, and if that fails, go back and handle
4181      it without the && and ||, which at present handles the && case if there
4182      was no ELSE block.  */
4183   if (cond_exec_process_if_block (ce_info, TRUE))
4184     return TRUE;
4185
4186   if (ce_info->num_multiple_test_blocks)
4187     {
4188       cancel_changes (0);
4189
4190       if (cond_exec_process_if_block (ce_info, FALSE))
4191         return TRUE;
4192     }
4193
4194   return FALSE;
4195 }
4196
4197 /* Convert a branch over a trap, or a branch
4198    to a trap, into a conditional trap.  */
4199
4200 static int
4201 find_cond_trap (basic_block test_bb, edge then_edge, edge else_edge)
4202 {
4203   basic_block then_bb = then_edge->dest;
4204   basic_block else_bb = else_edge->dest;
4205   basic_block other_bb, trap_bb;
4206   rtx_insn *trap, *jump;
4207   rtx cond;
4208   rtx_insn *cond_earliest;
4209   enum rtx_code code;
4210
4211   /* Locate the block with the trap instruction.  */
4212   /* ??? While we look for no successors, we really ought to allow
4213      EH successors.  Need to fix merge_if_block for that to work.  */
4214   if ((trap = block_has_only_trap (then_bb)) != NULL)
4215     trap_bb = then_bb, other_bb = else_bb;
4216   else if ((trap = block_has_only_trap (else_bb)) != NULL)
4217     trap_bb = else_bb, other_bb = then_bb;
4218   else
4219     return FALSE;
4220
4221   if (dump_file)
4222     {
4223       fprintf (dump_file, "\nTRAP-IF block found, start %d, trap %d\n",
4224                test_bb->index, trap_bb->index);
4225     }
4226
4227   /* If this is not a standard conditional jump, we can't parse it.  */
4228   jump = BB_END (test_bb);
4229   cond = noce_get_condition (jump, &cond_earliest, false);
4230   if (! cond)
4231     return FALSE;
4232
4233   /* If the conditional jump is more than just a conditional jump, then
4234      we can not do if-conversion on this block.  */
4235   if (! onlyjump_p (jump))
4236     return FALSE;
4237
4238   /* We must be comparing objects whose modes imply the size.  */
4239   if (GET_MODE (XEXP (cond, 0)) == BLKmode)
4240     return FALSE;
4241
4242   /* Reverse the comparison code, if necessary.  */
4243   code = GET_CODE (cond);
4244   if (then_bb == trap_bb)
4245     {
4246       code = reversed_comparison_code (cond, jump);
4247       if (code == UNKNOWN)
4248         return FALSE;
4249     }
4250
4251   /* Attempt to generate the conditional trap.  */
4252   rtx_insn *seq = gen_cond_trap (code, copy_rtx (XEXP (cond, 0)),
4253                                  copy_rtx (XEXP (cond, 1)),
4254                                  TRAP_CODE (PATTERN (trap)));
4255   if (seq == NULL)
4256     return FALSE;
4257
4258   /* Emit the new insns before cond_earliest.  */
4259   emit_insn_before_setloc (seq, cond_earliest, INSN_LOCATION (trap));
4260
4261   /* Delete the trap block if possible.  */
4262   remove_edge (trap_bb == then_bb ? then_edge : else_edge);
4263   df_set_bb_dirty (test_bb);
4264   df_set_bb_dirty (then_bb);
4265   df_set_bb_dirty (else_bb);
4266
4267   if (EDGE_COUNT (trap_bb->preds) == 0)
4268     {
4269       delete_basic_block (trap_bb);
4270       num_true_changes++;
4271     }
4272
4273   /* Wire together the blocks again.  */
4274   if (current_ir_type () == IR_RTL_CFGLAYOUT)
4275     single_succ_edge (test_bb)->flags |= EDGE_FALLTHRU;
4276   else if (trap_bb == then_bb)
4277     {
4278       rtx lab = JUMP_LABEL (jump);
4279       rtx_insn *seq = targetm.gen_jump (lab);
4280       rtx_jump_insn *newjump = emit_jump_insn_after (seq, jump);
4281       LABEL_NUSES (lab) += 1;
4282       JUMP_LABEL (newjump) = lab;
4283       emit_barrier_after (newjump);
4284     }
4285   delete_insn (jump);
4286
4287   if (can_merge_blocks_p (test_bb, other_bb))
4288     {
4289       merge_blocks (test_bb, other_bb);
4290       num_true_changes++;
4291     }
4292
4293   num_updated_if_blocks++;
4294   return TRUE;
4295 }
4296
4297 /* Subroutine of find_cond_trap: if BB contains only a trap insn,
4298    return it.  */
4299
4300 static rtx_insn *
4301 block_has_only_trap (basic_block bb)
4302 {
4303   rtx_insn *trap;
4304
4305   /* We're not the exit block.  */
4306   if (bb == EXIT_BLOCK_PTR_FOR_FN (cfun))
4307     return NULL;
4308
4309   /* The block must have no successors.  */
4310   if (EDGE_COUNT (bb->succs) > 0)
4311     return NULL;
4312
4313   /* The only instruction in the THEN block must be the trap.  */
4314   trap = first_active_insn (bb);
4315   if (! (trap == BB_END (bb)
4316          && GET_CODE (PATTERN (trap)) == TRAP_IF
4317          && TRAP_CONDITION (PATTERN (trap)) == const_true_rtx))
4318     return NULL;
4319
4320   return trap;
4321 }
4322
4323 /* Look for IF-THEN-ELSE cases in which one of THEN or ELSE is
4324    transformable, but not necessarily the other.  There need be no
4325    JOIN block.
4326
4327    Return TRUE if we were successful at converting the block.
4328
4329    Cases we'd like to look at:
4330
4331    (1)
4332         if (test) goto over; // x not live
4333         x = a;
4334         goto label;
4335         over:
4336
4337    becomes
4338
4339         x = a;
4340         if (! test) goto label;
4341
4342    (2)
4343         if (test) goto E; // x not live
4344         x = big();
4345         goto L;
4346         E:
4347         x = b;
4348         goto M;
4349
4350    becomes
4351
4352         x = b;
4353         if (test) goto M;
4354         x = big();
4355         goto L;
4356
4357    (3) // This one's really only interesting for targets that can do
4358        // multiway branching, e.g. IA-64 BBB bundles.  For other targets
4359        // it results in multiple branches on a cache line, which often
4360        // does not sit well with predictors.
4361
4362         if (test1) goto E; // predicted not taken
4363         x = a;
4364         if (test2) goto F;
4365         ...
4366         E:
4367         x = b;
4368         J:
4369
4370    becomes
4371
4372         x = a;
4373         if (test1) goto E;
4374         if (test2) goto F;
4375
4376    Notes:
4377
4378    (A) Don't do (2) if the branch is predicted against the block we're
4379    eliminating.  Do it anyway if we can eliminate a branch; this requires
4380    that the sole successor of the eliminated block postdominate the other
4381    side of the if.
4382
4383    (B) With CE, on (3) we can steal from both sides of the if, creating
4384
4385         if (test1) x = a;
4386         if (!test1) x = b;
4387         if (test1) goto J;
4388         if (test2) goto F;
4389         ...
4390         J:
4391
4392    Again, this is most useful if J postdominates.
4393
4394    (C) CE substitutes for helpful life information.
4395
4396    (D) These heuristics need a lot of work.  */
4397
4398 /* Tests for case 1 above.  */
4399
4400 static int
4401 find_if_case_1 (basic_block test_bb, edge then_edge, edge else_edge)
4402 {
4403   basic_block then_bb = then_edge->dest;
4404   basic_block else_bb = else_edge->dest;
4405   basic_block new_bb;
4406   int then_bb_index, then_prob;
4407   rtx else_target = NULL_RTX;
4408
4409   /* If we are partitioning hot/cold basic blocks, we don't want to
4410      mess up unconditional or indirect jumps that cross between hot
4411      and cold sections.
4412
4413      Basic block partitioning may result in some jumps that appear to
4414      be optimizable (or blocks that appear to be mergeable), but which really
4415      must be left untouched (they are required to make it safely across
4416      partition boundaries).  See  the comments at the top of
4417      bb-reorder.c:partition_hot_cold_basic_blocks for complete details.  */
4418
4419   if ((BB_END (then_bb)
4420        && JUMP_P (BB_END (then_bb))
4421        && CROSSING_JUMP_P (BB_END (then_bb)))
4422       || (BB_END (test_bb)
4423           && JUMP_P (BB_END (test_bb))
4424           && CROSSING_JUMP_P (BB_END (test_bb)))
4425       || (BB_END (else_bb)
4426           && JUMP_P (BB_END (else_bb))
4427           && CROSSING_JUMP_P (BB_END (else_bb))))
4428     return FALSE;
4429
4430   /* THEN has one successor.  */
4431   if (!single_succ_p (then_bb))
4432     return FALSE;
4433
4434   /* THEN does not fall through, but is not strange either.  */
4435   if (single_succ_edge (then_bb)->flags & (EDGE_COMPLEX | EDGE_FALLTHRU))
4436     return FALSE;
4437
4438   /* THEN has one predecessor.  */
4439   if (!single_pred_p (then_bb))
4440     return FALSE;
4441
4442   /* THEN must do something.  */
4443   if (forwarder_block_p (then_bb))
4444     return FALSE;
4445
4446   num_possible_if_blocks++;
4447   if (dump_file)
4448     fprintf (dump_file,
4449              "\nIF-CASE-1 found, start %d, then %d\n",
4450              test_bb->index, then_bb->index);
4451
4452   if (then_edge->probability)
4453     then_prob = REG_BR_PROB_BASE - then_edge->probability;
4454   else
4455     then_prob = REG_BR_PROB_BASE / 2;
4456
4457   /* We're speculating from the THEN path, we want to make sure the cost
4458      of speculation is within reason.  */
4459   if (! cheap_bb_rtx_cost_p (then_bb, then_prob,
4460         COSTS_N_INSNS (BRANCH_COST (optimize_bb_for_speed_p (then_edge->src),
4461                                     predictable_edge_p (then_edge)))))
4462     return FALSE;
4463
4464   if (else_bb == EXIT_BLOCK_PTR_FOR_FN (cfun))
4465     {
4466       rtx_insn *jump = BB_END (else_edge->src);
4467       gcc_assert (JUMP_P (jump));
4468       else_target = JUMP_LABEL (jump);
4469     }
4470
4471   /* Registers set are dead, or are predicable.  */
4472   if (! dead_or_predicable (test_bb, then_bb, else_bb,
4473                             single_succ_edge (then_bb), 1))
4474     return FALSE;
4475
4476   /* Conversion went ok, including moving the insns and fixing up the
4477      jump.  Adjust the CFG to match.  */
4478
4479   /* We can avoid creating a new basic block if then_bb is immediately
4480      followed by else_bb, i.e. deleting then_bb allows test_bb to fall
4481      through to else_bb.  */
4482
4483   if (then_bb->next_bb == else_bb
4484       && then_bb->prev_bb == test_bb
4485       && else_bb != EXIT_BLOCK_PTR_FOR_FN (cfun))
4486     {
4487       redirect_edge_succ (FALLTHRU_EDGE (test_bb), else_bb);
4488       new_bb = 0;
4489     }
4490   else if (else_bb == EXIT_BLOCK_PTR_FOR_FN (cfun))
4491     new_bb = force_nonfallthru_and_redirect (FALLTHRU_EDGE (test_bb),
4492                                              else_bb, else_target);
4493   else
4494     new_bb = redirect_edge_and_branch_force (FALLTHRU_EDGE (test_bb),
4495                                              else_bb);
4496
4497   df_set_bb_dirty (test_bb);
4498   df_set_bb_dirty (else_bb);
4499
4500   then_bb_index = then_bb->index;
4501   delete_basic_block (then_bb);
4502
4503   /* Make rest of code believe that the newly created block is the THEN_BB
4504      block we removed.  */
4505   if (new_bb)
4506     {
4507       df_bb_replace (then_bb_index, new_bb);
4508       /* This should have been done above via force_nonfallthru_and_redirect
4509          (possibly called from redirect_edge_and_branch_force).  */
4510       gcc_checking_assert (BB_PARTITION (new_bb) == BB_PARTITION (test_bb));
4511     }
4512
4513   num_true_changes++;
4514   num_updated_if_blocks++;
4515
4516   return TRUE;
4517 }
4518
4519 /* Test for case 2 above.  */
4520
4521 static int
4522 find_if_case_2 (basic_block test_bb, edge then_edge, edge else_edge)
4523 {
4524   basic_block then_bb = then_edge->dest;
4525   basic_block else_bb = else_edge->dest;
4526   edge else_succ;
4527   int then_prob, else_prob;
4528
4529   /* We do not want to speculate (empty) loop latches.  */
4530   if (current_loops
4531       && else_bb->loop_father->latch == else_bb)
4532     return FALSE;
4533
4534   /* If we are partitioning hot/cold basic blocks, we don't want to
4535      mess up unconditional or indirect jumps that cross between hot
4536      and cold sections.
4537
4538      Basic block partitioning may result in some jumps that appear to
4539      be optimizable (or blocks that appear to be mergeable), but which really
4540      must be left untouched (they are required to make it safely across
4541      partition boundaries).  See  the comments at the top of
4542      bb-reorder.c:partition_hot_cold_basic_blocks for complete details.  */
4543
4544   if ((BB_END (then_bb)
4545        && JUMP_P (BB_END (then_bb))
4546        && CROSSING_JUMP_P (BB_END (then_bb)))
4547       || (BB_END (test_bb)
4548           && JUMP_P (BB_END (test_bb))
4549           && CROSSING_JUMP_P (BB_END (test_bb)))
4550       || (BB_END (else_bb)
4551           && JUMP_P (BB_END (else_bb))
4552           && CROSSING_JUMP_P (BB_END (else_bb))))
4553     return FALSE;
4554
4555   /* ELSE has one successor.  */
4556   if (!single_succ_p (else_bb))
4557     return FALSE;
4558   else
4559     else_succ = single_succ_edge (else_bb);
4560
4561   /* ELSE outgoing edge is not complex.  */
4562   if (else_succ->flags & EDGE_COMPLEX)
4563     return FALSE;
4564
4565   /* ELSE has one predecessor.  */
4566   if (!single_pred_p (else_bb))
4567     return FALSE;
4568
4569   /* THEN is not EXIT.  */
4570   if (then_bb->index < NUM_FIXED_BLOCKS)
4571     return FALSE;
4572
4573   if (else_edge->probability)
4574     {
4575       else_prob = else_edge->probability;
4576       then_prob = REG_BR_PROB_BASE - else_prob;
4577     }
4578   else
4579     {
4580       else_prob = REG_BR_PROB_BASE / 2;
4581       then_prob = REG_BR_PROB_BASE / 2;
4582     }
4583
4584   /* ELSE is predicted or SUCC(ELSE) postdominates THEN.  */
4585   if (else_prob > then_prob)
4586     ;
4587   else if (else_succ->dest->index < NUM_FIXED_BLOCKS
4588            || dominated_by_p (CDI_POST_DOMINATORS, then_bb,
4589                               else_succ->dest))
4590     ;
4591   else
4592     return FALSE;
4593
4594   num_possible_if_blocks++;
4595   if (dump_file)
4596     fprintf (dump_file,
4597              "\nIF-CASE-2 found, start %d, else %d\n",
4598              test_bb->index, else_bb->index);
4599
4600   /* We're speculating from the ELSE path, we want to make sure the cost
4601      of speculation is within reason.  */
4602   if (! cheap_bb_rtx_cost_p (else_bb, else_prob,
4603         COSTS_N_INSNS (BRANCH_COST (optimize_bb_for_speed_p (else_edge->src),
4604                                     predictable_edge_p (else_edge)))))
4605     return FALSE;
4606
4607   /* Registers set are dead, or are predicable.  */
4608   if (! dead_or_predicable (test_bb, else_bb, then_bb, else_succ, 0))
4609     return FALSE;
4610
4611   /* Conversion went ok, including moving the insns and fixing up the
4612      jump.  Adjust the CFG to match.  */
4613
4614   df_set_bb_dirty (test_bb);
4615   df_set_bb_dirty (then_bb);
4616   delete_basic_block (else_bb);
4617
4618   num_true_changes++;
4619   num_updated_if_blocks++;
4620
4621   /* ??? We may now fallthru from one of THEN's successors into a join
4622      block.  Rerun cleanup_cfg?  Examine things manually?  Wait?  */
4623
4624   return TRUE;
4625 }
4626
4627 /* Used by the code above to perform the actual rtl transformations.
4628    Return TRUE if successful.
4629
4630    TEST_BB is the block containing the conditional branch.  MERGE_BB
4631    is the block containing the code to manipulate.  DEST_EDGE is an
4632    edge representing a jump to the join block; after the conversion,
4633    TEST_BB should be branching to its destination.
4634    REVERSEP is true if the sense of the branch should be reversed.  */
4635
4636 static int
4637 dead_or_predicable (basic_block test_bb, basic_block merge_bb,
4638                     basic_block other_bb, edge dest_edge, int reversep)
4639 {
4640   basic_block new_dest = dest_edge->dest;
4641   rtx_insn *head, *end, *jump;
4642   rtx_insn *earliest = NULL;
4643   rtx old_dest;
4644   bitmap merge_set = NULL;
4645   /* Number of pending changes.  */
4646   int n_validated_changes = 0;
4647   rtx new_dest_label = NULL_RTX;
4648
4649   jump = BB_END (test_bb);
4650
4651   /* Find the extent of the real code in the merge block.  */
4652   head = BB_HEAD (merge_bb);
4653   end = BB_END (merge_bb);
4654
4655   while (DEBUG_INSN_P (end) && end != head)
4656     end = PREV_INSN (end);
4657
4658   /* If merge_bb ends with a tablejump, predicating/moving insn's
4659      into test_bb and then deleting merge_bb will result in the jumptable
4660      that follows merge_bb being removed along with merge_bb and then we
4661      get an unresolved reference to the jumptable.  */
4662   if (tablejump_p (end, NULL, NULL))
4663     return FALSE;
4664
4665   if (LABEL_P (head))
4666     head = NEXT_INSN (head);
4667   while (DEBUG_INSN_P (head) && head != end)
4668     head = NEXT_INSN (head);
4669   if (NOTE_P (head))
4670     {
4671       if (head == end)
4672         {
4673           head = end = NULL;
4674           goto no_body;
4675         }
4676       head = NEXT_INSN (head);
4677       while (DEBUG_INSN_P (head) && head != end)
4678         head = NEXT_INSN (head);
4679     }
4680
4681   if (JUMP_P (end))
4682     {
4683       if (!onlyjump_p (end))
4684         return FALSE;
4685       if (head == end)
4686         {
4687           head = end = NULL;
4688           goto no_body;
4689         }
4690       end = PREV_INSN (end);
4691       while (DEBUG_INSN_P (end) && end != head)
4692         end = PREV_INSN (end);
4693     }
4694
4695   /* Don't move frame-related insn across the conditional branch.  This
4696      can lead to one of the paths of the branch having wrong unwind info.  */
4697   if (epilogue_completed)
4698     {
4699       rtx_insn *insn = head;
4700       while (1)
4701         {
4702           if (INSN_P (insn) && RTX_FRAME_RELATED_P (insn))
4703             return FALSE;
4704           if (insn == end)
4705             break;
4706           insn = NEXT_INSN (insn);
4707         }
4708     }
4709
4710   /* Disable handling dead code by conditional execution if the machine needs
4711      to do anything funny with the tests, etc.  */
4712 #ifndef IFCVT_MODIFY_TESTS
4713   if (targetm.have_conditional_execution ())
4714     {
4715       /* In the conditional execution case, we have things easy.  We know
4716          the condition is reversible.  We don't have to check life info
4717          because we're going to conditionally execute the code anyway.
4718          All that's left is making sure the insns involved can actually
4719          be predicated.  */
4720
4721       rtx cond;
4722
4723       cond = cond_exec_get_condition (jump);
4724       if (! cond)
4725         return FALSE;
4726
4727       rtx note = find_reg_note (jump, REG_BR_PROB, NULL_RTX);
4728       int prob_val = (note ? XINT (note, 0) : -1);
4729
4730       if (reversep)
4731         {
4732           enum rtx_code rev = reversed_comparison_code (cond, jump);
4733           if (rev == UNKNOWN)
4734             return FALSE;
4735           cond = gen_rtx_fmt_ee (rev, GET_MODE (cond), XEXP (cond, 0),
4736                                  XEXP (cond, 1));
4737           if (prob_val >= 0)
4738             prob_val = REG_BR_PROB_BASE - prob_val;
4739         }
4740
4741       if (cond_exec_process_insns (NULL, head, end, cond, prob_val, 0)
4742           && verify_changes (0))
4743         n_validated_changes = num_validated_changes ();
4744       else
4745         cancel_changes (0);
4746
4747       earliest = jump;
4748     }
4749 #endif
4750
4751   /* If we allocated new pseudos (e.g. in the conditional move
4752      expander called from noce_emit_cmove), we must resize the
4753      array first.  */
4754   if (max_regno < max_reg_num ())
4755     max_regno = max_reg_num ();
4756
4757   /* Try the NCE path if the CE path did not result in any changes.  */
4758   if (n_validated_changes == 0)
4759     {
4760       rtx cond;
4761       rtx_insn *insn;
4762       regset live;
4763       bool success;
4764
4765       /* In the non-conditional execution case, we have to verify that there
4766          are no trapping operations, no calls, no references to memory, and
4767          that any registers modified are dead at the branch site.  */
4768
4769       if (!any_condjump_p (jump))
4770         return FALSE;
4771
4772       /* Find the extent of the conditional.  */
4773       cond = noce_get_condition (jump, &earliest, false);
4774       if (!cond)
4775         return FALSE;
4776
4777       live = BITMAP_ALLOC (&reg_obstack);
4778       simulate_backwards_to_point (merge_bb, live, end);
4779       success = can_move_insns_across (head, end, earliest, jump,
4780                                        merge_bb, live,
4781                                        df_get_live_in (other_bb), NULL);
4782       BITMAP_FREE (live);
4783       if (!success)
4784         return FALSE;
4785
4786       /* Collect the set of registers set in MERGE_BB.  */
4787       merge_set = BITMAP_ALLOC (&reg_obstack);
4788
4789       FOR_BB_INSNS (merge_bb, insn)
4790         if (NONDEBUG_INSN_P (insn))
4791           df_simulate_find_defs (insn, merge_set);
4792
4793       /* If shrink-wrapping, disable this optimization when test_bb is
4794          the first basic block and merge_bb exits.  The idea is to not
4795          move code setting up a return register as that may clobber a
4796          register used to pass function parameters, which then must be
4797          saved in caller-saved regs.  A caller-saved reg requires the
4798          prologue, killing a shrink-wrap opportunity.  */
4799       if ((SHRINK_WRAPPING_ENABLED && !epilogue_completed)
4800           && ENTRY_BLOCK_PTR_FOR_FN (cfun)->next_bb == test_bb
4801           && single_succ_p (new_dest)
4802           && single_succ (new_dest) == EXIT_BLOCK_PTR_FOR_FN (cfun)
4803           && bitmap_intersect_p (df_get_live_in (new_dest), merge_set))
4804         {
4805           regset return_regs;
4806           unsigned int i;
4807
4808           return_regs = BITMAP_ALLOC (&reg_obstack);
4809
4810           /* Start off with the intersection of regs used to pass
4811              params and regs used to return values.  */
4812           for (i = 0; i < FIRST_PSEUDO_REGISTER; i++)
4813             if (FUNCTION_ARG_REGNO_P (i)
4814                 && targetm.calls.function_value_regno_p (i))
4815               bitmap_set_bit (return_regs, INCOMING_REGNO (i));
4816
4817           bitmap_and_into (return_regs,
4818                            df_get_live_out (ENTRY_BLOCK_PTR_FOR_FN (cfun)));
4819           bitmap_and_into (return_regs,
4820                            df_get_live_in (EXIT_BLOCK_PTR_FOR_FN (cfun)));
4821           if (!bitmap_empty_p (return_regs))
4822             {
4823               FOR_BB_INSNS_REVERSE (new_dest, insn)
4824                 if (NONDEBUG_INSN_P (insn))
4825                   {
4826                     df_ref def;
4827
4828                     /* If this insn sets any reg in return_regs, add all
4829                        reg uses to the set of regs we're interested in.  */
4830                     FOR_EACH_INSN_DEF (def, insn)
4831                       if (bitmap_bit_p (return_regs, DF_REF_REGNO (def)))
4832                         {
4833                           df_simulate_uses (insn, return_regs);
4834                           break;
4835                         }
4836                   }
4837               if (bitmap_intersect_p (merge_set, return_regs))
4838                 {
4839                   BITMAP_FREE (return_regs);
4840                   BITMAP_FREE (merge_set);
4841                   return FALSE;
4842                 }
4843             }
4844           BITMAP_FREE (return_regs);
4845         }
4846     }
4847
4848  no_body:
4849   /* We don't want to use normal invert_jump or redirect_jump because
4850      we don't want to delete_insn called.  Also, we want to do our own
4851      change group management.  */
4852
4853   old_dest = JUMP_LABEL (jump);
4854   if (other_bb != new_dest)
4855     {
4856       if (!any_condjump_p (jump))
4857         goto cancel;
4858
4859       if (JUMP_P (BB_END (dest_edge->src)))
4860         new_dest_label = JUMP_LABEL (BB_END (dest_edge->src));
4861       else if (new_dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
4862         new_dest_label = ret_rtx;
4863       else
4864         new_dest_label = block_label (new_dest);
4865
4866       rtx_jump_insn *jump_insn = as_a <rtx_jump_insn *> (jump);
4867       if (reversep
4868           ? ! invert_jump_1 (jump_insn, new_dest_label)
4869           : ! redirect_jump_1 (jump_insn, new_dest_label))
4870         goto cancel;
4871     }
4872
4873   if (verify_changes (n_validated_changes))
4874     confirm_change_group ();
4875   else
4876     goto cancel;
4877
4878   if (other_bb != new_dest)
4879     {
4880       redirect_jump_2 (as_a <rtx_jump_insn *> (jump), old_dest, new_dest_label,
4881                        0, reversep);
4882
4883       redirect_edge_succ (BRANCH_EDGE (test_bb), new_dest);
4884       if (reversep)
4885         {
4886           std::swap (BRANCH_EDGE (test_bb)->count,
4887                      FALLTHRU_EDGE (test_bb)->count);
4888           std::swap (BRANCH_EDGE (test_bb)->probability,
4889                      FALLTHRU_EDGE (test_bb)->probability);
4890           update_br_prob_note (test_bb);
4891         }
4892     }
4893
4894   /* Move the insns out of MERGE_BB to before the branch.  */
4895   if (head != NULL)
4896     {
4897       rtx_insn *insn;
4898
4899       if (end == BB_END (merge_bb))
4900         BB_END (merge_bb) = PREV_INSN (head);
4901
4902       /* PR 21767: when moving insns above a conditional branch, the REG_EQUAL
4903          notes being moved might become invalid.  */
4904       insn = head;
4905       do
4906         {
4907           rtx note;
4908
4909           if (! INSN_P (insn))
4910             continue;
4911           note = find_reg_note (insn, REG_EQUAL, NULL_RTX);
4912           if (! note)
4913             continue;
4914           remove_note (insn, note);
4915         } while (insn != end && (insn = NEXT_INSN (insn)));
4916
4917       /* PR46315: when moving insns above a conditional branch, the REG_EQUAL
4918          notes referring to the registers being set might become invalid.  */
4919       if (merge_set)
4920         {
4921           unsigned i;
4922           bitmap_iterator bi;
4923
4924           EXECUTE_IF_SET_IN_BITMAP (merge_set, 0, i, bi)
4925             remove_reg_equal_equiv_notes_for_regno (i);
4926
4927           BITMAP_FREE (merge_set);
4928         }
4929
4930       reorder_insns (head, end, PREV_INSN (earliest));
4931     }
4932
4933   /* Remove the jump and edge if we can.  */
4934   if (other_bb == new_dest)
4935     {
4936       delete_insn (jump);
4937       remove_edge (BRANCH_EDGE (test_bb));
4938       /* ??? Can't merge blocks here, as then_bb is still in use.
4939          At minimum, the merge will get done just before bb-reorder.  */
4940     }
4941
4942   return TRUE;
4943
4944  cancel:
4945   cancel_changes (0);
4946
4947   if (merge_set)
4948     BITMAP_FREE (merge_set);
4949
4950   return FALSE;
4951 }
4952 \f
4953 /* Main entry point for all if-conversion.  AFTER_COMBINE is true if
4954    we are after combine pass.  */
4955
4956 static void
4957 if_convert (bool after_combine)
4958 {
4959   basic_block bb;
4960   int pass;
4961
4962   if (optimize == 1)
4963     {
4964       df_live_add_problem ();
4965       df_live_set_all_dirty ();
4966     }
4967
4968   /* Record whether we are after combine pass.  */
4969   ifcvt_after_combine = after_combine;
4970   have_cbranchcc4 = (direct_optab_handler (cbranch_optab, CCmode)
4971                      != CODE_FOR_nothing);
4972   num_possible_if_blocks = 0;
4973   num_updated_if_blocks = 0;
4974   num_true_changes = 0;
4975
4976   loop_optimizer_init (AVOID_CFG_MODIFICATIONS);
4977   mark_loop_exit_edges ();
4978   loop_optimizer_finalize ();
4979   free_dominance_info (CDI_DOMINATORS);
4980
4981   /* Compute postdominators.  */
4982   calculate_dominance_info (CDI_POST_DOMINATORS);
4983
4984   df_set_flags (DF_LR_RUN_DCE);
4985
4986   /* Go through each of the basic blocks looking for things to convert.  If we
4987      have conditional execution, we make multiple passes to allow us to handle
4988      IF-THEN{-ELSE} blocks within other IF-THEN{-ELSE} blocks.  */
4989   pass = 0;
4990   do
4991     {
4992       df_analyze ();
4993       /* Only need to do dce on the first pass.  */
4994       df_clear_flags (DF_LR_RUN_DCE);
4995       cond_exec_changed_p = FALSE;
4996       pass++;
4997
4998 #ifdef IFCVT_MULTIPLE_DUMPS
4999       if (dump_file && pass > 1)
5000         fprintf (dump_file, "\n\n========== Pass %d ==========\n", pass);
5001 #endif
5002
5003       FOR_EACH_BB_FN (bb, cfun)
5004         {
5005           basic_block new_bb;
5006           while (!df_get_bb_dirty (bb)
5007                  && (new_bb = find_if_header (bb, pass)) != NULL)
5008             bb = new_bb;
5009         }
5010
5011 #ifdef IFCVT_MULTIPLE_DUMPS
5012       if (dump_file && cond_exec_changed_p)
5013         print_rtl_with_bb (dump_file, get_insns (), dump_flags);
5014 #endif
5015     }
5016   while (cond_exec_changed_p);
5017
5018 #ifdef IFCVT_MULTIPLE_DUMPS
5019   if (dump_file)
5020     fprintf (dump_file, "\n\n========== no more changes\n");
5021 #endif
5022
5023   free_dominance_info (CDI_POST_DOMINATORS);
5024
5025   if (dump_file)
5026     fflush (dump_file);
5027
5028   clear_aux_for_blocks ();
5029
5030   /* If we allocated new pseudos, we must resize the array for sched1.  */
5031   if (max_regno < max_reg_num ())
5032     max_regno = max_reg_num ();
5033
5034   /* Write the final stats.  */
5035   if (dump_file && num_possible_if_blocks > 0)
5036     {
5037       fprintf (dump_file,
5038                "\n%d possible IF blocks searched.\n",
5039                num_possible_if_blocks);
5040       fprintf (dump_file,
5041                "%d IF blocks converted.\n",
5042                num_updated_if_blocks);
5043       fprintf (dump_file,
5044                "%d true changes made.\n\n\n",
5045                num_true_changes);
5046     }
5047
5048   if (optimize == 1)
5049     df_remove_problem (df_live);
5050
5051 #ifdef ENABLE_CHECKING
5052   verify_flow_info ();
5053 #endif
5054 }
5055 \f
5056 /* If-conversion and CFG cleanup.  */
5057 static unsigned int
5058 rest_of_handle_if_conversion (void)
5059 {
5060   if (flag_if_conversion)
5061     {
5062       if (dump_file)
5063         {
5064           dump_reg_info (dump_file);
5065           dump_flow_info (dump_file, dump_flags);
5066         }
5067       cleanup_cfg (CLEANUP_EXPENSIVE);
5068       if_convert (false);
5069     }
5070
5071   cleanup_cfg (0);
5072   return 0;
5073 }
5074
5075 namespace {
5076
5077 const pass_data pass_data_rtl_ifcvt =
5078 {
5079   RTL_PASS, /* type */
5080   "ce1", /* name */
5081   OPTGROUP_NONE, /* optinfo_flags */
5082   TV_IFCVT, /* tv_id */
5083   0, /* properties_required */
5084   0, /* properties_provided */
5085   0, /* properties_destroyed */
5086   0, /* todo_flags_start */
5087   TODO_df_finish, /* todo_flags_finish */
5088 };
5089
5090 class pass_rtl_ifcvt : public rtl_opt_pass
5091 {
5092 public:
5093   pass_rtl_ifcvt (gcc::context *ctxt)
5094     : rtl_opt_pass (pass_data_rtl_ifcvt, ctxt)
5095   {}
5096
5097   /* opt_pass methods: */
5098   virtual bool gate (function *)
5099     {
5100       return (optimize > 0) && dbg_cnt (if_conversion);
5101     }
5102
5103   virtual unsigned int execute (function *)
5104     {
5105       return rest_of_handle_if_conversion ();
5106     }
5107
5108 }; // class pass_rtl_ifcvt
5109
5110 } // anon namespace
5111
5112 rtl_opt_pass *
5113 make_pass_rtl_ifcvt (gcc::context *ctxt)
5114 {
5115   return new pass_rtl_ifcvt (ctxt);
5116 }
5117
5118
5119 /* Rerun if-conversion, as combine may have simplified things enough
5120    to now meet sequence length restrictions.  */
5121
5122 namespace {
5123
5124 const pass_data pass_data_if_after_combine =
5125 {
5126   RTL_PASS, /* type */
5127   "ce2", /* name */
5128   OPTGROUP_NONE, /* optinfo_flags */
5129   TV_IFCVT, /* tv_id */
5130   0, /* properties_required */
5131   0, /* properties_provided */
5132   0, /* properties_destroyed */
5133   0, /* todo_flags_start */
5134   TODO_df_finish, /* todo_flags_finish */
5135 };
5136
5137 class pass_if_after_combine : public rtl_opt_pass
5138 {
5139 public:
5140   pass_if_after_combine (gcc::context *ctxt)
5141     : rtl_opt_pass (pass_data_if_after_combine, ctxt)
5142   {}
5143
5144   /* opt_pass methods: */
5145   virtual bool gate (function *)
5146     {
5147       return optimize > 0 && flag_if_conversion
5148         && dbg_cnt (if_after_combine);
5149     }
5150
5151   virtual unsigned int execute (function *)
5152     {
5153       if_convert (true);
5154       return 0;
5155     }
5156
5157 }; // class pass_if_after_combine
5158
5159 } // anon namespace
5160
5161 rtl_opt_pass *
5162 make_pass_if_after_combine (gcc::context *ctxt)
5163 {
5164   return new pass_if_after_combine (ctxt);
5165 }
5166
5167
5168 namespace {
5169
5170 const pass_data pass_data_if_after_reload =
5171 {
5172   RTL_PASS, /* type */
5173   "ce3", /* name */
5174   OPTGROUP_NONE, /* optinfo_flags */
5175   TV_IFCVT2, /* tv_id */
5176   0, /* properties_required */
5177   0, /* properties_provided */
5178   0, /* properties_destroyed */
5179   0, /* todo_flags_start */
5180   TODO_df_finish, /* todo_flags_finish */
5181 };
5182
5183 class pass_if_after_reload : public rtl_opt_pass
5184 {
5185 public:
5186   pass_if_after_reload (gcc::context *ctxt)
5187     : rtl_opt_pass (pass_data_if_after_reload, ctxt)
5188   {}
5189
5190   /* opt_pass methods: */
5191   virtual bool gate (function *)
5192     {
5193       return optimize > 0 && flag_if_conversion2
5194         && dbg_cnt (if_after_reload);
5195     }
5196
5197   virtual unsigned int execute (function *)
5198     {
5199       if_convert (true);
5200       return 0;
5201     }
5202
5203 }; // class pass_if_after_reload
5204
5205 } // anon namespace
5206
5207 rtl_opt_pass *
5208 make_pass_if_after_reload (gcc::context *ctxt)
5209 {
5210   return new pass_if_after_reload (ctxt);
5211 }