OSDN Git Service

2012-10-08 Tobias Burnus <burnus@net-b.de>
[pf3gnuchains/gcc-fork.git] / gcc / cprop.c
1 /* Global constant/copy propagation for RTL.
2    Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
3    2006, 2007, 2008, 2009, 2010, 2011 Free Software Foundation, Inc.
4
5 This file is part of GCC.
6
7 GCC is free software; you can redistribute it and/or modify it under
8 the terms of the GNU General Public License as published by the Free
9 Software Foundation; either version 3, or (at your option) any later
10 version.
11
12 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
15 for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with GCC; see the file COPYING3.  If not see
19 <http://www.gnu.org/licenses/>.  */
20
21 #include "config.h"
22 #include "system.h"
23 #include "coretypes.h"
24 #include "tm.h"
25 #include "diagnostic-core.h"
26 #include "toplev.h"
27
28 #include "rtl.h"
29 #include "tree.h"
30 #include "tm_p.h"
31 #include "regs.h"
32 #include "hard-reg-set.h"
33 #include "flags.h"
34 #include "insn-config.h"
35 #include "recog.h"
36 #include "basic-block.h"
37 #include "function.h"
38 #include "expr.h"
39 #include "except.h"
40 #include "params.h"
41 #include "cselib.h"
42 #include "intl.h"
43 #include "obstack.h"
44 #include "tree-pass.h"
45 #include "hashtab.h"
46 #include "df.h"
47 #include "dbgcnt.h"
48 #include "target.h"
49 #include "cfgloop.h"
50
51 \f
52 /* An obstack for our working variables.  */
53 static struct obstack cprop_obstack;
54
55 /* Occurrence of an expression.
56    There is one per basic block.  If a pattern appears more than once the
57    last appearance is used.  */
58
59 struct occr
60 {
61   /* Next occurrence of this expression.  */
62   struct occr *next;
63   /* The insn that computes the expression.  */
64   rtx insn;
65 };
66
67 typedef struct occr *occr_t;
68 DEF_VEC_P (occr_t);
69 DEF_VEC_ALLOC_P (occr_t, heap);
70
71 /* Hash table entry for assignment expressions.  */
72
73 struct expr
74 {
75   /* The expression (DEST := SRC).  */
76   rtx dest;
77   rtx src;
78
79   /* Index in the available expression bitmaps.  */
80   int bitmap_index;
81   /* Next entry with the same hash.  */
82   struct expr *next_same_hash;
83   /* List of available occurrence in basic blocks in the function.
84      An "available occurrence" is one that is the last occurrence in the
85      basic block and whose operands are not modified by following statements
86      in the basic block [including this insn].  */
87   struct occr *avail_occr;
88 };
89
90 /* Hash table for copy propagation expressions.
91    Each hash table is an array of buckets.
92    ??? It is known that if it were an array of entries, structure elements
93    `next_same_hash' and `bitmap_index' wouldn't be necessary.  However, it is
94    not clear whether in the final analysis a sufficient amount of memory would
95    be saved as the size of the available expression bitmaps would be larger
96    [one could build a mapping table without holes afterwards though].
97    Someday I'll perform the computation and figure it out.  */
98
99 struct hash_table_d
100 {
101   /* The table itself.
102      This is an array of `set_hash_table_size' elements.  */
103   struct expr **table;
104
105   /* Size of the hash table, in elements.  */
106   unsigned int size;
107
108   /* Number of hash table elements.  */
109   unsigned int n_elems;
110 };
111
112 /* Copy propagation hash table.  */
113 static struct hash_table_d set_hash_table;
114
115 /* Array of implicit set patterns indexed by basic block index.  */
116 static rtx *implicit_sets;
117
118 /* Array of indexes of expressions for implicit set patterns indexed by basic
119    block index.  In other words, implicit_set_indexes[i] is the bitmap_index
120    of the expression whose RTX is implicit_sets[i].  */
121 static int *implicit_set_indexes;
122
123 /* Bitmap containing one bit for each register in the program.
124    Used when performing GCSE to track which registers have been set since
125    the start or end of the basic block while traversing that block.  */
126 static regset reg_set_bitmap;
127
128 /* Various variables for statistics gathering.  */
129
130 /* Memory used in a pass.
131    This isn't intended to be absolutely precise.  Its intent is only
132    to keep an eye on memory usage.  */
133 static int bytes_used;
134
135 /* Number of local constants propagated.  */
136 static int local_const_prop_count;
137 /* Number of local copies propagated.  */
138 static int local_copy_prop_count;
139 /* Number of global constants propagated.  */
140 static int global_const_prop_count;
141 /* Number of global copies propagated.  */
142 static int global_copy_prop_count;
143
144 #define GOBNEW(T)               ((T *) cprop_alloc (sizeof (T)))
145 #define GOBNEWVAR(T, S)         ((T *) cprop_alloc ((S)))
146
147 /* Cover function to obstack_alloc.  */
148
149 static void *
150 cprop_alloc (unsigned long size)
151 {
152   bytes_used += size;
153   return obstack_alloc (&cprop_obstack, size);
154 }
155 \f
156 /* Return nonzero if register X is unchanged from INSN to the end
157    of INSN's basic block.  */
158
159 static int
160 reg_available_p (const_rtx x, const_rtx insn ATTRIBUTE_UNUSED)
161 {
162   return ! REGNO_REG_SET_P (reg_set_bitmap, REGNO (x));
163 }
164
165 /* Hash a set of register REGNO.
166
167    Sets are hashed on the register that is set.  This simplifies the PRE copy
168    propagation code.
169
170    ??? May need to make things more elaborate.  Later, as necessary.  */
171
172 static unsigned int
173 hash_set (int regno, int hash_table_size)
174 {
175   unsigned int hash;
176
177   hash = regno;
178   return hash % hash_table_size;
179 }
180
181 /* Insert assignment DEST:=SET from INSN in the hash table.
182    DEST is a register and SET is a register or a suitable constant.
183    If the assignment is already present in the table, record it as
184    the last occurrence in INSN's basic block.
185    IMPLICIT is true if it's an implicit set, false otherwise.  */
186
187 static void
188 insert_set_in_table (rtx dest, rtx src, rtx insn, struct hash_table_d *table,
189                      bool implicit)
190 {
191   bool found = false;
192   unsigned int hash;
193   struct expr *cur_expr, *last_expr = NULL;
194   struct occr *cur_occr;
195
196   hash = hash_set (REGNO (dest), table->size);
197
198   for (cur_expr = table->table[hash]; cur_expr;
199        cur_expr = cur_expr->next_same_hash)
200     {
201       if (dest == cur_expr->dest
202           && src == cur_expr->src)
203         {
204           found = true;
205           break;
206         }
207       last_expr = cur_expr;
208     }
209
210   if (! found)
211     {
212       cur_expr = GOBNEW (struct expr);
213       bytes_used += sizeof (struct expr);
214       if (table->table[hash] == NULL)
215         /* This is the first pattern that hashed to this index.  */
216         table->table[hash] = cur_expr;
217       else
218         /* Add EXPR to end of this hash chain.  */
219         last_expr->next_same_hash = cur_expr;
220
221       /* Set the fields of the expr element.
222          We must copy X because it can be modified when copy propagation is
223          performed on its operands.  */
224       cur_expr->dest = copy_rtx (dest);
225       cur_expr->src = copy_rtx (src);
226       cur_expr->bitmap_index = table->n_elems++;
227       cur_expr->next_same_hash = NULL;
228       cur_expr->avail_occr = NULL;
229     }
230
231   /* Now record the occurrence.  */
232   cur_occr = cur_expr->avail_occr;
233
234   if (cur_occr
235       && BLOCK_FOR_INSN (cur_occr->insn) == BLOCK_FOR_INSN (insn))
236     {
237       /* Found another instance of the expression in the same basic block.
238          Prefer this occurrence to the currently recorded one.  We want
239          the last one in the block and the block is scanned from start
240          to end.  */
241       cur_occr->insn = insn;
242     }
243   else
244     {
245       /* First occurrence of this expression in this basic block.  */
246       cur_occr = GOBNEW (struct occr);
247       bytes_used += sizeof (struct occr);
248       cur_occr->insn = insn;
249       cur_occr->next = cur_expr->avail_occr;
250       cur_expr->avail_occr = cur_occr;
251     }
252
253   /* Record bitmap_index of the implicit set in implicit_set_indexes.  */
254   if (implicit)
255     implicit_set_indexes[BLOCK_FOR_INSN(insn)->index] = cur_expr->bitmap_index;
256 }
257
258 /* Determine whether the rtx X should be treated as a constant for CPROP.
259    Since X might be inserted more than once we have to take care that it
260    is sharable.  */
261
262 static bool
263 cprop_constant_p (const_rtx x)
264 {
265   return CONSTANT_P (x) && (GET_CODE (x) != CONST || shared_const_p (x));
266 }
267
268 /* Scan SET present in INSN and add an entry to the hash TABLE.
269    IMPLICIT is true if it's an implicit set, false otherwise.  */
270
271 static void
272 hash_scan_set (rtx set, rtx insn, struct hash_table_d *table, bool implicit)
273 {
274   rtx src = SET_SRC (set);
275   rtx dest = SET_DEST (set);
276
277   if (REG_P (dest)
278       && ! HARD_REGISTER_P (dest)
279       && reg_available_p (dest, insn)
280       && can_copy_p (GET_MODE (dest)))
281     {
282       /* See if a REG_EQUAL note shows this equivalent to a simpler expression.
283
284          This allows us to do a single CPROP pass and still eliminate
285          redundant constants, addresses or other expressions that are
286          constructed with multiple instructions.
287
288          However, keep the original SRC if INSN is a simple reg-reg move.  In
289          In this case, there will almost always be a REG_EQUAL note on the
290          insn that sets SRC.  By recording the REG_EQUAL value here as SRC
291          for INSN, we miss copy propagation opportunities.
292
293          Note that this does not impede profitable constant propagations.  We
294          "look through" reg-reg sets in lookup_set.  */
295       rtx note = find_reg_equal_equiv_note (insn);
296       if (note != 0
297           && REG_NOTE_KIND (note) == REG_EQUAL
298           && !REG_P (src)
299           && cprop_constant_p (XEXP (note, 0)))
300         src = XEXP (note, 0), set = gen_rtx_SET (VOIDmode, dest, src);
301
302       /* Record sets for constant/copy propagation.  */
303       if ((REG_P (src)
304            && src != dest
305            && ! HARD_REGISTER_P (src)
306            && reg_available_p (src, insn))
307           || cprop_constant_p (src))
308         insert_set_in_table (dest, src, insn, table, implicit);
309     }
310 }
311
312 /* Process INSN and add hash table entries as appropriate.  */
313
314 static void
315 hash_scan_insn (rtx insn, struct hash_table_d *table)
316 {
317   rtx pat = PATTERN (insn);
318   int i;
319
320   /* Pick out the sets of INSN and for other forms of instructions record
321      what's been modified.  */
322
323   if (GET_CODE (pat) == SET)
324     hash_scan_set (pat, insn, table, false);
325   else if (GET_CODE (pat) == PARALLEL)
326     for (i = 0; i < XVECLEN (pat, 0); i++)
327       {
328         rtx x = XVECEXP (pat, 0, i);
329
330         if (GET_CODE (x) == SET)
331           hash_scan_set (x, insn, table, false);
332       }
333 }
334
335 /* Dump the hash table TABLE to file FILE under the name NAME.  */
336
337 static void
338 dump_hash_table (FILE *file, const char *name, struct hash_table_d *table)
339 {
340   int i;
341   /* Flattened out table, so it's printed in proper order.  */
342   struct expr **flat_table;
343   unsigned int *hash_val;
344   struct expr *expr;
345
346   flat_table = XCNEWVEC (struct expr *, table->n_elems);
347   hash_val = XNEWVEC (unsigned int, table->n_elems);
348
349   for (i = 0; i < (int) table->size; i++)
350     for (expr = table->table[i]; expr != NULL; expr = expr->next_same_hash)
351       {
352         flat_table[expr->bitmap_index] = expr;
353         hash_val[expr->bitmap_index] = i;
354       }
355
356   fprintf (file, "%s hash table (%d buckets, %d entries)\n",
357            name, table->size, table->n_elems);
358
359   for (i = 0; i < (int) table->n_elems; i++)
360     if (flat_table[i] != 0)
361       {
362         expr = flat_table[i];
363         fprintf (file, "Index %d (hash value %d)\n  ",
364                  expr->bitmap_index, hash_val[i]);
365         print_rtl (file, expr->dest);
366         fprintf (file, " := ");
367         print_rtl (file, expr->src);
368         fprintf (file, "\n");
369       }
370
371   fprintf (file, "\n");
372
373   free (flat_table);
374   free (hash_val);
375 }
376
377 /* Record as unavailable all registers that are DEF operands of INSN.  */
378
379 static void
380 make_set_regs_unavailable (rtx insn)
381 {
382   struct df_insn_info *insn_info = DF_INSN_INFO_GET (insn);
383   df_ref *def_rec;
384
385   for (def_rec = DF_INSN_INFO_DEFS (insn_info); *def_rec; def_rec++)
386     SET_REGNO_REG_SET (reg_set_bitmap, DF_REF_REGNO (*def_rec));
387 }
388
389 /* Top level function to create an assignment hash table.
390
391    Assignment entries are placed in the hash table if
392    - they are of the form (set (pseudo-reg) src),
393    - src is something we want to perform const/copy propagation on,
394    - none of the operands or target are subsequently modified in the block
395
396    Currently src must be a pseudo-reg or a const_int.
397
398    TABLE is the table computed.  */
399
400 static void
401 compute_hash_table_work (struct hash_table_d *table)
402 {
403   basic_block bb;
404
405   /* Allocate vars to track sets of regs.  */
406   reg_set_bitmap = ALLOC_REG_SET (NULL);
407
408   FOR_EACH_BB (bb)
409     {
410       rtx insn;
411
412       /* Reset tables used to keep track of what's not yet invalid [since
413          the end of the block].  */
414       CLEAR_REG_SET (reg_set_bitmap);
415
416       /* Go over all insns from the last to the first.  This is convenient
417          for tracking available registers, i.e. not set between INSN and
418          the end of the basic block BB.  */
419       FOR_BB_INSNS_REVERSE (bb, insn)
420         {
421           /* Only real insns are interesting.  */
422           if (!NONDEBUG_INSN_P (insn))
423             continue;
424
425           /* Record interesting sets from INSN in the hash table.  */
426           hash_scan_insn (insn, table);
427
428           /* Any registers set in INSN will make SETs above it not AVAIL.  */
429           make_set_regs_unavailable (insn);
430         }
431
432       /* Insert implicit sets in the hash table, pretending they appear as
433          insns at the head of the basic block.  */
434       if (implicit_sets[bb->index] != NULL_RTX)
435         hash_scan_set (implicit_sets[bb->index], BB_HEAD (bb), table, true);
436     }
437
438   FREE_REG_SET (reg_set_bitmap);
439 }
440
441 /* Allocate space for the set/expr hash TABLE.
442    It is used to determine the number of buckets to use.  */
443
444 static void
445 alloc_hash_table (struct hash_table_d *table)
446 {
447   int n;
448
449   n = get_max_insn_count ();
450
451   table->size = n / 4;
452   if (table->size < 11)
453     table->size = 11;
454
455   /* Attempt to maintain efficient use of hash table.
456      Making it an odd number is simplest for now.
457      ??? Later take some measurements.  */
458   table->size |= 1;
459   n = table->size * sizeof (struct expr *);
460   table->table = XNEWVAR (struct expr *, n);
461 }
462
463 /* Free things allocated by alloc_hash_table.  */
464
465 static void
466 free_hash_table (struct hash_table_d *table)
467 {
468   free (table->table);
469 }
470
471 /* Compute the hash TABLE for doing copy/const propagation or
472    expression hash table.  */
473
474 static void
475 compute_hash_table (struct hash_table_d *table)
476 {
477   /* Initialize count of number of entries in hash table.  */
478   table->n_elems = 0;
479   memset (table->table, 0, table->size * sizeof (struct expr *));
480
481   compute_hash_table_work (table);
482 }
483 \f
484 /* Expression tracking support.  */
485
486 /* Lookup REGNO in the set TABLE.  The result is a pointer to the
487    table entry, or NULL if not found.  */
488
489 static struct expr *
490 lookup_set (unsigned int regno, struct hash_table_d *table)
491 {
492   unsigned int hash = hash_set (regno, table->size);
493   struct expr *expr;
494
495   expr = table->table[hash];
496
497   while (expr && REGNO (expr->dest) != regno)
498     expr = expr->next_same_hash;
499
500   return expr;
501 }
502
503 /* Return the next entry for REGNO in list EXPR.  */
504
505 static struct expr *
506 next_set (unsigned int regno, struct expr *expr)
507 {
508   do
509     expr = expr->next_same_hash;
510   while (expr && REGNO (expr->dest) != regno);
511
512   return expr;
513 }
514
515 /* Reset tables used to keep track of what's still available [since the
516    start of the block].  */
517
518 static void
519 reset_opr_set_tables (void)
520 {
521   /* Maintain a bitmap of which regs have been set since beginning of
522      the block.  */
523   CLEAR_REG_SET (reg_set_bitmap);
524 }
525
526 /* Return nonzero if the register X has not been set yet [since the
527    start of the basic block containing INSN].  */
528
529 static int
530 reg_not_set_p (const_rtx x, const_rtx insn ATTRIBUTE_UNUSED)
531 {
532   return ! REGNO_REG_SET_P (reg_set_bitmap, REGNO (x));
533 }
534
535 /* Record things set by INSN.
536    This data is used by reg_not_set_p.  */
537
538 static void
539 mark_oprs_set (rtx insn)
540 {
541   struct df_insn_info *insn_info = DF_INSN_INFO_GET (insn);
542   df_ref *def_rec;
543
544   for (def_rec = DF_INSN_INFO_DEFS (insn_info); *def_rec; def_rec++)
545     SET_REGNO_REG_SET (reg_set_bitmap, DF_REF_REGNO (*def_rec));
546 }
547 \f
548 /* Compute copy/constant propagation working variables.  */
549
550 /* Local properties of assignments.  */
551 static sbitmap *cprop_avloc;
552 static sbitmap *cprop_kill;
553
554 /* Global properties of assignments (computed from the local properties).  */
555 static sbitmap *cprop_avin;
556 static sbitmap *cprop_avout;
557
558 /* Allocate vars used for copy/const propagation.  N_BLOCKS is the number of
559    basic blocks.  N_SETS is the number of sets.  */
560
561 static void
562 alloc_cprop_mem (int n_blocks, int n_sets)
563 {
564   cprop_avloc = sbitmap_vector_alloc (n_blocks, n_sets);
565   cprop_kill = sbitmap_vector_alloc (n_blocks, n_sets);
566
567   cprop_avin = sbitmap_vector_alloc (n_blocks, n_sets);
568   cprop_avout = sbitmap_vector_alloc (n_blocks, n_sets);
569 }
570
571 /* Free vars used by copy/const propagation.  */
572
573 static void
574 free_cprop_mem (void)
575 {
576   sbitmap_vector_free (cprop_avloc);
577   sbitmap_vector_free (cprop_kill);
578   sbitmap_vector_free (cprop_avin);
579   sbitmap_vector_free (cprop_avout);
580 }
581
582 /* Compute the local properties of each recorded expression.
583
584    Local properties are those that are defined by the block, irrespective of
585    other blocks.
586
587    An expression is killed in a block if its operands, either DEST or SRC, are
588    modified in the block.
589
590    An expression is computed (locally available) in a block if it is computed
591    at least once and expression would contain the same value if the
592    computation was moved to the end of the block.
593
594    KILL and COMP are destination sbitmaps for recording local properties.  */
595
596 static void
597 compute_local_properties (sbitmap *kill, sbitmap *comp,
598                           struct hash_table_d *table)
599 {
600   unsigned int i;
601
602   /* Initialize the bitmaps that were passed in.  */
603   sbitmap_vector_zero (kill, last_basic_block);
604   sbitmap_vector_zero (comp, last_basic_block);
605
606   for (i = 0; i < table->size; i++)
607     {
608       struct expr *expr;
609
610       for (expr = table->table[i]; expr != NULL; expr = expr->next_same_hash)
611         {
612           int indx = expr->bitmap_index;
613           df_ref def;
614           struct occr *occr;
615
616           /* For each definition of the destination pseudo-reg, the expression
617              is killed in the block where the definition is.  */
618           for (def = DF_REG_DEF_CHAIN (REGNO (expr->dest));
619                def; def = DF_REF_NEXT_REG (def))
620             SET_BIT (kill[DF_REF_BB (def)->index], indx);
621
622           /* If the source is a pseudo-reg, for each definition of the source,
623              the expression is killed in the block where the definition is.  */
624           if (REG_P (expr->src))
625             for (def = DF_REG_DEF_CHAIN (REGNO (expr->src));
626                  def; def = DF_REF_NEXT_REG (def))
627               SET_BIT (kill[DF_REF_BB (def)->index], indx);
628
629           /* The occurrences recorded in avail_occr are exactly those that
630              are locally available in the block where they are.  */
631           for (occr = expr->avail_occr; occr != NULL; occr = occr->next)
632             {
633               SET_BIT (comp[BLOCK_FOR_INSN (occr->insn)->index], indx);
634             }
635         }
636     }
637 }
638 \f
639 /* Hash table support.  */
640
641 /* Top level routine to do the dataflow analysis needed by copy/const
642    propagation.  */
643
644 static void
645 compute_cprop_data (void)
646 {
647   basic_block bb;
648
649   compute_local_properties (cprop_kill, cprop_avloc, &set_hash_table);
650   compute_available (cprop_avloc, cprop_kill, cprop_avout, cprop_avin);
651
652   /* Merge implicit sets into CPROP_AVIN.  They are always available at the
653      entry of their basic block.  We need to do this because 1) implicit sets
654      aren't recorded for the local pass so they cannot be propagated within
655      their basic block by this pass and 2) the global pass would otherwise
656      propagate them only in the successors of their basic block.  */
657   FOR_EACH_BB (bb)
658     {
659       int index = implicit_set_indexes[bb->index];
660       if (index != -1)
661         SET_BIT (cprop_avin[bb->index], index);
662     }
663 }
664 \f
665 /* Copy/constant propagation.  */
666
667 /* Maximum number of register uses in an insn that we handle.  */
668 #define MAX_USES 8
669
670 /* Table of uses (registers, both hard and pseudo) found in an insn.
671    Allocated statically to avoid alloc/free complexity and overhead.  */
672 static rtx reg_use_table[MAX_USES];
673
674 /* Index into `reg_use_table' while building it.  */
675 static unsigned reg_use_count;
676
677 /* Set up a list of register numbers used in INSN.  The found uses are stored
678    in `reg_use_table'.  `reg_use_count' is initialized to zero before entry,
679    and contains the number of uses in the table upon exit.
680
681    ??? If a register appears multiple times we will record it multiple times.
682    This doesn't hurt anything but it will slow things down.  */
683
684 static void
685 find_used_regs (rtx *xptr, void *data ATTRIBUTE_UNUSED)
686 {
687   int i, j;
688   enum rtx_code code;
689   const char *fmt;
690   rtx x = *xptr;
691
692   /* repeat is used to turn tail-recursion into iteration since GCC
693      can't do it when there's no return value.  */
694  repeat:
695   if (x == 0)
696     return;
697
698   code = GET_CODE (x);
699   if (REG_P (x))
700     {
701       if (reg_use_count == MAX_USES)
702         return;
703
704       reg_use_table[reg_use_count] = x;
705       reg_use_count++;
706     }
707
708   /* Recursively scan the operands of this expression.  */
709
710   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
711     {
712       if (fmt[i] == 'e')
713         {
714           /* If we are about to do the last recursive call
715              needed at this level, change it into iteration.
716              This function is called enough to be worth it.  */
717           if (i == 0)
718             {
719               x = XEXP (x, 0);
720               goto repeat;
721             }
722
723           find_used_regs (&XEXP (x, i), data);
724         }
725       else if (fmt[i] == 'E')
726         for (j = 0; j < XVECLEN (x, i); j++)
727           find_used_regs (&XVECEXP (x, i, j), data);
728     }
729 }
730
731 /* Try to replace all uses of FROM in INSN with TO.
732    Return nonzero if successful.  */
733
734 static int
735 try_replace_reg (rtx from, rtx to, rtx insn)
736 {
737   rtx note = find_reg_equal_equiv_note (insn);
738   rtx src = 0;
739   int success = 0;
740   rtx set = single_set (insn);
741
742   /* Usually we substitute easy stuff, so we won't copy everything.
743      We however need to take care to not duplicate non-trivial CONST
744      expressions.  */
745   to = copy_rtx (to);
746
747   validate_replace_src_group (from, to, insn);
748   if (num_changes_pending () && apply_change_group ())
749     success = 1;
750
751   /* Try to simplify SET_SRC if we have substituted a constant.  */
752   if (success && set && CONSTANT_P (to))
753     {
754       src = simplify_rtx (SET_SRC (set));
755
756       if (src)
757         validate_change (insn, &SET_SRC (set), src, 0);
758     }
759
760   /* If there is already a REG_EQUAL note, update the expression in it
761      with our replacement.  */
762   if (note != 0 && REG_NOTE_KIND (note) == REG_EQUAL)
763     set_unique_reg_note (insn, REG_EQUAL,
764                          simplify_replace_rtx (XEXP (note, 0), from, to));
765   if (!success && set && reg_mentioned_p (from, SET_SRC (set)))
766     {
767       /* If above failed and this is a single set, try to simplify the source
768          of the set given our substitution.  We could perhaps try this for
769          multiple SETs, but it probably won't buy us anything.  */
770       src = simplify_replace_rtx (SET_SRC (set), from, to);
771
772       if (!rtx_equal_p (src, SET_SRC (set))
773           && validate_change (insn, &SET_SRC (set), src, 0))
774         success = 1;
775
776       /* If we've failed perform the replacement, have a single SET to
777          a REG destination and don't yet have a note, add a REG_EQUAL note
778          to not lose information.  */
779       if (!success && note == 0 && set != 0 && REG_P (SET_DEST (set)))
780         note = set_unique_reg_note (insn, REG_EQUAL, copy_rtx (src));
781     }
782
783   if (set && MEM_P (SET_DEST (set)) && reg_mentioned_p (from, SET_DEST (set)))
784     {
785       /* Registers can also appear as uses in SET_DEST if it is a MEM.
786          We could perhaps try this for multiple SETs, but it probably
787          won't buy us anything.  */
788       rtx dest = simplify_replace_rtx (SET_DEST (set), from, to);
789
790       if (!rtx_equal_p (dest, SET_DEST (set))
791           && validate_change (insn, &SET_DEST (set), dest, 0))
792         success = 1;
793     }
794
795   /* REG_EQUAL may get simplified into register.
796      We don't allow that. Remove that note. This code ought
797      not to happen, because previous code ought to synthesize
798      reg-reg move, but be on the safe side.  */
799   if (note && REG_NOTE_KIND (note) == REG_EQUAL && REG_P (XEXP (note, 0)))
800     remove_note (insn, note);
801
802   return success;
803 }
804
805 /* Find a set of REGNOs that are available on entry to INSN's block.  Return
806    NULL no such set is found.  */
807
808 static struct expr *
809 find_avail_set (int regno, rtx insn)
810 {
811   /* SET1 contains the last set found that can be returned to the caller for
812      use in a substitution.  */
813   struct expr *set1 = 0;
814
815   /* Loops are not possible here.  To get a loop we would need two sets
816      available at the start of the block containing INSN.  i.e. we would
817      need two sets like this available at the start of the block:
818
819        (set (reg X) (reg Y))
820        (set (reg Y) (reg X))
821
822      This can not happen since the set of (reg Y) would have killed the
823      set of (reg X) making it unavailable at the start of this block.  */
824   while (1)
825     {
826       rtx src;
827       struct expr *set = lookup_set (regno, &set_hash_table);
828
829       /* Find a set that is available at the start of the block
830          which contains INSN.  */
831       while (set)
832         {
833           if (TEST_BIT (cprop_avin[BLOCK_FOR_INSN (insn)->index],
834                         set->bitmap_index))
835             break;
836           set = next_set (regno, set);
837         }
838
839       /* If no available set was found we've reached the end of the
840          (possibly empty) copy chain.  */
841       if (set == 0)
842         break;
843
844       src = set->src;
845
846       /* We know the set is available.
847          Now check that SRC is locally anticipatable (i.e. none of the
848          source operands have changed since the start of the block).
849
850          If the source operand changed, we may still use it for the next
851          iteration of this loop, but we may not use it for substitutions.  */
852
853       if (cprop_constant_p (src) || reg_not_set_p (src, insn))
854         set1 = set;
855
856       /* If the source of the set is anything except a register, then
857          we have reached the end of the copy chain.  */
858       if (! REG_P (src))
859         break;
860
861       /* Follow the copy chain, i.e. start another iteration of the loop
862          and see if we have an available copy into SRC.  */
863       regno = REGNO (src);
864     }
865
866   /* SET1 holds the last set that was available and anticipatable at
867      INSN.  */
868   return set1;
869 }
870
871 /* Subroutine of cprop_insn that tries to propagate constants into
872    JUMP_INSNS.  JUMP must be a conditional jump.  If SETCC is non-NULL
873    it is the instruction that immediately precedes JUMP, and must be a
874    single SET of a register.  FROM is what we will try to replace,
875    SRC is the constant we will try to substitute for it.  Return nonzero
876    if a change was made.  */
877
878 static int
879 cprop_jump (basic_block bb, rtx setcc, rtx jump, rtx from, rtx src)
880 {
881   rtx new_rtx, set_src, note_src;
882   rtx set = pc_set (jump);
883   rtx note = find_reg_equal_equiv_note (jump);
884
885   if (note)
886     {
887       note_src = XEXP (note, 0);
888       if (GET_CODE (note_src) == EXPR_LIST)
889         note_src = NULL_RTX;
890     }
891   else note_src = NULL_RTX;
892
893   /* Prefer REG_EQUAL notes except those containing EXPR_LISTs.  */
894   set_src = note_src ? note_src : SET_SRC (set);
895
896   /* First substitute the SETCC condition into the JUMP instruction,
897      then substitute that given values into this expanded JUMP.  */
898   if (setcc != NULL_RTX
899       && !modified_between_p (from, setcc, jump)
900       && !modified_between_p (src, setcc, jump))
901     {
902       rtx setcc_src;
903       rtx setcc_set = single_set (setcc);
904       rtx setcc_note = find_reg_equal_equiv_note (setcc);
905       setcc_src = (setcc_note && GET_CODE (XEXP (setcc_note, 0)) != EXPR_LIST)
906                 ? XEXP (setcc_note, 0) : SET_SRC (setcc_set);
907       set_src = simplify_replace_rtx (set_src, SET_DEST (setcc_set),
908                                       setcc_src);
909     }
910   else
911     setcc = NULL_RTX;
912
913   new_rtx = simplify_replace_rtx (set_src, from, src);
914
915   /* If no simplification can be made, then try the next register.  */
916   if (rtx_equal_p (new_rtx, SET_SRC (set)))
917     return 0;
918
919   /* If this is now a no-op delete it, otherwise this must be a valid insn.  */
920   if (new_rtx == pc_rtx)
921     delete_insn (jump);
922   else
923     {
924       /* Ensure the value computed inside the jump insn to be equivalent
925          to one computed by setcc.  */
926       if (setcc && modified_in_p (new_rtx, setcc))
927         return 0;
928       if (! validate_unshare_change (jump, &SET_SRC (set), new_rtx, 0))
929         {
930           /* When (some) constants are not valid in a comparison, and there
931              are two registers to be replaced by constants before the entire
932              comparison can be folded into a constant, we need to keep
933              intermediate information in REG_EQUAL notes.  For targets with
934              separate compare insns, such notes are added by try_replace_reg.
935              When we have a combined compare-and-branch instruction, however,
936              we need to attach a note to the branch itself to make this
937              optimization work.  */
938
939           if (!rtx_equal_p (new_rtx, note_src))
940             set_unique_reg_note (jump, REG_EQUAL, copy_rtx (new_rtx));
941           return 0;
942         }
943
944       /* Remove REG_EQUAL note after simplification.  */
945       if (note_src)
946         remove_note (jump, note);
947      }
948
949 #ifdef HAVE_cc0
950   /* Delete the cc0 setter.  */
951   if (setcc != NULL && CC0_P (SET_DEST (single_set (setcc))))
952     delete_insn (setcc);
953 #endif
954
955   global_const_prop_count++;
956   if (dump_file != NULL)
957     {
958       fprintf (dump_file,
959                "GLOBAL CONST-PROP: Replacing reg %d in jump_insn %d with"
960                "constant ", REGNO (from), INSN_UID (jump));
961       print_rtl (dump_file, src);
962       fprintf (dump_file, "\n");
963     }
964   purge_dead_edges (bb);
965
966   /* If a conditional jump has been changed into unconditional jump, remove
967      the jump and make the edge fallthru - this is always called in
968      cfglayout mode.  */
969   if (new_rtx != pc_rtx && simplejump_p (jump))
970     {
971       edge e;
972       edge_iterator ei;
973
974       FOR_EACH_EDGE (e, ei, bb->succs)
975         if (e->dest != EXIT_BLOCK_PTR
976             && BB_HEAD (e->dest) == JUMP_LABEL (jump))
977           {
978             e->flags |= EDGE_FALLTHRU;
979             break;
980           }
981       delete_insn (jump);
982     }
983
984   return 1;
985 }
986
987 /* Subroutine of cprop_insn that tries to propagate constants.  FROM is what
988    we will try to replace, SRC is the constant we will try to substitute for
989    it and INSN is the instruction where this will be happening.  */
990
991 static int
992 constprop_register (rtx from, rtx src, rtx insn)
993 {
994   rtx sset;
995
996   /* Check for reg or cc0 setting instructions followed by
997      conditional branch instructions first.  */
998   if ((sset = single_set (insn)) != NULL
999       && NEXT_INSN (insn)
1000       && any_condjump_p (NEXT_INSN (insn)) && onlyjump_p (NEXT_INSN (insn)))
1001     {
1002       rtx dest = SET_DEST (sset);
1003       if ((REG_P (dest) || CC0_P (dest))
1004           && cprop_jump (BLOCK_FOR_INSN (insn), insn, NEXT_INSN (insn),
1005                          from, src))
1006         return 1;
1007     }
1008
1009   /* Handle normal insns next.  */
1010   if (NONJUMP_INSN_P (insn) && try_replace_reg (from, src, insn))
1011     return 1;
1012
1013   /* Try to propagate a CONST_INT into a conditional jump.
1014      We're pretty specific about what we will handle in this
1015      code, we can extend this as necessary over time.
1016
1017      Right now the insn in question must look like
1018      (set (pc) (if_then_else ...))  */
1019   else if (any_condjump_p (insn) && onlyjump_p (insn))
1020     return cprop_jump (BLOCK_FOR_INSN (insn), NULL, insn, from, src);
1021   return 0;
1022 }
1023
1024 /* Perform constant and copy propagation on INSN.
1025    Return nonzero if a change was made.  */
1026
1027 static int
1028 cprop_insn (rtx insn)
1029 {
1030   unsigned i;
1031   int changed = 0, changed_this_round;
1032   rtx note;
1033
1034 retry:
1035   changed_this_round = 0;
1036   reg_use_count = 0;
1037   note_uses (&PATTERN (insn), find_used_regs, NULL);
1038
1039   /* We may win even when propagating constants into notes.  */
1040   note = find_reg_equal_equiv_note (insn);
1041   if (note)
1042     find_used_regs (&XEXP (note, 0), NULL);
1043
1044   for (i = 0; i < reg_use_count; i++)
1045     {
1046       rtx reg_used = reg_use_table[i];
1047       unsigned int regno = REGNO (reg_used);
1048       rtx src;
1049       struct expr *set;
1050
1051       /* If the register has already been set in this block, there's
1052          nothing we can do.  */
1053       if (! reg_not_set_p (reg_used, insn))
1054         continue;
1055
1056       /* Find an assignment that sets reg_used and is available
1057          at the start of the block.  */
1058       set = find_avail_set (regno, insn);
1059       if (! set)
1060         continue;
1061
1062       src = set->src;
1063
1064       /* Constant propagation.  */
1065       if (cprop_constant_p (src))
1066         {
1067           if (constprop_register (reg_used, src, insn))
1068             {
1069               changed_this_round = changed = 1;
1070               global_const_prop_count++;
1071               if (dump_file != NULL)
1072                 {
1073                   fprintf (dump_file,
1074                            "GLOBAL CONST-PROP: Replacing reg %d in ", regno);
1075                   fprintf (dump_file, "insn %d with constant ",
1076                            INSN_UID (insn));
1077                   print_rtl (dump_file, src);
1078                   fprintf (dump_file, "\n");
1079                 }
1080               if (INSN_DELETED_P (insn))
1081                 return 1;
1082             }
1083         }
1084       else if (REG_P (src)
1085                && REGNO (src) >= FIRST_PSEUDO_REGISTER
1086                && REGNO (src) != regno)
1087         {
1088           if (try_replace_reg (reg_used, src, insn))
1089             {
1090               changed_this_round = changed = 1;
1091               global_copy_prop_count++;
1092               if (dump_file != NULL)
1093                 {
1094                   fprintf (dump_file,
1095                            "GLOBAL COPY-PROP: Replacing reg %d in insn %d",
1096                            regno, INSN_UID (insn));
1097                   fprintf (dump_file, " with reg %d\n", REGNO (src));
1098                 }
1099
1100               /* The original insn setting reg_used may or may not now be
1101                  deletable.  We leave the deletion to DCE.  */
1102               /* FIXME: If it turns out that the insn isn't deletable,
1103                  then we may have unnecessarily extended register lifetimes
1104                  and made things worse.  */
1105             }
1106         }
1107
1108       /* If try_replace_reg simplified the insn, the regs found
1109          by find_used_regs may not be valid anymore.  Start over.  */
1110       if (changed_this_round)
1111         goto retry;
1112     }
1113
1114   if (changed && DEBUG_INSN_P (insn))
1115     return 0;
1116
1117   return changed;
1118 }
1119
1120 /* Like find_used_regs, but avoid recording uses that appear in
1121    input-output contexts such as zero_extract or pre_dec.  This
1122    restricts the cases we consider to those for which local cprop
1123    can legitimately make replacements.  */
1124
1125 static void
1126 local_cprop_find_used_regs (rtx *xptr, void *data)
1127 {
1128   rtx x = *xptr;
1129
1130   if (x == 0)
1131     return;
1132
1133   switch (GET_CODE (x))
1134     {
1135     case ZERO_EXTRACT:
1136     case SIGN_EXTRACT:
1137     case STRICT_LOW_PART:
1138       return;
1139
1140     case PRE_DEC:
1141     case PRE_INC:
1142     case POST_DEC:
1143     case POST_INC:
1144     case PRE_MODIFY:
1145     case POST_MODIFY:
1146       /* Can only legitimately appear this early in the context of
1147          stack pushes for function arguments, but handle all of the
1148          codes nonetheless.  */
1149       return;
1150
1151     case SUBREG:
1152       /* Setting a subreg of a register larger than word_mode leaves
1153          the non-written words unchanged.  */
1154       if (GET_MODE_BITSIZE (GET_MODE (SUBREG_REG (x))) > BITS_PER_WORD)
1155         return;
1156       break;
1157
1158     default:
1159       break;
1160     }
1161
1162   find_used_regs (xptr, data);
1163 }
1164
1165 /* Try to perform local const/copy propagation on X in INSN.  */
1166
1167 static bool
1168 do_local_cprop (rtx x, rtx insn)
1169 {
1170   rtx newreg = NULL, newcnst = NULL;
1171
1172   /* Rule out USE instructions and ASM statements as we don't want to
1173      change the hard registers mentioned.  */
1174   if (REG_P (x)
1175       && (REGNO (x) >= FIRST_PSEUDO_REGISTER
1176           || (GET_CODE (PATTERN (insn)) != USE
1177               && asm_noperands (PATTERN (insn)) < 0)))
1178     {
1179       cselib_val *val = cselib_lookup (x, GET_MODE (x), 0, VOIDmode);
1180       struct elt_loc_list *l;
1181
1182       if (!val)
1183         return false;
1184       for (l = val->locs; l; l = l->next)
1185         {
1186           rtx this_rtx = l->loc;
1187           rtx note;
1188
1189           if (cprop_constant_p (this_rtx))
1190             newcnst = this_rtx;
1191           if (REG_P (this_rtx) && REGNO (this_rtx) >= FIRST_PSEUDO_REGISTER
1192               /* Don't copy propagate if it has attached REG_EQUIV note.
1193                  At this point this only function parameters should have
1194                  REG_EQUIV notes and if the argument slot is used somewhere
1195                  explicitly, it means address of parameter has been taken,
1196                  so we should not extend the lifetime of the pseudo.  */
1197               && (!(note = find_reg_note (l->setting_insn, REG_EQUIV, NULL_RTX))
1198                   || ! MEM_P (XEXP (note, 0))))
1199             newreg = this_rtx;
1200         }
1201       if (newcnst && constprop_register (x, newcnst, insn))
1202         {
1203           if (dump_file != NULL)
1204             {
1205               fprintf (dump_file, "LOCAL CONST-PROP: Replacing reg %d in ",
1206                        REGNO (x));
1207               fprintf (dump_file, "insn %d with constant ",
1208                        INSN_UID (insn));
1209               print_rtl (dump_file, newcnst);
1210               fprintf (dump_file, "\n");
1211             }
1212           local_const_prop_count++;
1213           return true;
1214         }
1215       else if (newreg && newreg != x && try_replace_reg (x, newreg, insn))
1216         {
1217           if (dump_file != NULL)
1218             {
1219               fprintf (dump_file,
1220                        "LOCAL COPY-PROP: Replacing reg %d in insn %d",
1221                        REGNO (x), INSN_UID (insn));
1222               fprintf (dump_file, " with reg %d\n", REGNO (newreg));
1223             }
1224           local_copy_prop_count++;
1225           return true;
1226         }
1227     }
1228   return false;
1229 }
1230
1231 /* Do local const/copy propagation (i.e. within each basic block).  */
1232
1233 static int
1234 local_cprop_pass (void)
1235 {
1236   basic_block bb;
1237   rtx insn;
1238   bool changed = false;
1239   unsigned i;
1240
1241   cselib_init (0);
1242   FOR_EACH_BB (bb)
1243     {
1244       FOR_BB_INSNS (bb, insn)
1245         {
1246           if (INSN_P (insn))
1247             {
1248               rtx note = find_reg_equal_equiv_note (insn);
1249               do
1250                 {
1251                   reg_use_count = 0;
1252                   note_uses (&PATTERN (insn), local_cprop_find_used_regs,
1253                              NULL);
1254                   if (note)
1255                     local_cprop_find_used_regs (&XEXP (note, 0), NULL);
1256
1257                   for (i = 0; i < reg_use_count; i++)
1258                     {
1259                       if (do_local_cprop (reg_use_table[i], insn))
1260                         {
1261                           if (!DEBUG_INSN_P (insn))
1262                             changed = true;
1263                           break;
1264                         }
1265                     }
1266                   if (INSN_DELETED_P (insn))
1267                     break;
1268                 }
1269               while (i < reg_use_count);
1270             }
1271           cselib_process_insn (insn);
1272         }
1273
1274       /* Forget everything at the end of a basic block.  */
1275       cselib_clear_table ();
1276     }
1277
1278   cselib_finish ();
1279
1280   return changed;
1281 }
1282
1283 /* Similar to get_condition, only the resulting condition must be
1284    valid at JUMP, instead of at EARLIEST.
1285
1286    This differs from noce_get_condition in ifcvt.c in that we prefer not to
1287    settle for the condition variable in the jump instruction being integral.
1288    We prefer to be able to record the value of a user variable, rather than
1289    the value of a temporary used in a condition.  This could be solved by
1290    recording the value of *every* register scanned by canonicalize_condition,
1291    but this would require some code reorganization.  */
1292
1293 rtx
1294 fis_get_condition (rtx jump)
1295 {
1296   return get_condition (jump, NULL, false, true);
1297 }
1298
1299 /* Check the comparison COND to see if we can safely form an implicit
1300    set from it.  */
1301
1302 static bool
1303 implicit_set_cond_p (const_rtx cond)
1304 {
1305   enum machine_mode mode;
1306   rtx cst;
1307
1308   /* COND must be either an EQ or NE comparison.  */
1309   if (GET_CODE (cond) != EQ && GET_CODE (cond) != NE)
1310     return false;
1311
1312   /* The first operand of COND must be a pseudo-reg.  */
1313   if (! REG_P (XEXP (cond, 0))
1314       || HARD_REGISTER_P (XEXP (cond, 0)))
1315     return false;
1316
1317   /* The second operand of COND must be a suitable constant.  */
1318   mode = GET_MODE (XEXP (cond, 0));
1319   cst = XEXP (cond, 1);
1320
1321   /* We can't perform this optimization if either operand might be or might
1322      contain a signed zero.  */
1323   if (HONOR_SIGNED_ZEROS (mode))
1324     {
1325       /* It is sufficient to check if CST is or contains a zero.  We must
1326          handle float, complex, and vector.  If any subpart is a zero, then
1327          the optimization can't be performed.  */
1328       /* ??? The complex and vector checks are not implemented yet.  We just
1329          always return zero for them.  */
1330       if (CONST_DOUBLE_AS_FLOAT_P (cst))
1331         {
1332           REAL_VALUE_TYPE d;
1333           REAL_VALUE_FROM_CONST_DOUBLE (d, cst);
1334           if (REAL_VALUES_EQUAL (d, dconst0))
1335             return 0;
1336         }
1337       else
1338         return 0;
1339     }
1340
1341   return cprop_constant_p (cst);
1342 }
1343
1344 /* Find the implicit sets of a function.  An "implicit set" is a constraint
1345    on the value of a variable, implied by a conditional jump.  For example,
1346    following "if (x == 2)", the then branch may be optimized as though the
1347    conditional performed an "explicit set", in this example, "x = 2".  This
1348    function records the set patterns that are implicit at the start of each
1349    basic block.
1350
1351    If an implicit set is found but the set is implicit on a critical edge,
1352    this critical edge is split.
1353
1354    Return true if the CFG was modified, false otherwise.  */
1355
1356 static bool
1357 find_implicit_sets (void)
1358 {
1359   basic_block bb, dest;
1360   rtx cond, new_rtx;
1361   unsigned int count = 0;
1362   bool edges_split = false;
1363   size_t implicit_sets_size = last_basic_block + 10;
1364
1365   implicit_sets = XCNEWVEC (rtx, implicit_sets_size);
1366
1367   FOR_EACH_BB (bb)
1368     {
1369       /* Check for more than one successor.  */
1370       if (EDGE_COUNT (bb->succs) <= 1)
1371         continue;
1372
1373       cond = fis_get_condition (BB_END (bb));
1374
1375       /* If no condition is found or if it isn't of a suitable form,
1376          ignore it.  */
1377       if (! cond || ! implicit_set_cond_p (cond))
1378         continue;
1379
1380       dest = GET_CODE (cond) == EQ
1381         ? BRANCH_EDGE (bb)->dest : FALLTHRU_EDGE (bb)->dest;
1382
1383       /* If DEST doesn't go anywhere, ignore it.  */
1384       if (! dest || dest == EXIT_BLOCK_PTR)
1385         continue;
1386
1387       /* We have found a suitable implicit set.  Try to record it now as
1388          a SET in DEST.  If DEST has more than one predecessor, the edge
1389          between BB and DEST is a critical edge and we must split it,
1390          because we can only record one implicit set per DEST basic block.  */
1391       if (! single_pred_p (dest))
1392         {
1393           dest = split_edge (find_edge (bb, dest));
1394           edges_split = true;
1395         }
1396
1397       if (implicit_sets_size <= (size_t) dest->index)
1398       {
1399         size_t old_implicit_sets_size = implicit_sets_size;
1400         implicit_sets_size *= 2;
1401         implicit_sets = XRESIZEVEC (rtx, implicit_sets, implicit_sets_size);
1402         memset (implicit_sets + old_implicit_sets_size, 0,
1403                 (implicit_sets_size - old_implicit_sets_size) * sizeof (rtx));
1404       }
1405
1406       new_rtx = gen_rtx_SET (VOIDmode, XEXP (cond, 0),
1407                              XEXP (cond, 1));
1408       implicit_sets[dest->index] = new_rtx;
1409       if (dump_file)
1410         {
1411           fprintf(dump_file, "Implicit set of reg %d in ",
1412                   REGNO (XEXP (cond, 0)));
1413           fprintf(dump_file, "basic block %d\n", dest->index);
1414         }
1415       count++;
1416     }
1417
1418   if (dump_file)
1419     fprintf (dump_file, "Found %d implicit sets\n", count);
1420
1421   /* Confess our sins.  */
1422   return edges_split;
1423 }
1424
1425 /* Bypass conditional jumps.  */
1426
1427 /* The value of last_basic_block at the beginning of the jump_bypass
1428    pass.  The use of redirect_edge_and_branch_force may introduce new
1429    basic blocks, but the data flow analysis is only valid for basic
1430    block indices less than bypass_last_basic_block.  */
1431
1432 static int bypass_last_basic_block;
1433
1434 /* Find a set of REGNO to a constant that is available at the end of basic
1435    block BB.  Return NULL if no such set is found.  Based heavily upon
1436    find_avail_set.  */
1437
1438 static struct expr *
1439 find_bypass_set (int regno, int bb)
1440 {
1441   struct expr *result = 0;
1442
1443   for (;;)
1444     {
1445       rtx src;
1446       struct expr *set = lookup_set (regno, &set_hash_table);
1447
1448       while (set)
1449         {
1450           if (TEST_BIT (cprop_avout[bb], set->bitmap_index))
1451             break;
1452           set = next_set (regno, set);
1453         }
1454
1455       if (set == 0)
1456         break;
1457
1458       src = set->src;
1459       if (cprop_constant_p (src))
1460         result = set;
1461
1462       if (! REG_P (src))
1463         break;
1464
1465       regno = REGNO (src);
1466     }
1467   return result;
1468 }
1469
1470 /* Subroutine of bypass_block that checks whether a pseudo is killed by
1471    any of the instructions inserted on an edge.  Jump bypassing places
1472    condition code setters on CFG edges using insert_insn_on_edge.  This
1473    function is required to check that our data flow analysis is still
1474    valid prior to commit_edge_insertions.  */
1475
1476 static bool
1477 reg_killed_on_edge (const_rtx reg, const_edge e)
1478 {
1479   rtx insn;
1480
1481   for (insn = e->insns.r; insn; insn = NEXT_INSN (insn))
1482     if (INSN_P (insn) && reg_set_p (reg, insn))
1483       return true;
1484
1485   return false;
1486 }
1487
1488 /* Subroutine of bypass_conditional_jumps that attempts to bypass the given
1489    basic block BB which has more than one predecessor.  If not NULL, SETCC
1490    is the first instruction of BB, which is immediately followed by JUMP_INSN
1491    JUMP.  Otherwise, SETCC is NULL, and JUMP is the first insn of BB.
1492    Returns nonzero if a change was made.
1493
1494    During the jump bypassing pass, we may place copies of SETCC instructions
1495    on CFG edges.  The following routine must be careful to pay attention to
1496    these inserted insns when performing its transformations.  */
1497
1498 static int
1499 bypass_block (basic_block bb, rtx setcc, rtx jump)
1500 {
1501   rtx insn, note;
1502   edge e, edest;
1503   int change;
1504   int may_be_loop_header;
1505   unsigned removed_p;
1506   unsigned i;
1507   edge_iterator ei;
1508
1509   insn = (setcc != NULL) ? setcc : jump;
1510
1511   /* Determine set of register uses in INSN.  */
1512   reg_use_count = 0;
1513   note_uses (&PATTERN (insn), find_used_regs, NULL);
1514   note = find_reg_equal_equiv_note (insn);
1515   if (note)
1516     find_used_regs (&XEXP (note, 0), NULL);
1517
1518   may_be_loop_header = false;
1519   FOR_EACH_EDGE (e, ei, bb->preds)
1520     if (e->flags & EDGE_DFS_BACK)
1521       {
1522         may_be_loop_header = true;
1523         break;
1524       }
1525
1526   change = 0;
1527   for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
1528     {
1529       removed_p = 0;
1530
1531       if (e->flags & EDGE_COMPLEX)
1532         {
1533           ei_next (&ei);
1534           continue;
1535         }
1536
1537       /* We can't redirect edges from new basic blocks.  */
1538       if (e->src->index >= bypass_last_basic_block)
1539         {
1540           ei_next (&ei);
1541           continue;
1542         }
1543
1544       /* The irreducible loops created by redirecting of edges entering the
1545          loop from outside would decrease effectiveness of some of the
1546          following optimizations, so prevent this.  */
1547       if (may_be_loop_header
1548           && !(e->flags & EDGE_DFS_BACK))
1549         {
1550           ei_next (&ei);
1551           continue;
1552         }
1553
1554       for (i = 0; i < reg_use_count; i++)
1555         {
1556           rtx reg_used = reg_use_table[i];
1557           unsigned int regno = REGNO (reg_used);
1558           basic_block dest, old_dest;
1559           struct expr *set;
1560           rtx src, new_rtx;
1561
1562           set = find_bypass_set (regno, e->src->index);
1563
1564           if (! set)
1565             continue;
1566
1567           /* Check the data flow is valid after edge insertions.  */
1568           if (e->insns.r && reg_killed_on_edge (reg_used, e))
1569             continue;
1570
1571           src = SET_SRC (pc_set (jump));
1572
1573           if (setcc != NULL)
1574             src = simplify_replace_rtx (src,
1575                                         SET_DEST (PATTERN (setcc)),
1576                                         SET_SRC (PATTERN (setcc)));
1577
1578           new_rtx = simplify_replace_rtx (src, reg_used, set->src);
1579
1580           /* Jump bypassing may have already placed instructions on
1581              edges of the CFG.  We can't bypass an outgoing edge that
1582              has instructions associated with it, as these insns won't
1583              get executed if the incoming edge is redirected.  */
1584           if (new_rtx == pc_rtx)
1585             {
1586               edest = FALLTHRU_EDGE (bb);
1587               dest = edest->insns.r ? NULL : edest->dest;
1588             }
1589           else if (GET_CODE (new_rtx) == LABEL_REF)
1590             {
1591               dest = BLOCK_FOR_INSN (XEXP (new_rtx, 0));
1592               /* Don't bypass edges containing instructions.  */
1593               edest = find_edge (bb, dest);
1594               if (edest && edest->insns.r)
1595                 dest = NULL;
1596             }
1597           else
1598             dest = NULL;
1599
1600           /* Avoid unification of the edge with other edges from original
1601              branch.  We would end up emitting the instruction on "both"
1602              edges.  */
1603           if (dest && setcc && !CC0_P (SET_DEST (PATTERN (setcc)))
1604               && find_edge (e->src, dest))
1605             dest = NULL;
1606
1607           old_dest = e->dest;
1608           if (dest != NULL
1609               && dest != old_dest
1610               && dest != EXIT_BLOCK_PTR)
1611             {
1612               if (current_loops != NULL
1613                   && e->src->loop_father->latch == e->src)
1614                 {
1615                   /* ???  Now we are creating (or may create) a loop
1616                      with multiple entries.  Simply mark it for
1617                      removal.  Alternatively we could not do this
1618                      threading.  */
1619                   e->src->loop_father->header = NULL;
1620                   e->src->loop_father->latch = NULL;
1621                 }
1622
1623               redirect_edge_and_branch_force (e, dest);
1624
1625               /* Copy the register setter to the redirected edge.
1626                  Don't copy CC0 setters, as CC0 is dead after jump.  */
1627               if (setcc)
1628                 {
1629                   rtx pat = PATTERN (setcc);
1630                   if (!CC0_P (SET_DEST (pat)))
1631                     insert_insn_on_edge (copy_insn (pat), e);
1632                 }
1633
1634               if (dump_file != NULL)
1635                 {
1636                   fprintf (dump_file, "JUMP-BYPASS: Proved reg %d "
1637                                       "in jump_insn %d equals constant ",
1638                            regno, INSN_UID (jump));
1639                   print_rtl (dump_file, set->src);
1640                   fprintf (dump_file, "\nBypass edge from %d->%d to %d\n",
1641                            e->src->index, old_dest->index, dest->index);
1642                 }
1643               change = 1;
1644               removed_p = 1;
1645               break;
1646             }
1647         }
1648       if (!removed_p)
1649         ei_next (&ei);
1650     }
1651   return change;
1652 }
1653
1654 /* Find basic blocks with more than one predecessor that only contain a
1655    single conditional jump.  If the result of the comparison is known at
1656    compile-time from any incoming edge, redirect that edge to the
1657    appropriate target.  Return nonzero if a change was made.
1658
1659    This function is now mis-named, because we also handle indirect jumps.  */
1660
1661 static int
1662 bypass_conditional_jumps (void)
1663 {
1664   basic_block bb;
1665   int changed;
1666   rtx setcc;
1667   rtx insn;
1668   rtx dest;
1669
1670   /* Note we start at block 1.  */
1671   if (ENTRY_BLOCK_PTR->next_bb == EXIT_BLOCK_PTR)
1672     return 0;
1673
1674   bypass_last_basic_block = last_basic_block;
1675   mark_dfs_back_edges ();
1676
1677   changed = 0;
1678   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR->next_bb->next_bb,
1679                   EXIT_BLOCK_PTR, next_bb)
1680     {
1681       /* Check for more than one predecessor.  */
1682       if (!single_pred_p (bb))
1683         {
1684           setcc = NULL_RTX;
1685           FOR_BB_INSNS (bb, insn)
1686             if (DEBUG_INSN_P (insn))
1687               continue;
1688             else if (NONJUMP_INSN_P (insn))
1689               {
1690                 if (setcc)
1691                   break;
1692                 if (GET_CODE (PATTERN (insn)) != SET)
1693                   break;
1694
1695                 dest = SET_DEST (PATTERN (insn));
1696                 if (REG_P (dest) || CC0_P (dest))
1697                   setcc = insn;
1698                 else
1699                   break;
1700               }
1701             else if (JUMP_P (insn))
1702               {
1703                 if ((any_condjump_p (insn) || computed_jump_p (insn))
1704                     && onlyjump_p (insn))
1705                   changed |= bypass_block (bb, setcc, insn);
1706                 break;
1707               }
1708             else if (INSN_P (insn))
1709               break;
1710         }
1711     }
1712
1713   /* If we bypassed any register setting insns, we inserted a
1714      copy on the redirected edge.  These need to be committed.  */
1715   if (changed)
1716     commit_edge_insertions ();
1717
1718   return changed;
1719 }
1720 \f
1721 /* Return true if the graph is too expensive to optimize.  PASS is the
1722    optimization about to be performed.  */
1723
1724 static bool
1725 is_too_expensive (const char *pass)
1726 {
1727   /* Trying to perform global optimizations on flow graphs which have
1728      a high connectivity will take a long time and is unlikely to be
1729      particularly useful.
1730
1731      In normal circumstances a cfg should have about twice as many
1732      edges as blocks.  But we do not want to punish small functions
1733      which have a couple switch statements.  Rather than simply
1734      threshold the number of blocks, uses something with a more
1735      graceful degradation.  */
1736   if (n_edges > 20000 + n_basic_blocks * 4)
1737     {
1738       warning (OPT_Wdisabled_optimization,
1739                "%s: %d basic blocks and %d edges/basic block",
1740                pass, n_basic_blocks, n_edges / n_basic_blocks);
1741
1742       return true;
1743     }
1744
1745   /* If allocating memory for the cprop bitmap would take up too much
1746      storage it's better just to disable the optimization.  */
1747   if ((n_basic_blocks
1748        * SBITMAP_SET_SIZE (max_reg_num ())
1749        * sizeof (SBITMAP_ELT_TYPE)) > MAX_GCSE_MEMORY)
1750     {
1751       warning (OPT_Wdisabled_optimization,
1752                "%s: %d basic blocks and %d registers",
1753                pass, n_basic_blocks, max_reg_num ());
1754
1755       return true;
1756     }
1757
1758   return false;
1759 }
1760 \f
1761 /* Main function for the CPROP pass.  */
1762
1763 static int
1764 one_cprop_pass (void)
1765 {
1766   int i;
1767   int changed = 0;
1768
1769   /* Return if there's nothing to do, or it is too expensive.  */
1770   if (n_basic_blocks <= NUM_FIXED_BLOCKS + 1
1771       || is_too_expensive (_ ("const/copy propagation disabled")))
1772     return 0;
1773
1774   global_const_prop_count = local_const_prop_count = 0;
1775   global_copy_prop_count = local_copy_prop_count = 0;
1776
1777   bytes_used = 0;
1778   gcc_obstack_init (&cprop_obstack);
1779
1780   /* Do a local const/copy propagation pass first.  The global pass
1781      only handles global opportunities.
1782      If the local pass changes something, remove any unreachable blocks
1783      because the CPROP global dataflow analysis may get into infinite
1784      loops for CFGs with unreachable blocks.
1785
1786      FIXME: This local pass should not be necessary after CSE (but for
1787             some reason it still is).  It is also (proven) not necessary
1788             to run the local pass right after FWPWOP.
1789
1790      FIXME: The global analysis would not get into infinite loops if it
1791             would use the DF solver (via df_simple_dataflow) instead of
1792             the solver implemented in this file.  */
1793   changed |= local_cprop_pass ();
1794   if (changed)
1795     delete_unreachable_blocks ();
1796
1797   /* Determine implicit sets.  This may change the CFG (split critical
1798      edges if that exposes an implicit set).
1799      Note that find_implicit_sets() does not rely on up-to-date DF caches
1800      so that we do not have to re-run df_analyze() even if local CPROP
1801      changed something.
1802      ??? This could run earlier so that any uncovered implicit sets
1803          sets could be exploited in local_cprop_pass() also.  Later.  */
1804   changed |= find_implicit_sets ();
1805
1806   /* If local_cprop_pass() or find_implicit_sets() changed something,
1807      run df_analyze() to bring all insn caches up-to-date, and to take
1808      new basic blocks from edge splitting on the DF radar.
1809      NB: This also runs the fast DCE pass, because execute_rtl_cprop
1810      sets DF_LR_RUN_DCE.  */
1811   if (changed)
1812     df_analyze ();
1813
1814   /* Initialize implicit_set_indexes array.  */
1815   implicit_set_indexes = XNEWVEC (int, last_basic_block);
1816   for (i = 0; i < last_basic_block; i++)
1817     implicit_set_indexes[i] = -1;
1818
1819   alloc_hash_table (&set_hash_table);
1820   compute_hash_table (&set_hash_table);
1821
1822   /* Free implicit_sets before peak usage.  */
1823   free (implicit_sets);
1824   implicit_sets = NULL;
1825
1826   if (dump_file)
1827     dump_hash_table (dump_file, "SET", &set_hash_table);
1828   if (set_hash_table.n_elems > 0)
1829     {
1830       basic_block bb;
1831       rtx insn;
1832
1833       alloc_cprop_mem (last_basic_block, set_hash_table.n_elems);
1834       compute_cprop_data ();
1835
1836       free (implicit_set_indexes);
1837       implicit_set_indexes = NULL;
1838
1839       /* Allocate vars to track sets of regs.  */
1840       reg_set_bitmap = ALLOC_REG_SET (NULL);
1841
1842       FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR->next_bb->next_bb, EXIT_BLOCK_PTR,
1843                       next_bb)
1844         {
1845           /* Reset tables used to keep track of what's still valid [since
1846              the start of the block].  */
1847           reset_opr_set_tables ();
1848
1849           FOR_BB_INSNS (bb, insn)
1850             if (INSN_P (insn))
1851               {
1852                 changed |= cprop_insn (insn);
1853
1854                 /* Keep track of everything modified by this insn.  */
1855                 /* ??? Need to be careful w.r.t. mods done to INSN.
1856                        Don't call mark_oprs_set if we turned the
1857                        insn into a NOTE, or deleted the insn.  */
1858                 if (! NOTE_P (insn) && ! INSN_DELETED_P (insn))
1859                   mark_oprs_set (insn);
1860               }
1861         }
1862
1863       changed |= bypass_conditional_jumps ();
1864
1865       FREE_REG_SET (reg_set_bitmap);
1866       free_cprop_mem ();
1867     }
1868   else
1869     {
1870       free (implicit_set_indexes);
1871       implicit_set_indexes = NULL;
1872     }
1873
1874   free_hash_table (&set_hash_table);
1875   obstack_free (&cprop_obstack, NULL);
1876
1877   if (dump_file)
1878     {
1879       fprintf (dump_file, "CPROP of %s, %d basic blocks, %d bytes needed, ",
1880                current_function_name (), n_basic_blocks, bytes_used);
1881       fprintf (dump_file, "%d local const props, %d local copy props, ",
1882                local_const_prop_count, local_copy_prop_count);
1883       fprintf (dump_file, "%d global const props, %d global copy props\n\n",
1884                global_const_prop_count, global_copy_prop_count);
1885     }
1886
1887   return changed;
1888 }
1889 \f
1890 /* All the passes implemented in this file.  Each pass has its
1891    own gate and execute function, and at the end of the file a
1892    pass definition for passes.c.
1893
1894    We do not construct an accurate cfg in functions which call
1895    setjmp, so none of these passes runs if the function calls
1896    setjmp.
1897    FIXME: Should just handle setjmp via REG_SETJMP notes.  */
1898
1899 static bool
1900 gate_rtl_cprop (void)
1901 {
1902   return optimize > 0 && flag_gcse
1903     && !cfun->calls_setjmp
1904     && dbg_cnt (cprop);
1905 }
1906
1907 static unsigned int
1908 execute_rtl_cprop (void)
1909 {
1910   int changed;
1911   delete_unreachable_blocks ();
1912   df_set_flags (DF_LR_RUN_DCE);
1913   df_analyze ();
1914   changed = one_cprop_pass ();
1915   flag_rerun_cse_after_global_opts |= changed;
1916   if (changed)
1917     cleanup_cfg (CLEANUP_CFG_CHANGED);
1918   return 0;
1919 }
1920
1921 struct rtl_opt_pass pass_rtl_cprop =
1922 {
1923  {
1924   RTL_PASS,
1925   "cprop",                              /* name */
1926   gate_rtl_cprop,                       /* gate */
1927   execute_rtl_cprop,                    /* execute */
1928   NULL,                                 /* sub */
1929   NULL,                                 /* next */
1930   0,                                    /* static_pass_number */
1931   TV_CPROP,                             /* tv_id */
1932   PROP_cfglayout,                       /* properties_required */
1933   0,                                    /* properties_provided */
1934   0,                                    /* properties_destroyed */
1935   0,                                    /* todo_flags_start */
1936   TODO_df_finish | TODO_verify_rtl_sharing |
1937   TODO_verify_flow | TODO_ggc_collect   /* todo_flags_finish */
1938  }
1939 };