OSDN Git Service

* gcse.c (gcse_constant_p): Fix typo in last change.
[pf3gnuchains/gcc-fork.git] / gcc / gcse.c
1 /* Global common subexpression elimination/Partial redundancy elimination
2    and global constant/copy propagation for GNU compiler.
3    Copyright (C) 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005,
4    2006, 2007, 2008, 2009 Free Software Foundation, Inc.
5
6 This file is part of GCC.
7
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
12
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
16 for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3.  If not see
20 <http://www.gnu.org/licenses/>.  */
21
22 /* TODO
23    - reordering of memory allocation and freeing to be more space efficient
24    - do rough calc of how many regs are needed in each block, and a rough
25      calc of how many regs are available in each class and use that to
26      throttle back the code in cases where RTX_COST is minimal.
27    - a store to the same address as a load does not kill the load if the
28      source of the store is also the destination of the load.  Handling this
29      allows more load motion, particularly out of loops.
30
31 */
32
33 /* References searched while implementing this.
34
35    Compilers Principles, Techniques and Tools
36    Aho, Sethi, Ullman
37    Addison-Wesley, 1988
38
39    Global Optimization by Suppression of Partial Redundancies
40    E. Morel, C. Renvoise
41    communications of the acm, Vol. 22, Num. 2, Feb. 1979
42
43    A Portable Machine-Independent Global Optimizer - Design and Measurements
44    Frederick Chow
45    Stanford Ph.D. thesis, Dec. 1983
46
47    A Fast Algorithm for Code Movement Optimization
48    D.M. Dhamdhere
49    SIGPLAN Notices, Vol. 23, Num. 10, Oct. 1988
50
51    A Solution to a Problem with Morel and Renvoise's
52    Global Optimization by Suppression of Partial Redundancies
53    K-H Drechsler, M.P. Stadel
54    ACM TOPLAS, Vol. 10, Num. 4, Oct. 1988
55
56    Practical Adaptation of the Global Optimization
57    Algorithm of Morel and Renvoise
58    D.M. Dhamdhere
59    ACM TOPLAS, Vol. 13, Num. 2. Apr. 1991
60
61    Efficiently Computing Static Single Assignment Form and the Control
62    Dependence Graph
63    R. Cytron, J. Ferrante, B.K. Rosen, M.N. Wegman, and F.K. Zadeck
64    ACM TOPLAS, Vol. 13, Num. 4, Oct. 1991
65
66    Lazy Code Motion
67    J. Knoop, O. Ruthing, B. Steffen
68    ACM SIGPLAN Notices Vol. 27, Num. 7, Jul. 1992, '92 Conference on PLDI
69
70    What's In a Region?  Or Computing Control Dependence Regions in Near-Linear
71    Time for Reducible Flow Control
72    Thomas Ball
73    ACM Letters on Programming Languages and Systems,
74    Vol. 2, Num. 1-4, Mar-Dec 1993
75
76    An Efficient Representation for Sparse Sets
77    Preston Briggs, Linda Torczon
78    ACM Letters on Programming Languages and Systems,
79    Vol. 2, Num. 1-4, Mar-Dec 1993
80
81    A Variation of Knoop, Ruthing, and Steffen's Lazy Code Motion
82    K-H Drechsler, M.P. Stadel
83    ACM SIGPLAN Notices, Vol. 28, Num. 5, May 1993
84
85    Partial Dead Code Elimination
86    J. Knoop, O. Ruthing, B. Steffen
87    ACM SIGPLAN Notices, Vol. 29, Num. 6, Jun. 1994
88
89    Effective Partial Redundancy Elimination
90    P. Briggs, K.D. Cooper
91    ACM SIGPLAN Notices, Vol. 29, Num. 6, Jun. 1994
92
93    The Program Structure Tree: Computing Control Regions in Linear Time
94    R. Johnson, D. Pearson, K. Pingali
95    ACM SIGPLAN Notices, Vol. 29, Num. 6, Jun. 1994
96
97    Optimal Code Motion: Theory and Practice
98    J. Knoop, O. Ruthing, B. Steffen
99    ACM TOPLAS, Vol. 16, Num. 4, Jul. 1994
100
101    The power of assignment motion
102    J. Knoop, O. Ruthing, B. Steffen
103    ACM SIGPLAN Notices Vol. 30, Num. 6, Jun. 1995, '95 Conference on PLDI
104
105    Global code motion / global value numbering
106    C. Click
107    ACM SIGPLAN Notices Vol. 30, Num. 6, Jun. 1995, '95 Conference on PLDI
108
109    Value Driven Redundancy Elimination
110    L.T. Simpson
111    Rice University Ph.D. thesis, Apr. 1996
112
113    Value Numbering
114    L.T. Simpson
115    Massively Scalar Compiler Project, Rice University, Sep. 1996
116
117    High Performance Compilers for Parallel Computing
118    Michael Wolfe
119    Addison-Wesley, 1996
120
121    Advanced Compiler Design and Implementation
122    Steven Muchnick
123    Morgan Kaufmann, 1997
124
125    Building an Optimizing Compiler
126    Robert Morgan
127    Digital Press, 1998
128
129    People wishing to speed up the code here should read:
130      Elimination Algorithms for Data Flow Analysis
131      B.G. Ryder, M.C. Paull
132      ACM Computing Surveys, Vol. 18, Num. 3, Sep. 1986
133
134      How to Analyze Large Programs Efficiently and Informatively
135      D.M. Dhamdhere, B.K. Rosen, F.K. Zadeck
136      ACM SIGPLAN Notices Vol. 27, Num. 7, Jul. 1992, '92 Conference on PLDI
137
138    People wishing to do something different can find various possibilities
139    in the above papers and elsewhere.
140 */
141
142 #include "config.h"
143 #include "system.h"
144 #include "coretypes.h"
145 #include "tm.h"
146 #include "toplev.h"
147
148 #include "rtl.h"
149 #include "tree.h"
150 #include "tm_p.h"
151 #include "regs.h"
152 #include "hard-reg-set.h"
153 #include "flags.h"
154 #include "real.h"
155 #include "insn-config.h"
156 #include "recog.h"
157 #include "basic-block.h"
158 #include "output.h"
159 #include "function.h"
160 #include "expr.h"
161 #include "except.h"
162 #include "ggc.h"
163 #include "params.h"
164 #include "cselib.h"
165 #include "intl.h"
166 #include "obstack.h"
167 #include "timevar.h"
168 #include "tree-pass.h"
169 #include "hashtab.h"
170 #include "df.h"
171 #include "dbgcnt.h"
172
173 /* Propagate flow information through back edges and thus enable PRE's
174    moving loop invariant calculations out of loops.
175
176    Originally this tended to create worse overall code, but several
177    improvements during the development of PRE seem to have made following
178    back edges generally a win.
179
180    Note much of the loop invariant code motion done here would normally
181    be done by loop.c, which has more heuristics for when to move invariants
182    out of loops.  At some point we might need to move some of those
183    heuristics into gcse.c.  */
184
185 /* We support GCSE via Partial Redundancy Elimination.  PRE optimizations
186    are a superset of those done by GCSE.
187
188    We perform the following steps:
189
190    1) Compute table of places where registers are set.
191
192    2) Perform copy/constant propagation.
193
194    3) Perform global cse using lazy code motion if not optimizing
195       for size, or code hoisting if we are.
196
197    4) Perform another pass of copy/constant propagation.  Try to bypass
198       conditional jumps if the condition can be computed from a value of
199       an incoming edge.
200
201    5) Perform store motion.
202
203    Two passes of copy/constant propagation are done because the first one
204    enables more GCSE and the second one helps to clean up the copies that
205    GCSE creates.  This is needed more for PRE than for Classic because Classic
206    GCSE will try to use an existing register containing the common
207    subexpression rather than create a new one.  This is harder to do for PRE
208    because of the code motion (which Classic GCSE doesn't do).
209
210    Expressions we are interested in GCSE-ing are of the form
211    (set (pseudo-reg) (expression)).
212    Function want_to_gcse_p says what these are.
213
214    In addition, expressions in REG_EQUAL notes are candidates for GXSE-ing.
215    This allows PRE to hoist expressions that are expressed in multiple insns,
216    such as comprex address calculations (e.g. for PIC code, or loads with a 
217    high part and as lowe part).
218
219    PRE handles moving invariant expressions out of loops (by treating them as
220    partially redundant).
221
222    Eventually it would be nice to replace cse.c/gcse.c with SSA (static single
223    assignment) based GVN (global value numbering).  L. T. Simpson's paper
224    (Rice University) on value numbering is a useful reference for this.
225
226    **********************
227
228    We used to support multiple passes but there are diminishing returns in
229    doing so.  The first pass usually makes 90% of the changes that are doable.
230    A second pass can make a few more changes made possible by the first pass.
231    Experiments show any further passes don't make enough changes to justify
232    the expense.
233
234    A study of spec92 using an unlimited number of passes:
235    [1 pass] = 1208 substitutions, [2] = 577, [3] = 202, [4] = 192, [5] = 83,
236    [6] = 34, [7] = 17, [8] = 9, [9] = 4, [10] = 4, [11] = 2,
237    [12] = 2, [13] = 1, [15] = 1, [16] = 2, [41] = 1
238
239    It was found doing copy propagation between each pass enables further
240    substitutions.
241
242    This study was done before expressions in REG_EQUAL notes were added as
243    candidate expressions for optimization, and before the GIMPLE optimizers
244    were added.  Probably, multiple passes is even less efficient now than
245    at the time when the study was conducted.
246
247    PRE is quite expensive in complicated functions because the DFA can take
248    a while to converge.  Hence we only perform one pass.
249
250    **********************
251
252    The steps for PRE are:
253
254    1) Build the hash table of expressions we wish to GCSE (expr_hash_table).
255
256    2) Perform the data flow analysis for PRE.
257
258    3) Delete the redundant instructions
259
260    4) Insert the required copies [if any] that make the partially
261       redundant instructions fully redundant.
262
263    5) For other reaching expressions, insert an instruction to copy the value
264       to a newly created pseudo that will reach the redundant instruction.
265
266    The deletion is done first so that when we do insertions we
267    know which pseudo reg to use.
268
269    Various papers have argued that PRE DFA is expensive (O(n^2)) and others
270    argue it is not.  The number of iterations for the algorithm to converge
271    is typically 2-4 so I don't view it as that expensive (relatively speaking).
272
273    PRE GCSE depends heavily on the second CSE pass to clean up the copies
274    we create.  To make an expression reach the place where it's redundant,
275    the result of the expression is copied to a new register, and the redundant
276    expression is deleted by replacing it with this new register.  Classic GCSE
277    doesn't have this problem as much as it computes the reaching defs of
278    each register in each block and thus can try to use an existing
279    register.  */
280 \f
281 /* GCSE global vars.  */
282
283 /* Set to non-zero if CSE should run after all GCSE optimizations are done.  */
284 int flag_rerun_cse_after_global_opts;
285
286 /* An obstack for our working variables.  */
287 static struct obstack gcse_obstack;
288
289 struct reg_use {rtx reg_rtx; };
290
291 /* Hash table of expressions.  */
292
293 struct expr
294 {
295   /* The expression (SET_SRC for expressions, PATTERN for assignments).  */
296   rtx expr;
297   /* Index in the available expression bitmaps.  */
298   int bitmap_index;
299   /* Next entry with the same hash.  */
300   struct expr *next_same_hash;
301   /* List of anticipatable occurrences in basic blocks in the function.
302      An "anticipatable occurrence" is one that is the first occurrence in the
303      basic block, the operands are not modified in the basic block prior
304      to the occurrence and the output is not used between the start of
305      the block and the occurrence.  */
306   struct occr *antic_occr;
307   /* List of available occurrence in basic blocks in the function.
308      An "available occurrence" is one that is the last occurrence in the
309      basic block and the operands are not modified by following statements in
310      the basic block [including this insn].  */
311   struct occr *avail_occr;
312   /* Non-null if the computation is PRE redundant.
313      The value is the newly created pseudo-reg to record a copy of the
314      expression in all the places that reach the redundant copy.  */
315   rtx reaching_reg;
316 };
317
318 /* Occurrence of an expression.
319    There is one per basic block.  If a pattern appears more than once the
320    last appearance is used [or first for anticipatable expressions].  */
321
322 struct occr
323 {
324   /* Next occurrence of this expression.  */
325   struct occr *next;
326   /* The insn that computes the expression.  */
327   rtx insn;
328   /* Nonzero if this [anticipatable] occurrence has been deleted.  */
329   char deleted_p;
330   /* Nonzero if this [available] occurrence has been copied to
331      reaching_reg.  */
332   /* ??? This is mutually exclusive with deleted_p, so they could share
333      the same byte.  */
334   char copied_p;
335 };
336
337 /* Expression and copy propagation hash tables.
338    Each hash table is an array of buckets.
339    ??? It is known that if it were an array of entries, structure elements
340    `next_same_hash' and `bitmap_index' wouldn't be necessary.  However, it is
341    not clear whether in the final analysis a sufficient amount of memory would
342    be saved as the size of the available expression bitmaps would be larger
343    [one could build a mapping table without holes afterwards though].
344    Someday I'll perform the computation and figure it out.  */
345
346 struct hash_table
347 {
348   /* The table itself.
349      This is an array of `expr_hash_table_size' elements.  */
350   struct expr **table;
351
352   /* Size of the hash table, in elements.  */
353   unsigned int size;
354
355   /* Number of hash table elements.  */
356   unsigned int n_elems;
357
358   /* Whether the table is expression of copy propagation one.  */
359   int set_p;
360 };
361
362 /* Expression hash table.  */
363 static struct hash_table expr_hash_table;
364
365 /* Copy propagation hash table.  */
366 static struct hash_table set_hash_table;
367
368 /* This is a list of expressions which are MEMs and will be used by load
369    or store motion.
370    Load motion tracks MEMs which aren't killed by
371    anything except itself. (i.e., loads and stores to a single location).
372    We can then allow movement of these MEM refs with a little special
373    allowance. (all stores copy the same value to the reaching reg used
374    for the loads).  This means all values used to store into memory must have
375    no side effects so we can re-issue the setter value.
376    Store Motion uses this structure as an expression table to track stores
377    which look interesting, and might be moveable towards the exit block.  */
378
379 struct ls_expr
380 {
381   struct expr * expr;           /* Gcse expression reference for LM.  */
382   rtx pattern;                  /* Pattern of this mem.  */
383   rtx pattern_regs;             /* List of registers mentioned by the mem.  */
384   rtx loads;                    /* INSN list of loads seen.  */
385   rtx stores;                   /* INSN list of stores seen.  */
386   struct ls_expr * next;        /* Next in the list.  */
387   int invalid;                  /* Invalid for some reason.  */
388   int index;                    /* If it maps to a bitmap index.  */
389   unsigned int hash_index;      /* Index when in a hash table.  */
390   rtx reaching_reg;             /* Register to use when re-writing.  */
391 };
392
393 /* Array of implicit set patterns indexed by basic block index.  */
394 static rtx *implicit_sets;
395
396 /* Head of the list of load/store memory refs.  */
397 static struct ls_expr * pre_ldst_mems = NULL;
398
399 /* Hashtable for the load/store memory refs.  */
400 static htab_t pre_ldst_table = NULL;
401
402 /* Bitmap containing one bit for each register in the program.
403    Used when performing GCSE to track which registers have been set since
404    the start of the basic block.  */
405 static regset reg_set_bitmap;
406
407 /* Array, indexed by basic block number for a list of insns which modify
408    memory within that block.  */
409 static rtx * modify_mem_list;
410 static bitmap modify_mem_list_set;
411
412 /* This array parallels modify_mem_list, but is kept canonicalized.  */
413 static rtx * canon_modify_mem_list;
414
415 /* Bitmap indexed by block numbers to record which blocks contain
416    function calls.  */
417 static bitmap blocks_with_calls;
418
419 /* Various variables for statistics gathering.  */
420
421 /* Memory used in a pass.
422    This isn't intended to be absolutely precise.  Its intent is only
423    to keep an eye on memory usage.  */
424 static int bytes_used;
425
426 /* GCSE substitutions made.  */
427 static int gcse_subst_count;
428 /* Number of copy instructions created.  */
429 static int gcse_create_count;
430 /* Number of local constants propagated.  */
431 static int local_const_prop_count;
432 /* Number of local copies propagated.  */
433 static int local_copy_prop_count;
434 /* Number of global constants propagated.  */
435 static int global_const_prop_count;
436 /* Number of global copies propagated.  */
437 static int global_copy_prop_count;
438 \f
439 /* For available exprs */
440 static sbitmap *ae_kill, *ae_gen;
441 \f
442 static void compute_can_copy (void);
443 static void *gmalloc (size_t) ATTRIBUTE_MALLOC;
444 static void *gcalloc (size_t, size_t) ATTRIBUTE_MALLOC;
445 static void *gcse_alloc (unsigned long);
446 static void alloc_gcse_mem (void);
447 static void free_gcse_mem (void);
448 static void hash_scan_insn (rtx, struct hash_table *);
449 static void hash_scan_set (rtx, rtx, struct hash_table *);
450 static void hash_scan_clobber (rtx, rtx, struct hash_table *);
451 static void hash_scan_call (rtx, rtx, struct hash_table *);
452 static int want_to_gcse_p (rtx);
453 static bool can_assign_to_reg_p (rtx);
454 static bool gcse_constant_p (const_rtx);
455 static int oprs_unchanged_p (const_rtx, const_rtx, int);
456 static int oprs_anticipatable_p (const_rtx, const_rtx);
457 static int oprs_available_p (const_rtx, const_rtx);
458 static void insert_expr_in_table (rtx, enum machine_mode, rtx, int, int,
459                                   struct hash_table *);
460 static void insert_set_in_table (rtx, rtx, struct hash_table *);
461 static unsigned int hash_expr (const_rtx, enum machine_mode, int *, int);
462 static unsigned int hash_set (int, int);
463 static int expr_equiv_p (const_rtx, const_rtx);
464 static void record_last_reg_set_info (rtx, int);
465 static void record_last_mem_set_info (rtx);
466 static void record_last_set_info (rtx, const_rtx, void *);
467 static void compute_hash_table (struct hash_table *);
468 static void alloc_hash_table (int, struct hash_table *, int);
469 static void free_hash_table (struct hash_table *);
470 static void compute_hash_table_work (struct hash_table *);
471 static void dump_hash_table (FILE *, const char *, struct hash_table *);
472 static struct expr *lookup_set (unsigned int, struct hash_table *);
473 static struct expr *next_set (unsigned int, struct expr *);
474 static void reset_opr_set_tables (void);
475 static int oprs_not_set_p (const_rtx, const_rtx);
476 static void mark_call (rtx);
477 static void mark_set (rtx, rtx);
478 static void mark_clobber (rtx, rtx);
479 static void mark_oprs_set (rtx);
480 static void alloc_cprop_mem (int, int);
481 static void free_cprop_mem (void);
482 static void compute_transp (const_rtx, int, sbitmap *, int);
483 static void compute_transpout (void);
484 static void compute_local_properties (sbitmap *, sbitmap *, sbitmap *,
485                                       struct hash_table *);
486 static void compute_cprop_data (void);
487 static void find_used_regs (rtx *, void *);
488 static int try_replace_reg (rtx, rtx, rtx);
489 static struct expr *find_avail_set (int, rtx);
490 static int cprop_jump (basic_block, rtx, rtx, rtx, rtx);
491 static void mems_conflict_for_gcse_p (rtx, const_rtx, void *);
492 static int load_killed_in_block_p (const_basic_block, int, const_rtx, int);
493 static void canon_list_insert (rtx, const_rtx, void *);
494 static int cprop_insn (rtx);
495 static void find_implicit_sets (void);
496 static int one_cprop_pass (void);
497 static bool constprop_register (rtx, rtx, rtx);
498 static struct expr *find_bypass_set (int, int);
499 static bool reg_killed_on_edge (const_rtx, const_edge);
500 static int bypass_block (basic_block, rtx, rtx);
501 static int bypass_conditional_jumps (void);
502 static void alloc_pre_mem (int, int);
503 static void free_pre_mem (void);
504 static void compute_pre_data (void);
505 static int pre_expr_reaches_here_p (basic_block, struct expr *,
506                                     basic_block);
507 static void insert_insn_end_basic_block (struct expr *, basic_block, int);
508 static void pre_insert_copy_insn (struct expr *, rtx);
509 static void pre_insert_copies (void);
510 static int pre_delete (void);
511 static int pre_gcse (void);
512 static int one_pre_gcse_pass (void);
513 static void add_label_notes (rtx, rtx);
514 static void alloc_code_hoist_mem (int, int);
515 static void free_code_hoist_mem (void);
516 static void compute_code_hoist_vbeinout (void);
517 static void compute_code_hoist_data (void);
518 static int hoist_expr_reaches_here_p (basic_block, int, basic_block, char *);
519 static int hoist_code (void);
520 static int one_code_hoisting_pass (void);
521 static rtx process_insert_insn (struct expr *);
522 static int pre_edge_insert (struct edge_list *, struct expr **);
523 static int pre_expr_reaches_here_p_work (basic_block, struct expr *,
524                                          basic_block, char *);
525 static struct ls_expr * ldst_entry (rtx);
526 static void free_ldst_entry (struct ls_expr *);
527 static void free_ldst_mems (void);
528 static void print_ldst_list (FILE *);
529 static struct ls_expr * find_rtx_in_ldst (rtx);
530 static int enumerate_ldsts (void);
531 static inline struct ls_expr * first_ls_expr (void);
532 static inline struct ls_expr * next_ls_expr (struct ls_expr *);
533 static int simple_mem (const_rtx);
534 static void invalidate_any_buried_refs (rtx);
535 static void compute_ld_motion_mems (void);
536 static void trim_ld_motion_mems (void);
537 static void update_ld_motion_stores (struct expr *);
538 static void reg_set_info (rtx, const_rtx, void *);
539 static void reg_clear_last_set (rtx, const_rtx, void *);
540 static bool store_ops_ok (const_rtx, int *);
541 static rtx extract_mentioned_regs (rtx);
542 static rtx extract_mentioned_regs_helper (rtx, rtx);
543 static void find_moveable_store (rtx, int *, int *);
544 static int compute_store_table (void);
545 static bool load_kills_store (const_rtx, const_rtx, int);
546 static bool find_loads (const_rtx, const_rtx, int);
547 static bool store_killed_in_insn (const_rtx, const_rtx, const_rtx, int);
548 static bool store_killed_after (const_rtx, const_rtx, const_rtx, const_basic_block, int *, rtx *);
549 static bool store_killed_before (const_rtx, const_rtx, const_rtx, const_basic_block, int *);
550 static void build_store_vectors (void);
551 static void insert_insn_start_basic_block (rtx, basic_block);
552 static int insert_store (struct ls_expr *, edge);
553 static void remove_reachable_equiv_notes (basic_block, struct ls_expr *);
554 static void replace_store_insn (rtx, rtx, basic_block, struct ls_expr *);
555 static void delete_store (struct ls_expr *, basic_block);
556 static void free_store_memory (void);
557 static int one_store_motion_pass (void);
558 static void free_insn_expr_list_list (rtx *);
559 static void clear_modify_mem_tables (void);
560 static void free_modify_mem_tables (void);
561 static rtx gcse_emit_move_after (rtx, rtx, rtx);
562 static void local_cprop_find_used_regs (rtx *, void *);
563 static bool do_local_cprop (rtx, rtx);
564 static int local_cprop_pass (void);
565 static bool is_too_expensive (const char *);
566
567 #define GNEW(T)                 ((T *) gmalloc (sizeof (T)))
568 #define GCNEW(T)                ((T *) gcalloc (1, sizeof (T)))
569
570 #define GNEWVEC(T, N)           ((T *) gmalloc (sizeof (T) * (N)))
571 #define GCNEWVEC(T, N)          ((T *) gcalloc ((N), sizeof (T)))
572
573 #define GNEWVAR(T, S)           ((T *) gmalloc ((S)))
574 #define GCNEWVAR(T, S)          ((T *) gcalloc (1, (S)))
575
576 #define GOBNEW(T)               ((T *) gcse_alloc (sizeof (T)))
577 #define GOBNEWVAR(T, S)         ((T *) gcse_alloc ((S)))
578 \f
579 /* Misc. utilities.  */
580
581 /* Nonzero for each mode that supports (set (reg) (reg)).
582    This is trivially true for integer and floating point values.
583    It may or may not be true for condition codes.  */
584 static char can_copy[(int) NUM_MACHINE_MODES];
585
586 /* Compute which modes support reg/reg copy operations.  */
587
588 static void
589 compute_can_copy (void)
590 {
591   int i;
592 #ifndef AVOID_CCMODE_COPIES
593   rtx reg, insn;
594 #endif
595   memset (can_copy, 0, NUM_MACHINE_MODES);
596
597   start_sequence ();
598   for (i = 0; i < NUM_MACHINE_MODES; i++)
599     if (GET_MODE_CLASS (i) == MODE_CC)
600       {
601 #ifdef AVOID_CCMODE_COPIES
602         can_copy[i] = 0;
603 #else
604         reg = gen_rtx_REG ((enum machine_mode) i, LAST_VIRTUAL_REGISTER + 1);
605         insn = emit_insn (gen_rtx_SET (VOIDmode, reg, reg));
606         if (recog (PATTERN (insn), insn, NULL) >= 0)
607           can_copy[i] = 1;
608 #endif
609       }
610     else
611       can_copy[i] = 1;
612
613   end_sequence ();
614 }
615
616 /* Returns whether the mode supports reg/reg copy operations.  */
617
618 bool
619 can_copy_p (enum machine_mode mode)
620 {
621   static bool can_copy_init_p = false;
622
623   if (! can_copy_init_p)
624     {
625       compute_can_copy ();
626       can_copy_init_p = true;
627     }
628
629   return can_copy[mode] != 0;
630 }
631
632 \f
633 /* Cover function to xmalloc to record bytes allocated.  */
634
635 static void *
636 gmalloc (size_t size)
637 {
638   bytes_used += size;
639   return xmalloc (size);
640 }
641
642 /* Cover function to xcalloc to record bytes allocated.  */
643
644 static void *
645 gcalloc (size_t nelem, size_t elsize)
646 {
647   bytes_used += nelem * elsize;
648   return xcalloc (nelem, elsize);
649 }
650
651 /* Cover function to obstack_alloc.  */
652
653 static void *
654 gcse_alloc (unsigned long size)
655 {
656   bytes_used += size;
657   return obstack_alloc (&gcse_obstack, size);
658 }
659
660 /* Allocate memory for the reg/memory set tracking tables.
661    This is called at the start of each pass.  */
662
663 static void
664 alloc_gcse_mem (void)
665 {
666   /* Allocate vars to track sets of regs.  */
667   reg_set_bitmap = BITMAP_ALLOC (NULL);
668
669   /* Allocate array to keep a list of insns which modify memory in each
670      basic block.  */
671   modify_mem_list = GCNEWVEC (rtx, last_basic_block);
672   canon_modify_mem_list = GCNEWVEC (rtx, last_basic_block);
673   modify_mem_list_set = BITMAP_ALLOC (NULL);
674   blocks_with_calls = BITMAP_ALLOC (NULL);
675 }
676
677 /* Free memory allocated by alloc_gcse_mem.  */
678
679 static void
680 free_gcse_mem (void)
681 {
682   free_modify_mem_tables ();
683   BITMAP_FREE (modify_mem_list_set);
684   BITMAP_FREE (blocks_with_calls);
685 }
686 \f
687 /* Compute the local properties of each recorded expression.
688
689    Local properties are those that are defined by the block, irrespective of
690    other blocks.
691
692    An expression is transparent in a block if its operands are not modified
693    in the block.
694
695    An expression is computed (locally available) in a block if it is computed
696    at least once and expression would contain the same value if the
697    computation was moved to the end of the block.
698
699    An expression is locally anticipatable in a block if it is computed at
700    least once and expression would contain the same value if the computation
701    was moved to the beginning of the block.
702
703    We call this routine for cprop, pre and code hoisting.  They all compute
704    basically the same information and thus can easily share this code.
705
706    TRANSP, COMP, and ANTLOC are destination sbitmaps for recording local
707    properties.  If NULL, then it is not necessary to compute or record that
708    particular property.
709
710    TABLE controls which hash table to look at.  If it is  set hash table,
711    additionally, TRANSP is computed as ~TRANSP, since this is really cprop's
712    ABSALTERED.  */
713
714 static void
715 compute_local_properties (sbitmap *transp, sbitmap *comp, sbitmap *antloc,
716                           struct hash_table *table)
717 {
718   unsigned int i;
719
720   /* Initialize any bitmaps that were passed in.  */
721   if (transp)
722     {
723       if (table->set_p)
724         sbitmap_vector_zero (transp, last_basic_block);
725       else
726         sbitmap_vector_ones (transp, last_basic_block);
727     }
728
729   if (comp)
730     sbitmap_vector_zero (comp, last_basic_block);
731   if (antloc)
732     sbitmap_vector_zero (antloc, last_basic_block);
733
734   for (i = 0; i < table->size; i++)
735     {
736       struct expr *expr;
737
738       for (expr = table->table[i]; expr != NULL; expr = expr->next_same_hash)
739         {
740           int indx = expr->bitmap_index;
741           struct occr *occr;
742
743           /* The expression is transparent in this block if it is not killed.
744              We start by assuming all are transparent [none are killed], and
745              then reset the bits for those that are.  */
746           if (transp)
747             compute_transp (expr->expr, indx, transp, table->set_p);
748
749           /* The occurrences recorded in antic_occr are exactly those that
750              we want to set to nonzero in ANTLOC.  */
751           if (antloc)
752             for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
753               {
754                 SET_BIT (antloc[BLOCK_NUM (occr->insn)], indx);
755
756                 /* While we're scanning the table, this is a good place to
757                    initialize this.  */
758                 occr->deleted_p = 0;
759               }
760
761           /* The occurrences recorded in avail_occr are exactly those that
762              we want to set to nonzero in COMP.  */
763           if (comp)
764             for (occr = expr->avail_occr; occr != NULL; occr = occr->next)
765               {
766                 SET_BIT (comp[BLOCK_NUM (occr->insn)], indx);
767
768                 /* While we're scanning the table, this is a good place to
769                    initialize this.  */
770                 occr->copied_p = 0;
771               }
772
773           /* While we're scanning the table, this is a good place to
774              initialize this.  */
775           expr->reaching_reg = 0;
776         }
777     }
778 }
779 \f
780 /* Hash table support.  */
781
782 struct reg_avail_info
783 {
784   basic_block last_bb;
785   int first_set;
786   int last_set;
787 };
788
789 static struct reg_avail_info *reg_avail_info;
790 static basic_block current_bb;
791
792
793 /* See whether X, the source of a set, is something we want to consider for
794    GCSE.  */
795
796 static int
797 want_to_gcse_p (rtx x)
798 {
799 #ifdef STACK_REGS
800   /* On register stack architectures, don't GCSE constants from the
801      constant pool, as the benefits are often swamped by the overhead
802      of shuffling the register stack between basic blocks.  */
803   if (IS_STACK_MODE (GET_MODE (x)))
804     x = avoid_constant_pool_reference (x);
805 #endif
806
807   switch (GET_CODE (x))
808     {
809     case REG:
810     case SUBREG:
811     case CONST_INT:
812     case CONST_DOUBLE:
813     case CONST_FIXED:
814     case CONST_VECTOR:
815     case CALL:
816       return 0;
817
818     default:
819       return can_assign_to_reg_p (x);
820     }
821 }
822
823 /* Used internally by can_assign_to_reg_p.  */
824
825 static GTY(()) rtx test_insn;
826
827 /* Return true if we can assign X to a pseudo register.  */
828
829 static bool
830 can_assign_to_reg_p (rtx x)
831 {
832   int num_clobbers = 0;
833   int icode;
834
835   /* If this is a valid operand, we are OK.  If it's VOIDmode, we aren't.  */
836   if (general_operand (x, GET_MODE (x)))
837     return 1;
838   else if (GET_MODE (x) == VOIDmode)
839     return 0;
840
841   /* Otherwise, check if we can make a valid insn from it.  First initialize
842      our test insn if we haven't already.  */
843   if (test_insn == 0)
844     {
845       test_insn
846         = make_insn_raw (gen_rtx_SET (VOIDmode,
847                                       gen_rtx_REG (word_mode,
848                                                    FIRST_PSEUDO_REGISTER * 2),
849                                       const0_rtx));
850       NEXT_INSN (test_insn) = PREV_INSN (test_insn) = 0;
851     }
852
853   /* Now make an insn like the one we would make when GCSE'ing and see if
854      valid.  */
855   PUT_MODE (SET_DEST (PATTERN (test_insn)), GET_MODE (x));
856   SET_SRC (PATTERN (test_insn)) = x;
857   return ((icode = recog (PATTERN (test_insn), test_insn, &num_clobbers)) >= 0
858           && (num_clobbers == 0 || ! added_clobbers_hard_reg_p (icode)));
859 }
860
861 /* Return nonzero if the operands of expression X are unchanged from the
862    start of INSN's basic block up to but not including INSN (if AVAIL_P == 0),
863    or from INSN to the end of INSN's basic block (if AVAIL_P != 0).  */
864
865 static int
866 oprs_unchanged_p (const_rtx x, const_rtx insn, int avail_p)
867 {
868   int i, j;
869   enum rtx_code code;
870   const char *fmt;
871
872   if (x == 0)
873     return 1;
874
875   code = GET_CODE (x);
876   switch (code)
877     {
878     case REG:
879       {
880         struct reg_avail_info *info = &reg_avail_info[REGNO (x)];
881
882         if (info->last_bb != current_bb)
883           return 1;
884         if (avail_p)
885           return info->last_set < DF_INSN_LUID (insn);
886         else
887           return info->first_set >= DF_INSN_LUID (insn);
888       }
889
890     case MEM:
891       if (load_killed_in_block_p (current_bb, DF_INSN_LUID (insn),
892                                   x, avail_p))
893         return 0;
894       else
895         return oprs_unchanged_p (XEXP (x, 0), insn, avail_p);
896
897     case PRE_DEC:
898     case PRE_INC:
899     case POST_DEC:
900     case POST_INC:
901     case PRE_MODIFY:
902     case POST_MODIFY:
903       return 0;
904
905     case PC:
906     case CC0: /*FIXME*/
907     case CONST:
908     case CONST_INT:
909     case CONST_DOUBLE:
910     case CONST_FIXED:
911     case CONST_VECTOR:
912     case SYMBOL_REF:
913     case LABEL_REF:
914     case ADDR_VEC:
915     case ADDR_DIFF_VEC:
916       return 1;
917
918     default:
919       break;
920     }
921
922   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
923     {
924       if (fmt[i] == 'e')
925         {
926           /* If we are about to do the last recursive call needed at this
927              level, change it into iteration.  This function is called enough
928              to be worth it.  */
929           if (i == 0)
930             return oprs_unchanged_p (XEXP (x, i), insn, avail_p);
931
932           else if (! oprs_unchanged_p (XEXP (x, i), insn, avail_p))
933             return 0;
934         }
935       else if (fmt[i] == 'E')
936         for (j = 0; j < XVECLEN (x, i); j++)
937           if (! oprs_unchanged_p (XVECEXP (x, i, j), insn, avail_p))
938             return 0;
939     }
940
941   return 1;
942 }
943
944 /* Used for communication between mems_conflict_for_gcse_p and
945    load_killed_in_block_p.  Nonzero if mems_conflict_for_gcse_p finds a
946    conflict between two memory references.  */
947 static int gcse_mems_conflict_p;
948
949 /* Used for communication between mems_conflict_for_gcse_p and
950    load_killed_in_block_p.  A memory reference for a load instruction,
951    mems_conflict_for_gcse_p will see if a memory store conflicts with
952    this memory load.  */
953 static const_rtx gcse_mem_operand;
954
955 /* DEST is the output of an instruction.  If it is a memory reference, and
956    possibly conflicts with the load found in gcse_mem_operand, then set
957    gcse_mems_conflict_p to a nonzero value.  */
958
959 static void
960 mems_conflict_for_gcse_p (rtx dest, const_rtx setter ATTRIBUTE_UNUSED,
961                           void *data ATTRIBUTE_UNUSED)
962 {
963   while (GET_CODE (dest) == SUBREG
964          || GET_CODE (dest) == ZERO_EXTRACT
965          || GET_CODE (dest) == STRICT_LOW_PART)
966     dest = XEXP (dest, 0);
967
968   /* If DEST is not a MEM, then it will not conflict with the load.  Note
969      that function calls are assumed to clobber memory, but are handled
970      elsewhere.  */
971   if (! MEM_P (dest))
972     return;
973
974   /* If we are setting a MEM in our list of specially recognized MEMs,
975      don't mark as killed this time.  */
976
977   if (expr_equiv_p (dest, gcse_mem_operand) && pre_ldst_mems != NULL)
978     {
979       if (!find_rtx_in_ldst (dest))
980         gcse_mems_conflict_p = 1;
981       return;
982     }
983
984   if (true_dependence (dest, GET_MODE (dest), gcse_mem_operand,
985                        rtx_addr_varies_p))
986     gcse_mems_conflict_p = 1;
987 }
988
989 /* Return nonzero if the expression in X (a memory reference) is killed
990    in block BB before or after the insn with the LUID in UID_LIMIT.
991    AVAIL_P is nonzero for kills after UID_LIMIT, and zero for kills
992    before UID_LIMIT.
993
994    To check the entire block, set UID_LIMIT to max_uid + 1 and
995    AVAIL_P to 0.  */
996
997 static int
998 load_killed_in_block_p (const_basic_block bb, int uid_limit, const_rtx x, int avail_p)
999 {
1000   rtx list_entry = modify_mem_list[bb->index];
1001
1002   /* If this is a readonly then we aren't going to be changing it.  */
1003   if (MEM_READONLY_P (x))
1004     return 0;
1005
1006   while (list_entry)
1007     {
1008       rtx setter;
1009       /* Ignore entries in the list that do not apply.  */
1010       if ((avail_p
1011            && DF_INSN_LUID (XEXP (list_entry, 0)) < uid_limit)
1012           || (! avail_p
1013               && DF_INSN_LUID (XEXP (list_entry, 0)) > uid_limit))
1014         {
1015           list_entry = XEXP (list_entry, 1);
1016           continue;
1017         }
1018
1019       setter = XEXP (list_entry, 0);
1020
1021       /* If SETTER is a call everything is clobbered.  Note that calls
1022          to pure functions are never put on the list, so we need not
1023          worry about them.  */
1024       if (CALL_P (setter))
1025         return 1;
1026
1027       /* SETTER must be an INSN of some kind that sets memory.  Call
1028          note_stores to examine each hunk of memory that is modified.
1029
1030          The note_stores interface is pretty limited, so we have to
1031          communicate via global variables.  Yuk.  */
1032       gcse_mem_operand = x;
1033       gcse_mems_conflict_p = 0;
1034       note_stores (PATTERN (setter), mems_conflict_for_gcse_p, NULL);
1035       if (gcse_mems_conflict_p)
1036         return 1;
1037       list_entry = XEXP (list_entry, 1);
1038     }
1039   return 0;
1040 }
1041
1042 /* Return nonzero if the operands of expression X are unchanged from
1043    the start of INSN's basic block up to but not including INSN.  */
1044
1045 static int
1046 oprs_anticipatable_p (const_rtx x, const_rtx insn)
1047 {
1048   return oprs_unchanged_p (x, insn, 0);
1049 }
1050
1051 /* Return nonzero if the operands of expression X are unchanged from
1052    INSN to the end of INSN's basic block.  */
1053
1054 static int
1055 oprs_available_p (const_rtx x, const_rtx insn)
1056 {
1057   return oprs_unchanged_p (x, insn, 1);
1058 }
1059
1060 /* Hash expression X.
1061
1062    MODE is only used if X is a CONST_INT.  DO_NOT_RECORD_P is a boolean
1063    indicating if a volatile operand is found or if the expression contains
1064    something we don't want to insert in the table.  HASH_TABLE_SIZE is
1065    the current size of the hash table to be probed.  */
1066
1067 static unsigned int
1068 hash_expr (const_rtx x, enum machine_mode mode, int *do_not_record_p,
1069            int hash_table_size)
1070 {
1071   unsigned int hash;
1072
1073   *do_not_record_p = 0;
1074
1075   hash = hash_rtx (x, mode, do_not_record_p,
1076                    NULL,  /*have_reg_qty=*/false);
1077   return hash % hash_table_size;
1078 }
1079
1080 /* Hash a set of register REGNO.
1081
1082    Sets are hashed on the register that is set.  This simplifies the PRE copy
1083    propagation code.
1084
1085    ??? May need to make things more elaborate.  Later, as necessary.  */
1086
1087 static unsigned int
1088 hash_set (int regno, int hash_table_size)
1089 {
1090   unsigned int hash;
1091
1092   hash = regno;
1093   return hash % hash_table_size;
1094 }
1095
1096 /* Return nonzero if exp1 is equivalent to exp2.  */
1097
1098 static int
1099 expr_equiv_p (const_rtx x, const_rtx y)
1100 {
1101   return exp_equiv_p (x, y, 0, true);
1102 }
1103
1104 /* Insert expression X in INSN in the hash TABLE.
1105    If it is already present, record it as the last occurrence in INSN's
1106    basic block.
1107
1108    MODE is the mode of the value X is being stored into.
1109    It is only used if X is a CONST_INT.
1110
1111    ANTIC_P is nonzero if X is an anticipatable expression.
1112    AVAIL_P is nonzero if X is an available expression.  */
1113
1114 static void
1115 insert_expr_in_table (rtx x, enum machine_mode mode, rtx insn, int antic_p,
1116                       int avail_p, struct hash_table *table)
1117 {
1118   int found, do_not_record_p;
1119   unsigned int hash;
1120   struct expr *cur_expr, *last_expr = NULL;
1121   struct occr *antic_occr, *avail_occr;
1122
1123   hash = hash_expr (x, mode, &do_not_record_p, table->size);
1124
1125   /* Do not insert expression in table if it contains volatile operands,
1126      or if hash_expr determines the expression is something we don't want
1127      to or can't handle.  */
1128   if (do_not_record_p)
1129     return;
1130
1131   cur_expr = table->table[hash];
1132   found = 0;
1133
1134   while (cur_expr && 0 == (found = expr_equiv_p (cur_expr->expr, x)))
1135     {
1136       /* If the expression isn't found, save a pointer to the end of
1137          the list.  */
1138       last_expr = cur_expr;
1139       cur_expr = cur_expr->next_same_hash;
1140     }
1141
1142   if (! found)
1143     {
1144       cur_expr = GOBNEW (struct expr);
1145       bytes_used += sizeof (struct expr);
1146       if (table->table[hash] == NULL)
1147         /* This is the first pattern that hashed to this index.  */
1148         table->table[hash] = cur_expr;
1149       else
1150         /* Add EXPR to end of this hash chain.  */
1151         last_expr->next_same_hash = cur_expr;
1152
1153       /* Set the fields of the expr element.  */
1154       cur_expr->expr = x;
1155       cur_expr->bitmap_index = table->n_elems++;
1156       cur_expr->next_same_hash = NULL;
1157       cur_expr->antic_occr = NULL;
1158       cur_expr->avail_occr = NULL;
1159     }
1160
1161   /* Now record the occurrence(s).  */
1162   if (antic_p)
1163     {
1164       antic_occr = cur_expr->antic_occr;
1165
1166       if (antic_occr && BLOCK_NUM (antic_occr->insn) != BLOCK_NUM (insn))
1167         antic_occr = NULL;
1168
1169       if (antic_occr)
1170         /* Found another instance of the expression in the same basic block.
1171            Prefer the currently recorded one.  We want the first one in the
1172            block and the block is scanned from start to end.  */
1173         ; /* nothing to do */
1174       else
1175         {
1176           /* First occurrence of this expression in this basic block.  */
1177           antic_occr = GOBNEW (struct occr);
1178           bytes_used += sizeof (struct occr);
1179           antic_occr->insn = insn;
1180           antic_occr->next = cur_expr->antic_occr;
1181           antic_occr->deleted_p = 0;
1182           cur_expr->antic_occr = antic_occr;
1183         }
1184     }
1185
1186   if (avail_p)
1187     {
1188       avail_occr = cur_expr->avail_occr;
1189
1190       if (avail_occr && BLOCK_NUM (avail_occr->insn) == BLOCK_NUM (insn))
1191         {
1192           /* Found another instance of the expression in the same basic block.
1193              Prefer this occurrence to the currently recorded one.  We want
1194              the last one in the block and the block is scanned from start
1195              to end.  */
1196           avail_occr->insn = insn;
1197         }
1198       else
1199         {
1200           /* First occurrence of this expression in this basic block.  */
1201           avail_occr = GOBNEW (struct occr);
1202           bytes_used += sizeof (struct occr);
1203           avail_occr->insn = insn;
1204           avail_occr->next = cur_expr->avail_occr;
1205           avail_occr->deleted_p = 0;
1206           cur_expr->avail_occr = avail_occr;
1207         }
1208     }
1209 }
1210
1211 /* Insert pattern X in INSN in the hash table.
1212    X is a SET of a reg to either another reg or a constant.
1213    If it is already present, record it as the last occurrence in INSN's
1214    basic block.  */
1215
1216 static void
1217 insert_set_in_table (rtx x, rtx insn, struct hash_table *table)
1218 {
1219   int found;
1220   unsigned int hash;
1221   struct expr *cur_expr, *last_expr = NULL;
1222   struct occr *cur_occr;
1223
1224   gcc_assert (GET_CODE (x) == SET && REG_P (SET_DEST (x)));
1225
1226   hash = hash_set (REGNO (SET_DEST (x)), table->size);
1227
1228   cur_expr = table->table[hash];
1229   found = 0;
1230
1231   while (cur_expr && 0 == (found = expr_equiv_p (cur_expr->expr, x)))
1232     {
1233       /* If the expression isn't found, save a pointer to the end of
1234          the list.  */
1235       last_expr = cur_expr;
1236       cur_expr = cur_expr->next_same_hash;
1237     }
1238
1239   if (! found)
1240     {
1241       cur_expr = GOBNEW (struct expr);
1242       bytes_used += sizeof (struct expr);
1243       if (table->table[hash] == NULL)
1244         /* This is the first pattern that hashed to this index.  */
1245         table->table[hash] = cur_expr;
1246       else
1247         /* Add EXPR to end of this hash chain.  */
1248         last_expr->next_same_hash = cur_expr;
1249
1250       /* Set the fields of the expr element.
1251          We must copy X because it can be modified when copy propagation is
1252          performed on its operands.  */
1253       cur_expr->expr = copy_rtx (x);
1254       cur_expr->bitmap_index = table->n_elems++;
1255       cur_expr->next_same_hash = NULL;
1256       cur_expr->antic_occr = NULL;
1257       cur_expr->avail_occr = NULL;
1258     }
1259
1260   /* Now record the occurrence.  */
1261   cur_occr = cur_expr->avail_occr;
1262
1263   if (cur_occr && BLOCK_NUM (cur_occr->insn) == BLOCK_NUM (insn))
1264     {
1265       /* Found another instance of the expression in the same basic block.
1266          Prefer this occurrence to the currently recorded one.  We want
1267          the last one in the block and the block is scanned from start
1268          to end.  */
1269       cur_occr->insn = insn;
1270     }
1271   else
1272     {
1273       /* First occurrence of this expression in this basic block.  */
1274       cur_occr = GOBNEW (struct occr);
1275       bytes_used += sizeof (struct occr);
1276       cur_occr->insn = insn;
1277       cur_occr->next = cur_expr->avail_occr;
1278       cur_occr->deleted_p = 0;
1279       cur_expr->avail_occr = cur_occr;
1280     }
1281 }
1282
1283 /* Determine whether the rtx X should be treated as a constant for
1284    the purposes of GCSE's constant propagation.  */
1285
1286 static bool
1287 gcse_constant_p (const_rtx x)
1288 {
1289   /* Consider a COMPARE of two integers constant.  */
1290   if (GET_CODE (x) == COMPARE
1291       && GET_CODE (XEXP (x, 0)) == CONST_INT
1292       && GET_CODE (XEXP (x, 1)) == CONST_INT)
1293     return true;
1294
1295   /* Consider a COMPARE of the same registers is a constant
1296      if they are not floating point registers.  */
1297   if (GET_CODE(x) == COMPARE
1298       && REG_P (XEXP (x, 0)) && REG_P (XEXP (x, 1))
1299       && REGNO (XEXP (x, 0)) == REGNO (XEXP (x, 1))
1300       && ! FLOAT_MODE_P (GET_MODE (XEXP (x, 0)))
1301       && ! FLOAT_MODE_P (GET_MODE (XEXP (x, 1))))
1302     return true;
1303
1304   /* Since X might be inserted more than once we have to take care that it
1305      is sharable.  */
1306   return CONSTANT_P (x) && (GET_CODE (x) != CONST || shared_const_p (x));
1307 }
1308
1309 /* Scan pattern PAT of INSN and add an entry to the hash TABLE (set or
1310    expression one).  */
1311
1312 static void
1313 hash_scan_set (rtx pat, rtx insn, struct hash_table *table)
1314 {
1315   rtx src = SET_SRC (pat);
1316   rtx dest = SET_DEST (pat);
1317   rtx note;
1318
1319   if (GET_CODE (src) == CALL)
1320     hash_scan_call (src, insn, table);
1321
1322   else if (REG_P (dest))
1323     {
1324       unsigned int regno = REGNO (dest);
1325       rtx tmp;
1326
1327       /* See if a REG_EQUAL note shows this equivalent to a simpler expression.
1328
1329          This allows us to do a single GCSE pass and still eliminate
1330          redundant constants, addresses or other expressions that are
1331          constructed with multiple instructions.
1332
1333          However, keep the original SRC if INSN is a simple reg-reg move.  In
1334          In this case, there will almost always be a REG_EQUAL note on the
1335          insn that sets SRC.  By recording the REG_EQUAL value here as SRC
1336          for INSN, we miss copy propagation opportunities and we perform the
1337          same PRE GCSE operation repeatedly on the same REG_EQUAL value if we
1338          do more than one PRE GCSE pass.
1339
1340          Note that this does not impede profitable constant propagations.  We
1341          "look through" reg-reg sets in lookup_avail_set.  */
1342       note = find_reg_equal_equiv_note (insn);
1343       if (note != 0
1344           && REG_NOTE_KIND (note) == REG_EQUAL
1345           && !REG_P (src)
1346           && (table->set_p
1347               ? gcse_constant_p (XEXP (note, 0))
1348               : want_to_gcse_p (XEXP (note, 0))))
1349         src = XEXP (note, 0), pat = gen_rtx_SET (VOIDmode, dest, src);
1350
1351       /* Only record sets of pseudo-regs in the hash table.  */
1352       if (! table->set_p
1353           && regno >= FIRST_PSEUDO_REGISTER
1354           /* Don't GCSE something if we can't do a reg/reg copy.  */
1355           && can_copy_p (GET_MODE (dest))
1356           /* GCSE commonly inserts instruction after the insn.  We can't
1357              do that easily for EH_REGION notes so disable GCSE on these
1358              for now.  */
1359           && !find_reg_note (insn, REG_EH_REGION, NULL_RTX)
1360           /* Is SET_SRC something we want to gcse?  */
1361           && want_to_gcse_p (src)
1362           /* Don't CSE a nop.  */
1363           && ! set_noop_p (pat)
1364           /* Don't GCSE if it has attached REG_EQUIV note.
1365              At this point this only function parameters should have
1366              REG_EQUIV notes and if the argument slot is used somewhere
1367              explicitly, it means address of parameter has been taken,
1368              so we should not extend the lifetime of the pseudo.  */
1369           && (note == NULL_RTX || ! MEM_P (XEXP (note, 0))))
1370         {
1371           /* An expression is not anticipatable if its operands are
1372              modified before this insn or if this is not the only SET in
1373              this insn.  The latter condition does not have to mean that
1374              SRC itself is not anticipatable, but we just will not be
1375              able to handle code motion of insns with multiple sets.  */
1376           int antic_p = oprs_anticipatable_p (src, insn)
1377                         && !multiple_sets (insn);
1378           /* An expression is not available if its operands are
1379              subsequently modified, including this insn.  It's also not
1380              available if this is a branch, because we can't insert
1381              a set after the branch.  */
1382           int avail_p = (oprs_available_p (src, insn)
1383                          && ! JUMP_P (insn));
1384
1385           insert_expr_in_table (src, GET_MODE (dest), insn, antic_p, avail_p, table);
1386         }
1387
1388       /* Record sets for constant/copy propagation.  */
1389       else if (table->set_p
1390                && regno >= FIRST_PSEUDO_REGISTER
1391                && ((REG_P (src)
1392                     && REGNO (src) >= FIRST_PSEUDO_REGISTER
1393                     && can_copy_p (GET_MODE (dest))
1394                     && REGNO (src) != regno)
1395                    || gcse_constant_p (src))
1396                /* A copy is not available if its src or dest is subsequently
1397                   modified.  Here we want to search from INSN+1 on, but
1398                   oprs_available_p searches from INSN on.  */
1399                && (insn == BB_END (BLOCK_FOR_INSN (insn))
1400                    || (tmp = next_nonnote_insn (insn)) == NULL_RTX
1401                    || BLOCK_FOR_INSN (tmp) != BLOCK_FOR_INSN (insn)
1402                    || oprs_available_p (pat, tmp)))
1403         insert_set_in_table (pat, insn, table);
1404     }
1405   /* In case of store we want to consider the memory value as available in
1406      the REG stored in that memory. This makes it possible to remove
1407      redundant loads from due to stores to the same location.  */
1408   else if (flag_gcse_las && REG_P (src) && MEM_P (dest))
1409       {
1410         unsigned int regno = REGNO (src);
1411
1412         /* Do not do this for constant/copy propagation.  */
1413         if (! table->set_p
1414             /* Only record sets of pseudo-regs in the hash table.  */
1415             && regno >= FIRST_PSEUDO_REGISTER
1416            /* Don't GCSE something if we can't do a reg/reg copy.  */
1417            && can_copy_p (GET_MODE (src))
1418            /* GCSE commonly inserts instruction after the insn.  We can't
1419               do that easily for EH_REGION notes so disable GCSE on these
1420               for now.  */
1421            && ! find_reg_note (insn, REG_EH_REGION, NULL_RTX)
1422            /* Is SET_DEST something we want to gcse?  */
1423            && want_to_gcse_p (dest)
1424            /* Don't CSE a nop.  */
1425            && ! set_noop_p (pat)
1426            /* Don't GCSE if it has attached REG_EQUIV note.
1427               At this point this only function parameters should have
1428               REG_EQUIV notes and if the argument slot is used somewhere
1429               explicitly, it means address of parameter has been taken,
1430               so we should not extend the lifetime of the pseudo.  */
1431            && ((note = find_reg_note (insn, REG_EQUIV, NULL_RTX)) == 0
1432                || ! MEM_P (XEXP (note, 0))))
1433              {
1434                /* Stores are never anticipatable.  */
1435                int antic_p = 0;
1436                /* An expression is not available if its operands are
1437                   subsequently modified, including this insn.  It's also not
1438                   available if this is a branch, because we can't insert
1439                   a set after the branch.  */
1440                int avail_p = oprs_available_p (dest, insn)
1441                              && ! JUMP_P (insn);
1442
1443                /* Record the memory expression (DEST) in the hash table.  */
1444                insert_expr_in_table (dest, GET_MODE (dest), insn,
1445                                      antic_p, avail_p, table);
1446              }
1447       }
1448 }
1449
1450 static void
1451 hash_scan_clobber (rtx x ATTRIBUTE_UNUSED, rtx insn ATTRIBUTE_UNUSED,
1452                    struct hash_table *table ATTRIBUTE_UNUSED)
1453 {
1454   /* Currently nothing to do.  */
1455 }
1456
1457 static void
1458 hash_scan_call (rtx x ATTRIBUTE_UNUSED, rtx insn ATTRIBUTE_UNUSED,
1459                 struct hash_table *table ATTRIBUTE_UNUSED)
1460 {
1461   /* Currently nothing to do.  */
1462 }
1463
1464 /* Process INSN and add hash table entries as appropriate.
1465
1466    Only available expressions that set a single pseudo-reg are recorded.
1467
1468    Single sets in a PARALLEL could be handled, but it's an extra complication
1469    that isn't dealt with right now.  The trick is handling the CLOBBERs that
1470    are also in the PARALLEL.  Later.
1471
1472    If SET_P is nonzero, this is for the assignment hash table,
1473    otherwise it is for the expression hash table.  */
1474
1475 static void
1476 hash_scan_insn (rtx insn, struct hash_table *table)
1477 {
1478   rtx pat = PATTERN (insn);
1479   int i;
1480
1481   /* Pick out the sets of INSN and for other forms of instructions record
1482      what's been modified.  */
1483
1484   if (GET_CODE (pat) == SET)
1485     hash_scan_set (pat, insn, table);
1486   else if (GET_CODE (pat) == PARALLEL)
1487     for (i = 0; i < XVECLEN (pat, 0); i++)
1488       {
1489         rtx x = XVECEXP (pat, 0, i);
1490
1491         if (GET_CODE (x) == SET)
1492           hash_scan_set (x, insn, table);
1493         else if (GET_CODE (x) == CLOBBER)
1494           hash_scan_clobber (x, insn, table);
1495         else if (GET_CODE (x) == CALL)
1496           hash_scan_call (x, insn, table);
1497       }
1498
1499   else if (GET_CODE (pat) == CLOBBER)
1500     hash_scan_clobber (pat, insn, table);
1501   else if (GET_CODE (pat) == CALL)
1502     hash_scan_call (pat, insn, table);
1503 }
1504
1505 static void
1506 dump_hash_table (FILE *file, const char *name, struct hash_table *table)
1507 {
1508   int i;
1509   /* Flattened out table, so it's printed in proper order.  */
1510   struct expr **flat_table;
1511   unsigned int *hash_val;
1512   struct expr *expr;
1513
1514   flat_table = XCNEWVEC (struct expr *, table->n_elems);
1515   hash_val = XNEWVEC (unsigned int, table->n_elems);
1516
1517   for (i = 0; i < (int) table->size; i++)
1518     for (expr = table->table[i]; expr != NULL; expr = expr->next_same_hash)
1519       {
1520         flat_table[expr->bitmap_index] = expr;
1521         hash_val[expr->bitmap_index] = i;
1522       }
1523
1524   fprintf (file, "%s hash table (%d buckets, %d entries)\n",
1525            name, table->size, table->n_elems);
1526
1527   for (i = 0; i < (int) table->n_elems; i++)
1528     if (flat_table[i] != 0)
1529       {
1530         expr = flat_table[i];
1531         fprintf (file, "Index %d (hash value %d)\n  ",
1532                  expr->bitmap_index, hash_val[i]);
1533         print_rtl (file, expr->expr);
1534         fprintf (file, "\n");
1535       }
1536
1537   fprintf (file, "\n");
1538
1539   free (flat_table);
1540   free (hash_val);
1541 }
1542
1543 /* Record register first/last/block set information for REGNO in INSN.
1544
1545    first_set records the first place in the block where the register
1546    is set and is used to compute "anticipatability".
1547
1548    last_set records the last place in the block where the register
1549    is set and is used to compute "availability".
1550
1551    last_bb records the block for which first_set and last_set are
1552    valid, as a quick test to invalidate them.  */
1553
1554 static void
1555 record_last_reg_set_info (rtx insn, int regno)
1556 {
1557   struct reg_avail_info *info = &reg_avail_info[regno];
1558   int luid = DF_INSN_LUID (insn);
1559
1560   info->last_set = luid;
1561   if (info->last_bb != current_bb)
1562     {
1563       info->last_bb = current_bb;
1564       info->first_set = luid;
1565     }
1566 }
1567
1568
1569 /* Record all of the canonicalized MEMs of record_last_mem_set_info's insn.
1570    Note we store a pair of elements in the list, so they have to be
1571    taken off pairwise.  */
1572
1573 static void
1574 canon_list_insert (rtx dest ATTRIBUTE_UNUSED, const_rtx unused1 ATTRIBUTE_UNUSED,
1575                    void * v_insn)
1576 {
1577   rtx dest_addr, insn;
1578   int bb;
1579
1580   while (GET_CODE (dest) == SUBREG
1581       || GET_CODE (dest) == ZERO_EXTRACT
1582       || GET_CODE (dest) == STRICT_LOW_PART)
1583     dest = XEXP (dest, 0);
1584
1585   /* If DEST is not a MEM, then it will not conflict with a load.  Note
1586      that function calls are assumed to clobber memory, but are handled
1587      elsewhere.  */
1588
1589   if (! MEM_P (dest))
1590     return;
1591
1592   dest_addr = get_addr (XEXP (dest, 0));
1593   dest_addr = canon_rtx (dest_addr);
1594   insn = (rtx) v_insn;
1595   bb = BLOCK_NUM (insn);
1596
1597   canon_modify_mem_list[bb] =
1598     alloc_EXPR_LIST (VOIDmode, dest_addr, canon_modify_mem_list[bb]);
1599   canon_modify_mem_list[bb] =
1600     alloc_EXPR_LIST (VOIDmode, dest, canon_modify_mem_list[bb]);
1601 }
1602
1603 /* Record memory modification information for INSN.  We do not actually care
1604    about the memory location(s) that are set, or even how they are set (consider
1605    a CALL_INSN).  We merely need to record which insns modify memory.  */
1606
1607 static void
1608 record_last_mem_set_info (rtx insn)
1609 {
1610   int bb = BLOCK_NUM (insn);
1611
1612   /* load_killed_in_block_p will handle the case of calls clobbering
1613      everything.  */
1614   modify_mem_list[bb] = alloc_INSN_LIST (insn, modify_mem_list[bb]);
1615   bitmap_set_bit (modify_mem_list_set, bb);
1616
1617   if (CALL_P (insn))
1618     {
1619       /* Note that traversals of this loop (other than for free-ing)
1620          will break after encountering a CALL_INSN.  So, there's no
1621          need to insert a pair of items, as canon_list_insert does.  */
1622       canon_modify_mem_list[bb] =
1623         alloc_INSN_LIST (insn, canon_modify_mem_list[bb]);
1624       bitmap_set_bit (blocks_with_calls, bb);
1625     }
1626   else
1627     note_stores (PATTERN (insn), canon_list_insert, (void*) insn);
1628 }
1629
1630 /* Called from compute_hash_table via note_stores to handle one
1631    SET or CLOBBER in an insn.  DATA is really the instruction in which
1632    the SET is taking place.  */
1633
1634 static void
1635 record_last_set_info (rtx dest, const_rtx setter ATTRIBUTE_UNUSED, void *data)
1636 {
1637   rtx last_set_insn = (rtx) data;
1638
1639   if (GET_CODE (dest) == SUBREG)
1640     dest = SUBREG_REG (dest);
1641
1642   if (REG_P (dest))
1643     record_last_reg_set_info (last_set_insn, REGNO (dest));
1644   else if (MEM_P (dest)
1645            /* Ignore pushes, they clobber nothing.  */
1646            && ! push_operand (dest, GET_MODE (dest)))
1647     record_last_mem_set_info (last_set_insn);
1648 }
1649
1650 /* Top level function to create an expression or assignment hash table.
1651
1652    Expression entries are placed in the hash table if
1653    - they are of the form (set (pseudo-reg) src),
1654    - src is something we want to perform GCSE on,
1655    - none of the operands are subsequently modified in the block
1656
1657    Assignment entries are placed in the hash table if
1658    - they are of the form (set (pseudo-reg) src),
1659    - src is something we want to perform const/copy propagation on,
1660    - none of the operands or target are subsequently modified in the block
1661
1662    Currently src must be a pseudo-reg or a const_int.
1663
1664    TABLE is the table computed.  */
1665
1666 static void
1667 compute_hash_table_work (struct hash_table *table)
1668 {
1669   int i;
1670
1671   /* re-Cache any INSN_LIST nodes we have allocated.  */
1672   clear_modify_mem_tables ();
1673   /* Some working arrays used to track first and last set in each block.  */
1674   reg_avail_info = GNEWVEC (struct reg_avail_info, max_reg_num ());
1675
1676   for (i = 0; i < max_reg_num (); ++i)
1677     reg_avail_info[i].last_bb = NULL;
1678
1679   FOR_EACH_BB (current_bb)
1680     {
1681       rtx insn;
1682       unsigned int regno;
1683
1684       /* First pass over the instructions records information used to
1685          determine when registers and memory are first and last set.  */
1686       FOR_BB_INSNS (current_bb, insn)
1687         {
1688           if (! INSN_P (insn))
1689             continue;
1690
1691           if (CALL_P (insn))
1692             {
1693               for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
1694                 if (TEST_HARD_REG_BIT (regs_invalidated_by_call, regno))
1695                   record_last_reg_set_info (insn, regno);
1696
1697               mark_call (insn);
1698             }
1699
1700           note_stores (PATTERN (insn), record_last_set_info, insn);
1701         }
1702
1703       /* Insert implicit sets in the hash table.  */
1704       if (table->set_p
1705           && implicit_sets[current_bb->index] != NULL_RTX)
1706         hash_scan_set (implicit_sets[current_bb->index],
1707                        BB_HEAD (current_bb), table);
1708
1709       /* The next pass builds the hash table.  */
1710       FOR_BB_INSNS (current_bb, insn)
1711         if (INSN_P (insn))
1712           hash_scan_insn (insn, table);
1713     }
1714
1715   free (reg_avail_info);
1716   reg_avail_info = NULL;
1717 }
1718
1719 /* Allocate space for the set/expr hash TABLE.
1720    N_INSNS is the number of instructions in the function.
1721    It is used to determine the number of buckets to use.
1722    SET_P determines whether set or expression table will
1723    be created.  */
1724
1725 static void
1726 alloc_hash_table (int n_insns, struct hash_table *table, int set_p)
1727 {
1728   int n;
1729
1730   table->size = n_insns / 4;
1731   if (table->size < 11)
1732     table->size = 11;
1733
1734   /* Attempt to maintain efficient use of hash table.
1735      Making it an odd number is simplest for now.
1736      ??? Later take some measurements.  */
1737   table->size |= 1;
1738   n = table->size * sizeof (struct expr *);
1739   table->table = GNEWVAR (struct expr *, n);
1740   table->set_p = set_p;
1741 }
1742
1743 /* Free things allocated by alloc_hash_table.  */
1744
1745 static void
1746 free_hash_table (struct hash_table *table)
1747 {
1748   free (table->table);
1749 }
1750
1751 /* Compute the hash TABLE for doing copy/const propagation or
1752    expression hash table.  */
1753
1754 static void
1755 compute_hash_table (struct hash_table *table)
1756 {
1757   /* Initialize count of number of entries in hash table.  */
1758   table->n_elems = 0;
1759   memset (table->table, 0, table->size * sizeof (struct expr *));
1760
1761   compute_hash_table_work (table);
1762 }
1763 \f
1764 /* Expression tracking support.  */
1765
1766 /* Lookup REGNO in the set TABLE.  The result is a pointer to the
1767    table entry, or NULL if not found.  */
1768
1769 static struct expr *
1770 lookup_set (unsigned int regno, struct hash_table *table)
1771 {
1772   unsigned int hash = hash_set (regno, table->size);
1773   struct expr *expr;
1774
1775   expr = table->table[hash];
1776
1777   while (expr && REGNO (SET_DEST (expr->expr)) != regno)
1778     expr = expr->next_same_hash;
1779
1780   return expr;
1781 }
1782
1783 /* Return the next entry for REGNO in list EXPR.  */
1784
1785 static struct expr *
1786 next_set (unsigned int regno, struct expr *expr)
1787 {
1788   do
1789     expr = expr->next_same_hash;
1790   while (expr && REGNO (SET_DEST (expr->expr)) != regno);
1791
1792   return expr;
1793 }
1794
1795 /* Like free_INSN_LIST_list or free_EXPR_LIST_list, except that the node
1796    types may be mixed.  */
1797
1798 static void
1799 free_insn_expr_list_list (rtx *listp)
1800 {
1801   rtx list, next;
1802
1803   for (list = *listp; list ; list = next)
1804     {
1805       next = XEXP (list, 1);
1806       if (GET_CODE (list) == EXPR_LIST)
1807         free_EXPR_LIST_node (list);
1808       else
1809         free_INSN_LIST_node (list);
1810     }
1811
1812   *listp = NULL;
1813 }
1814
1815 /* Clear canon_modify_mem_list and modify_mem_list tables.  */
1816 static void
1817 clear_modify_mem_tables (void)
1818 {
1819   unsigned i;
1820   bitmap_iterator bi;
1821
1822   EXECUTE_IF_SET_IN_BITMAP (modify_mem_list_set, 0, i, bi)
1823     {
1824       free_INSN_LIST_list (modify_mem_list + i);
1825       free_insn_expr_list_list (canon_modify_mem_list + i);
1826     }
1827   bitmap_clear (modify_mem_list_set);
1828   bitmap_clear (blocks_with_calls);
1829 }
1830
1831 /* Release memory used by modify_mem_list_set.  */
1832
1833 static void
1834 free_modify_mem_tables (void)
1835 {
1836   clear_modify_mem_tables ();
1837   free (modify_mem_list);
1838   free (canon_modify_mem_list);
1839   modify_mem_list = 0;
1840   canon_modify_mem_list = 0;
1841 }
1842
1843 /* Reset tables used to keep track of what's still available [since the
1844    start of the block].  */
1845
1846 static void
1847 reset_opr_set_tables (void)
1848 {
1849   /* Maintain a bitmap of which regs have been set since beginning of
1850      the block.  */
1851   CLEAR_REG_SET (reg_set_bitmap);
1852
1853   /* Also keep a record of the last instruction to modify memory.
1854      For now this is very trivial, we only record whether any memory
1855      location has been modified.  */
1856   clear_modify_mem_tables ();
1857 }
1858
1859 /* Return nonzero if the operands of X are not set before INSN in
1860    INSN's basic block.  */
1861
1862 static int
1863 oprs_not_set_p (const_rtx x, const_rtx insn)
1864 {
1865   int i, j;
1866   enum rtx_code code;
1867   const char *fmt;
1868
1869   if (x == 0)
1870     return 1;
1871
1872   code = GET_CODE (x);
1873   switch (code)
1874     {
1875     case PC:
1876     case CC0:
1877     case CONST:
1878     case CONST_INT:
1879     case CONST_DOUBLE:
1880     case CONST_FIXED:
1881     case CONST_VECTOR:
1882     case SYMBOL_REF:
1883     case LABEL_REF:
1884     case ADDR_VEC:
1885     case ADDR_DIFF_VEC:
1886       return 1;
1887
1888     case MEM:
1889       if (load_killed_in_block_p (BLOCK_FOR_INSN (insn),
1890                                   DF_INSN_LUID (insn), x, 0))
1891         return 0;
1892       else
1893         return oprs_not_set_p (XEXP (x, 0), insn);
1894
1895     case REG:
1896       return ! REGNO_REG_SET_P (reg_set_bitmap, REGNO (x));
1897
1898     default:
1899       break;
1900     }
1901
1902   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
1903     {
1904       if (fmt[i] == 'e')
1905         {
1906           /* If we are about to do the last recursive call
1907              needed at this level, change it into iteration.
1908              This function is called enough to be worth it.  */
1909           if (i == 0)
1910             return oprs_not_set_p (XEXP (x, i), insn);
1911
1912           if (! oprs_not_set_p (XEXP (x, i), insn))
1913             return 0;
1914         }
1915       else if (fmt[i] == 'E')
1916         for (j = 0; j < XVECLEN (x, i); j++)
1917           if (! oprs_not_set_p (XVECEXP (x, i, j), insn))
1918             return 0;
1919     }
1920
1921   return 1;
1922 }
1923
1924 /* Mark things set by a CALL.  */
1925
1926 static void
1927 mark_call (rtx insn)
1928 {
1929   if (! RTL_CONST_OR_PURE_CALL_P (insn))
1930     record_last_mem_set_info (insn);
1931 }
1932
1933 /* Mark things set by a SET.  */
1934
1935 static void
1936 mark_set (rtx pat, rtx insn)
1937 {
1938   rtx dest = SET_DEST (pat);
1939
1940   while (GET_CODE (dest) == SUBREG
1941          || GET_CODE (dest) == ZERO_EXTRACT
1942          || GET_CODE (dest) == STRICT_LOW_PART)
1943     dest = XEXP (dest, 0);
1944
1945   if (REG_P (dest))
1946     SET_REGNO_REG_SET (reg_set_bitmap, REGNO (dest));
1947   else if (MEM_P (dest))
1948     record_last_mem_set_info (insn);
1949
1950   if (GET_CODE (SET_SRC (pat)) == CALL)
1951     mark_call (insn);
1952 }
1953
1954 /* Record things set by a CLOBBER.  */
1955
1956 static void
1957 mark_clobber (rtx pat, rtx insn)
1958 {
1959   rtx clob = XEXP (pat, 0);
1960
1961   while (GET_CODE (clob) == SUBREG || GET_CODE (clob) == STRICT_LOW_PART)
1962     clob = XEXP (clob, 0);
1963
1964   if (REG_P (clob))
1965     SET_REGNO_REG_SET (reg_set_bitmap, REGNO (clob));
1966   else
1967     record_last_mem_set_info (insn);
1968 }
1969
1970 /* Record things set by INSN.
1971    This data is used by oprs_not_set_p.  */
1972
1973 static void
1974 mark_oprs_set (rtx insn)
1975 {
1976   rtx pat = PATTERN (insn);
1977   int i;
1978
1979   if (GET_CODE (pat) == SET)
1980     mark_set (pat, insn);
1981   else if (GET_CODE (pat) == PARALLEL)
1982     for (i = 0; i < XVECLEN (pat, 0); i++)
1983       {
1984         rtx x = XVECEXP (pat, 0, i);
1985
1986         if (GET_CODE (x) == SET)
1987           mark_set (x, insn);
1988         else if (GET_CODE (x) == CLOBBER)
1989           mark_clobber (x, insn);
1990         else if (GET_CODE (x) == CALL)
1991           mark_call (insn);
1992       }
1993
1994   else if (GET_CODE (pat) == CLOBBER)
1995     mark_clobber (pat, insn);
1996   else if (GET_CODE (pat) == CALL)
1997     mark_call (insn);
1998 }
1999
2000 \f
2001 /* Compute copy/constant propagation working variables.  */
2002
2003 /* Local properties of assignments.  */
2004 static sbitmap *cprop_pavloc;
2005 static sbitmap *cprop_absaltered;
2006
2007 /* Global properties of assignments (computed from the local properties).  */
2008 static sbitmap *cprop_avin;
2009 static sbitmap *cprop_avout;
2010
2011 /* Allocate vars used for copy/const propagation.  N_BLOCKS is the number of
2012    basic blocks.  N_SETS is the number of sets.  */
2013
2014 static void
2015 alloc_cprop_mem (int n_blocks, int n_sets)
2016 {
2017   cprop_pavloc = sbitmap_vector_alloc (n_blocks, n_sets);
2018   cprop_absaltered = sbitmap_vector_alloc (n_blocks, n_sets);
2019
2020   cprop_avin = sbitmap_vector_alloc (n_blocks, n_sets);
2021   cprop_avout = sbitmap_vector_alloc (n_blocks, n_sets);
2022 }
2023
2024 /* Free vars used by copy/const propagation.  */
2025
2026 static void
2027 free_cprop_mem (void)
2028 {
2029   sbitmap_vector_free (cprop_pavloc);
2030   sbitmap_vector_free (cprop_absaltered);
2031   sbitmap_vector_free (cprop_avin);
2032   sbitmap_vector_free (cprop_avout);
2033 }
2034
2035 /* For each block, compute whether X is transparent.  X is either an
2036    expression or an assignment [though we don't care which, for this context
2037    an assignment is treated as an expression].  For each block where an
2038    element of X is modified, set (SET_P == 1) or reset (SET_P == 0) the INDX
2039    bit in BMAP.  */
2040
2041 static void
2042 compute_transp (const_rtx x, int indx, sbitmap *bmap, int set_p)
2043 {
2044   int i, j;
2045   enum rtx_code code;
2046   const char *fmt;
2047
2048   /* repeat is used to turn tail-recursion into iteration since GCC
2049      can't do it when there's no return value.  */
2050  repeat:
2051
2052   if (x == 0)
2053     return;
2054
2055   code = GET_CODE (x);
2056   switch (code)
2057     {
2058     case REG:
2059       if (set_p)
2060         {
2061           df_ref def;
2062           for (def = DF_REG_DEF_CHAIN (REGNO (x));
2063                def;
2064                def = DF_REF_NEXT_REG (def))
2065             SET_BIT (bmap[DF_REF_BB (def)->index], indx);
2066         }
2067       else
2068         {
2069           df_ref def;
2070           for (def = DF_REG_DEF_CHAIN (REGNO (x));
2071                def;
2072                def = DF_REF_NEXT_REG (def))
2073             RESET_BIT (bmap[DF_REF_BB (def)->index], indx);
2074         }
2075
2076       return;
2077
2078     case MEM:
2079       if (! MEM_READONLY_P (x))
2080         {
2081           bitmap_iterator bi;
2082           unsigned bb_index;
2083
2084           /* First handle all the blocks with calls.  We don't need to
2085              do any list walking for them.  */
2086           EXECUTE_IF_SET_IN_BITMAP (blocks_with_calls, 0, bb_index, bi)
2087             {
2088               if (set_p)
2089                 SET_BIT (bmap[bb_index], indx);
2090               else
2091                 RESET_BIT (bmap[bb_index], indx);
2092             }
2093
2094             /* Now iterate over the blocks which have memory modifications
2095                but which do not have any calls.  */
2096             EXECUTE_IF_AND_COMPL_IN_BITMAP (modify_mem_list_set, 
2097                                             blocks_with_calls,
2098                                             0, bb_index, bi)
2099               {
2100                 rtx list_entry = canon_modify_mem_list[bb_index];
2101
2102                 while (list_entry)
2103                   {
2104                     rtx dest, dest_addr;
2105
2106                     /* LIST_ENTRY must be an INSN of some kind that sets memory.
2107                        Examine each hunk of memory that is modified.  */
2108
2109                     dest = XEXP (list_entry, 0);
2110                     list_entry = XEXP (list_entry, 1);
2111                     dest_addr = XEXP (list_entry, 0);
2112
2113                     if (canon_true_dependence (dest, GET_MODE (dest), dest_addr,
2114                                                x, NULL_RTX, rtx_addr_varies_p))
2115                       {
2116                         if (set_p)
2117                           SET_BIT (bmap[bb_index], indx);
2118                         else
2119                           RESET_BIT (bmap[bb_index], indx);
2120                         break;
2121                       }
2122                     list_entry = XEXP (list_entry, 1);
2123                   }
2124               }
2125         }
2126
2127       x = XEXP (x, 0);
2128       goto repeat;
2129
2130     case PC:
2131     case CC0: /*FIXME*/
2132     case CONST:
2133     case CONST_INT:
2134     case CONST_DOUBLE:
2135     case CONST_FIXED:
2136     case CONST_VECTOR:
2137     case SYMBOL_REF:
2138     case LABEL_REF:
2139     case ADDR_VEC:
2140     case ADDR_DIFF_VEC:
2141       return;
2142
2143     default:
2144       break;
2145     }
2146
2147   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
2148     {
2149       if (fmt[i] == 'e')
2150         {
2151           /* If we are about to do the last recursive call
2152              needed at this level, change it into iteration.
2153              This function is called enough to be worth it.  */
2154           if (i == 0)
2155             {
2156               x = XEXP (x, i);
2157               goto repeat;
2158             }
2159
2160           compute_transp (XEXP (x, i), indx, bmap, set_p);
2161         }
2162       else if (fmt[i] == 'E')
2163         for (j = 0; j < XVECLEN (x, i); j++)
2164           compute_transp (XVECEXP (x, i, j), indx, bmap, set_p);
2165     }
2166 }
2167
2168 /* Top level routine to do the dataflow analysis needed by copy/const
2169    propagation.  */
2170
2171 static void
2172 compute_cprop_data (void)
2173 {
2174   compute_local_properties (cprop_absaltered, cprop_pavloc, NULL, &set_hash_table);
2175   compute_available (cprop_pavloc, cprop_absaltered,
2176                      cprop_avout, cprop_avin);
2177 }
2178 \f
2179 /* Copy/constant propagation.  */
2180
2181 /* Maximum number of register uses in an insn that we handle.  */
2182 #define MAX_USES 8
2183
2184 /* Table of uses found in an insn.
2185    Allocated statically to avoid alloc/free complexity and overhead.  */
2186 static struct reg_use reg_use_table[MAX_USES];
2187
2188 /* Index into `reg_use_table' while building it.  */
2189 static int reg_use_count;
2190
2191 /* Set up a list of register numbers used in INSN.  The found uses are stored
2192    in `reg_use_table'.  `reg_use_count' is initialized to zero before entry,
2193    and contains the number of uses in the table upon exit.
2194
2195    ??? If a register appears multiple times we will record it multiple times.
2196    This doesn't hurt anything but it will slow things down.  */
2197
2198 static void
2199 find_used_regs (rtx *xptr, void *data ATTRIBUTE_UNUSED)
2200 {
2201   int i, j;
2202   enum rtx_code code;
2203   const char *fmt;
2204   rtx x = *xptr;
2205
2206   /* repeat is used to turn tail-recursion into iteration since GCC
2207      can't do it when there's no return value.  */
2208  repeat:
2209   if (x == 0)
2210     return;
2211
2212   code = GET_CODE (x);
2213   if (REG_P (x))
2214     {
2215       if (reg_use_count == MAX_USES)
2216         return;
2217
2218       reg_use_table[reg_use_count].reg_rtx = x;
2219       reg_use_count++;
2220     }
2221
2222   /* Recursively scan the operands of this expression.  */
2223
2224   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
2225     {
2226       if (fmt[i] == 'e')
2227         {
2228           /* If we are about to do the last recursive call
2229              needed at this level, change it into iteration.
2230              This function is called enough to be worth it.  */
2231           if (i == 0)
2232             {
2233               x = XEXP (x, 0);
2234               goto repeat;
2235             }
2236
2237           find_used_regs (&XEXP (x, i), data);
2238         }
2239       else if (fmt[i] == 'E')
2240         for (j = 0; j < XVECLEN (x, i); j++)
2241           find_used_regs (&XVECEXP (x, i, j), data);
2242     }
2243 }
2244
2245 /* Try to replace all non-SET_DEST occurrences of FROM in INSN with TO.
2246    Returns nonzero is successful.  */
2247
2248 static int
2249 try_replace_reg (rtx from, rtx to, rtx insn)
2250 {
2251   rtx note = find_reg_equal_equiv_note (insn);
2252   rtx src = 0;
2253   int success = 0;
2254   rtx set = single_set (insn);
2255
2256   /* Usually we substitute easy stuff, so we won't copy everything.
2257      We however need to take care to not duplicate non-trivial CONST
2258      expressions.  */
2259   to = copy_rtx (to);
2260
2261   validate_replace_src_group (from, to, insn);
2262   if (num_changes_pending () && apply_change_group ())
2263     success = 1;
2264
2265   /* Try to simplify SET_SRC if we have substituted a constant.  */
2266   if (success && set && CONSTANT_P (to))
2267     {
2268       src = simplify_rtx (SET_SRC (set));
2269
2270       if (src)
2271         validate_change (insn, &SET_SRC (set), src, 0);
2272     }
2273
2274   /* If there is already a REG_EQUAL note, update the expression in it
2275      with our replacement.  */
2276   if (note != 0 && REG_NOTE_KIND (note) == REG_EQUAL)
2277     set_unique_reg_note (insn, REG_EQUAL,
2278                          simplify_replace_rtx (XEXP (note, 0), from,
2279                          copy_rtx (to)));
2280   if (!success && set && reg_mentioned_p (from, SET_SRC (set)))
2281     {
2282       /* If above failed and this is a single set, try to simplify the source of
2283          the set given our substitution.  We could perhaps try this for multiple
2284          SETs, but it probably won't buy us anything.  */
2285       src = simplify_replace_rtx (SET_SRC (set), from, to);
2286
2287       if (!rtx_equal_p (src, SET_SRC (set))
2288           && validate_change (insn, &SET_SRC (set), src, 0))
2289         success = 1;
2290
2291       /* If we've failed to do replacement, have a single SET, don't already
2292          have a note, and have no special SET, add a REG_EQUAL note to not
2293          lose information.  */
2294       if (!success && note == 0 && set != 0
2295           && GET_CODE (SET_DEST (set)) != ZERO_EXTRACT
2296           && GET_CODE (SET_DEST (set)) != STRICT_LOW_PART)
2297         note = set_unique_reg_note (insn, REG_EQUAL, copy_rtx (src));
2298     }
2299
2300   /* REG_EQUAL may get simplified into register.
2301      We don't allow that. Remove that note. This code ought
2302      not to happen, because previous code ought to synthesize
2303      reg-reg move, but be on the safe side.  */
2304   if (note && REG_NOTE_KIND (note) == REG_EQUAL && REG_P (XEXP (note, 0)))
2305     remove_note (insn, note);
2306
2307   return success;
2308 }
2309
2310 /* Find a set of REGNOs that are available on entry to INSN's block.  Returns
2311    NULL no such set is found.  */
2312
2313 static struct expr *
2314 find_avail_set (int regno, rtx insn)
2315 {
2316   /* SET1 contains the last set found that can be returned to the caller for
2317      use in a substitution.  */
2318   struct expr *set1 = 0;
2319
2320   /* Loops are not possible here.  To get a loop we would need two sets
2321      available at the start of the block containing INSN.  i.e. we would
2322      need two sets like this available at the start of the block:
2323
2324        (set (reg X) (reg Y))
2325        (set (reg Y) (reg X))
2326
2327      This can not happen since the set of (reg Y) would have killed the
2328      set of (reg X) making it unavailable at the start of this block.  */
2329   while (1)
2330     {
2331       rtx src;
2332       struct expr *set = lookup_set (regno, &set_hash_table);
2333
2334       /* Find a set that is available at the start of the block
2335          which contains INSN.  */
2336       while (set)
2337         {
2338           if (TEST_BIT (cprop_avin[BLOCK_NUM (insn)], set->bitmap_index))
2339             break;
2340           set = next_set (regno, set);
2341         }
2342
2343       /* If no available set was found we've reached the end of the
2344          (possibly empty) copy chain.  */
2345       if (set == 0)
2346         break;
2347
2348       gcc_assert (GET_CODE (set->expr) == SET);
2349
2350       src = SET_SRC (set->expr);
2351
2352       /* We know the set is available.
2353          Now check that SRC is ANTLOC (i.e. none of the source operands
2354          have changed since the start of the block).
2355
2356          If the source operand changed, we may still use it for the next
2357          iteration of this loop, but we may not use it for substitutions.  */
2358
2359       if (gcse_constant_p (src) || oprs_not_set_p (src, insn))
2360         set1 = set;
2361
2362       /* If the source of the set is anything except a register, then
2363          we have reached the end of the copy chain.  */
2364       if (! REG_P (src))
2365         break;
2366
2367       /* Follow the copy chain, i.e. start another iteration of the loop
2368          and see if we have an available copy into SRC.  */
2369       regno = REGNO (src);
2370     }
2371
2372   /* SET1 holds the last set that was available and anticipatable at
2373      INSN.  */
2374   return set1;
2375 }
2376
2377 /* Subroutine of cprop_insn that tries to propagate constants into
2378    JUMP_INSNS.  JUMP must be a conditional jump.  If SETCC is non-NULL
2379    it is the instruction that immediately precedes JUMP, and must be a
2380    single SET of a register.  FROM is what we will try to replace,
2381    SRC is the constant we will try to substitute for it.  Returns nonzero
2382    if a change was made.  */
2383
2384 static int
2385 cprop_jump (basic_block bb, rtx setcc, rtx jump, rtx from, rtx src)
2386 {
2387   rtx new_rtx, set_src, note_src;
2388   rtx set = pc_set (jump);
2389   rtx note = find_reg_equal_equiv_note (jump);
2390
2391   if (note)
2392     {
2393       note_src = XEXP (note, 0);
2394       if (GET_CODE (note_src) == EXPR_LIST)
2395         note_src = NULL_RTX;
2396     }
2397   else note_src = NULL_RTX;
2398
2399   /* Prefer REG_EQUAL notes except those containing EXPR_LISTs.  */
2400   set_src = note_src ? note_src : SET_SRC (set);
2401
2402   /* First substitute the SETCC condition into the JUMP instruction,
2403      then substitute that given values into this expanded JUMP.  */
2404   if (setcc != NULL_RTX
2405       && !modified_between_p (from, setcc, jump)
2406       && !modified_between_p (src, setcc, jump))
2407     {
2408       rtx setcc_src;
2409       rtx setcc_set = single_set (setcc);
2410       rtx setcc_note = find_reg_equal_equiv_note (setcc);
2411       setcc_src = (setcc_note && GET_CODE (XEXP (setcc_note, 0)) != EXPR_LIST)
2412                 ? XEXP (setcc_note, 0) : SET_SRC (setcc_set);
2413       set_src = simplify_replace_rtx (set_src, SET_DEST (setcc_set),
2414                                       setcc_src);
2415     }
2416   else
2417     setcc = NULL_RTX;
2418
2419   new_rtx = simplify_replace_rtx (set_src, from, src);
2420
2421   /* If no simplification can be made, then try the next register.  */
2422   if (rtx_equal_p (new_rtx, SET_SRC (set)))
2423     return 0;
2424
2425   /* If this is now a no-op delete it, otherwise this must be a valid insn.  */
2426   if (new_rtx == pc_rtx)
2427     delete_insn (jump);
2428   else
2429     {
2430       /* Ensure the value computed inside the jump insn to be equivalent
2431          to one computed by setcc.  */
2432       if (setcc && modified_in_p (new_rtx, setcc))
2433         return 0;
2434       if (! validate_unshare_change (jump, &SET_SRC (set), new_rtx, 0))
2435         {
2436           /* When (some) constants are not valid in a comparison, and there
2437              are two registers to be replaced by constants before the entire
2438              comparison can be folded into a constant, we need to keep
2439              intermediate information in REG_EQUAL notes.  For targets with
2440              separate compare insns, such notes are added by try_replace_reg.
2441              When we have a combined compare-and-branch instruction, however,
2442              we need to attach a note to the branch itself to make this
2443              optimization work.  */
2444
2445           if (!rtx_equal_p (new_rtx, note_src))
2446             set_unique_reg_note (jump, REG_EQUAL, copy_rtx (new_rtx));
2447           return 0;
2448         }
2449
2450       /* Remove REG_EQUAL note after simplification.  */
2451       if (note_src)
2452         remove_note (jump, note);
2453      }
2454
2455 #ifdef HAVE_cc0
2456   /* Delete the cc0 setter.  */
2457   if (setcc != NULL && CC0_P (SET_DEST (single_set (setcc))))
2458     delete_insn (setcc);
2459 #endif
2460
2461   global_const_prop_count++;
2462   if (dump_file != NULL)
2463     {
2464       fprintf (dump_file,
2465                "GLOBAL CONST-PROP: Replacing reg %d in jump_insn %d with constant ",
2466                REGNO (from), INSN_UID (jump));
2467       print_rtl (dump_file, src);
2468       fprintf (dump_file, "\n");
2469     }
2470   purge_dead_edges (bb);
2471
2472   /* If a conditional jump has been changed into unconditional jump, remove
2473      the jump and make the edge fallthru - this is always called in
2474      cfglayout mode.  */
2475   if (new_rtx != pc_rtx && simplejump_p (jump))
2476     {
2477       edge e;
2478       edge_iterator ei;
2479
2480       for (ei = ei_start (bb->succs); (e = ei_safe_edge (ei)); ei_next (&ei))
2481         if (e->dest != EXIT_BLOCK_PTR
2482             && BB_HEAD (e->dest) == JUMP_LABEL (jump))
2483           {
2484             e->flags |= EDGE_FALLTHRU;
2485             break;
2486           }
2487       delete_insn (jump);
2488     }
2489
2490   return 1;
2491 }
2492
2493 static bool
2494 constprop_register (rtx insn, rtx from, rtx to)
2495 {
2496   rtx sset;
2497
2498   /* Check for reg or cc0 setting instructions followed by
2499      conditional branch instructions first.  */
2500   if ((sset = single_set (insn)) != NULL
2501       && NEXT_INSN (insn)
2502       && any_condjump_p (NEXT_INSN (insn)) && onlyjump_p (NEXT_INSN (insn)))
2503     {
2504       rtx dest = SET_DEST (sset);
2505       if ((REG_P (dest) || CC0_P (dest))
2506           && cprop_jump (BLOCK_FOR_INSN (insn), insn, NEXT_INSN (insn), from, to))
2507         return 1;
2508     }
2509
2510   /* Handle normal insns next.  */
2511   if (NONJUMP_INSN_P (insn)
2512       && try_replace_reg (from, to, insn))
2513     return 1;
2514
2515   /* Try to propagate a CONST_INT into a conditional jump.
2516      We're pretty specific about what we will handle in this
2517      code, we can extend this as necessary over time.
2518
2519      Right now the insn in question must look like
2520      (set (pc) (if_then_else ...))  */
2521   else if (any_condjump_p (insn) && onlyjump_p (insn))
2522     return cprop_jump (BLOCK_FOR_INSN (insn), NULL, insn, from, to);
2523   return 0;
2524 }
2525
2526 /* Perform constant and copy propagation on INSN.
2527    The result is nonzero if a change was made.  */
2528
2529 static int
2530 cprop_insn (rtx insn)
2531 {
2532   struct reg_use *reg_used;
2533   int changed = 0;
2534   rtx note;
2535
2536   if (!INSN_P (insn))
2537     return 0;
2538
2539   reg_use_count = 0;
2540   note_uses (&PATTERN (insn), find_used_regs, NULL);
2541
2542   note = find_reg_equal_equiv_note (insn);
2543
2544   /* We may win even when propagating constants into notes.  */
2545   if (note)
2546     find_used_regs (&XEXP (note, 0), NULL);
2547
2548   for (reg_used = &reg_use_table[0]; reg_use_count > 0;
2549        reg_used++, reg_use_count--)
2550     {
2551       unsigned int regno = REGNO (reg_used->reg_rtx);
2552       rtx pat, src;
2553       struct expr *set;
2554
2555       /* If the register has already been set in this block, there's
2556          nothing we can do.  */
2557       if (! oprs_not_set_p (reg_used->reg_rtx, insn))
2558         continue;
2559
2560       /* Find an assignment that sets reg_used and is available
2561          at the start of the block.  */
2562       set = find_avail_set (regno, insn);
2563       if (! set)
2564         continue;
2565
2566       pat = set->expr;
2567       /* ??? We might be able to handle PARALLELs.  Later.  */
2568       gcc_assert (GET_CODE (pat) == SET);
2569
2570       src = SET_SRC (pat);
2571
2572       /* Constant propagation.  */
2573       if (gcse_constant_p (src))
2574         {
2575           if (constprop_register (insn, reg_used->reg_rtx, src))
2576             {
2577               changed = 1;
2578               global_const_prop_count++;
2579               if (dump_file != NULL)
2580                 {
2581                   fprintf (dump_file, "GLOBAL CONST-PROP: Replacing reg %d in ", regno);
2582                   fprintf (dump_file, "insn %d with constant ", INSN_UID (insn));
2583                   print_rtl (dump_file, src);
2584                   fprintf (dump_file, "\n");
2585                 }
2586               if (INSN_DELETED_P (insn))
2587                 return 1;
2588             }
2589         }
2590       else if (REG_P (src)
2591                && REGNO (src) >= FIRST_PSEUDO_REGISTER
2592                && REGNO (src) != regno)
2593         {
2594           if (try_replace_reg (reg_used->reg_rtx, src, insn))
2595             {
2596               changed = 1;
2597               global_copy_prop_count++;
2598               if (dump_file != NULL)
2599                 {
2600                   fprintf (dump_file, "GLOBAL COPY-PROP: Replacing reg %d in insn %d",
2601                            regno, INSN_UID (insn));
2602                   fprintf (dump_file, " with reg %d\n", REGNO (src));
2603                 }
2604
2605               /* The original insn setting reg_used may or may not now be
2606                  deletable.  We leave the deletion to flow.  */
2607               /* FIXME: If it turns out that the insn isn't deletable,
2608                  then we may have unnecessarily extended register lifetimes
2609                  and made things worse.  */
2610             }
2611         }
2612     }
2613
2614   return changed;
2615 }
2616
2617 /* Like find_used_regs, but avoid recording uses that appear in
2618    input-output contexts such as zero_extract or pre_dec.  This
2619    restricts the cases we consider to those for which local cprop
2620    can legitimately make replacements.  */
2621
2622 static void
2623 local_cprop_find_used_regs (rtx *xptr, void *data)
2624 {
2625   rtx x = *xptr;
2626
2627   if (x == 0)
2628     return;
2629
2630   switch (GET_CODE (x))
2631     {
2632     case ZERO_EXTRACT:
2633     case SIGN_EXTRACT:
2634     case STRICT_LOW_PART:
2635       return;
2636
2637     case PRE_DEC:
2638     case PRE_INC:
2639     case POST_DEC:
2640     case POST_INC:
2641     case PRE_MODIFY:
2642     case POST_MODIFY:
2643       /* Can only legitimately appear this early in the context of
2644          stack pushes for function arguments, but handle all of the
2645          codes nonetheless.  */
2646       return;
2647
2648     case SUBREG:
2649       /* Setting a subreg of a register larger than word_mode leaves
2650          the non-written words unchanged.  */
2651       if (GET_MODE_BITSIZE (GET_MODE (SUBREG_REG (x))) > BITS_PER_WORD)
2652         return;
2653       break;
2654
2655     default:
2656       break;
2657     }
2658
2659   find_used_regs (xptr, data);
2660 }
2661
2662 /* Try to perform local const/copy propagation on X in INSN.  */
2663
2664 static bool
2665 do_local_cprop (rtx x, rtx insn)
2666 {
2667   rtx newreg = NULL, newcnst = NULL;
2668
2669   /* Rule out USE instructions and ASM statements as we don't want to
2670      change the hard registers mentioned.  */
2671   if (REG_P (x)
2672       && (REGNO (x) >= FIRST_PSEUDO_REGISTER
2673           || (GET_CODE (PATTERN (insn)) != USE
2674               && asm_noperands (PATTERN (insn)) < 0)))
2675     {
2676       cselib_val *val = cselib_lookup (x, GET_MODE (x), 0);
2677       struct elt_loc_list *l;
2678
2679       if (!val)
2680         return false;
2681       for (l = val->locs; l; l = l->next)
2682         {
2683           rtx this_rtx = l->loc;
2684           rtx note;
2685
2686           if (gcse_constant_p (this_rtx))
2687             newcnst = this_rtx;
2688           if (REG_P (this_rtx) && REGNO (this_rtx) >= FIRST_PSEUDO_REGISTER
2689               /* Don't copy propagate if it has attached REG_EQUIV note.
2690                  At this point this only function parameters should have
2691                  REG_EQUIV notes and if the argument slot is used somewhere
2692                  explicitly, it means address of parameter has been taken,
2693                  so we should not extend the lifetime of the pseudo.  */
2694               && (!(note = find_reg_note (l->setting_insn, REG_EQUIV, NULL_RTX))
2695                   || ! MEM_P (XEXP (note, 0))))
2696             newreg = this_rtx;
2697         }
2698       if (newcnst && constprop_register (insn, x, newcnst))
2699         {
2700           if (dump_file != NULL)
2701             {
2702               fprintf (dump_file, "LOCAL CONST-PROP: Replacing reg %d in ",
2703                        REGNO (x));
2704               fprintf (dump_file, "insn %d with constant ",
2705                        INSN_UID (insn));
2706               print_rtl (dump_file, newcnst);
2707               fprintf (dump_file, "\n");
2708             }
2709           local_const_prop_count++;
2710           return true;
2711         }
2712       else if (newreg && newreg != x && try_replace_reg (x, newreg, insn))
2713         {
2714           if (dump_file != NULL)
2715             {
2716               fprintf (dump_file,
2717                        "LOCAL COPY-PROP: Replacing reg %d in insn %d",
2718                        REGNO (x), INSN_UID (insn));
2719               fprintf (dump_file, " with reg %d\n", REGNO (newreg));
2720             }
2721           local_copy_prop_count++;
2722           return true;
2723         }
2724     }
2725   return false;
2726 }
2727
2728 /* Do local const/copy propagation (i.e. within each basic block).  */
2729
2730 static int
2731 local_cprop_pass (void)
2732 {
2733   basic_block bb;
2734   rtx insn;
2735   struct reg_use *reg_used;
2736   bool changed = false;
2737
2738   cselib_init (false);
2739   FOR_EACH_BB (bb)
2740     {
2741       FOR_BB_INSNS (bb, insn)
2742         {
2743           if (INSN_P (insn))
2744             {
2745               rtx note = find_reg_equal_equiv_note (insn);
2746               do
2747                 {
2748                   reg_use_count = 0;
2749                   note_uses (&PATTERN (insn), local_cprop_find_used_regs,
2750                              NULL);
2751                   if (note)
2752                     local_cprop_find_used_regs (&XEXP (note, 0), NULL);
2753
2754                   for (reg_used = &reg_use_table[0]; reg_use_count > 0;
2755                        reg_used++, reg_use_count--)
2756                     {
2757                       if (do_local_cprop (reg_used->reg_rtx, insn))
2758                         {
2759                           changed = true;
2760                           break;
2761                         }
2762                     }
2763                   if (INSN_DELETED_P (insn))
2764                     break;
2765                 }
2766               while (reg_use_count);
2767             }
2768           cselib_process_insn (insn);
2769         }
2770
2771       /* Forget everything at the end of a basic block.  */
2772       cselib_clear_table ();
2773     }
2774
2775   cselib_finish ();
2776
2777   return changed;
2778 }
2779
2780 /* Similar to get_condition, only the resulting condition must be
2781    valid at JUMP, instead of at EARLIEST.
2782
2783    This differs from noce_get_condition in ifcvt.c in that we prefer not to
2784    settle for the condition variable in the jump instruction being integral.
2785    We prefer to be able to record the value of a user variable, rather than
2786    the value of a temporary used in a condition.  This could be solved by
2787    recording the value of *every* register scanned by canonicalize_condition,
2788    but this would require some code reorganization.  */
2789
2790 rtx
2791 fis_get_condition (rtx jump)
2792 {
2793   return get_condition (jump, NULL, false, true);
2794 }
2795
2796 /* Check the comparison COND to see if we can safely form an implicit set from
2797    it.  COND is either an EQ or NE comparison.  */
2798
2799 static bool
2800 implicit_set_cond_p (const_rtx cond)
2801 {
2802   const enum machine_mode mode = GET_MODE (XEXP (cond, 0));
2803   const_rtx cst = XEXP (cond, 1);
2804
2805   /* We can't perform this optimization if either operand might be or might
2806      contain a signed zero.  */
2807   if (HONOR_SIGNED_ZEROS (mode))
2808     {
2809       /* It is sufficient to check if CST is or contains a zero.  We must
2810          handle float, complex, and vector.  If any subpart is a zero, then
2811          the optimization can't be performed.  */
2812       /* ??? The complex and vector checks are not implemented yet.  We just
2813          always return zero for them.  */
2814       if (GET_CODE (cst) == CONST_DOUBLE)
2815         {
2816           REAL_VALUE_TYPE d;
2817           REAL_VALUE_FROM_CONST_DOUBLE (d, cst);
2818           if (REAL_VALUES_EQUAL (d, dconst0))
2819             return 0;
2820         }
2821       else
2822         return 0;
2823     }
2824
2825   return gcse_constant_p (cst);
2826 }
2827
2828 /* Find the implicit sets of a function.  An "implicit set" is a constraint
2829    on the value of a variable, implied by a conditional jump.  For example,
2830    following "if (x == 2)", the then branch may be optimized as though the
2831    conditional performed an "explicit set", in this example, "x = 2".  This
2832    function records the set patterns that are implicit at the start of each
2833    basic block.
2834
2835    FIXME: This would be more effective if critical edges are pre-split.  As
2836           it is now, we can't record implicit sets for blocks that have
2837           critical successor edges.  This results in missed optimizations
2838           and in more (unnecessary) work in cfgcleanup.c:thread_jump().  */
2839
2840 static void
2841 find_implicit_sets (void)
2842 {
2843   basic_block bb, dest;
2844   unsigned int count;
2845   rtx cond, new_rtx;
2846
2847   count = 0;
2848   FOR_EACH_BB (bb)
2849     /* Check for more than one successor.  */
2850     if (EDGE_COUNT (bb->succs) > 1)
2851       {
2852         cond = fis_get_condition (BB_END (bb));
2853
2854         if (cond
2855             && (GET_CODE (cond) == EQ || GET_CODE (cond) == NE)
2856             && REG_P (XEXP (cond, 0))
2857             && REGNO (XEXP (cond, 0)) >= FIRST_PSEUDO_REGISTER
2858             && implicit_set_cond_p (cond))
2859           {
2860             dest = GET_CODE (cond) == EQ ? BRANCH_EDGE (bb)->dest
2861                                          : FALLTHRU_EDGE (bb)->dest;
2862
2863             if (dest
2864                 /* Record nothing for a critical edge.  */
2865                 && single_pred_p (dest)
2866                 && dest != EXIT_BLOCK_PTR)
2867               {
2868                 new_rtx = gen_rtx_SET (VOIDmode, XEXP (cond, 0),
2869                                              XEXP (cond, 1));
2870                 implicit_sets[dest->index] = new_rtx;
2871                 if (dump_file)
2872                   {
2873                     fprintf(dump_file, "Implicit set of reg %d in ",
2874                             REGNO (XEXP (cond, 0)));
2875                     fprintf(dump_file, "basic block %d\n", dest->index);
2876                   }
2877                 count++;
2878               }
2879           }
2880       }
2881
2882   if (dump_file)
2883     fprintf (dump_file, "Found %d implicit sets\n", count);
2884 }
2885
2886 /* Bypass conditional jumps.  */
2887
2888 /* The value of last_basic_block at the beginning of the jump_bypass
2889    pass.  The use of redirect_edge_and_branch_force may introduce new
2890    basic blocks, but the data flow analysis is only valid for basic
2891    block indices less than bypass_last_basic_block.  */
2892
2893 static int bypass_last_basic_block;
2894
2895 /* Find a set of REGNO to a constant that is available at the end of basic
2896    block BB.  Returns NULL if no such set is found.  Based heavily upon
2897    find_avail_set.  */
2898
2899 static struct expr *
2900 find_bypass_set (int regno, int bb)
2901 {
2902   struct expr *result = 0;
2903
2904   for (;;)
2905     {
2906       rtx src;
2907       struct expr *set = lookup_set (regno, &set_hash_table);
2908
2909       while (set)
2910         {
2911           if (TEST_BIT (cprop_avout[bb], set->bitmap_index))
2912             break;
2913           set = next_set (regno, set);
2914         }
2915
2916       if (set == 0)
2917         break;
2918
2919       gcc_assert (GET_CODE (set->expr) == SET);
2920
2921       src = SET_SRC (set->expr);
2922       if (gcse_constant_p (src))
2923         result = set;
2924
2925       if (! REG_P (src))
2926         break;
2927
2928       regno = REGNO (src);
2929     }
2930   return result;
2931 }
2932
2933
2934 /* Subroutine of bypass_block that checks whether a pseudo is killed by
2935    any of the instructions inserted on an edge.  Jump bypassing places
2936    condition code setters on CFG edges using insert_insn_on_edge.  This
2937    function is required to check that our data flow analysis is still
2938    valid prior to commit_edge_insertions.  */
2939
2940 static bool
2941 reg_killed_on_edge (const_rtx reg, const_edge e)
2942 {
2943   rtx insn;
2944
2945   for (insn = e->insns.r; insn; insn = NEXT_INSN (insn))
2946     if (INSN_P (insn) && reg_set_p (reg, insn))
2947       return true;
2948
2949   return false;
2950 }
2951
2952 /* Subroutine of bypass_conditional_jumps that attempts to bypass the given
2953    basic block BB which has more than one predecessor.  If not NULL, SETCC
2954    is the first instruction of BB, which is immediately followed by JUMP_INSN
2955    JUMP.  Otherwise, SETCC is NULL, and JUMP is the first insn of BB.
2956    Returns nonzero if a change was made.
2957
2958    During the jump bypassing pass, we may place copies of SETCC instructions
2959    on CFG edges.  The following routine must be careful to pay attention to
2960    these inserted insns when performing its transformations.  */
2961
2962 static int
2963 bypass_block (basic_block bb, rtx setcc, rtx jump)
2964 {
2965   rtx insn, note;
2966   edge e, edest;
2967   int i, change;
2968   int may_be_loop_header;
2969   unsigned removed_p;
2970   edge_iterator ei;
2971
2972   insn = (setcc != NULL) ? setcc : jump;
2973
2974   /* Determine set of register uses in INSN.  */
2975   reg_use_count = 0;
2976   note_uses (&PATTERN (insn), find_used_regs, NULL);
2977   note = find_reg_equal_equiv_note (insn);
2978   if (note)
2979     find_used_regs (&XEXP (note, 0), NULL);
2980
2981   may_be_loop_header = false;
2982   FOR_EACH_EDGE (e, ei, bb->preds)
2983     if (e->flags & EDGE_DFS_BACK)
2984       {
2985         may_be_loop_header = true;
2986         break;
2987       }
2988
2989   change = 0;
2990   for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
2991     {
2992       removed_p = 0;
2993           
2994       if (e->flags & EDGE_COMPLEX)
2995         {
2996           ei_next (&ei);
2997           continue;
2998         }
2999
3000       /* We can't redirect edges from new basic blocks.  */
3001       if (e->src->index >= bypass_last_basic_block)
3002         {
3003           ei_next (&ei);
3004           continue;
3005         }
3006
3007       /* The irreducible loops created by redirecting of edges entering the
3008          loop from outside would decrease effectiveness of some of the following
3009          optimizations, so prevent this.  */
3010       if (may_be_loop_header
3011           && !(e->flags & EDGE_DFS_BACK))
3012         {
3013           ei_next (&ei);
3014           continue;
3015         }
3016
3017       for (i = 0; i < reg_use_count; i++)
3018         {
3019           struct reg_use *reg_used = &reg_use_table[i];
3020           unsigned int regno = REGNO (reg_used->reg_rtx);
3021           basic_block dest, old_dest;
3022           struct expr *set;
3023           rtx src, new_rtx;
3024
3025           set = find_bypass_set (regno, e->src->index);
3026
3027           if (! set)
3028             continue;
3029
3030           /* Check the data flow is valid after edge insertions.  */
3031           if (e->insns.r && reg_killed_on_edge (reg_used->reg_rtx, e))
3032             continue;
3033
3034           src = SET_SRC (pc_set (jump));
3035
3036           if (setcc != NULL)
3037               src = simplify_replace_rtx (src,
3038                                           SET_DEST (PATTERN (setcc)),
3039                                           SET_SRC (PATTERN (setcc)));
3040
3041           new_rtx = simplify_replace_rtx (src, reg_used->reg_rtx,
3042                                       SET_SRC (set->expr));
3043
3044           /* Jump bypassing may have already placed instructions on
3045              edges of the CFG.  We can't bypass an outgoing edge that
3046              has instructions associated with it, as these insns won't
3047              get executed if the incoming edge is redirected.  */
3048
3049           if (new_rtx == pc_rtx)
3050             {
3051               edest = FALLTHRU_EDGE (bb);
3052               dest = edest->insns.r ? NULL : edest->dest;
3053             }
3054           else if (GET_CODE (new_rtx) == LABEL_REF)
3055             {
3056               dest = BLOCK_FOR_INSN (XEXP (new_rtx, 0));
3057               /* Don't bypass edges containing instructions.  */
3058               edest = find_edge (bb, dest);
3059               if (edest && edest->insns.r)
3060                 dest = NULL;
3061             }
3062           else
3063             dest = NULL;
3064
3065           /* Avoid unification of the edge with other edges from original
3066              branch.  We would end up emitting the instruction on "both"
3067              edges.  */
3068
3069           if (dest && setcc && !CC0_P (SET_DEST (PATTERN (setcc)))
3070               && find_edge (e->src, dest))
3071             dest = NULL;
3072
3073           old_dest = e->dest;
3074           if (dest != NULL
3075               && dest != old_dest
3076               && dest != EXIT_BLOCK_PTR)
3077             {
3078               redirect_edge_and_branch_force (e, dest);
3079
3080               /* Copy the register setter to the redirected edge.
3081                  Don't copy CC0 setters, as CC0 is dead after jump.  */
3082               if (setcc)
3083                 {
3084                   rtx pat = PATTERN (setcc);
3085                   if (!CC0_P (SET_DEST (pat)))
3086                     insert_insn_on_edge (copy_insn (pat), e);
3087                 }
3088
3089               if (dump_file != NULL)
3090                 {
3091                   fprintf (dump_file, "JUMP-BYPASS: Proved reg %d "
3092                                       "in jump_insn %d equals constant ",
3093                            regno, INSN_UID (jump));
3094                   print_rtl (dump_file, SET_SRC (set->expr));
3095                   fprintf (dump_file, "\nBypass edge from %d->%d to %d\n",
3096                            e->src->index, old_dest->index, dest->index);
3097                 }
3098               change = 1;
3099               removed_p = 1;
3100               break;
3101             }
3102         }
3103       if (!removed_p)
3104         ei_next (&ei);
3105     }
3106   return change;
3107 }
3108
3109 /* Find basic blocks with more than one predecessor that only contain a
3110    single conditional jump.  If the result of the comparison is known at
3111    compile-time from any incoming edge, redirect that edge to the
3112    appropriate target.  Returns nonzero if a change was made.
3113
3114    This function is now mis-named, because we also handle indirect jumps.  */
3115
3116 static int
3117 bypass_conditional_jumps (void)
3118 {
3119   basic_block bb;
3120   int changed;
3121   rtx setcc;
3122   rtx insn;
3123   rtx dest;
3124
3125   /* Note we start at block 1.  */
3126   if (ENTRY_BLOCK_PTR->next_bb == EXIT_BLOCK_PTR)
3127     return 0;
3128
3129   bypass_last_basic_block = last_basic_block;
3130   mark_dfs_back_edges ();
3131
3132   changed = 0;
3133   FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR->next_bb->next_bb,
3134                   EXIT_BLOCK_PTR, next_bb)
3135     {
3136       /* Check for more than one predecessor.  */
3137       if (!single_pred_p (bb))
3138         {
3139           setcc = NULL_RTX;
3140           FOR_BB_INSNS (bb, insn)
3141             if (NONJUMP_INSN_P (insn))
3142               {
3143                 if (setcc)
3144                   break;
3145                 if (GET_CODE (PATTERN (insn)) != SET)
3146                   break;
3147
3148                 dest = SET_DEST (PATTERN (insn));
3149                 if (REG_P (dest) || CC0_P (dest))
3150                   setcc = insn;
3151                 else
3152                   break;
3153               }
3154             else if (JUMP_P (insn))
3155               {
3156                 if ((any_condjump_p (insn) || computed_jump_p (insn))
3157                     && onlyjump_p (insn))
3158                   changed |= bypass_block (bb, setcc, insn);
3159                 break;
3160               }
3161             else if (INSN_P (insn))
3162               break;
3163         }
3164     }
3165
3166   /* If we bypassed any register setting insns, we inserted a
3167      copy on the redirected edge.  These need to be committed.  */
3168   if (changed)
3169     commit_edge_insertions ();
3170
3171   return changed;
3172 }
3173 \f
3174 /* Compute PRE+LCM working variables.  */
3175
3176 /* Local properties of expressions.  */
3177 /* Nonzero for expressions that are transparent in the block.  */
3178 static sbitmap *transp;
3179
3180 /* Nonzero for expressions that are transparent at the end of the block.
3181    This is only zero for expressions killed by abnormal critical edge
3182    created by a calls.  */
3183 static sbitmap *transpout;
3184
3185 /* Nonzero for expressions that are computed (available) in the block.  */
3186 static sbitmap *comp;
3187
3188 /* Nonzero for expressions that are locally anticipatable in the block.  */
3189 static sbitmap *antloc;
3190
3191 /* Nonzero for expressions where this block is an optimal computation
3192    point.  */
3193 static sbitmap *pre_optimal;
3194
3195 /* Nonzero for expressions which are redundant in a particular block.  */
3196 static sbitmap *pre_redundant;
3197
3198 /* Nonzero for expressions which should be inserted on a specific edge.  */
3199 static sbitmap *pre_insert_map;
3200
3201 /* Nonzero for expressions which should be deleted in a specific block.  */
3202 static sbitmap *pre_delete_map;
3203
3204 /* Contains the edge_list returned by pre_edge_lcm.  */
3205 static struct edge_list *edge_list;
3206
3207 /* Allocate vars used for PRE analysis.  */
3208
3209 static void
3210 alloc_pre_mem (int n_blocks, int n_exprs)
3211 {
3212   transp = sbitmap_vector_alloc (n_blocks, n_exprs);
3213   comp = sbitmap_vector_alloc (n_blocks, n_exprs);
3214   antloc = sbitmap_vector_alloc (n_blocks, n_exprs);
3215
3216   pre_optimal = NULL;
3217   pre_redundant = NULL;
3218   pre_insert_map = NULL;
3219   pre_delete_map = NULL;
3220   ae_kill = sbitmap_vector_alloc (n_blocks, n_exprs);
3221
3222   /* pre_insert and pre_delete are allocated later.  */
3223 }
3224
3225 /* Free vars used for PRE analysis.  */
3226
3227 static void
3228 free_pre_mem (void)
3229 {
3230   sbitmap_vector_free (transp);
3231   sbitmap_vector_free (comp);
3232
3233   /* ANTLOC and AE_KILL are freed just after pre_lcm finishes.  */
3234
3235   if (pre_optimal)
3236     sbitmap_vector_free (pre_optimal);
3237   if (pre_redundant)
3238     sbitmap_vector_free (pre_redundant);
3239   if (pre_insert_map)
3240     sbitmap_vector_free (pre_insert_map);
3241   if (pre_delete_map)
3242     sbitmap_vector_free (pre_delete_map);
3243
3244   transp = comp = NULL;
3245   pre_optimal = pre_redundant = pre_insert_map = pre_delete_map = NULL;
3246 }
3247
3248 /* Top level routine to do the dataflow analysis needed by PRE.  */
3249
3250 static void
3251 compute_pre_data (void)
3252 {
3253   sbitmap trapping_expr;
3254   basic_block bb;
3255   unsigned int ui;
3256
3257   compute_local_properties (transp, comp, antloc, &expr_hash_table);
3258   sbitmap_vector_zero (ae_kill, last_basic_block);
3259
3260   /* Collect expressions which might trap.  */
3261   trapping_expr = sbitmap_alloc (expr_hash_table.n_elems);
3262   sbitmap_zero (trapping_expr);
3263   for (ui = 0; ui < expr_hash_table.size; ui++)
3264     {
3265       struct expr *e;
3266       for (e = expr_hash_table.table[ui]; e != NULL; e = e->next_same_hash)
3267         if (may_trap_p (e->expr))
3268           SET_BIT (trapping_expr, e->bitmap_index);
3269     }
3270
3271   /* Compute ae_kill for each basic block using:
3272
3273      ~(TRANSP | COMP)
3274   */
3275
3276   FOR_EACH_BB (bb)
3277     {
3278       edge e;
3279       edge_iterator ei;
3280
3281       /* If the current block is the destination of an abnormal edge, we
3282          kill all trapping expressions because we won't be able to properly
3283          place the instruction on the edge.  So make them neither
3284          anticipatable nor transparent.  This is fairly conservative.  */
3285       FOR_EACH_EDGE (e, ei, bb->preds)
3286         if (e->flags & EDGE_ABNORMAL)
3287           {
3288             sbitmap_difference (antloc[bb->index], antloc[bb->index], trapping_expr);
3289             sbitmap_difference (transp[bb->index], transp[bb->index], trapping_expr);
3290             break;
3291           }
3292
3293       sbitmap_a_or_b (ae_kill[bb->index], transp[bb->index], comp[bb->index]);
3294       sbitmap_not (ae_kill[bb->index], ae_kill[bb->index]);
3295     }
3296
3297   edge_list = pre_edge_lcm (expr_hash_table.n_elems, transp, comp, antloc,
3298                             ae_kill, &pre_insert_map, &pre_delete_map);
3299   sbitmap_vector_free (antloc);
3300   antloc = NULL;
3301   sbitmap_vector_free (ae_kill);
3302   ae_kill = NULL;
3303   sbitmap_free (trapping_expr);
3304 }
3305 \f
3306 /* PRE utilities */
3307
3308 /* Return nonzero if an occurrence of expression EXPR in OCCR_BB would reach
3309    block BB.
3310
3311    VISITED is a pointer to a working buffer for tracking which BB's have
3312    been visited.  It is NULL for the top-level call.
3313
3314    We treat reaching expressions that go through blocks containing the same
3315    reaching expression as "not reaching".  E.g. if EXPR is generated in blocks
3316    2 and 3, INSN is in block 4, and 2->3->4, we treat the expression in block
3317    2 as not reaching.  The intent is to improve the probability of finding
3318    only one reaching expression and to reduce register lifetimes by picking
3319    the closest such expression.  */
3320
3321 static int
3322 pre_expr_reaches_here_p_work (basic_block occr_bb, struct expr *expr, basic_block bb, char *visited)
3323 {
3324   edge pred;
3325   edge_iterator ei;
3326   
3327   FOR_EACH_EDGE (pred, ei, bb->preds)
3328     {
3329       basic_block pred_bb = pred->src;
3330
3331       if (pred->src == ENTRY_BLOCK_PTR
3332           /* Has predecessor has already been visited?  */
3333           || visited[pred_bb->index])
3334         ;/* Nothing to do.  */
3335
3336       /* Does this predecessor generate this expression?  */
3337       else if (TEST_BIT (comp[pred_bb->index], expr->bitmap_index))
3338         {
3339           /* Is this the occurrence we're looking for?
3340              Note that there's only one generating occurrence per block
3341              so we just need to check the block number.  */
3342           if (occr_bb == pred_bb)
3343             return 1;
3344
3345           visited[pred_bb->index] = 1;
3346         }
3347       /* Ignore this predecessor if it kills the expression.  */
3348       else if (! TEST_BIT (transp[pred_bb->index], expr->bitmap_index))
3349         visited[pred_bb->index] = 1;
3350
3351       /* Neither gen nor kill.  */
3352       else
3353         {
3354           visited[pred_bb->index] = 1;
3355           if (pre_expr_reaches_here_p_work (occr_bb, expr, pred_bb, visited))
3356             return 1;
3357         }
3358     }
3359
3360   /* All paths have been checked.  */
3361   return 0;
3362 }
3363
3364 /* The wrapper for pre_expr_reaches_here_work that ensures that any
3365    memory allocated for that function is returned.  */
3366
3367 static int
3368 pre_expr_reaches_here_p (basic_block occr_bb, struct expr *expr, basic_block bb)
3369 {
3370   int rval;
3371   char *visited = XCNEWVEC (char, last_basic_block);
3372
3373   rval = pre_expr_reaches_here_p_work (occr_bb, expr, bb, visited);
3374
3375   free (visited);
3376   return rval;
3377 }
3378 \f
3379
3380 /* Given an expr, generate RTL which we can insert at the end of a BB,
3381    or on an edge.  Set the block number of any insns generated to
3382    the value of BB.  */
3383
3384 static rtx
3385 process_insert_insn (struct expr *expr)
3386 {
3387   rtx reg = expr->reaching_reg;
3388   rtx exp = copy_rtx (expr->expr);
3389   rtx pat;
3390
3391   start_sequence ();
3392
3393   /* If the expression is something that's an operand, like a constant,
3394      just copy it to a register.  */
3395   if (general_operand (exp, GET_MODE (reg)))
3396     emit_move_insn (reg, exp);
3397
3398   /* Otherwise, make a new insn to compute this expression and make sure the
3399      insn will be recognized (this also adds any needed CLOBBERs).  Copy the
3400      expression to make sure we don't have any sharing issues.  */
3401   else
3402     {
3403       rtx insn = emit_insn (gen_rtx_SET (VOIDmode, reg, exp));
3404
3405       if (insn_invalid_p (insn))
3406         gcc_unreachable ();
3407     }
3408   
3409
3410   pat = get_insns ();
3411   end_sequence ();
3412
3413   return pat;
3414 }
3415
3416 /* Add EXPR to the end of basic block BB.
3417
3418    This is used by both the PRE and code hoisting.
3419
3420    For PRE, we want to verify that the expr is either transparent
3421    or locally anticipatable in the target block.  This check makes
3422    no sense for code hoisting.  */
3423
3424 static void
3425 insert_insn_end_basic_block (struct expr *expr, basic_block bb, int pre)
3426 {
3427   rtx insn = BB_END (bb);
3428   rtx new_insn;
3429   rtx reg = expr->reaching_reg;
3430   int regno = REGNO (reg);
3431   rtx pat, pat_end;
3432
3433   pat = process_insert_insn (expr);
3434   gcc_assert (pat && INSN_P (pat));
3435
3436   pat_end = pat;
3437   while (NEXT_INSN (pat_end) != NULL_RTX)
3438     pat_end = NEXT_INSN (pat_end);
3439
3440   /* If the last insn is a jump, insert EXPR in front [taking care to
3441      handle cc0, etc. properly].  Similarly we need to care trapping
3442      instructions in presence of non-call exceptions.  */
3443
3444   if (JUMP_P (insn)
3445       || (NONJUMP_INSN_P (insn)
3446           && (!single_succ_p (bb)
3447               || single_succ_edge (bb)->flags & EDGE_ABNORMAL)))
3448     {
3449 #ifdef HAVE_cc0
3450       rtx note;
3451 #endif
3452       /* It should always be the case that we can put these instructions
3453          anywhere in the basic block with performing PRE optimizations.
3454          Check this.  */
3455       gcc_assert (!NONJUMP_INSN_P (insn) || !pre
3456                   || TEST_BIT (antloc[bb->index], expr->bitmap_index)
3457                   || TEST_BIT (transp[bb->index], expr->bitmap_index));
3458
3459       /* If this is a jump table, then we can't insert stuff here.  Since
3460          we know the previous real insn must be the tablejump, we insert
3461          the new instruction just before the tablejump.  */
3462       if (GET_CODE (PATTERN (insn)) == ADDR_VEC
3463           || GET_CODE (PATTERN (insn)) == ADDR_DIFF_VEC)
3464         insn = prev_real_insn (insn);
3465
3466 #ifdef HAVE_cc0
3467       /* FIXME: 'twould be nice to call prev_cc0_setter here but it aborts
3468          if cc0 isn't set.  */
3469       note = find_reg_note (insn, REG_CC_SETTER, NULL_RTX);
3470       if (note)
3471         insn = XEXP (note, 0);
3472       else
3473         {
3474           rtx maybe_cc0_setter = prev_nonnote_insn (insn);
3475           if (maybe_cc0_setter
3476               && INSN_P (maybe_cc0_setter)
3477               && sets_cc0_p (PATTERN (maybe_cc0_setter)))
3478             insn = maybe_cc0_setter;
3479         }
3480 #endif
3481       /* FIXME: What if something in cc0/jump uses value set in new insn?  */
3482       new_insn = emit_insn_before_noloc (pat, insn, bb);
3483     }
3484
3485   /* Likewise if the last insn is a call, as will happen in the presence
3486      of exception handling.  */
3487   else if (CALL_P (insn)
3488            && (!single_succ_p (bb)
3489                || single_succ_edge (bb)->flags & EDGE_ABNORMAL))
3490     {
3491       /* Keeping in mind SMALL_REGISTER_CLASSES and parameters in registers,
3492          we search backward and place the instructions before the first
3493          parameter is loaded.  Do this for everyone for consistency and a
3494          presumption that we'll get better code elsewhere as well.
3495
3496          It should always be the case that we can put these instructions
3497          anywhere in the basic block with performing PRE optimizations.
3498          Check this.  */
3499
3500       gcc_assert (!pre
3501                   || TEST_BIT (antloc[bb->index], expr->bitmap_index)
3502                   || TEST_BIT (transp[bb->index], expr->bitmap_index));
3503
3504       /* Since different machines initialize their parameter registers
3505          in different orders, assume nothing.  Collect the set of all
3506          parameter registers.  */
3507       insn = find_first_parameter_load (insn, BB_HEAD (bb));
3508
3509       /* If we found all the parameter loads, then we want to insert
3510          before the first parameter load.
3511
3512          If we did not find all the parameter loads, then we might have
3513          stopped on the head of the block, which could be a CODE_LABEL.
3514          If we inserted before the CODE_LABEL, then we would be putting
3515          the insn in the wrong basic block.  In that case, put the insn
3516          after the CODE_LABEL.  Also, respect NOTE_INSN_BASIC_BLOCK.  */
3517       while (LABEL_P (insn)
3518              || NOTE_INSN_BASIC_BLOCK_P (insn))
3519         insn = NEXT_INSN (insn);
3520
3521       new_insn = emit_insn_before_noloc (pat, insn, bb);
3522     }
3523   else
3524     new_insn = emit_insn_after_noloc (pat, insn, bb);
3525
3526   while (1)
3527     {
3528       if (INSN_P (pat))
3529         add_label_notes (PATTERN (pat), new_insn);
3530       if (pat == pat_end)
3531         break;
3532       pat = NEXT_INSN (pat);
3533     }
3534
3535   gcse_create_count++;
3536
3537   if (dump_file)
3538     {
3539       fprintf (dump_file, "PRE/HOIST: end of bb %d, insn %d, ",
3540                bb->index, INSN_UID (new_insn));
3541       fprintf (dump_file, "copying expression %d to reg %d\n",
3542                expr->bitmap_index, regno);
3543     }
3544 }
3545
3546 /* Insert partially redundant expressions on edges in the CFG to make
3547    the expressions fully redundant.  */
3548
3549 static int
3550 pre_edge_insert (struct edge_list *edge_list, struct expr **index_map)
3551 {
3552   int e, i, j, num_edges, set_size, did_insert = 0;
3553   sbitmap *inserted;
3554
3555   /* Where PRE_INSERT_MAP is nonzero, we add the expression on that edge
3556      if it reaches any of the deleted expressions.  */
3557
3558   set_size = pre_insert_map[0]->size;
3559   num_edges = NUM_EDGES (edge_list);
3560   inserted = sbitmap_vector_alloc (num_edges, expr_hash_table.n_elems);
3561   sbitmap_vector_zero (inserted, num_edges);
3562
3563   for (e = 0; e < num_edges; e++)
3564     {
3565       int indx;
3566       basic_block bb = INDEX_EDGE_PRED_BB (edge_list, e);
3567
3568       for (i = indx = 0; i < set_size; i++, indx += SBITMAP_ELT_BITS)
3569         {
3570           SBITMAP_ELT_TYPE insert = pre_insert_map[e]->elms[i];
3571
3572           for (j = indx; insert && j < (int) expr_hash_table.n_elems; j++, insert >>= 1)
3573             if ((insert & 1) != 0 && index_map[j]->reaching_reg != NULL_RTX)
3574               {
3575                 struct expr *expr = index_map[j];
3576                 struct occr *occr;
3577
3578                 /* Now look at each deleted occurrence of this expression.  */
3579                 for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
3580                   {
3581                     if (! occr->deleted_p)
3582                       continue;
3583
3584                     /* Insert this expression on this edge if it would
3585                        reach the deleted occurrence in BB.  */
3586                     if (!TEST_BIT (inserted[e], j))
3587                       {
3588                         rtx insn;
3589                         edge eg = INDEX_EDGE (edge_list, e);
3590
3591                         /* We can't insert anything on an abnormal and
3592                            critical edge, so we insert the insn at the end of
3593                            the previous block. There are several alternatives
3594                            detailed in Morgans book P277 (sec 10.5) for
3595                            handling this situation.  This one is easiest for
3596                            now.  */
3597
3598                         if (eg->flags & EDGE_ABNORMAL)
3599                           insert_insn_end_basic_block (index_map[j], bb, 0);
3600                         else
3601                           {
3602                             insn = process_insert_insn (index_map[j]);
3603                             insert_insn_on_edge (insn, eg);
3604                           }
3605
3606                         if (dump_file)
3607                           {
3608                             fprintf (dump_file, "PRE: edge (%d,%d), ",
3609                                      bb->index,
3610                                      INDEX_EDGE_SUCC_BB (edge_list, e)->index);
3611                             fprintf (dump_file, "copy expression %d\n",
3612                                      expr->bitmap_index);
3613                           }
3614
3615                         update_ld_motion_stores (expr);
3616                         SET_BIT (inserted[e], j);
3617                         did_insert = 1;
3618                         gcse_create_count++;
3619                       }
3620                   }
3621               }
3622         }
3623     }
3624
3625   sbitmap_vector_free (inserted);
3626   return did_insert;
3627 }
3628
3629 /* Copy the result of EXPR->EXPR generated by INSN to EXPR->REACHING_REG.
3630    Given "old_reg <- expr" (INSN), instead of adding after it
3631      reaching_reg <- old_reg
3632    it's better to do the following:
3633      reaching_reg <- expr
3634      old_reg      <- reaching_reg
3635    because this way copy propagation can discover additional PRE
3636    opportunities.  But if this fails, we try the old way.
3637    When "expr" is a store, i.e.
3638    given "MEM <- old_reg", instead of adding after it
3639      reaching_reg <- old_reg
3640    it's better to add it before as follows:
3641      reaching_reg <- old_reg
3642      MEM          <- reaching_reg.  */
3643
3644 static void
3645 pre_insert_copy_insn (struct expr *expr, rtx insn)
3646 {
3647   rtx reg = expr->reaching_reg;
3648   int regno = REGNO (reg);
3649   int indx = expr->bitmap_index;
3650   rtx pat = PATTERN (insn);
3651   rtx set, first_set, new_insn;
3652   rtx old_reg;
3653   int i;
3654
3655   /* This block matches the logic in hash_scan_insn.  */
3656   switch (GET_CODE (pat))
3657     {
3658     case SET:
3659       set = pat;
3660       break;
3661
3662     case PARALLEL:
3663       /* Search through the parallel looking for the set whose
3664          source was the expression that we're interested in.  */
3665       first_set = NULL_RTX;
3666       set = NULL_RTX;
3667       for (i = 0; i < XVECLEN (pat, 0); i++)
3668         {
3669           rtx x = XVECEXP (pat, 0, i);
3670           if (GET_CODE (x) == SET)
3671             {
3672               /* If the source was a REG_EQUAL or REG_EQUIV note, we
3673                  may not find an equivalent expression, but in this
3674                  case the PARALLEL will have a single set.  */
3675               if (first_set == NULL_RTX)
3676                 first_set = x;
3677               if (expr_equiv_p (SET_SRC (x), expr->expr))
3678                 {
3679                   set = x;
3680                   break;
3681                 }
3682             }
3683         }
3684
3685       gcc_assert (first_set);
3686       if (set == NULL_RTX)
3687         set = first_set;
3688       break;
3689
3690     default:
3691       gcc_unreachable ();
3692     }
3693
3694   if (REG_P (SET_DEST (set)))
3695     {
3696       old_reg = SET_DEST (set);
3697       /* Check if we can modify the set destination in the original insn.  */
3698       if (validate_change (insn, &SET_DEST (set), reg, 0))
3699         {
3700           new_insn = gen_move_insn (old_reg, reg);
3701           new_insn = emit_insn_after (new_insn, insn);
3702         }
3703       else
3704         {
3705           new_insn = gen_move_insn (reg, old_reg);
3706           new_insn = emit_insn_after (new_insn, insn);
3707         }
3708     }
3709   else /* This is possible only in case of a store to memory.  */
3710     {
3711       old_reg = SET_SRC (set);
3712       new_insn = gen_move_insn (reg, old_reg);
3713
3714       /* Check if we can modify the set source in the original insn.  */
3715       if (validate_change (insn, &SET_SRC (set), reg, 0))
3716         new_insn = emit_insn_before (new_insn, insn);
3717       else
3718         new_insn = emit_insn_after (new_insn, insn);
3719     }
3720
3721   gcse_create_count++;
3722
3723   if (dump_file)
3724     fprintf (dump_file,
3725              "PRE: bb %d, insn %d, copy expression %d in insn %d to reg %d\n",
3726               BLOCK_NUM (insn), INSN_UID (new_insn), indx,
3727               INSN_UID (insn), regno);
3728 }
3729
3730 /* Copy available expressions that reach the redundant expression
3731    to `reaching_reg'.  */
3732
3733 static void
3734 pre_insert_copies (void)
3735 {
3736   unsigned int i, added_copy;
3737   struct expr *expr;
3738   struct occr *occr;
3739   struct occr *avail;
3740
3741   /* For each available expression in the table, copy the result to
3742      `reaching_reg' if the expression reaches a deleted one.
3743
3744      ??? The current algorithm is rather brute force.
3745      Need to do some profiling.  */
3746
3747   for (i = 0; i < expr_hash_table.size; i++)
3748     for (expr = expr_hash_table.table[i]; expr != NULL; expr = expr->next_same_hash)
3749       {
3750         /* If the basic block isn't reachable, PPOUT will be TRUE.  However,
3751            we don't want to insert a copy here because the expression may not
3752            really be redundant.  So only insert an insn if the expression was
3753            deleted.  This test also avoids further processing if the
3754            expression wasn't deleted anywhere.  */
3755         if (expr->reaching_reg == NULL)
3756           continue;
3757
3758         /* Set when we add a copy for that expression.  */
3759         added_copy = 0;
3760
3761         for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
3762           {
3763             if (! occr->deleted_p)
3764               continue;
3765
3766             for (avail = expr->avail_occr; avail != NULL; avail = avail->next)
3767               {
3768                 rtx insn = avail->insn;
3769
3770                 /* No need to handle this one if handled already.  */
3771                 if (avail->copied_p)
3772                   continue;
3773
3774                 /* Don't handle this one if it's a redundant one.  */
3775                 if (INSN_DELETED_P (insn))
3776                   continue;
3777
3778                 /* Or if the expression doesn't reach the deleted one.  */
3779                 if (! pre_expr_reaches_here_p (BLOCK_FOR_INSN (avail->insn),
3780                                                expr,
3781                                                BLOCK_FOR_INSN (occr->insn)))
3782                   continue;
3783
3784                 added_copy = 1;
3785
3786                 /* Copy the result of avail to reaching_reg.  */
3787                 pre_insert_copy_insn (expr, insn);
3788                 avail->copied_p = 1;
3789               }
3790           }
3791
3792           if (added_copy)
3793             update_ld_motion_stores (expr);
3794       }
3795 }
3796
3797 /* Emit move from SRC to DEST noting the equivalence with expression computed
3798    in INSN.  */
3799 static rtx
3800 gcse_emit_move_after (rtx src, rtx dest, rtx insn)
3801 {
3802   rtx new_rtx;
3803   rtx set = single_set (insn), set2;
3804   rtx note;
3805   rtx eqv;
3806
3807   /* This should never fail since we're creating a reg->reg copy
3808      we've verified to be valid.  */
3809
3810   new_rtx = emit_insn_after (gen_move_insn (dest, src), insn);
3811
3812   /* Note the equivalence for local CSE pass.  */
3813   set2 = single_set (new_rtx);
3814   if (!set2 || !rtx_equal_p (SET_DEST (set2), dest))
3815     return new_rtx;
3816   if ((note = find_reg_equal_equiv_note (insn)))
3817     eqv = XEXP (note, 0);
3818   else
3819     eqv = SET_SRC (set);
3820
3821   set_unique_reg_note (new_rtx, REG_EQUAL, copy_insn_1 (eqv));
3822
3823   return new_rtx;
3824 }
3825
3826 /* Delete redundant computations.
3827    Deletion is done by changing the insn to copy the `reaching_reg' of
3828    the expression into the result of the SET.  It is left to later passes
3829    (cprop, cse2, flow, combine, regmove) to propagate the copy or eliminate it.
3830
3831    Returns nonzero if a change is made.  */
3832
3833 static int
3834 pre_delete (void)
3835 {
3836   unsigned int i;
3837   int changed;
3838   struct expr *expr;
3839   struct occr *occr;
3840
3841   changed = 0;
3842   for (i = 0; i < expr_hash_table.size; i++)
3843     for (expr = expr_hash_table.table[i];
3844          expr != NULL;
3845          expr = expr->next_same_hash)
3846       {
3847         int indx = expr->bitmap_index;
3848
3849         /* We only need to search antic_occr since we require
3850            ANTLOC != 0.  */
3851
3852         for (occr = expr->antic_occr; occr != NULL; occr = occr->next)
3853           {
3854             rtx insn = occr->insn;
3855             rtx set;
3856             basic_block bb = BLOCK_FOR_INSN (insn);
3857
3858             /* We only delete insns that have a single_set.  */
3859             if (TEST_BIT (pre_delete_map[bb->index], indx)
3860                 && (set = single_set (insn)) != 0
3861                 && dbg_cnt (pre_insn))
3862               {
3863                 /* Create a pseudo-reg to store the result of reaching
3864                    expressions into.  Get the mode for the new pseudo from
3865                    the mode of the original destination pseudo.  */
3866                 if (expr->reaching_reg == NULL)
3867                   expr->reaching_reg = gen_reg_rtx_and_attrs (SET_DEST (set));
3868
3869                 gcse_emit_move_after (expr->reaching_reg, SET_DEST (set), insn);
3870                 delete_insn (insn);
3871                 occr->deleted_p = 1;
3872                 changed = 1;
3873                 gcse_subst_count++;
3874
3875                 if (dump_file)
3876                   {
3877                     fprintf (dump_file,
3878                              "PRE: redundant insn %d (expression %d) in ",
3879                                INSN_UID (insn), indx);
3880                     fprintf (dump_file, "bb %d, reaching reg is %d\n",
3881                              bb->index, REGNO (expr->reaching_reg));
3882                   }
3883               }
3884           }
3885       }
3886
3887   return changed;
3888 }
3889
3890 /* Perform GCSE optimizations using PRE.
3891    This is called by one_pre_gcse_pass after all the dataflow analysis
3892    has been done.
3893
3894    This is based on the original Morel-Renvoise paper Fred Chow's thesis, and
3895    lazy code motion from Knoop, Ruthing and Steffen as described in Advanced
3896    Compiler Design and Implementation.
3897
3898    ??? A new pseudo reg is created to hold the reaching expression.  The nice
3899    thing about the classical approach is that it would try to use an existing
3900    reg.  If the register can't be adequately optimized [i.e. we introduce
3901    reload problems], one could add a pass here to propagate the new register
3902    through the block.
3903
3904    ??? We don't handle single sets in PARALLELs because we're [currently] not
3905    able to copy the rest of the parallel when we insert copies to create full
3906    redundancies from partial redundancies.  However, there's no reason why we
3907    can't handle PARALLELs in the cases where there are no partial
3908    redundancies.  */
3909
3910 static int
3911 pre_gcse (void)
3912 {
3913   unsigned int i;
3914   int did_insert, changed;
3915   struct expr **index_map;
3916   struct expr *expr;
3917
3918   /* Compute a mapping from expression number (`bitmap_index') to
3919      hash table entry.  */
3920
3921   index_map = XCNEWVEC (struct expr *, expr_hash_table.n_elems);
3922   for (i = 0; i < expr_hash_table.size; i++)
3923     for (expr = expr_hash_table.table[i]; expr != NULL; expr = expr->next_same_hash)
3924       index_map[expr->bitmap_index] = expr;
3925
3926   /* Delete the redundant insns first so that
3927      - we know what register to use for the new insns and for the other
3928        ones with reaching expressions
3929      - we know which insns are redundant when we go to create copies  */
3930
3931   changed = pre_delete ();
3932   did_insert = pre_edge_insert (edge_list, index_map);
3933
3934   /* In other places with reaching expressions, copy the expression to the
3935      specially allocated pseudo-reg that reaches the redundant expr.  */
3936   pre_insert_copies ();
3937   if (did_insert)
3938     {
3939       commit_edge_insertions ();
3940       changed = 1;
3941     }
3942
3943   free (index_map);
3944   return changed;
3945 }
3946
3947 /* Top level routine to perform one PRE GCSE pass.
3948
3949    Return nonzero if a change was made.  */
3950
3951 static int
3952 one_pre_gcse_pass (void)
3953 {
3954   int changed = 0;
3955
3956   gcse_subst_count = 0;
3957   gcse_create_count = 0;
3958
3959   /* Return if there's nothing to do, or it is too expensive.  */
3960   if (n_basic_blocks <= NUM_FIXED_BLOCKS + 1
3961       || is_too_expensive (_("PRE disabled")))
3962     return 0;
3963
3964   /* We need alias.  */
3965   init_alias_analysis ();
3966
3967   bytes_used = 0;
3968   gcc_obstack_init (&gcse_obstack);
3969   alloc_gcse_mem ();
3970
3971   alloc_hash_table (get_max_uid (), &expr_hash_table, 0);
3972   add_noreturn_fake_exit_edges ();
3973   if (flag_gcse_lm)
3974     compute_ld_motion_mems ();
3975
3976   compute_hash_table (&expr_hash_table);
3977   trim_ld_motion_mems ();
3978   if (dump_file)
3979     dump_hash_table (dump_file, "Expression", &expr_hash_table);
3980
3981   if (expr_hash_table.n_elems > 0)
3982     {
3983       alloc_pre_mem (last_basic_block, expr_hash_table.n_elems);
3984       compute_pre_data ();
3985       changed |= pre_gcse ();
3986       free_edge_list (edge_list);
3987       free_pre_mem ();
3988     }
3989
3990   free_ldst_mems ();
3991   remove_fake_exit_edges ();
3992   free_hash_table (&expr_hash_table);
3993
3994   free_gcse_mem ();
3995   obstack_free (&gcse_obstack, NULL);
3996
3997   /* We are finished with alias.  */
3998   end_alias_analysis ();
3999
4000   if (dump_file)
4001     {
4002       fprintf (dump_file, "PRE GCSE of %s, %d basic blocks, %d bytes needed, ",
4003                current_function_name (), n_basic_blocks, bytes_used);
4004       fprintf (dump_file, "%d substs, %d insns created\n",
4005                gcse_subst_count, gcse_create_count);
4006     }
4007
4008   return changed;
4009 }
4010 \f
4011 /* If X contains any LABEL_REF's, add REG_LABEL_OPERAND notes for them
4012    to INSN.  If such notes are added to an insn which references a
4013    CODE_LABEL, the LABEL_NUSES count is incremented.  We have to add
4014    that note, because the following loop optimization pass requires
4015    them.  */
4016
4017 /* ??? If there was a jump optimization pass after gcse and before loop,
4018    then we would not need to do this here, because jump would add the
4019    necessary REG_LABEL_OPERAND and REG_LABEL_TARGET notes.  */
4020
4021 static void
4022 add_label_notes (rtx x, rtx insn)
4023 {
4024   enum rtx_code code = GET_CODE (x);
4025   int i, j;
4026   const char *fmt;
4027
4028   if (code == LABEL_REF && !LABEL_REF_NONLOCAL_P (x))
4029     {
4030       /* This code used to ignore labels that referred to dispatch tables to
4031          avoid flow generating (slightly) worse code.
4032
4033          We no longer ignore such label references (see LABEL_REF handling in
4034          mark_jump_label for additional information).  */
4035
4036       /* There's no reason for current users to emit jump-insns with
4037          such a LABEL_REF, so we don't have to handle REG_LABEL_TARGET
4038          notes.  */
4039       gcc_assert (!JUMP_P (insn));
4040       add_reg_note (insn, REG_LABEL_OPERAND, XEXP (x, 0));
4041
4042       if (LABEL_P (XEXP (x, 0)))
4043         LABEL_NUSES (XEXP (x, 0))++;
4044
4045       return;
4046     }
4047
4048   for (i = GET_RTX_LENGTH (code) - 1, fmt = GET_RTX_FORMAT (code); i >= 0; i--)
4049     {
4050       if (fmt[i] == 'e')
4051         add_label_notes (XEXP (x, i), insn);
4052       else if (fmt[i] == 'E')
4053         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
4054           add_label_notes (XVECEXP (x, i, j), insn);
4055     }
4056 }
4057
4058 /* Compute transparent outgoing information for each block.
4059
4060    An expression is transparent to an edge unless it is killed by
4061    the edge itself.  This can only happen with abnormal control flow,
4062    when the edge is traversed through a call.  This happens with
4063    non-local labels and exceptions.
4064
4065    This would not be necessary if we split the edge.  While this is
4066    normally impossible for abnormal critical edges, with some effort
4067    it should be possible with exception handling, since we still have
4068    control over which handler should be invoked.  But due to increased
4069    EH table sizes, this may not be worthwhile.  */
4070
4071 static void
4072 compute_transpout (void)
4073 {
4074   basic_block bb;
4075   unsigned int i;
4076   struct expr *expr;
4077
4078   sbitmap_vector_ones (transpout, last_basic_block);
4079
4080   FOR_EACH_BB (bb)
4081     {
4082       /* Note that flow inserted a nop at the end of basic blocks that
4083          end in call instructions for reasons other than abnormal
4084          control flow.  */
4085       if (! CALL_P (BB_END (bb)))
4086         continue;
4087
4088       for (i = 0; i < expr_hash_table.size; i++)
4089         for (expr = expr_hash_table.table[i]; expr ; expr = expr->next_same_hash)
4090           if (MEM_P (expr->expr))
4091             {
4092               if (GET_CODE (XEXP (expr->expr, 0)) == SYMBOL_REF
4093                   && CONSTANT_POOL_ADDRESS_P (XEXP (expr->expr, 0)))
4094                 continue;
4095
4096               /* ??? Optimally, we would use interprocedural alias
4097                  analysis to determine if this mem is actually killed
4098                  by this call.  */
4099               RESET_BIT (transpout[bb->index], expr->bitmap_index);
4100             }
4101     }
4102 }
4103
4104 /* Code Hoisting variables and subroutines.  */
4105
4106 /* Very busy expressions.  */
4107 static sbitmap *hoist_vbein;
4108 static sbitmap *hoist_vbeout;
4109
4110 /* Hoistable expressions.  */
4111 static sbitmap *hoist_exprs;
4112
4113 /* ??? We could compute post dominators and run this algorithm in
4114    reverse to perform tail merging, doing so would probably be
4115    more effective than the tail merging code in jump.c.
4116
4117    It's unclear if tail merging could be run in parallel with
4118    code hoisting.  It would be nice.  */
4119
4120 /* Allocate vars used for code hoisting analysis.  */
4121
4122 static void
4123 alloc_code_hoist_mem (int n_blocks, int n_exprs)
4124 {
4125   antloc = sbitmap_vector_alloc (n_blocks, n_exprs);
4126   transp = sbitmap_vector_alloc (n_blocks, n_exprs);
4127   comp = sbitmap_vector_alloc (n_blocks, n_exprs);
4128
4129   hoist_vbein = sbitmap_vector_alloc (n_blocks, n_exprs);
4130   hoist_vbeout = sbitmap_vector_alloc (n_blocks, n_exprs);
4131   hoist_exprs = sbitmap_vector_alloc (n_blocks, n_exprs);
4132   transpout = sbitmap_vector_alloc (n_blocks, n_exprs);
4133 }
4134
4135 /* Free vars used for code hoisting analysis.  */
4136
4137 static void
4138 free_code_hoist_mem (void)
4139 {
4140   sbitmap_vector_free (antloc);
4141   sbitmap_vector_free (transp);
4142   sbitmap_vector_free (comp);
4143
4144   sbitmap_vector_free (hoist_vbein);
4145   sbitmap_vector_free (hoist_vbeout);
4146   sbitmap_vector_free (hoist_exprs);
4147   sbitmap_vector_free (transpout);
4148
4149   free_dominance_info (CDI_DOMINATORS);
4150 }
4151
4152 /* Compute the very busy expressions at entry/exit from each block.
4153
4154    An expression is very busy if all paths from a given point
4155    compute the expression.  */
4156
4157 static void
4158 compute_code_hoist_vbeinout (void)
4159 {
4160   int changed, passes;
4161   basic_block bb;
4162
4163   sbitmap_vector_zero (hoist_vbeout, last_basic_block);
4164   sbitmap_vector_zero (hoist_vbein, last_basic_block);
4165
4166   passes = 0;
4167   changed = 1;
4168
4169   while (changed)
4170     {
4171       changed = 0;
4172
4173       /* We scan the blocks in the reverse order to speed up
4174          the convergence.  */
4175       FOR_EACH_BB_REVERSE (bb)
4176         {
4177           if (bb->next_bb != EXIT_BLOCK_PTR)
4178             sbitmap_intersection_of_succs (hoist_vbeout[bb->index],
4179                                            hoist_vbein, bb->index);
4180
4181           changed |= sbitmap_a_or_b_and_c_cg (hoist_vbein[bb->index],
4182                                               antloc[bb->index],
4183                                               hoist_vbeout[bb->index],
4184                                               transp[bb->index]);
4185         }
4186
4187       passes++;
4188     }
4189
4190   if (dump_file)
4191     fprintf (dump_file, "hoisting vbeinout computation: %d passes\n", passes);
4192 }
4193
4194 /* Top level routine to do the dataflow analysis needed by code hoisting.  */
4195
4196 static void
4197 compute_code_hoist_data (void)
4198 {
4199   compute_local_properties (transp, comp, antloc, &expr_hash_table);
4200   compute_transpout ();
4201   compute_code_hoist_vbeinout ();
4202   calculate_dominance_info (CDI_DOMINATORS);
4203   if (dump_file)
4204     fprintf (dump_file, "\n");
4205 }
4206
4207 /* Determine if the expression identified by EXPR_INDEX would
4208    reach BB unimpared if it was placed at the end of EXPR_BB.
4209
4210    It's unclear exactly what Muchnick meant by "unimpared".  It seems
4211    to me that the expression must either be computed or transparent in
4212    *every* block in the path(s) from EXPR_BB to BB.  Any other definition
4213    would allow the expression to be hoisted out of loops, even if
4214    the expression wasn't a loop invariant.
4215
4216    Contrast this to reachability for PRE where an expression is
4217    considered reachable if *any* path reaches instead of *all*
4218    paths.  */
4219
4220 static int
4221 hoist_expr_reaches_here_p (basic_block expr_bb, int expr_index, basic_block bb, char *visited)
4222 {
4223   edge pred;
4224   edge_iterator ei;
4225   int visited_allocated_locally = 0;
4226
4227
4228   if (visited == NULL)
4229     {
4230       visited_allocated_locally = 1;
4231       visited = XCNEWVEC (char, last_basic_block);
4232     }
4233
4234   FOR_EACH_EDGE (pred, ei, bb->preds)
4235     {
4236       basic_block pred_bb = pred->src;
4237
4238       if (pred->src == ENTRY_BLOCK_PTR)
4239         break;
4240       else if (pred_bb == expr_bb)
4241         continue;
4242       else if (visited[pred_bb->index])
4243         continue;
4244
4245       /* Does this predecessor generate this expression?  */
4246       else if (TEST_BIT (comp[pred_bb->index], expr_index))
4247         break;
4248       else if (! TEST_BIT (transp[pred_bb->index], expr_index))
4249         break;
4250
4251       /* Not killed.  */
4252       else
4253         {
4254           visited[pred_bb->index] = 1;
4255           if (! hoist_expr_reaches_here_p (expr_bb, expr_index,
4256                                            pred_bb, visited))
4257             break;
4258         }
4259     }
4260   if (visited_allocated_locally)
4261     free (visited);
4262
4263   return (pred == NULL);
4264 }
4265 \f
4266 /* Actually perform code hoisting.  */
4267
4268 static int
4269 hoist_code (void)
4270 {
4271   basic_block bb, dominated;
4272   VEC (basic_block, heap) *domby;
4273   unsigned int i,j;
4274   struct expr **index_map;
4275   struct expr *expr;
4276   int changed = 0;
4277
4278   sbitmap_vector_zero (hoist_exprs, last_basic_block);
4279
4280   /* Compute a mapping from expression number (`bitmap_index') to
4281      hash table entry.  */
4282
4283   index_map = XCNEWVEC (struct expr *, expr_hash_table.n_elems);
4284   for (i = 0; i < expr_hash_table.size; i++)
4285     for (expr = expr_hash_table.table[i]; expr != NULL; expr = expr->next_same_hash)
4286       index_map[expr->bitmap_index] = expr;
4287
4288   /* Walk over each basic block looking for potentially hoistable
4289      expressions, nothing gets hoisted from the entry block.  */
4290   FOR_EACH_BB (bb)
4291     {
4292       int found = 0;
4293       int insn_inserted_p;
4294
4295       domby = get_dominated_by (CDI_DOMINATORS, bb);
4296       /* Examine each expression that is very busy at the exit of this
4297          block.  These are the potentially hoistable expressions.  */
4298       for (i = 0; i < hoist_vbeout[bb->index]->n_bits; i++)
4299         {
4300           int hoistable = 0;
4301
4302           if (TEST_BIT (hoist_vbeout[bb->index], i)
4303               && TEST_BIT (transpout[bb->index], i))
4304             {
4305               /* We've found a potentially hoistable expression, now
4306                  we look at every block BB dominates to see if it
4307                  computes the expression.  */
4308               for (j = 0; VEC_iterate (basic_block, domby, j, dominated); j++)
4309                 {
4310                   /* Ignore self dominance.  */
4311                   if (bb == dominated)
4312                     continue;
4313                   /* We've found a dominated block, now see if it computes
4314                      the busy expression and whether or not moving that
4315                      expression to the "beginning" of that block is safe.  */
4316                   if (!TEST_BIT (antloc[dominated->index], i))
4317                     continue;
4318
4319                   /* Note if the expression would reach the dominated block
4320                      unimpared if it was placed at the end of BB.
4321
4322                      Keep track of how many times this expression is hoistable
4323                      from a dominated block into BB.  */
4324                   if (hoist_expr_reaches_here_p (bb, i, dominated, NULL))
4325                     hoistable++;
4326                 }
4327
4328               /* If we found more than one hoistable occurrence of this
4329                  expression, then note it in the bitmap of expressions to
4330                  hoist.  It makes no sense to hoist things which are computed
4331                  in only one BB, and doing so tends to pessimize register
4332                  allocation.  One could increase this value to try harder
4333                  to avoid any possible code expansion due to register
4334                  allocation issues; however experiments have shown that
4335                  the vast majority of hoistable expressions are only movable
4336                  from two successors, so raising this threshold is likely
4337                  to nullify any benefit we get from code hoisting.  */
4338               if (hoistable > 1)
4339                 {
4340                   SET_BIT (hoist_exprs[bb->index], i);
4341                   found = 1;
4342                 }
4343             }
4344         }
4345       /* If we found nothing to hoist, then quit now.  */
4346       if (! found)
4347         {
4348           VEC_free (basic_block, heap, domby);
4349           continue;
4350         }
4351
4352       /* Loop over all the hoistable expressions.  */
4353       for (i = 0; i < hoist_exprs[bb->index]->n_bits; i++)
4354         {
4355           /* We want to insert the expression into BB only once, so
4356              note when we've inserted it.  */
4357           insn_inserted_p = 0;
4358
4359           /* These tests should be the same as the tests above.  */
4360           if (TEST_BIT (hoist_exprs[bb->index], i))
4361             {
4362               /* We've found a potentially hoistable expression, now
4363                  we look at every block BB dominates to see if it
4364                  computes the expression.  */
4365               for (j = 0; VEC_iterate (basic_block, domby, j, dominated); j++)
4366                 {
4367                   /* Ignore self dominance.  */
4368                   if (bb == dominated)
4369                     continue;
4370
4371                   /* We've found a dominated block, now see if it computes
4372                      the busy expression and whether or not moving that
4373                      expression to the "beginning" of that block is safe.  */
4374                   if (!TEST_BIT (antloc[dominated->index], i))
4375                     continue;
4376
4377                   /* The expression is computed in the dominated block and
4378                      it would be safe to compute it at the start of the
4379                      dominated block.  Now we have to determine if the
4380                      expression would reach the dominated block if it was
4381                      placed at the end of BB.  */
4382                   if (hoist_expr_reaches_here_p (bb, i, dominated, NULL))
4383                     {
4384                       struct expr *expr = index_map[i];
4385                       struct occr *occr = expr->antic_occr;
4386                       rtx insn;
4387                       rtx set;
4388
4389                       /* Find the right occurrence of this expression.  */
4390                       while (BLOCK_FOR_INSN (occr->insn) != dominated && occr)
4391                         occr = occr->next;
4392
4393                       gcc_assert (occr);
4394                       insn = occr->insn;
4395                       set = single_set (insn);
4396                       gcc_assert (set);
4397
4398                       /* Create a pseudo-reg to store the result of reaching
4399                          expressions into.  Get the mode for the new pseudo
4400                          from the mode of the original destination pseudo.  */
4401                       if (expr->reaching_reg == NULL)
4402                         expr->reaching_reg
4403                           = gen_reg_rtx_and_attrs (SET_DEST (set));
4404
4405                       gcse_emit_move_after (expr->reaching_reg, SET_DEST (set), insn);
4406                       delete_insn (insn);
4407                       occr->deleted_p = 1;
4408                       changed = 1;
4409                       gcse_subst_count++;
4410
4411                       if (!insn_inserted_p)
4412                         {
4413                           insert_insn_end_basic_block (index_map[i], bb, 0);
4414                           insn_inserted_p = 1;
4415                         }
4416                     }
4417                 }
4418             }
4419         }
4420       VEC_free (basic_block, heap, domby);
4421     }
4422
4423   free (index_map);
4424
4425   return changed;
4426 }
4427
4428 /* Top level routine to perform one code hoisting (aka unification) pass
4429
4430    Return nonzero if a change was made.  */
4431
4432 static int
4433 one_code_hoisting_pass (void)
4434 {
4435   int changed = 0;
4436
4437   gcse_subst_count = 0;
4438   gcse_create_count = 0;
4439
4440   /* Return if there's nothing to do, or it is too expensive.  */
4441   if (n_basic_blocks <= NUM_FIXED_BLOCKS + 1
4442       || is_too_expensive (_("GCSE disabled")))
4443     return 0;
4444
4445   /* We need alias.  */
4446   init_alias_analysis ();
4447
4448   bytes_used = 0;
4449   gcc_obstack_init (&gcse_obstack);
4450   alloc_gcse_mem ();
4451
4452   alloc_hash_table (get_max_uid (), &expr_hash_table, 0);
4453   compute_hash_table (&expr_hash_table);
4454   if (dump_file)
4455     dump_hash_table (dump_file, "Code Hosting Expressions", &expr_hash_table);
4456
4457   if (expr_hash_table.n_elems > 0)
4458     {
4459       alloc_code_hoist_mem (last_basic_block, expr_hash_table.n_elems);
4460       compute_code_hoist_data ();
4461       changed = hoist_code ();
4462       free_code_hoist_mem ();
4463     }
4464
4465   free_hash_table (&expr_hash_table);
4466   free_gcse_mem ();
4467   obstack_free (&gcse_obstack, NULL);
4468
4469   /* We are finished with alias.  */
4470   end_alias_analysis ();
4471
4472   if (dump_file)
4473     {
4474       fprintf (dump_file, "HOIST of %s, %d basic blocks, %d bytes needed, ",
4475                current_function_name (), n_basic_blocks, bytes_used);
4476       fprintf (dump_file, "%d substs, %d insns created\n",
4477                gcse_subst_count, gcse_create_count);
4478     }
4479
4480   return changed;
4481 }
4482 \f
4483 /*  Here we provide the things required to do store motion towards
4484     the exit. In order for this to be effective, gcse also needed to
4485     be taught how to move a load when it is kill only by a store to itself.
4486
4487             int i;
4488             float a[10];
4489
4490             void foo(float scale)
4491             {
4492               for (i=0; i<10; i++)
4493                 a[i] *= scale;
4494             }
4495
4496     'i' is both loaded and stored to in the loop. Normally, gcse cannot move
4497     the load out since its live around the loop, and stored at the bottom
4498     of the loop.
4499
4500       The 'Load Motion' referred to and implemented in this file is
4501     an enhancement to gcse which when using edge based lcm, recognizes
4502     this situation and allows gcse to move the load out of the loop.
4503
4504       Once gcse has hoisted the load, store motion can then push this
4505     load towards the exit, and we end up with no loads or stores of 'i'
4506     in the loop.  */
4507
4508 static hashval_t
4509 pre_ldst_expr_hash (const void *p)
4510 {
4511   int do_not_record_p = 0;
4512   const struct ls_expr *const x = (const struct ls_expr *) p;
4513   return hash_rtx (x->pattern, GET_MODE (x->pattern), &do_not_record_p, NULL, false);
4514 }
4515
4516 static int
4517 pre_ldst_expr_eq (const void *p1, const void *p2)
4518 {
4519   const struct ls_expr *const ptr1 = (const struct ls_expr *) p1,
4520     *const ptr2 = (const struct ls_expr *) p2;
4521   return expr_equiv_p (ptr1->pattern, ptr2->pattern);
4522 }
4523
4524 /* This will search the ldst list for a matching expression. If it
4525    doesn't find one, we create one and initialize it.  */
4526
4527 static struct ls_expr *
4528 ldst_entry (rtx x)
4529 {
4530   int do_not_record_p = 0;
4531   struct ls_expr * ptr;
4532   unsigned int hash;
4533   void **slot;
4534   struct ls_expr e;
4535
4536   hash = hash_rtx (x, GET_MODE (x), &do_not_record_p,
4537                    NULL,  /*have_reg_qty=*/false);
4538
4539   e.pattern = x;
4540   slot = htab_find_slot_with_hash (pre_ldst_table, &e, hash, INSERT);
4541   if (*slot)
4542     return (struct ls_expr *)*slot;
4543
4544   ptr = XNEW (struct ls_expr);
4545
4546   ptr->next         = pre_ldst_mems;
4547   ptr->expr         = NULL;
4548   ptr->pattern      = x;
4549   ptr->pattern_regs = NULL_RTX;
4550   ptr->loads        = NULL_RTX;
4551   ptr->stores       = NULL_RTX;
4552   ptr->reaching_reg = NULL_RTX;
4553   ptr->invalid      = 0;
4554   ptr->index        = 0;
4555   ptr->hash_index   = hash;
4556   pre_ldst_mems     = ptr;
4557   *slot = ptr;
4558
4559   return ptr;
4560 }
4561
4562 /* Free up an individual ldst entry.  */
4563
4564 static void
4565 free_ldst_entry (struct ls_expr * ptr)
4566 {
4567   free_INSN_LIST_list (& ptr->loads);
4568   free_INSN_LIST_list (& ptr->stores);
4569
4570   free (ptr);
4571 }
4572
4573 /* Free up all memory associated with the ldst list.  */
4574
4575 static void
4576 free_ldst_mems (void)
4577 {
4578   if (pre_ldst_table)
4579     htab_delete (pre_ldst_table);
4580   pre_ldst_table = NULL;
4581
4582   while (pre_ldst_mems)
4583     {
4584       struct ls_expr * tmp = pre_ldst_mems;
4585
4586       pre_ldst_mems = pre_ldst_mems->next;
4587
4588       free_ldst_entry (tmp);
4589     }
4590
4591   pre_ldst_mems = NULL;
4592 }
4593
4594 /* Dump debugging info about the ldst list.  */
4595
4596 static void
4597 print_ldst_list (FILE * file)
4598 {
4599   struct ls_expr * ptr;
4600
4601   fprintf (file, "LDST list: \n");
4602
4603   for (ptr = first_ls_expr (); ptr != NULL; ptr = next_ls_expr (ptr))
4604     {
4605       fprintf (file, "  Pattern (%3d): ", ptr->index);
4606
4607       print_rtl (file, ptr->pattern);
4608
4609       fprintf (file, "\n         Loads : ");
4610
4611       if (ptr->loads)
4612         print_rtl (file, ptr->loads);
4613       else
4614         fprintf (file, "(nil)");
4615
4616       fprintf (file, "\n        Stores : ");
4617
4618       if (ptr->stores)
4619         print_rtl (file, ptr->stores);
4620       else
4621         fprintf (file, "(nil)");
4622
4623       fprintf (file, "\n\n");
4624     }
4625
4626   fprintf (file, "\n");
4627 }
4628
4629 /* Returns 1 if X is in the list of ldst only expressions.  */
4630
4631 static struct ls_expr *
4632 find_rtx_in_ldst (rtx x)
4633 {
4634   struct ls_expr e;
4635   void **slot;
4636   if (!pre_ldst_table)
4637     return NULL;
4638   e.pattern = x;
4639   slot = htab_find_slot (pre_ldst_table, &e, NO_INSERT);
4640   if (!slot || ((struct ls_expr *)*slot)->invalid)
4641     return NULL;
4642   return (struct ls_expr *) *slot;
4643 }
4644
4645 /* Assign each element of the list of mems a monotonically increasing value.  */
4646
4647 static int
4648 enumerate_ldsts (void)
4649 {
4650   struct ls_expr * ptr;
4651   int n = 0;
4652
4653   for (ptr = pre_ldst_mems; ptr != NULL; ptr = ptr->next)
4654     ptr->index = n++;
4655
4656   return n;
4657 }
4658
4659 /* Return first item in the list.  */
4660
4661 static inline struct ls_expr *
4662 first_ls_expr (void)
4663 {
4664   return pre_ldst_mems;
4665 }
4666
4667 /* Return the next item in the list after the specified one.  */
4668
4669 static inline struct ls_expr *
4670 next_ls_expr (struct ls_expr * ptr)
4671 {
4672   return ptr->next;
4673 }
4674 \f
4675 /* Load Motion for loads which only kill themselves.  */
4676
4677 /* Return true if x is a simple MEM operation, with no registers or
4678    side effects. These are the types of loads we consider for the
4679    ld_motion list, otherwise we let the usual aliasing take care of it.  */
4680
4681 static int
4682 simple_mem (const_rtx x)
4683 {
4684   if (! MEM_P (x))
4685     return 0;
4686
4687   if (MEM_VOLATILE_P (x))
4688     return 0;
4689
4690   if (GET_MODE (x) == BLKmode)
4691     return 0;
4692
4693   /* If we are handling exceptions, we must be careful with memory references
4694      that may trap. If we are not, the behavior is undefined, so we may just
4695      continue.  */
4696   if (flag_non_call_exceptions && may_trap_p (x))
4697     return 0;
4698
4699   if (side_effects_p (x))
4700     return 0;
4701
4702   /* Do not consider function arguments passed on stack.  */
4703   if (reg_mentioned_p (stack_pointer_rtx, x))
4704     return 0;
4705
4706   if (flag_float_store && FLOAT_MODE_P (GET_MODE (x)))
4707     return 0;
4708
4709   return 1;
4710 }
4711
4712 /* Make sure there isn't a buried reference in this pattern anywhere.
4713    If there is, invalidate the entry for it since we're not capable
4714    of fixing it up just yet.. We have to be sure we know about ALL
4715    loads since the aliasing code will allow all entries in the
4716    ld_motion list to not-alias itself.  If we miss a load, we will get
4717    the wrong value since gcse might common it and we won't know to
4718    fix it up.  */
4719
4720 static void
4721 invalidate_any_buried_refs (rtx x)
4722 {
4723   const char * fmt;
4724   int i, j;
4725   struct ls_expr * ptr;
4726
4727   /* Invalidate it in the list.  */
4728   if (MEM_P (x) && simple_mem (x))
4729     {
4730       ptr = ldst_entry (x);
4731       ptr->invalid = 1;
4732     }
4733
4734   /* Recursively process the insn.  */
4735   fmt = GET_RTX_FORMAT (GET_CODE (x));
4736
4737   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0; i--)
4738     {
4739       if (fmt[i] == 'e')
4740         invalidate_any_buried_refs (XEXP (x, i));
4741       else if (fmt[i] == 'E')
4742         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
4743           invalidate_any_buried_refs (XVECEXP (x, i, j));
4744     }
4745 }
4746
4747 /* Find all the 'simple' MEMs which are used in LOADs and STORES.  Simple
4748    being defined as MEM loads and stores to symbols, with no side effects
4749    and no registers in the expression.  For a MEM destination, we also
4750    check that the insn is still valid if we replace the destination with a
4751    REG, as is done in update_ld_motion_stores.  If there are any uses/defs
4752    which don't match this criteria, they are invalidated and trimmed out
4753    later.  */
4754
4755 static void
4756 compute_ld_motion_mems (void)
4757 {
4758   struct ls_expr * ptr;
4759   basic_block bb;
4760   rtx insn;
4761
4762   pre_ldst_mems = NULL;
4763   pre_ldst_table = htab_create (13, pre_ldst_expr_hash,
4764                                 pre_ldst_expr_eq, NULL);
4765
4766   FOR_EACH_BB (bb)
4767     {
4768       FOR_BB_INSNS (bb, insn)
4769         {
4770           if (INSN_P (insn))
4771             {
4772               if (GET_CODE (PATTERN (insn)) == SET)
4773                 {
4774                   rtx src = SET_SRC (PATTERN (insn));
4775                   rtx dest = SET_DEST (PATTERN (insn));
4776
4777                   /* Check for a simple LOAD...  */
4778                   if (MEM_P (src) && simple_mem (src))
4779                     {
4780                       ptr = ldst_entry (src);
4781                       if (REG_P (dest))
4782                         ptr->loads = alloc_INSN_LIST (insn, ptr->loads);
4783                       else
4784                         ptr->invalid = 1;
4785                     }
4786                   else
4787                     {
4788                       /* Make sure there isn't a buried load somewhere.  */
4789                       invalidate_any_buried_refs (src);
4790                     }
4791
4792                   /* Check for stores. Don't worry about aliased ones, they
4793                      will block any movement we might do later. We only care
4794                      about this exact pattern since those are the only
4795                      circumstance that we will ignore the aliasing info.  */
4796                   if (MEM_P (dest) && simple_mem (dest))
4797                     {
4798                       ptr = ldst_entry (dest);
4799
4800                       if (! MEM_P (src)
4801                           && GET_CODE (src) != ASM_OPERANDS
4802                           /* Check for REG manually since want_to_gcse_p
4803                              returns 0 for all REGs.  */
4804                           && can_assign_to_reg_p (src))
4805                         ptr->stores = alloc_INSN_LIST (insn, ptr->stores);
4806                       else
4807                         ptr->invalid = 1;
4808                     }
4809                 }
4810               else
4811                 invalidate_any_buried_refs (PATTERN (insn));
4812             }
4813         }
4814     }
4815 }
4816
4817 /* Remove any references that have been either invalidated or are not in the
4818    expression list for pre gcse.  */
4819
4820 static void
4821 trim_ld_motion_mems (void)
4822 {
4823   struct ls_expr * * last = & pre_ldst_mems;
4824   struct ls_expr * ptr = pre_ldst_mems;
4825
4826   while (ptr != NULL)
4827     {
4828       struct expr * expr;
4829
4830       /* Delete if entry has been made invalid.  */
4831       if (! ptr->invalid)
4832         {
4833           /* Delete if we cannot find this mem in the expression list.  */
4834           unsigned int hash = ptr->hash_index % expr_hash_table.size;
4835
4836           for (expr = expr_hash_table.table[hash];
4837                expr != NULL;
4838                expr = expr->next_same_hash)
4839             if (expr_equiv_p (expr->expr, ptr->pattern))
4840               break;
4841         }
4842       else
4843         expr = (struct expr *) 0;
4844
4845       if (expr)
4846         {
4847           /* Set the expression field if we are keeping it.  */
4848           ptr->expr = expr;
4849           last = & ptr->next;
4850           ptr = ptr->next;
4851         }
4852       else
4853         {
4854           *last = ptr->next;
4855           htab_remove_elt_with_hash (pre_ldst_table, ptr, ptr->hash_index);
4856           free_ldst_entry (ptr);
4857           ptr = * last;
4858         }
4859     }
4860
4861   /* Show the world what we've found.  */
4862   if (dump_file && pre_ldst_mems != NULL)
4863     print_ldst_list (dump_file);
4864 }
4865
4866 /* This routine will take an expression which we are replacing with
4867    a reaching register, and update any stores that are needed if
4868    that expression is in the ld_motion list.  Stores are updated by
4869    copying their SRC to the reaching register, and then storing
4870    the reaching register into the store location. These keeps the
4871    correct value in the reaching register for the loads.  */
4872
4873 static void
4874 update_ld_motion_stores (struct expr * expr)
4875 {
4876   struct ls_expr * mem_ptr;
4877
4878   if ((mem_ptr = find_rtx_in_ldst (expr->expr)))
4879     {
4880       /* We can try to find just the REACHED stores, but is shouldn't
4881          matter to set the reaching reg everywhere...  some might be
4882          dead and should be eliminated later.  */
4883
4884       /* We replace (set mem expr) with (set reg expr) (set mem reg)
4885          where reg is the reaching reg used in the load.  We checked in
4886          compute_ld_motion_mems that we can replace (set mem expr) with
4887          (set reg expr) in that insn.  */
4888       rtx list = mem_ptr->stores;
4889
4890       for ( ; list != NULL_RTX; list = XEXP (list, 1))
4891         {
4892           rtx insn = XEXP (list, 0);
4893           rtx pat = PATTERN (insn);
4894           rtx src = SET_SRC (pat);
4895           rtx reg = expr->reaching_reg;
4896           rtx copy, new_rtx;
4897
4898           /* If we've already copied it, continue.  */
4899           if (expr->reaching_reg == src)
4900             continue;
4901
4902           if (dump_file)
4903             {
4904               fprintf (dump_file, "PRE:  store updated with reaching reg ");
4905               print_rtl (dump_file, expr->reaching_reg);
4906               fprintf (dump_file, ":\n  ");
4907               print_inline_rtx (dump_file, insn, 8);
4908               fprintf (dump_file, "\n");
4909             }
4910
4911           copy = gen_move_insn (reg, copy_rtx (SET_SRC (pat)));
4912           new_rtx = emit_insn_before (copy, insn);
4913           SET_SRC (pat) = reg;
4914           df_insn_rescan (insn);
4915
4916           /* un-recognize this pattern since it's probably different now.  */
4917           INSN_CODE (insn) = -1;
4918           gcse_create_count++;
4919         }
4920     }
4921 }
4922 \f
4923 /* Store motion code.  */
4924
4925 #define ANTIC_STORE_LIST(x)             ((x)->loads)
4926 #define AVAIL_STORE_LIST(x)             ((x)->stores)
4927 #define LAST_AVAIL_CHECK_FAILURE(x)     ((x)->reaching_reg)
4928
4929 /* This is used to communicate the target bitvector we want to use in the
4930    reg_set_info routine when called via the note_stores mechanism.  */
4931 static int * regvec;
4932
4933 /* And current insn, for the same routine.  */
4934 static rtx compute_store_table_current_insn;
4935
4936 /* Used in computing the reverse edge graph bit vectors.  */
4937 static sbitmap * st_antloc;
4938
4939 /* Global holding the number of store expressions we are dealing with.  */
4940 static int num_stores;
4941
4942 /* Checks to set if we need to mark a register set.  Called from
4943    note_stores.  */
4944
4945 static void
4946 reg_set_info (rtx dest, const_rtx setter ATTRIBUTE_UNUSED,
4947               void *data ATTRIBUTE_UNUSED)
4948 {
4949   if (GET_CODE (dest) == SUBREG)
4950     dest = SUBREG_REG (dest);
4951
4952   if (REG_P (dest))
4953     regvec[REGNO (dest)] = INSN_UID (compute_store_table_current_insn);
4954 }
4955
4956 /* Clear any mark that says that this insn sets dest.  Called from
4957    note_stores.  */
4958
4959 static void
4960 reg_clear_last_set (rtx dest, const_rtx setter ATTRIBUTE_UNUSED,
4961               void *data)
4962 {
4963   int *dead_vec = (int *) data;
4964
4965   if (GET_CODE (dest) == SUBREG)
4966     dest = SUBREG_REG (dest);
4967
4968   if (REG_P (dest) &&
4969       dead_vec[REGNO (dest)] == INSN_UID (compute_store_table_current_insn))
4970     dead_vec[REGNO (dest)] = 0;
4971 }
4972
4973 /* Return zero if some of the registers in list X are killed
4974    due to set of registers in bitmap REGS_SET.  */
4975
4976 static bool
4977 store_ops_ok (const_rtx x, int *regs_set)
4978 {
4979   const_rtx reg;
4980
4981   for (; x; x = XEXP (x, 1))
4982     {
4983       reg = XEXP (x, 0);
4984       if (regs_set[REGNO(reg)])
4985         return false;
4986     }
4987
4988   return true;
4989 }
4990
4991 /* Returns a list of registers mentioned in X.  */
4992 static rtx
4993 extract_mentioned_regs (rtx x)
4994 {
4995   return extract_mentioned_regs_helper (x, NULL_RTX);
4996 }
4997
4998 /* Helper for extract_mentioned_regs; ACCUM is used to accumulate used
4999    registers.  */
5000 static rtx
5001 extract_mentioned_regs_helper (rtx x, rtx accum)
5002 {
5003   int i;
5004   enum rtx_code code;
5005   const char * fmt;
5006
5007   /* Repeat is used to turn tail-recursion into iteration.  */
5008  repeat:
5009
5010   if (x == 0)
5011     return accum;
5012
5013   code = GET_CODE (x);
5014   switch (code)
5015     {
5016     case REG:
5017       return alloc_EXPR_LIST (0, x, accum);
5018
5019     case MEM:
5020       x = XEXP (x, 0);
5021       goto repeat;
5022
5023     case PRE_DEC:
5024     case PRE_INC:
5025     case PRE_MODIFY:
5026     case POST_DEC:
5027     case POST_INC:
5028     case POST_MODIFY:
5029       /* We do not run this function with arguments having side effects.  */
5030       gcc_unreachable ();
5031
5032     case PC:
5033     case CC0: /*FIXME*/
5034     case CONST:
5035     case CONST_INT:
5036     case CONST_DOUBLE:
5037     case CONST_FIXED:
5038     case CONST_VECTOR:
5039     case SYMBOL_REF:
5040     case LABEL_REF:
5041     case ADDR_VEC:
5042     case ADDR_DIFF_VEC:
5043       return accum;
5044
5045     default:
5046       break;
5047     }
5048
5049   i = GET_RTX_LENGTH (code) - 1;
5050   fmt = GET_RTX_FORMAT (code);
5051
5052   for (; i >= 0; i--)
5053     {
5054       if (fmt[i] == 'e')
5055         {
5056           rtx tem = XEXP (x, i);
5057
5058           /* If we are about to do the last recursive call
5059              needed at this level, change it into iteration.  */
5060           if (i == 0)
5061             {
5062               x = tem;
5063               goto repeat;
5064             }
5065
5066           accum = extract_mentioned_regs_helper (tem, accum);
5067         }
5068       else if (fmt[i] == 'E')
5069         {
5070           int j;
5071
5072           for (j = 0; j < XVECLEN (x, i); j++)
5073             accum = extract_mentioned_regs_helper (XVECEXP (x, i, j), accum);
5074         }
5075     }
5076
5077   return accum;
5078 }
5079
5080 /* Determine whether INSN is MEM store pattern that we will consider moving.
5081    REGS_SET_BEFORE is bitmap of registers set before (and including) the
5082    current insn, REGS_SET_AFTER is bitmap of registers set after (and
5083    including) the insn in this basic block.  We must be passing through BB from
5084    head to end, as we are using this fact to speed things up.
5085
5086    The results are stored this way:
5087
5088    -- the first anticipatable expression is added into ANTIC_STORE_LIST
5089    -- if the processed expression is not anticipatable, NULL_RTX is added
5090       there instead, so that we can use it as indicator that no further
5091       expression of this type may be anticipatable
5092    -- if the expression is available, it is added as head of AVAIL_STORE_LIST;
5093       consequently, all of them but this head are dead and may be deleted.
5094    -- if the expression is not available, the insn due to that it fails to be
5095       available is stored in reaching_reg.
5096
5097    The things are complicated a bit by fact that there already may be stores
5098    to the same MEM from other blocks; also caller must take care of the
5099    necessary cleanup of the temporary markers after end of the basic block.
5100    */
5101
5102 static void
5103 find_moveable_store (rtx insn, int *regs_set_before, int *regs_set_after)
5104 {
5105   struct ls_expr * ptr;
5106   rtx dest, set, tmp;
5107   int check_anticipatable, check_available;
5108   basic_block bb = BLOCK_FOR_INSN (insn);
5109
5110   set = single_set (insn);
5111   if (!set)
5112     return;
5113
5114   dest = SET_DEST (set);
5115
5116   if (! MEM_P (dest) || MEM_VOLATILE_P (dest)
5117       || GET_MODE (dest) == BLKmode)
5118     return;
5119
5120   if (side_effects_p (dest))
5121     return;
5122
5123   /* If we are handling exceptions, we must be careful with memory references
5124      that may trap. If we are not, the behavior is undefined, so we may just
5125      continue.  */
5126   if (flag_non_call_exceptions && may_trap_p (dest))
5127     return;
5128
5129   /* Even if the destination cannot trap, the source may.  In this case we'd
5130      need to handle updating the REG_EH_REGION note.  */
5131   if (find_reg_note (insn, REG_EH_REGION, NULL_RTX))
5132     return;
5133
5134   /* Make sure that the SET_SRC of this store insns can be assigned to
5135      a register, or we will fail later on in replace_store_insn, which
5136      assumes that we can do this.  But sometimes the target machine has
5137      oddities like MEM read-modify-write instruction.  See for example
5138      PR24257.  */
5139   if (!can_assign_to_reg_p (SET_SRC (set)))
5140     return;
5141
5142   ptr = ldst_entry (dest);
5143   if (!ptr->pattern_regs)
5144     ptr->pattern_regs = extract_mentioned_regs (dest);
5145
5146   /* Do not check for anticipatability if we either found one anticipatable
5147      store already, or tested for one and found out that it was killed.  */
5148   check_anticipatable = 0;
5149   if (!ANTIC_STORE_LIST (ptr))
5150     check_anticipatable = 1;
5151   else
5152     {
5153       tmp = XEXP (ANTIC_STORE_LIST (ptr), 0);
5154       if (tmp != NULL_RTX
5155           && BLOCK_FOR_INSN (tmp) != bb)
5156         check_anticipatable = 1;
5157     }
5158   if (check_anticipatable)
5159     {
5160       if (store_killed_before (dest, ptr->pattern_regs, insn, bb, regs_set_before))
5161         tmp = NULL_RTX;
5162       else
5163         tmp = insn;
5164       ANTIC_STORE_LIST (ptr) = alloc_INSN_LIST (tmp,
5165                                                 ANTIC_STORE_LIST (ptr));
5166     }
5167
5168   /* It is not necessary to check whether store is available if we did
5169      it successfully before; if we failed before, do not bother to check
5170      until we reach the insn that caused us to fail.  */
5171   check_available = 0;
5172   if (!AVAIL_STORE_LIST (ptr))
5173     check_available = 1;
5174   else
5175     {
5176       tmp = XEXP (AVAIL_STORE_LIST (ptr), 0);
5177       if (BLOCK_FOR_INSN (tmp) != bb)
5178         check_available = 1;
5179     }
5180   if (check_available)
5181     {
5182       /* Check that we have already reached the insn at that the check
5183          failed last time.  */
5184       if (LAST_AVAIL_CHECK_FAILURE (ptr))
5185         {
5186           for (tmp = BB_END (bb);
5187                tmp != insn && tmp != LAST_AVAIL_CHECK_FAILURE (ptr);
5188                tmp = PREV_INSN (tmp))
5189             continue;
5190           if (tmp == insn)
5191             check_available = 0;
5192         }
5193       else
5194         check_available = store_killed_after (dest, ptr->pattern_regs, insn,
5195                                               bb, regs_set_after,
5196                                               &LAST_AVAIL_CHECK_FAILURE (ptr));
5197     }
5198   if (!check_available)
5199     AVAIL_STORE_LIST (ptr) = alloc_INSN_LIST (insn, AVAIL_STORE_LIST (ptr));
5200 }
5201
5202 /* Find available and anticipatable stores.  */
5203
5204 static int
5205 compute_store_table (void)
5206 {
5207   int ret;
5208   basic_block bb;
5209   unsigned regno;
5210   rtx insn, pat, tmp;
5211   int *last_set_in, *already_set;
5212   struct ls_expr * ptr, **prev_next_ptr_ptr;
5213   unsigned int max_gcse_regno = max_reg_num ();
5214
5215   pre_ldst_mems = 0;
5216   pre_ldst_table = htab_create (13, pre_ldst_expr_hash,
5217                                 pre_ldst_expr_eq, NULL);
5218   last_set_in = XCNEWVEC (int, max_gcse_regno);
5219   already_set = XNEWVEC (int, max_gcse_regno);
5220
5221   /* Find all the stores we care about.  */
5222   FOR_EACH_BB (bb)
5223     {
5224       /* First compute the registers set in this block.  */
5225       regvec = last_set_in;
5226
5227       FOR_BB_INSNS (bb, insn)
5228         {
5229           if (! INSN_P (insn))
5230             continue;
5231
5232           if (CALL_P (insn))
5233             {
5234               for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
5235                 if (TEST_HARD_REG_BIT (regs_invalidated_by_call, regno))
5236                   last_set_in[regno] = INSN_UID (insn);
5237             }
5238
5239           pat = PATTERN (insn);
5240           compute_store_table_current_insn = insn;
5241           note_stores (pat, reg_set_info, NULL);
5242         }
5243
5244       /* Now find the stores.  */
5245       memset (already_set, 0, sizeof (int) * max_gcse_regno);
5246       regvec = already_set;
5247       FOR_BB_INSNS (bb, insn)
5248         {
5249           if (! INSN_P (insn))
5250             continue;
5251
5252           if (CALL_P (insn))
5253             {
5254               for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
5255                 if (TEST_HARD_REG_BIT (regs_invalidated_by_call, regno))
5256                   already_set[regno] = 1;
5257             }
5258
5259           pat = PATTERN (insn);
5260           note_stores (pat, reg_set_info, NULL);
5261
5262           /* Now that we've marked regs, look for stores.  */
5263           find_moveable_store (insn, already_set, last_set_in);
5264
5265           /* Unmark regs that are no longer set.  */
5266           compute_store_table_current_insn = insn;
5267           note_stores (pat, reg_clear_last_set, last_set_in);
5268           if (CALL_P (insn))
5269             {
5270               for (regno = 0; regno < FIRST_PSEUDO_REGISTER; regno++)
5271                 if (TEST_HARD_REG_BIT (regs_invalidated_by_call, regno)
5272                     && last_set_in[regno] == INSN_UID (insn))
5273                   last_set_in[regno] = 0;
5274             }
5275         }
5276
5277 #ifdef ENABLE_CHECKING
5278       /* last_set_in should now be all-zero.  */
5279       for (regno = 0; regno < max_gcse_regno; regno++)
5280         gcc_assert (!last_set_in[regno]);
5281 #endif
5282
5283       /* Clear temporary marks.  */
5284       for (ptr = first_ls_expr (); ptr != NULL; ptr = next_ls_expr (ptr))
5285         {
5286           LAST_AVAIL_CHECK_FAILURE(ptr) = NULL_RTX;
5287           if (ANTIC_STORE_LIST (ptr)
5288               && (tmp = XEXP (ANTIC_STORE_LIST (ptr), 0)) == NULL_RTX)
5289             ANTIC_STORE_LIST (ptr) = XEXP (ANTIC_STORE_LIST (ptr), 1);
5290         }
5291     }
5292
5293   /* Remove the stores that are not available anywhere, as there will
5294      be no opportunity to optimize them.  */
5295   for (ptr = pre_ldst_mems, prev_next_ptr_ptr = &pre_ldst_mems;
5296        ptr != NULL;
5297        ptr = *prev_next_ptr_ptr)
5298     {
5299       if (!AVAIL_STORE_LIST (ptr))
5300         {
5301           *prev_next_ptr_ptr = ptr->next;
5302           htab_remove_elt_with_hash (pre_ldst_table, ptr, ptr->hash_index);
5303           free_ldst_entry (ptr);
5304         }
5305       else
5306         prev_next_ptr_ptr = &ptr->next;
5307     }
5308
5309   ret = enumerate_ldsts ();
5310
5311   if (dump_file)
5312     {
5313       fprintf (dump_file, "ST_avail and ST_antic (shown under loads..)\n");
5314       print_ldst_list (dump_file);
5315     }
5316
5317   free (last_set_in);
5318   free (already_set);
5319   return ret;
5320 }
5321
5322 /* Check to see if the load X is aliased with STORE_PATTERN.
5323    AFTER is true if we are checking the case when STORE_PATTERN occurs
5324    after the X.  */
5325
5326 static bool
5327 load_kills_store (const_rtx x, const_rtx store_pattern, int after)
5328 {
5329   if (after)
5330     return anti_dependence (x, store_pattern);
5331   else
5332     return true_dependence (store_pattern, GET_MODE (store_pattern), x,
5333                             rtx_addr_varies_p);
5334 }
5335
5336 /* Go through the entire insn X, looking for any loads which might alias
5337    STORE_PATTERN.  Return true if found.
5338    AFTER is true if we are checking the case when STORE_PATTERN occurs
5339    after the insn X.  */
5340
5341 static bool
5342 find_loads (const_rtx x, const_rtx store_pattern, int after)
5343 {
5344   const char * fmt;
5345   int i, j;
5346   int ret = false;
5347
5348   if (!x)
5349     return false;
5350
5351   if (GET_CODE (x) == SET)
5352     x = SET_SRC (x);
5353
5354   if (MEM_P (x))
5355     {
5356       if (load_kills_store (x, store_pattern, after))
5357         return true;
5358     }
5359
5360   /* Recursively process the insn.  */
5361   fmt = GET_RTX_FORMAT (GET_CODE (x));
5362
5363   for (i = GET_RTX_LENGTH (GET_CODE (x)) - 1; i >= 0 && !ret; i--)
5364     {
5365       if (fmt[i] == 'e')
5366         ret |= find_loads (XEXP (x, i), store_pattern, after);
5367       else if (fmt[i] == 'E')
5368         for (j = XVECLEN (x, i) - 1; j >= 0; j--)
5369           ret |= find_loads (XVECEXP (x, i, j), store_pattern, after);
5370     }
5371   return ret;
5372 }
5373
5374 static inline bool
5375 store_killed_in_pat (const_rtx x, const_rtx pat, int after)
5376 {
5377   if (GET_CODE (pat) == SET)
5378     {
5379       rtx dest = SET_DEST (pat);
5380
5381       if (GET_CODE (dest) == ZERO_EXTRACT)
5382         dest = XEXP (dest, 0);
5383
5384       /* Check for memory stores to aliased objects.  */
5385       if (MEM_P (dest)
5386           && !expr_equiv_p (dest, x))
5387         {
5388           if (after)
5389             {
5390               if (output_dependence (dest, x))
5391                 return true;
5392             }
5393           else
5394             {
5395               if (output_dependence (x, dest))
5396                 return true;
5397             }
5398         }
5399     }
5400
5401   if (find_loads (pat, x, after))
5402     return true;
5403
5404   return false;
5405 }
5406
5407 /* Check if INSN kills the store pattern X (is aliased with it).
5408    AFTER is true if we are checking the case when store X occurs
5409    after the insn.  Return true if it does.  */
5410
5411 static bool
5412 store_killed_in_insn (const_rtx x, const_rtx x_regs, const_rtx insn, int after)
5413 {
5414   const_rtx reg, base, note, pat;
5415
5416   if (!INSN_P (insn))
5417     return false;
5418
5419   if (CALL_P (insn))
5420     {
5421       /* A normal or pure call might read from pattern,
5422          but a const call will not.  */
5423       if (!RTL_CONST_CALL_P (insn))
5424         return true;
5425
5426       /* But even a const call reads its parameters.  Check whether the
5427          base of some of registers used in mem is stack pointer.  */
5428       for (reg = x_regs; reg; reg = XEXP (reg, 1))
5429         {
5430           base = find_base_term (XEXP (reg, 0));
5431           if (!base
5432               || (GET_CODE (base) == ADDRESS
5433                   && GET_MODE (base) == Pmode
5434                   && XEXP (base, 0) == stack_pointer_rtx))
5435             return true;
5436         }
5437
5438       return false;
5439     }
5440
5441   pat = PATTERN (insn);
5442   if (GET_CODE (pat) == SET)
5443     {
5444       if (store_killed_in_pat (x, pat, after))
5445         return true;
5446     }
5447   else if (GET_CODE (pat) == PARALLEL)
5448     {
5449       int i;
5450
5451       for (i = 0; i < XVECLEN (pat, 0); i++)
5452         if (store_killed_in_pat (x, XVECEXP (pat, 0, i), after))
5453           return true;
5454     }
5455   else if (find_loads (PATTERN (insn), x, after))
5456     return true;
5457
5458   /* If this insn has a REG_EQUAL or REG_EQUIV note referencing a memory
5459      location aliased with X, then this insn kills X.  */
5460   note = find_reg_equal_equiv_note (insn);
5461   if (! note)
5462     return false;
5463   note = XEXP (note, 0);
5464
5465   /* However, if the note represents a must alias rather than a may
5466      alias relationship, then it does not kill X.  */
5467   if (expr_equiv_p (note, x))
5468     return false;
5469
5470   /* See if there are any aliased loads in the note.  */
5471   return find_loads (note, x, after);
5472 }
5473
5474 /* Returns true if the expression X is loaded or clobbered on or after INSN
5475    within basic block BB.  REGS_SET_AFTER is bitmap of registers set in
5476    or after the insn.  X_REGS is list of registers mentioned in X. If the store
5477    is killed, return the last insn in that it occurs in FAIL_INSN.  */
5478
5479 static bool
5480 store_killed_after (const_rtx x, const_rtx x_regs, const_rtx insn, const_basic_block bb,
5481                     int *regs_set_after, rtx *fail_insn)
5482 {
5483   rtx last = BB_END (bb), act;
5484
5485   if (!store_ops_ok (x_regs, regs_set_after))
5486     {
5487       /* We do not know where it will happen.  */
5488       if (fail_insn)
5489         *fail_insn = NULL_RTX;
5490       return true;
5491     }
5492
5493   /* Scan from the end, so that fail_insn is determined correctly.  */
5494   for (act = last; act != PREV_INSN (insn); act = PREV_INSN (act))
5495     if (store_killed_in_insn (x, x_regs, act, false))
5496       {
5497         if (fail_insn)
5498           *fail_insn = act;
5499         return true;
5500       }
5501
5502   return false;
5503 }
5504
5505 /* Returns true if the expression X is loaded or clobbered on or before INSN
5506    within basic block BB. X_REGS is list of registers mentioned in X.
5507    REGS_SET_BEFORE is bitmap of registers set before or in this insn.  */
5508 static bool
5509 store_killed_before (const_rtx x, const_rtx x_regs, const_rtx insn, const_basic_block bb,
5510                      int *regs_set_before)
5511 {
5512   rtx first = BB_HEAD (bb);
5513
5514   if (!store_ops_ok (x_regs, regs_set_before))
5515     return true;
5516
5517   for ( ; insn != PREV_INSN (first); insn = PREV_INSN (insn))
5518     if (store_killed_in_insn (x, x_regs, insn, true))
5519       return true;
5520
5521   return false;
5522 }
5523
5524 /* Fill in available, anticipatable, transparent and kill vectors in
5525    STORE_DATA, based on lists of available and anticipatable stores.  */
5526 static void
5527 build_store_vectors (void)
5528 {
5529   basic_block bb;
5530   int *regs_set_in_block;
5531   rtx insn, st;
5532   struct ls_expr * ptr;
5533   unsigned int max_gcse_regno = max_reg_num ();
5534
5535   /* Build the gen_vector. This is any store in the table which is not killed
5536      by aliasing later in its block.  */
5537   ae_gen = sbitmap_vector_alloc (last_basic_block, num_stores);
5538   sbitmap_vector_zero (ae_gen, last_basic_block);
5539
5540   st_antloc = sbitmap_vector_alloc (last_basic_block, num_stores);
5541   sbitmap_vector_zero (st_antloc, last_basic_block);
5542
5543   for (ptr = first_ls_expr (); ptr != NULL; ptr = next_ls_expr (ptr))
5544     {
5545       for (st = AVAIL_STORE_LIST (ptr); st != NULL; st = XEXP (st, 1))
5546         {
5547           insn = XEXP (st, 0);
5548           bb = BLOCK_FOR_INSN (insn);
5549
5550           /* If we've already seen an available expression in this block,
5551              we can delete this one (It occurs earlier in the block). We'll
5552              copy the SRC expression to an unused register in case there
5553              are any side effects.  */
5554           if (TEST_BIT (ae_gen[bb->index], ptr->index))
5555             {
5556               rtx r = gen_reg_rtx_and_attrs (ptr->pattern);
5557               if (dump_file)
5558                 fprintf (dump_file, "Removing redundant store:\n");
5559               replace_store_insn (r, XEXP (st, 0), bb, ptr);
5560               continue;
5561             }
5562           SET_BIT (ae_gen[bb->index], ptr->index);
5563         }
5564
5565       for (st = ANTIC_STORE_LIST (ptr); st != NULL; st = XEXP (st, 1))
5566         {
5567           insn = XEXP (st, 0);
5568           bb = BLOCK_FOR_INSN (insn);
5569           SET_BIT (st_antloc[bb->index], ptr->index);
5570         }
5571     }
5572
5573   ae_kill = sbitmap_vector_alloc (last_basic_block, num_stores);
5574   sbitmap_vector_zero (ae_kill, last_basic_block);
5575
5576   transp = sbitmap_vector_alloc (last_basic_block, num_stores);
5577   sbitmap_vector_zero (transp, last_basic_block);
5578   regs_set_in_block = XNEWVEC (int, max_gcse_regno);
5579
5580   FOR_EACH_BB (bb)
5581     {
5582       FOR_BB_INSNS (bb, insn)
5583         if (INSN_P (insn))
5584           {
5585             df_ref *def_rec;
5586             for (def_rec = DF_INSN_DEFS (insn); *def_rec; def_rec++)
5587               {
5588                 unsigned int ref_regno = DF_REF_REGNO (*def_rec);
5589                 if (ref_regno < max_gcse_regno)
5590                   regs_set_in_block[DF_REF_REGNO (*def_rec)] = 1;
5591               }
5592           }
5593
5594       for (ptr = first_ls_expr (); ptr != NULL; ptr = next_ls_expr (ptr))
5595         {
5596           if (store_killed_after (ptr->pattern, ptr->pattern_regs, BB_HEAD (bb),
5597                                   bb, regs_set_in_block, NULL))
5598             {
5599               /* It should not be necessary to consider the expression
5600                  killed if it is both anticipatable and available.  */
5601               if (!TEST_BIT (st_antloc[bb->index], ptr->index)
5602                   || !TEST_BIT (ae_gen[bb->index], ptr->index))
5603                 SET_BIT (ae_kill[bb->index], ptr->index);
5604             }
5605           else
5606             SET_BIT (transp[bb->index], ptr->index);
5607         }
5608     }
5609
5610   free (regs_set_in_block);
5611
5612   if (dump_file)
5613     {
5614       dump_sbitmap_vector (dump_file, "st_antloc", "", st_antloc, last_basic_block);
5615       dump_sbitmap_vector (dump_file, "st_kill", "", ae_kill, last_basic_block);
5616       dump_sbitmap_vector (dump_file, "Transpt", "", transp, last_basic_block);
5617       dump_sbitmap_vector (dump_file, "st_avloc", "", ae_gen, last_basic_block);
5618     }
5619 }
5620
5621 /* Insert an instruction at the beginning of a basic block, and update
5622    the BB_HEAD if needed.  */
5623
5624 static void
5625 insert_insn_start_basic_block (rtx insn, basic_block bb)
5626 {
5627   /* Insert at start of successor block.  */
5628   rtx prev = PREV_INSN (BB_HEAD (bb));
5629   rtx before = BB_HEAD (bb);
5630   while (before != 0)
5631     {
5632       if (! LABEL_P (before)
5633           && !NOTE_INSN_BASIC_BLOCK_P (before))
5634         break;
5635       prev = before;
5636       if (prev == BB_END (bb))
5637         break;
5638       before = NEXT_INSN (before);
5639     }
5640
5641   insn = emit_insn_after_noloc (insn, prev, bb);
5642
5643   if (dump_file)
5644     {
5645       fprintf (dump_file, "STORE_MOTION  insert store at start of BB %d:\n",
5646                bb->index);
5647       print_inline_rtx (dump_file, insn, 6);
5648       fprintf (dump_file, "\n");
5649     }
5650 }
5651
5652 /* This routine will insert a store on an edge. EXPR is the ldst entry for
5653    the memory reference, and E is the edge to insert it on.  Returns nonzero
5654    if an edge insertion was performed.  */
5655
5656 static int
5657 insert_store (struct ls_expr * expr, edge e)
5658 {
5659   rtx reg, insn;
5660   basic_block bb;
5661   edge tmp;
5662   edge_iterator ei;
5663
5664   /* We did all the deleted before this insert, so if we didn't delete a
5665      store, then we haven't set the reaching reg yet either.  */
5666   if (expr->reaching_reg == NULL_RTX)
5667     return 0;
5668
5669   if (e->flags & EDGE_FAKE)
5670     return 0;
5671
5672   reg = expr->reaching_reg;
5673   insn = gen_move_insn (copy_rtx (expr->pattern), reg);
5674
5675   /* If we are inserting this expression on ALL predecessor edges of a BB,
5676      insert it at the start of the BB, and reset the insert bits on the other
5677      edges so we don't try to insert it on the other edges.  */
5678   bb = e->dest;
5679   FOR_EACH_EDGE (tmp, ei, e->dest->preds)
5680     if (!(tmp->flags & EDGE_FAKE))
5681       {
5682         int index = EDGE_INDEX (edge_list, tmp->src, tmp->dest);
5683         
5684         gcc_assert (index != EDGE_INDEX_NO_EDGE);
5685         if (! TEST_BIT (pre_insert_map[index], expr->index))
5686           break;
5687       }
5688
5689   /* If tmp is NULL, we found an insertion on every edge, blank the
5690      insertion vector for these edges, and insert at the start of the BB.  */
5691   if (!tmp && bb != EXIT_BLOCK_PTR)
5692     {
5693       FOR_EACH_EDGE (tmp, ei, e->dest->preds)
5694         {
5695           int index = EDGE_INDEX (edge_list, tmp->src, tmp->dest);
5696           RESET_BIT (pre_insert_map[index], expr->index);
5697         }
5698       insert_insn_start_basic_block (insn, bb);
5699       return 0;
5700     }
5701
5702   /* We can't put stores in the front of blocks pointed to by abnormal
5703      edges since that may put a store where one didn't used to be.  */
5704   gcc_assert (!(e->flags & EDGE_ABNORMAL));
5705
5706   insert_insn_on_edge (insn, e);
5707
5708   if (dump_file)
5709     {
5710       fprintf (dump_file, "STORE_MOTION  insert insn on edge (%d, %d):\n",
5711                e->src->index, e->dest->index);
5712       print_inline_rtx (dump_file, insn, 6);
5713       fprintf (dump_file, "\n");
5714     }
5715
5716   return 1;
5717 }
5718
5719 /* Remove any REG_EQUAL or REG_EQUIV notes containing a reference to the
5720    memory location in SMEXPR set in basic block BB.
5721
5722    This could be rather expensive.  */
5723
5724 static void
5725 remove_reachable_equiv_notes (basic_block bb, struct ls_expr *smexpr)
5726 {
5727   edge_iterator *stack, ei;
5728   int sp;
5729   edge act;
5730   sbitmap visited = sbitmap_alloc (last_basic_block);
5731   rtx last, insn, note;
5732   rtx mem = smexpr->pattern;
5733
5734   stack = XNEWVEC (edge_iterator, n_basic_blocks);
5735   sp = 0;
5736   ei = ei_start (bb->succs);
5737
5738   sbitmap_zero (visited);
5739
5740   act = (EDGE_COUNT (ei_container (ei)) > 0 ? EDGE_I (ei_container (ei), 0) : NULL);
5741   while (1)
5742     {
5743       if (!act)
5744         {
5745           if (!sp)
5746             {
5747               free (stack);
5748               sbitmap_free (visited);
5749               return;
5750             }
5751           act = ei_edge (stack[--sp]);
5752         }
5753       bb = act->dest;
5754
5755       if (bb == EXIT_BLOCK_PTR
5756           || TEST_BIT (visited, bb->index))
5757         {
5758           if (!ei_end_p (ei))
5759               ei_next (&ei);
5760           act = (! ei_end_p (ei)) ? ei_edge (ei) : NULL;
5761           continue;
5762         }
5763       SET_BIT (visited, bb->index);
5764
5765       if (TEST_BIT (st_antloc[bb->index], smexpr->index))
5766         {
5767           for (last = ANTIC_STORE_LIST (smexpr);
5768                BLOCK_FOR_INSN (XEXP (last, 0)) != bb;
5769                last = XEXP (last, 1))
5770             continue;
5771           last = XEXP (last, 0);
5772         }
5773       else
5774         last = NEXT_INSN (BB_END (bb));
5775
5776       for (insn = BB_HEAD (bb); insn != last; insn = NEXT_INSN (insn))
5777         if (INSN_P (insn))
5778           {
5779             note = find_reg_equal_equiv_note (insn);
5780             if (!note || !expr_equiv_p (XEXP (note, 0), mem))
5781               continue;
5782
5783             if (dump_file)
5784               fprintf (dump_file, "STORE_MOTION  drop REG_EQUAL note at insn %d:\n",
5785                        INSN_UID (insn));
5786             remove_note (insn, note);
5787           }
5788
5789       if (!ei_end_p (ei))
5790         ei_next (&ei);
5791       act = (! ei_end_p (ei)) ? ei_edge (ei) : NULL;
5792
5793       if (EDGE_COUNT (bb->succs) > 0)
5794         {
5795           if (act)
5796             stack[sp++] = ei;
5797           ei = ei_start (bb->succs);
5798           act = (EDGE_COUNT (ei_container (ei)) > 0 ? EDGE_I (ei_container (ei), 0) : NULL);
5799         }
5800     }
5801 }
5802
5803 /* This routine will replace a store with a SET to a specified register.  */
5804
5805 static void
5806 replace_store_insn (rtx reg, rtx del, basic_block bb, struct ls_expr *smexpr)
5807 {
5808   rtx insn, mem, note, set, ptr;
5809
5810   mem = smexpr->pattern;
5811   insn = gen_move_insn (reg, SET_SRC (single_set (del)));
5812
5813   for (ptr = ANTIC_STORE_LIST (smexpr); ptr; ptr = XEXP (ptr, 1))
5814     if (XEXP (ptr, 0) == del)
5815       {
5816         XEXP (ptr, 0) = insn;
5817         break;
5818       }
5819
5820   /* Move the notes from the deleted insn to its replacement.  */
5821   REG_NOTES (insn) = REG_NOTES (del);
5822
5823   /* Emit the insn AFTER all the notes are transferred.
5824      This is cheaper since we avoid df rescanning for the note change.  */
5825   insn = emit_insn_after (insn, del);
5826
5827   if (dump_file)
5828     {
5829       fprintf (dump_file,
5830                "STORE_MOTION  delete insn in BB %d:\n      ", bb->index);
5831       print_inline_rtx (dump_file, del, 6);
5832       fprintf (dump_file, "\nSTORE_MOTION  replaced with insn:\n      ");
5833       print_inline_rtx (dump_file, insn, 6);
5834       fprintf (dump_file, "\n");
5835     }
5836
5837   delete_insn (del);
5838
5839   /* Now we must handle REG_EQUAL notes whose contents is equal to the mem;
5840      they are no longer accurate provided that they are reached by this
5841      definition, so drop them.  */
5842   for (; insn != NEXT_INSN (BB_END (bb)); insn = NEXT_INSN (insn))
5843     if (INSN_P (insn))
5844       {
5845         set = single_set (insn);
5846         if (!set)
5847           continue;
5848         if (expr_equiv_p (SET_DEST (set), mem))
5849           return;
5850         note = find_reg_equal_equiv_note (insn);
5851         if (!note || !expr_equiv_p (XEXP (note, 0), mem))
5852           continue;
5853
5854         if (dump_file)
5855           fprintf (dump_file, "STORE_MOTION  drop REG_EQUAL note at insn %d:\n",
5856                    INSN_UID (insn));
5857         remove_note (insn, note);
5858       }
5859   remove_reachable_equiv_notes (bb, smexpr);
5860 }
5861
5862
5863 /* Delete a store, but copy the value that would have been stored into
5864    the reaching_reg for later storing.  */
5865
5866 static void
5867 delete_store (struct ls_expr * expr, basic_block bb)
5868 {
5869   rtx reg, i, del;
5870
5871   if (expr->reaching_reg == NULL_RTX)
5872     expr->reaching_reg = gen_reg_rtx_and_attrs (expr->pattern);
5873
5874   reg = expr->reaching_reg;
5875
5876   for (i = AVAIL_STORE_LIST (expr); i; i = XEXP (i, 1))
5877     {
5878       del = XEXP (i, 0);
5879       if (BLOCK_FOR_INSN (del) == bb)
5880         {
5881           /* We know there is only one since we deleted redundant
5882              ones during the available computation.  */
5883           replace_store_insn (reg, del, bb, expr);
5884           break;
5885         }
5886     }
5887 }
5888
5889 /* Free memory used by store motion.  */
5890
5891 static void
5892 free_store_memory (void)
5893 {
5894   free_ldst_mems ();
5895
5896   if (ae_gen)
5897     sbitmap_vector_free (ae_gen);
5898   if (ae_kill)
5899     sbitmap_vector_free (ae_kill);
5900   if (transp)
5901     sbitmap_vector_free (transp);
5902   if (st_antloc)
5903     sbitmap_vector_free (st_antloc);
5904   if (pre_insert_map)
5905     sbitmap_vector_free (pre_insert_map);
5906   if (pre_delete_map)
5907     sbitmap_vector_free (pre_delete_map);
5908
5909   ae_gen = ae_kill = transp = st_antloc = NULL;
5910   pre_insert_map = pre_delete_map = NULL;
5911 }
5912
5913 /* Perform store motion. Much like gcse, except we move expressions the
5914    other way by looking at the flowgraph in reverse.
5915    Return non-zero if transformations are performed by the pass.  */
5916
5917 static int
5918 one_store_motion_pass (void)
5919 {
5920   basic_block bb;
5921   int x;
5922   struct ls_expr * ptr;
5923   int update_flow = 0;
5924
5925   gcse_subst_count = 0;
5926   gcse_create_count = 0;
5927
5928   init_alias_analysis ();
5929
5930   /* Find all the available and anticipatable stores.  */
5931   num_stores = compute_store_table ();
5932   if (num_stores == 0)
5933     {
5934       htab_delete (pre_ldst_table);
5935       pre_ldst_table = NULL;
5936       end_alias_analysis ();
5937       return 0;
5938     }
5939
5940   /* Now compute kill & transp vectors.  */
5941   build_store_vectors ();
5942   add_noreturn_fake_exit_edges ();
5943   connect_infinite_loops_to_exit ();
5944
5945   edge_list = pre_edge_rev_lcm (num_stores, transp, ae_gen,
5946                                 st_antloc, ae_kill, &pre_insert_map,
5947                                 &pre_delete_map);
5948
5949   /* Now we want to insert the new stores which are going to be needed.  */
5950   for (ptr = first_ls_expr (); ptr != NULL; ptr = next_ls_expr (ptr))
5951     {
5952       /* If any of the edges we have above are abnormal, we can't move this
5953          store.  */
5954       for (x = NUM_EDGES (edge_list) - 1; x >= 0; x--)
5955         if (TEST_BIT (pre_insert_map[x], ptr->index)
5956             && (INDEX_EDGE (edge_list, x)->flags & EDGE_ABNORMAL))
5957           break;
5958
5959       if (x >= 0)
5960         {
5961           if (dump_file != NULL)
5962             fprintf (dump_file,
5963                      "Can't replace store %d: abnormal edge from %d to %d\n",
5964                      ptr->index, INDEX_EDGE (edge_list, x)->src->index,
5965                      INDEX_EDGE (edge_list, x)->dest->index);
5966           continue;
5967         }
5968                       
5969       /* Now we want to insert the new stores which are going to be needed.  */
5970
5971       FOR_EACH_BB (bb)
5972         if (TEST_BIT (pre_delete_map[bb->index], ptr->index))
5973           {
5974             delete_store (ptr, bb);
5975             gcse_subst_count++;
5976           }
5977
5978       for (x = 0; x < NUM_EDGES (edge_list); x++)
5979         if (TEST_BIT (pre_insert_map[x], ptr->index))
5980           {
5981             update_flow |= insert_store (ptr, INDEX_EDGE (edge_list, x));
5982             gcse_create_count++;
5983           }
5984     }
5985
5986   if (update_flow)
5987     commit_edge_insertions ();
5988
5989   free_store_memory ();
5990   free_edge_list (edge_list);
5991   remove_fake_exit_edges ();
5992   end_alias_analysis ();
5993
5994   if (dump_file)
5995     {
5996       fprintf (dump_file, "STORE_MOTION of %s, %d basic blocks, ",
5997                current_function_name (), n_basic_blocks);
5998       fprintf (dump_file, "%d substs, %d insns created\n",
5999                gcse_subst_count, gcse_create_count);
6000     }
6001
6002   return (gcse_subst_count > 0 || gcse_create_count > 0);
6003 }
6004
6005 \f
6006 /* Return true if the graph is too expensive to optimize. PASS is the
6007    optimization about to be performed.  */
6008
6009 static bool
6010 is_too_expensive (const char *pass)
6011 {
6012   /* Trying to perform global optimizations on flow graphs which have
6013      a high connectivity will take a long time and is unlikely to be
6014      particularly useful.
6015
6016      In normal circumstances a cfg should have about twice as many
6017      edges as blocks.  But we do not want to punish small functions
6018      which have a couple switch statements.  Rather than simply
6019      threshold the number of blocks, uses something with a more
6020      graceful degradation.  */
6021   if (n_edges > 20000 + n_basic_blocks * 4)
6022     {
6023       warning (OPT_Wdisabled_optimization,
6024                "%s: %d basic blocks and %d edges/basic block",
6025                pass, n_basic_blocks, n_edges / n_basic_blocks);
6026
6027       return true;
6028     }
6029
6030   /* If allocating memory for the cprop bitmap would take up too much
6031      storage it's better just to disable the optimization.  */
6032   if ((n_basic_blocks
6033        * SBITMAP_SET_SIZE (max_reg_num ())
6034        * sizeof (SBITMAP_ELT_TYPE)) > MAX_GCSE_MEMORY)
6035     {
6036       warning (OPT_Wdisabled_optimization,
6037                "%s: %d basic blocks and %d registers",
6038                pass, n_basic_blocks, max_reg_num ());
6039
6040       return true;
6041     }
6042
6043   return false;
6044 }
6045
6046 \f
6047 /* Main function for the CPROP pass.  */
6048
6049 static int
6050 one_cprop_pass (void)
6051 {
6052   int changed = 0;
6053
6054   /* Return if there's nothing to do, or it is too expensive.  */
6055   if (n_basic_blocks <= NUM_FIXED_BLOCKS + 1
6056       || is_too_expensive (_ ("const/copy propagation disabled")))
6057     return 0;
6058
6059   global_const_prop_count = local_const_prop_count = 0;
6060   global_copy_prop_count = local_copy_prop_count = 0;
6061
6062   bytes_used = 0;
6063   gcc_obstack_init (&gcse_obstack);
6064   alloc_gcse_mem ();
6065
6066   /* Do a local const/copy propagation pass first.  The global pass
6067      only handles global opportunities.
6068      If the local pass changes something, remove any unreachable blocks
6069      because the CPROP global dataflow analysis may get into infinite
6070      loops for CFGs with unreachable blocks.
6071
6072      FIXME: This local pass should not be necessary after CSE (but for
6073             some reason it still is).  It is also (proven) not necessary
6074             to run the local pass right after FWPWOP.
6075             
6076      FIXME: The global analysis would not get into infinite loops if it
6077             would use the DF solver (via df_simple_dataflow) instead of
6078             the solver implemented in this file.  */
6079   if (local_cprop_pass ())
6080     {
6081       delete_unreachable_blocks ();
6082       df_analyze ();
6083     }
6084
6085   /* Determine implicit sets.  */
6086   implicit_sets = XCNEWVEC (rtx, last_basic_block);
6087   find_implicit_sets ();
6088
6089   alloc_hash_table (get_max_uid (), &set_hash_table, 1);
6090   compute_hash_table (&set_hash_table);
6091
6092   /* Free implicit_sets before peak usage.  */
6093   free (implicit_sets);
6094   implicit_sets = NULL;
6095
6096   if (dump_file)
6097     dump_hash_table (dump_file, "SET", &set_hash_table);
6098   if (set_hash_table.n_elems > 0)
6099     {
6100       basic_block bb;
6101       rtx insn;
6102
6103       alloc_cprop_mem (last_basic_block, set_hash_table.n_elems);
6104       compute_cprop_data ();
6105
6106       FOR_BB_BETWEEN (bb, ENTRY_BLOCK_PTR->next_bb->next_bb, EXIT_BLOCK_PTR, next_bb)
6107         {
6108           /* Reset tables used to keep track of what's still valid [since
6109              the start of the block].  */
6110           reset_opr_set_tables ();
6111
6112           FOR_BB_INSNS (bb, insn)
6113             if (INSN_P (insn))
6114               {
6115                 changed |= cprop_insn (insn);
6116
6117                 /* Keep track of everything modified by this insn.  */
6118                 /* ??? Need to be careful w.r.t. mods done to INSN.
6119                        Don't call mark_oprs_set if we turned the
6120                        insn into a NOTE.  */
6121                 if (! NOTE_P (insn))
6122                   mark_oprs_set (insn);
6123               }
6124         }
6125
6126       changed |= bypass_conditional_jumps ();
6127       free_cprop_mem ();
6128     }
6129
6130   free_hash_table (&set_hash_table);
6131   free_gcse_mem ();
6132   obstack_free (&gcse_obstack, NULL);
6133
6134   if (dump_file)
6135     {
6136       fprintf (dump_file, "CPROP of %s, %d basic blocks, %d bytes needed, ",
6137                current_function_name (), n_basic_blocks, bytes_used);
6138       fprintf (dump_file, "%d local const props, %d local copy props, ",
6139                local_const_prop_count, local_copy_prop_count);
6140       fprintf (dump_file, "%d global const props, %d global copy props\n\n",
6141                global_const_prop_count, global_copy_prop_count);
6142     }
6143
6144   return changed;
6145 }
6146
6147 \f
6148 /* All the passes implemented in this file.  Each pass has its
6149    own gate and execute function, and at the end of the file a
6150    pass definition for passes.c.
6151
6152    We do not construct an accurate cfg in functions which call
6153    setjmp, so none of these passes runs if the function calls
6154    setjmp.
6155    FIXME: Should just handle setjmp via REG_SETJMP notes.  */
6156
6157 static bool
6158 gate_rtl_cprop (void)
6159 {
6160   return optimize > 0 && flag_gcse
6161     && !cfun->calls_setjmp
6162     && dbg_cnt (cprop);
6163 }
6164
6165 static unsigned int
6166 execute_rtl_cprop (void)
6167 {
6168   delete_unreachable_blocks ();
6169   df_note_add_problem ();
6170   df_set_flags (DF_LR_RUN_DCE);
6171   df_analyze ();
6172   flag_rerun_cse_after_global_opts |= one_cprop_pass ();
6173   return 0;
6174 }
6175
6176 static bool
6177 gate_rtl_pre (void)
6178 {
6179   return optimize > 0 && flag_gcse
6180     && !cfun->calls_setjmp
6181     && optimize_function_for_speed_p (cfun)
6182     && dbg_cnt (pre);
6183 }
6184
6185 static unsigned int
6186 execute_rtl_pre (void)
6187 {
6188   delete_unreachable_blocks ();
6189   df_note_add_problem ();
6190   df_analyze ();
6191   flag_rerun_cse_after_global_opts |= one_pre_gcse_pass ();
6192   return 0;
6193 }
6194
6195 static bool
6196 gate_rtl_hoist (void)
6197 {
6198   return optimize > 0 && flag_gcse
6199     && !cfun->calls_setjmp
6200     /* It does not make sense to run code hoisting unless we are optimizing
6201        for code size -- it rarely makes programs faster, and can make then
6202        bigger if we did PRE (when optimizing for space, we don't run PRE).  */
6203     && optimize_function_for_size_p (cfun)
6204     && dbg_cnt (hoist);
6205 }
6206
6207 static unsigned int
6208 execute_rtl_hoist (void)
6209 {
6210   delete_unreachable_blocks ();
6211   df_note_add_problem ();
6212   df_analyze ();
6213   flag_rerun_cse_after_global_opts |= one_code_hoisting_pass ();
6214   return 0;
6215 }
6216
6217 static bool
6218 gate_rtl_store_motion (void)
6219 {
6220   return optimize > 0 && flag_gcse_sm
6221     && !cfun->calls_setjmp
6222     && optimize_function_for_speed_p (cfun)
6223     && dbg_cnt (store_motion);
6224 }
6225
6226 static unsigned int
6227 execute_rtl_store_motion (void)
6228 {
6229   delete_unreachable_blocks ();
6230   df_note_add_problem ();
6231   df_analyze ();
6232   flag_rerun_cse_after_global_opts |= one_store_motion_pass ();
6233   return 0;
6234 }
6235
6236 struct rtl_opt_pass pass_rtl_cprop =
6237 {
6238  {
6239   RTL_PASS,
6240   "cprop",                              /* name */
6241   gate_rtl_cprop,                       /* gate */   
6242   execute_rtl_cprop,                    /* execute */       
6243   NULL,                                 /* sub */
6244   NULL,                                 /* next */
6245   0,                                    /* static_pass_number */
6246   TV_CPROP,                             /* tv_id */
6247   PROP_cfglayout,                       /* properties_required */
6248   0,                                    /* properties_provided */
6249   0,                                    /* properties_destroyed */
6250   0,                                    /* todo_flags_start */
6251   TODO_df_finish | TODO_verify_rtl_sharing |
6252   TODO_dump_func |
6253   TODO_verify_flow | TODO_ggc_collect   /* todo_flags_finish */
6254  }
6255 };
6256
6257 struct rtl_opt_pass pass_rtl_pre =
6258 {
6259  {
6260   RTL_PASS,
6261   "pre",                                /* name */
6262   gate_rtl_pre,                         /* gate */   
6263   execute_rtl_pre,                      /* execute */       
6264   NULL,                                 /* sub */
6265   NULL,                                 /* next */
6266   0,                                    /* static_pass_number */
6267   TV_PRE,                               /* tv_id */
6268   PROP_cfglayout,                       /* properties_required */
6269   0,                                    /* properties_provided */
6270   0,                                    /* properties_destroyed */
6271   0,                                    /* todo_flags_start */
6272   TODO_df_finish | TODO_verify_rtl_sharing |
6273   TODO_dump_func |
6274   TODO_verify_flow | TODO_ggc_collect   /* todo_flags_finish */
6275  }
6276 };
6277
6278 struct rtl_opt_pass pass_rtl_hoist =
6279 {
6280  {
6281   RTL_PASS,
6282   "hoist",                              /* name */
6283   gate_rtl_hoist,                       /* gate */   
6284   execute_rtl_hoist,                    /* execute */       
6285   NULL,                                 /* sub */
6286   NULL,                                 /* next */
6287   0,                                    /* static_pass_number */
6288   TV_HOIST,                             /* tv_id */
6289   PROP_cfglayout,                       /* properties_required */
6290   0,                                    /* properties_provided */
6291   0,                                    /* properties_destroyed */
6292   0,                                    /* todo_flags_start */
6293   TODO_df_finish | TODO_verify_rtl_sharing |
6294   TODO_dump_func |
6295   TODO_verify_flow | TODO_ggc_collect   /* todo_flags_finish */
6296  }
6297 };
6298
6299 struct rtl_opt_pass pass_rtl_store_motion =
6300 {
6301  {
6302   RTL_PASS,
6303   "store_motion",                       /* name */
6304   gate_rtl_store_motion,                /* gate */   
6305   execute_rtl_store_motion,             /* execute */       
6306   NULL,                                 /* sub */
6307   NULL,                                 /* next */
6308   0,                                    /* static_pass_number */
6309   TV_LSM,                               /* tv_id */
6310   PROP_cfglayout,                       /* properties_required */
6311   0,                                    /* properties_provided */
6312   0,                                    /* properties_destroyed */
6313   0,                                    /* todo_flags_start */
6314   TODO_df_finish | TODO_verify_rtl_sharing |
6315   TODO_dump_func |
6316   TODO_verify_flow | TODO_ggc_collect   /* todo_flags_finish */
6317  }
6318 };
6319
6320 #include "gt-gcse.h"