OSDN Git Service

2010-10-04 Matthias Klose <doko@ubuntu.com>
[pf3gnuchains/gcc-fork.git] / gcc / sel-sched-ir.c
1 /* Instruction scheduling pass.  Selective scheduler and pipeliner.
2    Copyright (C) 2006, 2007, 2008, 2009, 2010 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it under
7 the terms of the GNU General Public License as published by the Free
8 Software Foundation; either version 3, or (at your option) any later
9 version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
12 WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3.  If not see
18 <http://www.gnu.org/licenses/>.  */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "diagnostic-core.h"
25 #include "toplev.h"
26 #include "rtl.h"
27 #include "tm_p.h"
28 #include "hard-reg-set.h"
29 #include "regs.h"
30 #include "function.h"
31 #include "flags.h"
32 #include "insn-config.h"
33 #include "insn-attr.h"
34 #include "except.h"
35 #include "toplev.h"
36 #include "recog.h"
37 #include "params.h"
38 #include "target.h"
39 #include "timevar.h"
40 #include "tree-pass.h"
41 #include "sched-int.h"
42 #include "ggc.h"
43 #include "tree.h"
44 #include "vec.h"
45 #include "langhooks.h"
46 #include "rtlhooks-def.h"
47 #include "emit-rtl.h"  /* FIXME: Can go away once crtl is moved to rtl.h.  */
48
49 #ifdef INSN_SCHEDULING
50 #include "sel-sched-ir.h"
51 /* We don't have to use it except for sel_print_insn.  */
52 #include "sel-sched-dump.h"
53
54 /* A vector holding bb info for whole scheduling pass.  */
55 VEC(sel_global_bb_info_def, heap) *sel_global_bb_info = NULL;
56
57 /* A vector holding bb info.  */
58 VEC(sel_region_bb_info_def, heap) *sel_region_bb_info = NULL;
59
60 /* A pool for allocating all lists.  */
61 alloc_pool sched_lists_pool;
62
63 /* This contains information about successors for compute_av_set.  */
64 struct succs_info current_succs;
65
66 /* Data structure to describe interaction with the generic scheduler utils.  */
67 static struct common_sched_info_def sel_common_sched_info;
68
69 /* The loop nest being pipelined.  */
70 struct loop *current_loop_nest;
71
72 /* LOOP_NESTS is a vector containing the corresponding loop nest for
73    each region.  */
74 static VEC(loop_p, heap) *loop_nests = NULL;
75
76 /* Saves blocks already in loop regions, indexed by bb->index.  */
77 static sbitmap bbs_in_loop_rgns = NULL;
78
79 /* CFG hooks that are saved before changing create_basic_block hook.  */
80 static struct cfg_hooks orig_cfg_hooks;
81 \f
82
83 /* Array containing reverse topological index of function basic blocks,
84    indexed by BB->INDEX.  */
85 static int *rev_top_order_index = NULL;
86
87 /* Length of the above array.  */
88 static int rev_top_order_index_len = -1;
89
90 /* A regset pool structure.  */
91 static struct
92 {
93   /* The stack to which regsets are returned.  */
94   regset *v;
95
96   /* Its pointer.  */
97   int n;
98
99   /* Its size.  */
100   int s;
101
102   /* In VV we save all generated regsets so that, when destructing the
103      pool, we can compare it with V and check that every regset was returned
104      back to pool.  */
105   regset *vv;
106
107   /* The pointer of VV stack.  */
108   int nn;
109
110   /* Its size.  */
111   int ss;
112
113   /* The difference between allocated and returned regsets.  */
114   int diff;
115 } regset_pool = { NULL, 0, 0, NULL, 0, 0, 0 };
116
117 /* This represents the nop pool.  */
118 static struct
119 {
120   /* The vector which holds previously emitted nops.  */
121   insn_t *v;
122
123   /* Its pointer.  */
124   int n;
125
126   /* Its size.  */
127   int s;
128 } nop_pool = { NULL, 0, 0 };
129
130 /* The pool for basic block notes.  */
131 static rtx_vec_t bb_note_pool;
132
133 /* A NOP pattern used to emit placeholder insns.  */
134 rtx nop_pattern = NULL_RTX;
135 /* A special instruction that resides in EXIT_BLOCK.
136    EXIT_INSN is successor of the insns that lead to EXIT_BLOCK.  */
137 rtx exit_insn = NULL_RTX;
138
139 /* TRUE if while scheduling current region, which is loop, its preheader
140    was removed.  */
141 bool preheader_removed = false;
142 \f
143
144 /* Forward static declarations.  */
145 static void fence_clear (fence_t);
146
147 static void deps_init_id (idata_t, insn_t, bool);
148 static void init_id_from_df (idata_t, insn_t, bool);
149 static expr_t set_insn_init (expr_t, vinsn_t, int);
150
151 static void cfg_preds (basic_block, insn_t **, int *);
152 static void prepare_insn_expr (insn_t, int);
153 static void free_history_vect (VEC (expr_history_def, heap) **);
154
155 static void move_bb_info (basic_block, basic_block);
156 static void remove_empty_bb (basic_block, bool);
157 static void sel_remove_loop_preheader (void);
158
159 static bool insn_is_the_only_one_in_bb_p (insn_t);
160 static void create_initial_data_sets (basic_block);
161
162 static void free_av_set (basic_block);
163 static void invalidate_av_set (basic_block);
164 static void extend_insn_data (void);
165 static void sel_init_new_insn (insn_t, int);
166 static void finish_insns (void);
167 \f
168 /* Various list functions.  */
169
170 /* Copy an instruction list L.  */
171 ilist_t
172 ilist_copy (ilist_t l)
173 {
174   ilist_t head = NULL, *tailp = &head;
175
176   while (l)
177     {
178       ilist_add (tailp, ILIST_INSN (l));
179       tailp = &ILIST_NEXT (*tailp);
180       l = ILIST_NEXT (l);
181     }
182
183   return head;
184 }
185
186 /* Invert an instruction list L.  */
187 ilist_t
188 ilist_invert (ilist_t l)
189 {
190   ilist_t res = NULL;
191
192   while (l)
193     {
194       ilist_add (&res, ILIST_INSN (l));
195       l = ILIST_NEXT (l);
196     }
197
198   return res;
199 }
200
201 /* Add a new boundary to the LP list with parameters TO, PTR, and DC.  */
202 void
203 blist_add (blist_t *lp, insn_t to, ilist_t ptr, deps_t dc)
204 {
205   bnd_t bnd;
206
207   _list_add (lp);
208   bnd = BLIST_BND (*lp);
209
210   BND_TO (bnd) = to;
211   BND_PTR (bnd) = ptr;
212   BND_AV (bnd) = NULL;
213   BND_AV1 (bnd) = NULL;
214   BND_DC (bnd) = dc;
215 }
216
217 /* Remove the list note pointed to by LP.  */
218 void
219 blist_remove (blist_t *lp)
220 {
221   bnd_t b = BLIST_BND (*lp);
222
223   av_set_clear (&BND_AV (b));
224   av_set_clear (&BND_AV1 (b));
225   ilist_clear (&BND_PTR (b));
226
227   _list_remove (lp);
228 }
229
230 /* Init a fence tail L.  */
231 void
232 flist_tail_init (flist_tail_t l)
233 {
234   FLIST_TAIL_HEAD (l) = NULL;
235   FLIST_TAIL_TAILP (l) = &FLIST_TAIL_HEAD (l);
236 }
237
238 /* Try to find fence corresponding to INSN in L.  */
239 fence_t
240 flist_lookup (flist_t l, insn_t insn)
241 {
242   while (l)
243     {
244       if (FENCE_INSN (FLIST_FENCE (l)) == insn)
245         return FLIST_FENCE (l);
246
247       l = FLIST_NEXT (l);
248     }
249
250   return NULL;
251 }
252
253 /* Init the fields of F before running fill_insns.  */
254 static void
255 init_fence_for_scheduling (fence_t f)
256 {
257   FENCE_BNDS (f) = NULL;
258   FENCE_PROCESSED_P (f) = false;
259   FENCE_SCHEDULED_P (f) = false;
260 }
261
262 /* Add new fence consisting of INSN and STATE to the list pointed to by LP.  */
263 static void
264 flist_add (flist_t *lp, insn_t insn, state_t state, deps_t dc, void *tc,
265            insn_t last_scheduled_insn, VEC(rtx,gc) *executing_insns,
266            int *ready_ticks, int ready_ticks_size, insn_t sched_next,
267            int cycle, int cycle_issued_insns, int issue_more,
268            bool starts_cycle_p, bool after_stall_p)
269 {
270   fence_t f;
271
272   _list_add (lp);
273   f = FLIST_FENCE (*lp);
274
275   FENCE_INSN (f) = insn;
276
277   gcc_assert (state != NULL);
278   FENCE_STATE (f) = state;
279
280   FENCE_CYCLE (f) = cycle;
281   FENCE_ISSUED_INSNS (f) = cycle_issued_insns;
282   FENCE_STARTS_CYCLE_P (f) = starts_cycle_p;
283   FENCE_AFTER_STALL_P (f) = after_stall_p;
284
285   gcc_assert (dc != NULL);
286   FENCE_DC (f) = dc;
287
288   gcc_assert (tc != NULL || targetm.sched.alloc_sched_context == NULL);
289   FENCE_TC (f) = tc;
290
291   FENCE_LAST_SCHEDULED_INSN (f) = last_scheduled_insn;
292   FENCE_ISSUE_MORE (f) = issue_more;
293   FENCE_EXECUTING_INSNS (f) = executing_insns;
294   FENCE_READY_TICKS (f) = ready_ticks;
295   FENCE_READY_TICKS_SIZE (f) = ready_ticks_size;
296   FENCE_SCHED_NEXT (f) = sched_next;
297
298   init_fence_for_scheduling (f);
299 }
300
301 /* Remove the head node of the list pointed to by LP.  */
302 static void
303 flist_remove (flist_t *lp)
304 {
305   if (FENCE_INSN (FLIST_FENCE (*lp)))
306     fence_clear (FLIST_FENCE (*lp));
307   _list_remove (lp);
308 }
309
310 /* Clear the fence list pointed to by LP.  */
311 void
312 flist_clear (flist_t *lp)
313 {
314   while (*lp)
315     flist_remove (lp);
316 }
317
318 /* Add ORIGINAL_INSN the def list DL honoring CROSSES_CALL.  */
319 void
320 def_list_add (def_list_t *dl, insn_t original_insn, bool crosses_call)
321 {
322   def_t d;
323
324   _list_add (dl);
325   d = DEF_LIST_DEF (*dl);
326
327   d->orig_insn = original_insn;
328   d->crosses_call = crosses_call;
329 }
330 \f
331
332 /* Functions to work with target contexts.  */
333
334 /* Bulk target context.  It is convenient for debugging purposes to ensure
335    that there are no uninitialized (null) target contexts.  */
336 static tc_t bulk_tc = (tc_t) 1;
337
338 /* Target hooks wrappers.  In the future we can provide some default
339    implementations for them.  */
340
341 /* Allocate a store for the target context.  */
342 static tc_t
343 alloc_target_context (void)
344 {
345   return (targetm.sched.alloc_sched_context
346           ? targetm.sched.alloc_sched_context () : bulk_tc);
347 }
348
349 /* Init target context TC.
350    If CLEAN_P is true, then make TC as it is beginning of the scheduler.
351    Overwise, copy current backend context to TC.  */
352 static void
353 init_target_context (tc_t tc, bool clean_p)
354 {
355   if (targetm.sched.init_sched_context)
356     targetm.sched.init_sched_context (tc, clean_p);
357 }
358
359 /* Allocate and initialize a target context.  Meaning of CLEAN_P is the same as
360    int init_target_context ().  */
361 tc_t
362 create_target_context (bool clean_p)
363 {
364   tc_t tc = alloc_target_context ();
365
366   init_target_context (tc, clean_p);
367   return tc;
368 }
369
370 /* Copy TC to the current backend context.  */
371 void
372 set_target_context (tc_t tc)
373 {
374   if (targetm.sched.set_sched_context)
375     targetm.sched.set_sched_context (tc);
376 }
377
378 /* TC is about to be destroyed.  Free any internal data.  */
379 static void
380 clear_target_context (tc_t tc)
381 {
382   if (targetm.sched.clear_sched_context)
383     targetm.sched.clear_sched_context (tc);
384 }
385
386 /*  Clear and free it.  */
387 static void
388 delete_target_context (tc_t tc)
389 {
390   clear_target_context (tc);
391
392   if (targetm.sched.free_sched_context)
393     targetm.sched.free_sched_context (tc);
394 }
395
396 /* Make a copy of FROM in TO.
397    NB: May be this should be a hook.  */
398 static void
399 copy_target_context (tc_t to, tc_t from)
400 {
401   tc_t tmp = create_target_context (false);
402
403   set_target_context (from);
404   init_target_context (to, false);
405
406   set_target_context (tmp);
407   delete_target_context (tmp);
408 }
409
410 /* Create a copy of TC.  */
411 static tc_t
412 create_copy_of_target_context (tc_t tc)
413 {
414   tc_t copy = alloc_target_context ();
415
416   copy_target_context (copy, tc);
417
418   return copy;
419 }
420
421 /* Clear TC and initialize it according to CLEAN_P.  The meaning of CLEAN_P
422    is the same as in init_target_context ().  */
423 void
424 reset_target_context (tc_t tc, bool clean_p)
425 {
426   clear_target_context (tc);
427   init_target_context (tc, clean_p);
428 }
429 \f
430 /* Functions to work with dependence contexts.
431    Dc (aka deps context, aka deps_t, aka struct deps_desc *) is short for dependence
432    context.  It accumulates information about processed insns to decide if
433    current insn is dependent on the processed ones.  */
434
435 /* Make a copy of FROM in TO.  */
436 static void
437 copy_deps_context (deps_t to, deps_t from)
438 {
439   init_deps (to, false);
440   deps_join (to, from);
441 }
442
443 /* Allocate store for dep context.  */
444 static deps_t
445 alloc_deps_context (void)
446 {
447   return XNEW (struct deps_desc);
448 }
449
450 /* Allocate and initialize dep context.  */
451 static deps_t
452 create_deps_context (void)
453 {
454   deps_t dc = alloc_deps_context ();
455
456   init_deps (dc, false);
457   return dc;
458 }
459
460 /* Create a copy of FROM.  */
461 static deps_t
462 create_copy_of_deps_context (deps_t from)
463 {
464   deps_t to = alloc_deps_context ();
465
466   copy_deps_context (to, from);
467   return to;
468 }
469
470 /* Clean up internal data of DC.  */
471 static void
472 clear_deps_context (deps_t dc)
473 {
474   free_deps (dc);
475 }
476
477 /* Clear and free DC.  */
478 static void
479 delete_deps_context (deps_t dc)
480 {
481   clear_deps_context (dc);
482   free (dc);
483 }
484
485 /* Clear and init DC.  */
486 static void
487 reset_deps_context (deps_t dc)
488 {
489   clear_deps_context (dc);
490   init_deps (dc, false);
491 }
492
493 /* This structure describes the dependence analysis hooks for advancing
494    dependence context.  */
495 static struct sched_deps_info_def advance_deps_context_sched_deps_info =
496   {
497     NULL,
498
499     NULL, /* start_insn */
500     NULL, /* finish_insn */
501     NULL, /* start_lhs */
502     NULL, /* finish_lhs */
503     NULL, /* start_rhs */
504     NULL, /* finish_rhs */
505     haifa_note_reg_set,
506     haifa_note_reg_clobber,
507     haifa_note_reg_use,
508     NULL, /* note_mem_dep */
509     NULL, /* note_dep */
510
511     0, 0, 0
512   };
513
514 /* Process INSN and add its impact on DC.  */
515 void
516 advance_deps_context (deps_t dc, insn_t insn)
517 {
518   sched_deps_info = &advance_deps_context_sched_deps_info;
519   deps_analyze_insn (dc, insn);
520 }
521 \f
522
523 /* Functions to work with DFA states.  */
524
525 /* Allocate store for a DFA state.  */
526 static state_t
527 state_alloc (void)
528 {
529   return xmalloc (dfa_state_size);
530 }
531
532 /* Allocate and initialize DFA state.  */
533 static state_t
534 state_create (void)
535 {
536   state_t state = state_alloc ();
537
538   state_reset (state);
539   advance_state (state);
540   return state;
541 }
542
543 /* Free DFA state.  */
544 static void
545 state_free (state_t state)
546 {
547   free (state);
548 }
549
550 /* Make a copy of FROM in TO.  */
551 static void
552 state_copy (state_t to, state_t from)
553 {
554   memcpy (to, from, dfa_state_size);
555 }
556
557 /* Create a copy of FROM.  */
558 static state_t
559 state_create_copy (state_t from)
560 {
561   state_t to = state_alloc ();
562
563   state_copy (to, from);
564   return to;
565 }
566 \f
567
568 /* Functions to work with fences.  */
569
570 /* Clear the fence.  */
571 static void
572 fence_clear (fence_t f)
573 {
574   state_t s = FENCE_STATE (f);
575   deps_t dc = FENCE_DC (f);
576   void *tc = FENCE_TC (f);
577
578   ilist_clear (&FENCE_BNDS (f));
579
580   gcc_assert ((s != NULL && dc != NULL && tc != NULL)
581               || (s == NULL && dc == NULL && tc == NULL));
582
583   if (s != NULL)
584     free (s);
585
586   if (dc != NULL)
587     delete_deps_context (dc);
588
589   if (tc != NULL)
590     delete_target_context (tc);
591   VEC_free (rtx, gc, FENCE_EXECUTING_INSNS (f));
592   free (FENCE_READY_TICKS (f));
593   FENCE_READY_TICKS (f) = NULL;
594 }
595
596 /* Init a list of fences with successors of OLD_FENCE.  */
597 void
598 init_fences (insn_t old_fence)
599 {
600   insn_t succ;
601   succ_iterator si;
602   bool first = true;
603   int ready_ticks_size = get_max_uid () + 1;
604
605   FOR_EACH_SUCC_1 (succ, si, old_fence,
606                    SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
607     {
608
609       if (first)
610         first = false;
611       else
612         gcc_assert (flag_sel_sched_pipelining_outer_loops);
613
614       flist_add (&fences, succ,
615                  state_create (),
616                  create_deps_context () /* dc */,
617                  create_target_context (true) /* tc */,
618                  NULL_RTX /* last_scheduled_insn */,
619                  NULL, /* executing_insns */
620                  XCNEWVEC (int, ready_ticks_size), /* ready_ticks */
621                  ready_ticks_size,
622                  NULL_RTX /* sched_next */,
623                  1 /* cycle */, 0 /* cycle_issued_insns */,
624                  issue_rate, /* issue_more */
625                  1 /* starts_cycle_p */, 0 /* after_stall_p */);
626     }
627 }
628
629 /* Merges two fences (filling fields of fence F with resulting values) by
630    following rules: 1) state, target context and last scheduled insn are
631    propagated from fallthrough edge if it is available;
632    2) deps context and cycle is propagated from more probable edge;
633    3) all other fields are set to corresponding constant values.
634
635    INSN, STATE, DC, TC, LAST_SCHEDULED_INSN, EXECUTING_INSNS,
636    READY_TICKS, READY_TICKS_SIZE, SCHED_NEXT, CYCLE, ISSUE_MORE
637    and AFTER_STALL_P are the corresponding fields of the second fence.  */
638 static void
639 merge_fences (fence_t f, insn_t insn,
640               state_t state, deps_t dc, void *tc,
641               rtx last_scheduled_insn, VEC(rtx, gc) *executing_insns,
642               int *ready_ticks, int ready_ticks_size,
643               rtx sched_next, int cycle, int issue_more, bool after_stall_p)
644 {
645   insn_t last_scheduled_insn_old = FENCE_LAST_SCHEDULED_INSN (f);
646
647   gcc_assert (sel_bb_head_p (FENCE_INSN (f))
648               && !sched_next && !FENCE_SCHED_NEXT (f));
649
650   /* Check if we can decide which path fences came.
651      If we can't (or don't want to) - reset all.  */
652   if (last_scheduled_insn == NULL
653       || last_scheduled_insn_old == NULL
654       /* This is a case when INSN is reachable on several paths from
655          one insn (this can happen when pipelining of outer loops is on and
656          there are two edges: one going around of inner loop and the other -
657          right through it; in such case just reset everything).  */
658       || last_scheduled_insn == last_scheduled_insn_old)
659     {
660       state_reset (FENCE_STATE (f));
661       state_free (state);
662
663       reset_deps_context (FENCE_DC (f));
664       delete_deps_context (dc);
665
666       reset_target_context (FENCE_TC (f), true);
667       delete_target_context (tc);
668
669       if (cycle > FENCE_CYCLE (f))
670         FENCE_CYCLE (f) = cycle;
671
672       FENCE_LAST_SCHEDULED_INSN (f) = NULL;
673       FENCE_ISSUE_MORE (f) = issue_rate;
674       VEC_free (rtx, gc, executing_insns);
675       free (ready_ticks);
676       if (FENCE_EXECUTING_INSNS (f))
677         VEC_block_remove (rtx, FENCE_EXECUTING_INSNS (f), 0,
678                           VEC_length (rtx, FENCE_EXECUTING_INSNS (f)));
679       if (FENCE_READY_TICKS (f))
680         memset (FENCE_READY_TICKS (f), 0, FENCE_READY_TICKS_SIZE (f));
681     }
682   else
683     {
684       edge edge_old = NULL, edge_new = NULL;
685       edge candidate;
686       succ_iterator si;
687       insn_t succ;
688
689       /* Find fallthrough edge.  */
690       gcc_assert (BLOCK_FOR_INSN (insn)->prev_bb);
691       candidate = find_fallthru_edge (BLOCK_FOR_INSN (insn)->prev_bb);
692
693       if (!candidate
694           || (candidate->src != BLOCK_FOR_INSN (last_scheduled_insn)
695               && candidate->src != BLOCK_FOR_INSN (last_scheduled_insn_old)))
696         {
697           /* No fallthrough edge leading to basic block of INSN.  */
698           state_reset (FENCE_STATE (f));
699           state_free (state);
700
701           reset_target_context (FENCE_TC (f), true);
702           delete_target_context (tc);
703
704           FENCE_LAST_SCHEDULED_INSN (f) = NULL;
705           FENCE_ISSUE_MORE (f) = issue_rate;
706         }
707       else
708         if (candidate->src == BLOCK_FOR_INSN (last_scheduled_insn))
709           {
710             /* Would be weird if same insn is successor of several fallthrough
711                edges.  */
712             gcc_assert (BLOCK_FOR_INSN (insn)->prev_bb
713                         != BLOCK_FOR_INSN (last_scheduled_insn_old));
714
715             state_free (FENCE_STATE (f));
716             FENCE_STATE (f) = state;
717
718             delete_target_context (FENCE_TC (f));
719             FENCE_TC (f) = tc;
720
721             FENCE_LAST_SCHEDULED_INSN (f) = last_scheduled_insn;
722             FENCE_ISSUE_MORE (f) = issue_more;
723           }
724         else
725           {
726             /* Leave STATE, TC and LAST_SCHEDULED_INSN fields untouched.  */
727             state_free (state);
728             delete_target_context (tc);
729
730             gcc_assert (BLOCK_FOR_INSN (insn)->prev_bb
731                         != BLOCK_FOR_INSN (last_scheduled_insn));
732           }
733
734         /* Find edge of first predecessor (last_scheduled_insn_old->insn).  */
735         FOR_EACH_SUCC_1 (succ, si, last_scheduled_insn_old,
736                          SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
737           {
738             if (succ == insn)
739               {
740                 /* No same successor allowed from several edges.  */
741                 gcc_assert (!edge_old);
742                 edge_old = si.e1;
743               }
744           }
745         /* Find edge of second predecessor (last_scheduled_insn->insn).  */
746         FOR_EACH_SUCC_1 (succ, si, last_scheduled_insn,
747                          SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
748           {
749             if (succ == insn)
750               {
751                 /* No same successor allowed from several edges.  */
752                 gcc_assert (!edge_new);
753                 edge_new = si.e1;
754               }
755           }
756
757         /* Check if we can choose most probable predecessor.  */
758         if (edge_old == NULL || edge_new == NULL)
759           {
760             reset_deps_context (FENCE_DC (f));
761             delete_deps_context (dc);
762             VEC_free (rtx, gc, executing_insns);
763             free (ready_ticks);
764
765             FENCE_CYCLE (f) = MAX (FENCE_CYCLE (f), cycle);
766             if (FENCE_EXECUTING_INSNS (f))
767               VEC_block_remove (rtx, FENCE_EXECUTING_INSNS (f), 0,
768                                 VEC_length (rtx, FENCE_EXECUTING_INSNS (f)));
769             if (FENCE_READY_TICKS (f))
770               memset (FENCE_READY_TICKS (f), 0, FENCE_READY_TICKS_SIZE (f));
771           }
772         else
773           if (edge_new->probability > edge_old->probability)
774             {
775               delete_deps_context (FENCE_DC (f));
776               FENCE_DC (f) = dc;
777               VEC_free (rtx, gc, FENCE_EXECUTING_INSNS (f));
778               FENCE_EXECUTING_INSNS (f) = executing_insns;
779               free (FENCE_READY_TICKS (f));
780               FENCE_READY_TICKS (f) = ready_ticks;
781               FENCE_READY_TICKS_SIZE (f) = ready_ticks_size;
782               FENCE_CYCLE (f) = cycle;
783             }
784           else
785             {
786               /* Leave DC and CYCLE untouched.  */
787               delete_deps_context (dc);
788               VEC_free (rtx, gc, executing_insns);
789               free (ready_ticks);
790             }
791     }
792
793   /* Fill remaining invariant fields.  */
794   if (after_stall_p)
795     FENCE_AFTER_STALL_P (f) = 1;
796
797   FENCE_ISSUED_INSNS (f) = 0;
798   FENCE_STARTS_CYCLE_P (f) = 1;
799   FENCE_SCHED_NEXT (f) = NULL;
800 }
801
802 /* Add a new fence to NEW_FENCES list, initializing it from all
803    other parameters.  */
804 static void
805 add_to_fences (flist_tail_t new_fences, insn_t insn,
806                state_t state, deps_t dc, void *tc, rtx last_scheduled_insn,
807                VEC(rtx, gc) *executing_insns, int *ready_ticks,
808                int ready_ticks_size, rtx sched_next, int cycle,
809                int cycle_issued_insns, int issue_rate,
810                bool starts_cycle_p, bool after_stall_p)
811 {
812   fence_t f = flist_lookup (FLIST_TAIL_HEAD (new_fences), insn);
813
814   if (! f)
815     {
816       flist_add (FLIST_TAIL_TAILP (new_fences), insn, state, dc, tc,
817                  last_scheduled_insn, executing_insns, ready_ticks,
818                  ready_ticks_size, sched_next, cycle, cycle_issued_insns,
819                  issue_rate, starts_cycle_p, after_stall_p);
820
821       FLIST_TAIL_TAILP (new_fences)
822         = &FLIST_NEXT (*FLIST_TAIL_TAILP (new_fences));
823     }
824   else
825     {
826       merge_fences (f, insn, state, dc, tc, last_scheduled_insn,
827                     executing_insns, ready_ticks, ready_ticks_size,
828                     sched_next, cycle, issue_rate, after_stall_p);
829     }
830 }
831
832 /* Move the first fence in the OLD_FENCES list to NEW_FENCES.  */
833 void
834 move_fence_to_fences (flist_t old_fences, flist_tail_t new_fences)
835 {
836   fence_t f, old;
837   flist_t *tailp = FLIST_TAIL_TAILP (new_fences);
838
839   old = FLIST_FENCE (old_fences);
840   f = flist_lookup (FLIST_TAIL_HEAD (new_fences),
841                     FENCE_INSN (FLIST_FENCE (old_fences)));
842   if (f)
843     {
844       merge_fences (f, old->insn, old->state, old->dc, old->tc,
845                     old->last_scheduled_insn, old->executing_insns,
846                     old->ready_ticks, old->ready_ticks_size,
847                     old->sched_next, old->cycle, old->issue_more,
848                     old->after_stall_p);
849     }
850   else
851     {
852       _list_add (tailp);
853       FLIST_TAIL_TAILP (new_fences) = &FLIST_NEXT (*tailp);
854       *FLIST_FENCE (*tailp) = *old;
855       init_fence_for_scheduling (FLIST_FENCE (*tailp));
856     }
857   FENCE_INSN (old) = NULL;
858 }
859
860 /* Add a new fence to NEW_FENCES list and initialize most of its data
861    as a clean one.  */
862 void
863 add_clean_fence_to_fences (flist_tail_t new_fences, insn_t succ, fence_t fence)
864 {
865   int ready_ticks_size = get_max_uid () + 1;
866
867   add_to_fences (new_fences,
868                  succ, state_create (), create_deps_context (),
869                  create_target_context (true),
870                  NULL_RTX, NULL,
871                  XCNEWVEC (int, ready_ticks_size), ready_ticks_size,
872                  NULL_RTX, FENCE_CYCLE (fence) + 1,
873                  0, issue_rate, 1, FENCE_AFTER_STALL_P (fence));
874 }
875
876 /* Add a new fence to NEW_FENCES list and initialize all of its data
877    from FENCE and SUCC.  */
878 void
879 add_dirty_fence_to_fences (flist_tail_t new_fences, insn_t succ, fence_t fence)
880 {
881   int * new_ready_ticks
882     = XNEWVEC (int, FENCE_READY_TICKS_SIZE (fence));
883
884   memcpy (new_ready_ticks, FENCE_READY_TICKS (fence),
885           FENCE_READY_TICKS_SIZE (fence) * sizeof (int));
886   add_to_fences (new_fences,
887                  succ, state_create_copy (FENCE_STATE (fence)),
888                  create_copy_of_deps_context (FENCE_DC (fence)),
889                  create_copy_of_target_context (FENCE_TC (fence)),
890                  FENCE_LAST_SCHEDULED_INSN (fence),
891                  VEC_copy (rtx, gc, FENCE_EXECUTING_INSNS (fence)),
892                  new_ready_ticks,
893                  FENCE_READY_TICKS_SIZE (fence),
894                  FENCE_SCHED_NEXT (fence),
895                  FENCE_CYCLE (fence),
896                  FENCE_ISSUED_INSNS (fence),
897                  FENCE_ISSUE_MORE (fence),
898                  FENCE_STARTS_CYCLE_P (fence),
899                  FENCE_AFTER_STALL_P (fence));
900 }
901 \f
902
903 /* Functions to work with regset and nop pools.  */
904
905 /* Returns the new regset from pool.  It might have some of the bits set
906    from the previous usage.  */
907 regset
908 get_regset_from_pool (void)
909 {
910   regset rs;
911
912   if (regset_pool.n != 0)
913     rs = regset_pool.v[--regset_pool.n];
914   else
915     /* We need to create the regset.  */
916     {
917       rs = ALLOC_REG_SET (&reg_obstack);
918
919       if (regset_pool.nn == regset_pool.ss)
920         regset_pool.vv = XRESIZEVEC (regset, regset_pool.vv,
921                                      (regset_pool.ss = 2 * regset_pool.ss + 1));
922       regset_pool.vv[regset_pool.nn++] = rs;
923     }
924
925   regset_pool.diff++;
926
927   return rs;
928 }
929
930 /* Same as above, but returns the empty regset.  */
931 regset
932 get_clear_regset_from_pool (void)
933 {
934   regset rs = get_regset_from_pool ();
935
936   CLEAR_REG_SET (rs);
937   return rs;
938 }
939
940 /* Return regset RS to the pool for future use.  */
941 void
942 return_regset_to_pool (regset rs)
943 {
944   regset_pool.diff--;
945
946   if (regset_pool.n == regset_pool.s)
947     regset_pool.v = XRESIZEVEC (regset, regset_pool.v,
948                                 (regset_pool.s = 2 * regset_pool.s + 1));
949   regset_pool.v[regset_pool.n++] = rs;
950 }
951
952 #ifdef ENABLE_CHECKING
953 /* This is used as a qsort callback for sorting regset pool stacks.
954    X and XX are addresses of two regsets.  They are never equal.  */
955 static int
956 cmp_v_in_regset_pool (const void *x, const void *xx)
957 {
958   return *((const regset *) x) - *((const regset *) xx);
959 }
960 #endif
961
962 /*  Free the regset pool possibly checking for memory leaks.  */
963 void
964 free_regset_pool (void)
965 {
966 #ifdef ENABLE_CHECKING
967   {
968     regset *v = regset_pool.v;
969     int i = 0;
970     int n = regset_pool.n;
971
972     regset *vv = regset_pool.vv;
973     int ii = 0;
974     int nn = regset_pool.nn;
975
976     int diff = 0;
977
978     gcc_assert (n <= nn);
979
980     /* Sort both vectors so it will be possible to compare them.  */
981     qsort (v, n, sizeof (*v), cmp_v_in_regset_pool);
982     qsort (vv, nn, sizeof (*vv), cmp_v_in_regset_pool);
983
984     while (ii < nn)
985       {
986         if (v[i] == vv[ii])
987           i++;
988         else
989           /* VV[II] was lost.  */
990           diff++;
991
992         ii++;
993       }
994
995     gcc_assert (diff == regset_pool.diff);
996   }
997 #endif
998
999   /* If not true - we have a memory leak.  */
1000   gcc_assert (regset_pool.diff == 0);
1001
1002   while (regset_pool.n)
1003     {
1004       --regset_pool.n;
1005       FREE_REG_SET (regset_pool.v[regset_pool.n]);
1006     }
1007
1008   free (regset_pool.v);
1009   regset_pool.v = NULL;
1010   regset_pool.s = 0;
1011
1012   free (regset_pool.vv);
1013   regset_pool.vv = NULL;
1014   regset_pool.nn = 0;
1015   regset_pool.ss = 0;
1016
1017   regset_pool.diff = 0;
1018 }
1019 \f
1020
1021 /* Functions to work with nop pools.  NOP insns are used as temporary
1022    placeholders of the insns being scheduled to allow correct update of
1023    the data sets.  When update is finished, NOPs are deleted.  */
1024
1025 /* A vinsn that is used to represent a nop.  This vinsn is shared among all
1026    nops sel-sched generates.  */
1027 static vinsn_t nop_vinsn = NULL;
1028
1029 /* Emit a nop before INSN, taking it from pool.  */
1030 insn_t
1031 get_nop_from_pool (insn_t insn)
1032 {
1033   insn_t nop;
1034   bool old_p = nop_pool.n != 0;
1035   int flags;
1036
1037   if (old_p)
1038     nop = nop_pool.v[--nop_pool.n];
1039   else
1040     nop = nop_pattern;
1041
1042   nop = emit_insn_before (nop, insn);
1043
1044   if (old_p)
1045     flags = INSN_INIT_TODO_SSID;
1046   else
1047     flags = INSN_INIT_TODO_LUID | INSN_INIT_TODO_SSID;
1048
1049   set_insn_init (INSN_EXPR (insn), nop_vinsn, INSN_SEQNO (insn));
1050   sel_init_new_insn (nop, flags);
1051
1052   return nop;
1053 }
1054
1055 /* Remove NOP from the instruction stream and return it to the pool.  */
1056 void
1057 return_nop_to_pool (insn_t nop, bool full_tidying)
1058 {
1059   gcc_assert (INSN_IN_STREAM_P (nop));
1060   sel_remove_insn (nop, false, full_tidying);
1061
1062   if (nop_pool.n == nop_pool.s)
1063     nop_pool.v = XRESIZEVEC (rtx, nop_pool.v,
1064                              (nop_pool.s = 2 * nop_pool.s + 1));
1065   nop_pool.v[nop_pool.n++] = nop;
1066 }
1067
1068 /* Free the nop pool.  */
1069 void
1070 free_nop_pool (void)
1071 {
1072   nop_pool.n = 0;
1073   nop_pool.s = 0;
1074   free (nop_pool.v);
1075   nop_pool.v = NULL;
1076 }
1077 \f
1078
1079 /* Skip unspec to support ia64 speculation. Called from rtx_equal_p_cb.
1080    The callback is given two rtxes XX and YY and writes the new rtxes
1081    to NX and NY in case some needs to be skipped.  */
1082 static int
1083 skip_unspecs_callback (const_rtx *xx, const_rtx *yy, rtx *nx, rtx* ny)
1084 {
1085   const_rtx x = *xx;
1086   const_rtx y = *yy;
1087
1088   if (GET_CODE (x) == UNSPEC
1089       && (targetm.sched.skip_rtx_p == NULL
1090           || targetm.sched.skip_rtx_p (x)))
1091     {
1092       *nx = XVECEXP (x, 0, 0);
1093       *ny = CONST_CAST_RTX (y);
1094       return 1;
1095     }
1096
1097   if (GET_CODE (y) == UNSPEC
1098       && (targetm.sched.skip_rtx_p == NULL
1099           || targetm.sched.skip_rtx_p (y)))
1100     {
1101       *nx = CONST_CAST_RTX (x);
1102       *ny = XVECEXP (y, 0, 0);
1103       return 1;
1104     }
1105
1106   return 0;
1107 }
1108
1109 /* Callback, called from hash_rtx_cb.  Helps to hash UNSPEC rtx X in a correct way
1110    to support ia64 speculation.  When changes are needed, new rtx X and new mode
1111    NMODE are written, and the callback returns true.  */
1112 static int
1113 hash_with_unspec_callback (const_rtx x, enum machine_mode mode ATTRIBUTE_UNUSED,
1114                            rtx *nx, enum machine_mode* nmode)
1115 {
1116   if (GET_CODE (x) == UNSPEC
1117       && targetm.sched.skip_rtx_p
1118       && targetm.sched.skip_rtx_p (x))
1119     {
1120       *nx = XVECEXP (x, 0 ,0);
1121       *nmode = VOIDmode;
1122       return 1;
1123     }
1124
1125   return 0;
1126 }
1127
1128 /* Returns LHS and RHS are ok to be scheduled separately.  */
1129 static bool
1130 lhs_and_rhs_separable_p (rtx lhs, rtx rhs)
1131 {
1132   if (lhs == NULL || rhs == NULL)
1133     return false;
1134
1135   /* Do not schedule CONST, CONST_INT and CONST_DOUBLE etc as rhs: no point
1136      to use reg, if const can be used.  Moreover, scheduling const as rhs may
1137      lead to mode mismatch cause consts don't have modes but they could be
1138      merged from branches where the same const used in different modes.  */
1139   if (CONSTANT_P (rhs))
1140     return false;
1141
1142   /* ??? Do not rename predicate registers to avoid ICEs in bundling.  */
1143   if (COMPARISON_P (rhs))
1144       return false;
1145
1146   /* Do not allow single REG to be an rhs.  */
1147   if (REG_P (rhs))
1148     return false;
1149
1150   /* See comment at find_used_regs_1 (*1) for explanation of this
1151      restriction.  */
1152   /* FIXME: remove this later.  */
1153   if (MEM_P (lhs))
1154     return false;
1155
1156   /* This will filter all tricky things like ZERO_EXTRACT etc.
1157      For now we don't handle it.  */
1158   if (!REG_P (lhs) && !MEM_P (lhs))
1159     return false;
1160
1161   return true;
1162 }
1163
1164 /* Initialize vinsn VI for INSN.  Only for use from vinsn_create ().  When
1165    FORCE_UNIQUE_P is true, the resulting vinsn will not be clonable.  This is
1166    used e.g. for insns from recovery blocks.  */
1167 static void
1168 vinsn_init (vinsn_t vi, insn_t insn, bool force_unique_p)
1169 {
1170   hash_rtx_callback_function hrcf;
1171   int insn_class;
1172
1173   VINSN_INSN_RTX (vi) = insn;
1174   VINSN_COUNT (vi) = 0;
1175   vi->cost = -1;
1176
1177   if (DF_INSN_UID_SAFE_GET (INSN_UID (insn)) != NULL)
1178     init_id_from_df (VINSN_ID (vi), insn, force_unique_p);
1179   else
1180     deps_init_id (VINSN_ID (vi), insn, force_unique_p);
1181
1182   /* Hash vinsn depending on whether it is separable or not.  */
1183   hrcf = targetm.sched.skip_rtx_p ? hash_with_unspec_callback : NULL;
1184   if (VINSN_SEPARABLE_P (vi))
1185     {
1186       rtx rhs = VINSN_RHS (vi);
1187
1188       VINSN_HASH (vi) = hash_rtx_cb (rhs, GET_MODE (rhs),
1189                                      NULL, NULL, false, hrcf);
1190       VINSN_HASH_RTX (vi) = hash_rtx_cb (VINSN_PATTERN (vi),
1191                                          VOIDmode, NULL, NULL,
1192                                          false, hrcf);
1193     }
1194   else
1195     {
1196       VINSN_HASH (vi) = hash_rtx_cb (VINSN_PATTERN (vi), VOIDmode,
1197                                      NULL, NULL, false, hrcf);
1198       VINSN_HASH_RTX (vi) = VINSN_HASH (vi);
1199     }
1200
1201   insn_class = haifa_classify_insn (insn);
1202   if (insn_class >= 2
1203       && (!targetm.sched.get_insn_spec_ds
1204           || ((targetm.sched.get_insn_spec_ds (insn) & BEGIN_CONTROL)
1205               == 0)))
1206     VINSN_MAY_TRAP_P (vi) = true;
1207   else
1208     VINSN_MAY_TRAP_P (vi) = false;
1209 }
1210
1211 /* Indicate that VI has become the part of an rtx object.  */
1212 void
1213 vinsn_attach (vinsn_t vi)
1214 {
1215   /* Assert that VI is not pending for deletion.  */
1216   gcc_assert (VINSN_INSN_RTX (vi));
1217
1218   VINSN_COUNT (vi)++;
1219 }
1220
1221 /* Create and init VI from the INSN.  Use UNIQUE_P for determining the correct
1222    VINSN_TYPE (VI).  */
1223 static vinsn_t
1224 vinsn_create (insn_t insn, bool force_unique_p)
1225 {
1226   vinsn_t vi = XCNEW (struct vinsn_def);
1227
1228   vinsn_init (vi, insn, force_unique_p);
1229   return vi;
1230 }
1231
1232 /* Return a copy of VI.  When REATTACH_P is true, detach VI and attach
1233    the copy.  */
1234 vinsn_t
1235 vinsn_copy (vinsn_t vi, bool reattach_p)
1236 {
1237   rtx copy;
1238   bool unique = VINSN_UNIQUE_P (vi);
1239   vinsn_t new_vi;
1240
1241   copy = create_copy_of_insn_rtx (VINSN_INSN_RTX (vi));
1242   new_vi = create_vinsn_from_insn_rtx (copy, unique);
1243   if (reattach_p)
1244     {
1245       vinsn_detach (vi);
1246       vinsn_attach (new_vi);
1247     }
1248
1249   return new_vi;
1250 }
1251
1252 /* Delete the VI vinsn and free its data.  */
1253 static void
1254 vinsn_delete (vinsn_t vi)
1255 {
1256   gcc_assert (VINSN_COUNT (vi) == 0);
1257
1258   return_regset_to_pool (VINSN_REG_SETS (vi));
1259   return_regset_to_pool (VINSN_REG_USES (vi));
1260   return_regset_to_pool (VINSN_REG_CLOBBERS (vi));
1261
1262   free (vi);
1263 }
1264
1265 /* Indicate that VI is no longer a part of some rtx object.
1266    Remove VI if it is no longer needed.  */
1267 void
1268 vinsn_detach (vinsn_t vi)
1269 {
1270   gcc_assert (VINSN_COUNT (vi) > 0);
1271
1272   if (--VINSN_COUNT (vi) == 0)
1273     vinsn_delete (vi);
1274 }
1275
1276 /* Returns TRUE if VI is a branch.  */
1277 bool
1278 vinsn_cond_branch_p (vinsn_t vi)
1279 {
1280   insn_t insn;
1281
1282   if (!VINSN_UNIQUE_P (vi))
1283     return false;
1284
1285   insn = VINSN_INSN_RTX (vi);
1286   if (BB_END (BLOCK_FOR_INSN (insn)) != insn)
1287     return false;
1288
1289   return control_flow_insn_p (insn);
1290 }
1291
1292 /* Return latency of INSN.  */
1293 static int
1294 sel_insn_rtx_cost (rtx insn)
1295 {
1296   int cost;
1297
1298   /* A USE insn, or something else we don't need to
1299      understand.  We can't pass these directly to
1300      result_ready_cost or insn_default_latency because it will
1301      trigger a fatal error for unrecognizable insns.  */
1302   if (recog_memoized (insn) < 0)
1303     cost = 0;
1304   else
1305     {
1306       cost = insn_default_latency (insn);
1307
1308       if (cost < 0)
1309         cost = 0;
1310     }
1311
1312   return cost;
1313 }
1314
1315 /* Return the cost of the VI.
1316    !!! FIXME: Unify with haifa-sched.c: insn_cost ().  */
1317 int
1318 sel_vinsn_cost (vinsn_t vi)
1319 {
1320   int cost = vi->cost;
1321
1322   if (cost < 0)
1323     {
1324       cost = sel_insn_rtx_cost (VINSN_INSN_RTX (vi));
1325       vi->cost = cost;
1326     }
1327
1328   return cost;
1329 }
1330 \f
1331
1332 /* Functions for insn emitting.  */
1333
1334 /* Emit new insn after AFTER based on PATTERN and initialize its data from
1335    EXPR and SEQNO.  */
1336 insn_t
1337 sel_gen_insn_from_rtx_after (rtx pattern, expr_t expr, int seqno, insn_t after)
1338 {
1339   insn_t new_insn;
1340
1341   gcc_assert (EXPR_TARGET_AVAILABLE (expr) == true);
1342
1343   new_insn = emit_insn_after (pattern, after);
1344   set_insn_init (expr, NULL, seqno);
1345   sel_init_new_insn (new_insn, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SSID);
1346
1347   return new_insn;
1348 }
1349
1350 /* Force newly generated vinsns to be unique.  */
1351 static bool init_insn_force_unique_p = false;
1352
1353 /* Emit new speculation recovery insn after AFTER based on PATTERN and
1354    initialize its data from EXPR and SEQNO.  */
1355 insn_t
1356 sel_gen_recovery_insn_from_rtx_after (rtx pattern, expr_t expr, int seqno,
1357                                       insn_t after)
1358 {
1359   insn_t insn;
1360
1361   gcc_assert (!init_insn_force_unique_p);
1362
1363   init_insn_force_unique_p = true;
1364   insn = sel_gen_insn_from_rtx_after (pattern, expr, seqno, after);
1365   CANT_MOVE (insn) = 1;
1366   init_insn_force_unique_p = false;
1367
1368   return insn;
1369 }
1370
1371 /* Emit new insn after AFTER based on EXPR and SEQNO.  If VINSN is not NULL,
1372    take it as a new vinsn instead of EXPR's vinsn.
1373    We simplify insns later, after scheduling region in
1374    simplify_changed_insns.  */
1375 insn_t
1376 sel_gen_insn_from_expr_after (expr_t expr, vinsn_t vinsn, int seqno,
1377                               insn_t after)
1378 {
1379   expr_t emit_expr;
1380   insn_t insn;
1381   int flags;
1382
1383   emit_expr = set_insn_init (expr, vinsn ? vinsn : EXPR_VINSN (expr),
1384                              seqno);
1385   insn = EXPR_INSN_RTX (emit_expr);
1386   add_insn_after (insn, after, BLOCK_FOR_INSN (insn));
1387
1388   flags = INSN_INIT_TODO_SSID;
1389   if (INSN_LUID (insn) == 0)
1390     flags |= INSN_INIT_TODO_LUID;
1391   sel_init_new_insn (insn, flags);
1392
1393   return insn;
1394 }
1395
1396 /* Move insn from EXPR after AFTER.  */
1397 insn_t
1398 sel_move_insn (expr_t expr, int seqno, insn_t after)
1399 {
1400   insn_t insn = EXPR_INSN_RTX (expr);
1401   basic_block bb = BLOCK_FOR_INSN (after);
1402   insn_t next = NEXT_INSN (after);
1403
1404   /* Assert that in move_op we disconnected this insn properly.  */
1405   gcc_assert (EXPR_VINSN (INSN_EXPR (insn)) != NULL);
1406   PREV_INSN (insn) = after;
1407   NEXT_INSN (insn) = next;
1408
1409   NEXT_INSN (after) = insn;
1410   PREV_INSN (next) = insn;
1411
1412   /* Update links from insn to bb and vice versa.  */
1413   df_insn_change_bb (insn, bb);
1414   if (BB_END (bb) == after)
1415     BB_END (bb) = insn;
1416
1417   prepare_insn_expr (insn, seqno);
1418   return insn;
1419 }
1420
1421 \f
1422 /* Functions to work with right-hand sides.  */
1423
1424 /* Search for a hash value determined by UID/NEW_VINSN in a sorted vector
1425    VECT and return true when found.  Use NEW_VINSN for comparison only when
1426    COMPARE_VINSNS is true.  Write to INDP the index on which
1427    the search has stopped, such that inserting the new element at INDP will
1428    retain VECT's sort order.  */
1429 static bool
1430 find_in_history_vect_1 (VEC(expr_history_def, heap) *vect,
1431                         unsigned uid, vinsn_t new_vinsn,
1432                         bool compare_vinsns, int *indp)
1433 {
1434   expr_history_def *arr;
1435   int i, j, len = VEC_length (expr_history_def, vect);
1436
1437   if (len == 0)
1438     {
1439       *indp = 0;
1440       return false;
1441     }
1442
1443   arr = VEC_address (expr_history_def, vect);
1444   i = 0, j = len - 1;
1445
1446   while (i <= j)
1447     {
1448       unsigned auid = arr[i].uid;
1449       vinsn_t avinsn = arr[i].new_expr_vinsn;
1450
1451       if (auid == uid
1452           /* When undoing transformation on a bookkeeping copy, the new vinsn
1453              may not be exactly equal to the one that is saved in the vector.
1454              This is because the insn whose copy we're checking was possibly
1455              substituted itself.  */
1456           && (! compare_vinsns
1457               || vinsn_equal_p (avinsn, new_vinsn)))
1458         {
1459           *indp = i;
1460           return true;
1461         }
1462       else if (auid > uid)
1463         break;
1464       i++;
1465     }
1466
1467   *indp = i;
1468   return false;
1469 }
1470
1471 /* Search for a uid of INSN and NEW_VINSN in a sorted vector VECT.  Return
1472    the position found or -1, if no such value is in vector.
1473    Search also for UIDs of insn's originators, if ORIGINATORS_P is true.  */
1474 int
1475 find_in_history_vect (VEC(expr_history_def, heap) *vect, rtx insn,
1476                       vinsn_t new_vinsn, bool originators_p)
1477 {
1478   int ind;
1479
1480   if (find_in_history_vect_1 (vect, INSN_UID (insn), new_vinsn,
1481                               false, &ind))
1482     return ind;
1483
1484   if (INSN_ORIGINATORS (insn) && originators_p)
1485     {
1486       unsigned uid;
1487       bitmap_iterator bi;
1488
1489       EXECUTE_IF_SET_IN_BITMAP (INSN_ORIGINATORS (insn), 0, uid, bi)
1490         if (find_in_history_vect_1 (vect, uid, new_vinsn, false, &ind))
1491           return ind;
1492     }
1493
1494   return -1;
1495 }
1496
1497 /* Insert new element in a sorted history vector pointed to by PVECT,
1498    if it is not there already.  The element is searched using
1499    UID/NEW_EXPR_VINSN pair.  TYPE, OLD_EXPR_VINSN and SPEC_DS save
1500    the history of a transformation.  */
1501 void
1502 insert_in_history_vect (VEC (expr_history_def, heap) **pvect,
1503                         unsigned uid, enum local_trans_type type,
1504                         vinsn_t old_expr_vinsn, vinsn_t new_expr_vinsn,
1505                         ds_t spec_ds)
1506 {
1507   VEC(expr_history_def, heap) *vect = *pvect;
1508   expr_history_def temp;
1509   bool res;
1510   int ind;
1511
1512   res = find_in_history_vect_1 (vect, uid, new_expr_vinsn, true, &ind);
1513
1514   if (res)
1515     {
1516       expr_history_def *phist = VEC_index (expr_history_def, vect, ind);
1517
1518       /* It is possible that speculation types of expressions that were
1519          propagated through different paths will be different here.  In this
1520          case, merge the status to get the correct check later.  */
1521       if (phist->spec_ds != spec_ds)
1522         phist->spec_ds = ds_max_merge (phist->spec_ds, spec_ds);
1523       return;
1524     }
1525
1526   temp.uid = uid;
1527   temp.old_expr_vinsn = old_expr_vinsn;
1528   temp.new_expr_vinsn = new_expr_vinsn;
1529   temp.spec_ds = spec_ds;
1530   temp.type = type;
1531
1532   vinsn_attach (old_expr_vinsn);
1533   vinsn_attach (new_expr_vinsn);
1534   VEC_safe_insert (expr_history_def, heap, vect, ind, &temp);
1535   *pvect = vect;
1536 }
1537
1538 /* Free history vector PVECT.  */
1539 static void
1540 free_history_vect (VEC (expr_history_def, heap) **pvect)
1541 {
1542   unsigned i;
1543   expr_history_def *phist;
1544
1545   if (! *pvect)
1546     return;
1547
1548   for (i = 0;
1549        VEC_iterate (expr_history_def, *pvect, i, phist);
1550        i++)
1551     {
1552       vinsn_detach (phist->old_expr_vinsn);
1553       vinsn_detach (phist->new_expr_vinsn);
1554     }
1555
1556   VEC_free (expr_history_def, heap, *pvect);
1557   *pvect = NULL;
1558 }
1559
1560
1561 /* Compare two vinsns as rhses if possible and as vinsns otherwise.  */
1562 bool
1563 vinsn_equal_p (vinsn_t x, vinsn_t y)
1564 {
1565   rtx_equal_p_callback_function repcf;
1566
1567   if (x == y)
1568     return true;
1569
1570   if (VINSN_TYPE (x) != VINSN_TYPE (y))
1571     return false;
1572
1573   if (VINSN_HASH (x) != VINSN_HASH (y))
1574     return false;
1575
1576   repcf = targetm.sched.skip_rtx_p ? skip_unspecs_callback : NULL;
1577   if (VINSN_SEPARABLE_P (x))
1578     {
1579       /* Compare RHSes of VINSNs.  */
1580       gcc_assert (VINSN_RHS (x));
1581       gcc_assert (VINSN_RHS (y));
1582
1583       return rtx_equal_p_cb (VINSN_RHS (x), VINSN_RHS (y), repcf);
1584     }
1585
1586   return rtx_equal_p_cb (VINSN_PATTERN (x), VINSN_PATTERN (y), repcf);
1587 }
1588 \f
1589
1590 /* Functions for working with expressions.  */
1591
1592 /* Initialize EXPR.  */
1593 static void
1594 init_expr (expr_t expr, vinsn_t vi, int spec, int use, int priority,
1595            int sched_times, int orig_bb_index, ds_t spec_done_ds,
1596            ds_t spec_to_check_ds, int orig_sched_cycle,
1597            VEC(expr_history_def, heap) *history, bool target_available,
1598            bool was_substituted, bool was_renamed, bool needs_spec_check_p,
1599            bool cant_move)
1600 {
1601   vinsn_attach (vi);
1602
1603   EXPR_VINSN (expr) = vi;
1604   EXPR_SPEC (expr) = spec;
1605   EXPR_USEFULNESS (expr) = use;
1606   EXPR_PRIORITY (expr) = priority;
1607   EXPR_PRIORITY_ADJ (expr) = 0;
1608   EXPR_SCHED_TIMES (expr) = sched_times;
1609   EXPR_ORIG_BB_INDEX (expr) = orig_bb_index;
1610   EXPR_ORIG_SCHED_CYCLE (expr) = orig_sched_cycle;
1611   EXPR_SPEC_DONE_DS (expr) = spec_done_ds;
1612   EXPR_SPEC_TO_CHECK_DS (expr) = spec_to_check_ds;
1613
1614   if (history)
1615     EXPR_HISTORY_OF_CHANGES (expr) = history;
1616   else
1617     EXPR_HISTORY_OF_CHANGES (expr) = NULL;
1618
1619   EXPR_TARGET_AVAILABLE (expr) = target_available;
1620   EXPR_WAS_SUBSTITUTED (expr) = was_substituted;
1621   EXPR_WAS_RENAMED (expr) = was_renamed;
1622   EXPR_NEEDS_SPEC_CHECK_P (expr) = needs_spec_check_p;
1623   EXPR_CANT_MOVE (expr) = cant_move;
1624 }
1625
1626 /* Make a copy of the expr FROM into the expr TO.  */
1627 void
1628 copy_expr (expr_t to, expr_t from)
1629 {
1630   VEC(expr_history_def, heap) *temp = NULL;
1631
1632   if (EXPR_HISTORY_OF_CHANGES (from))
1633     {
1634       unsigned i;
1635       expr_history_def *phist;
1636
1637       temp = VEC_copy (expr_history_def, heap, EXPR_HISTORY_OF_CHANGES (from));
1638       for (i = 0;
1639            VEC_iterate (expr_history_def, temp, i, phist);
1640            i++)
1641         {
1642           vinsn_attach (phist->old_expr_vinsn);
1643           vinsn_attach (phist->new_expr_vinsn);
1644         }
1645     }
1646
1647   init_expr (to, EXPR_VINSN (from), EXPR_SPEC (from),
1648              EXPR_USEFULNESS (from), EXPR_PRIORITY (from),
1649              EXPR_SCHED_TIMES (from), EXPR_ORIG_BB_INDEX (from),
1650              EXPR_SPEC_DONE_DS (from), EXPR_SPEC_TO_CHECK_DS (from),
1651              EXPR_ORIG_SCHED_CYCLE (from), temp,
1652              EXPR_TARGET_AVAILABLE (from), EXPR_WAS_SUBSTITUTED (from),
1653              EXPR_WAS_RENAMED (from), EXPR_NEEDS_SPEC_CHECK_P (from),
1654              EXPR_CANT_MOVE (from));
1655 }
1656
1657 /* Same, but the final expr will not ever be in av sets, so don't copy
1658    "uninteresting" data such as bitmap cache.  */
1659 void
1660 copy_expr_onside (expr_t to, expr_t from)
1661 {
1662   init_expr (to, EXPR_VINSN (from), EXPR_SPEC (from), EXPR_USEFULNESS (from),
1663              EXPR_PRIORITY (from), EXPR_SCHED_TIMES (from), 0,
1664              EXPR_SPEC_DONE_DS (from), EXPR_SPEC_TO_CHECK_DS (from), 0, NULL,
1665              EXPR_TARGET_AVAILABLE (from), EXPR_WAS_SUBSTITUTED (from),
1666              EXPR_WAS_RENAMED (from), EXPR_NEEDS_SPEC_CHECK_P (from),
1667              EXPR_CANT_MOVE (from));
1668 }
1669
1670 /* Prepare the expr of INSN for scheduling.  Used when moving insn and when
1671    initializing new insns.  */
1672 static void
1673 prepare_insn_expr (insn_t insn, int seqno)
1674 {
1675   expr_t expr = INSN_EXPR (insn);
1676   ds_t ds;
1677
1678   INSN_SEQNO (insn) = seqno;
1679   EXPR_ORIG_BB_INDEX (expr) = BLOCK_NUM (insn);
1680   EXPR_SPEC (expr) = 0;
1681   EXPR_ORIG_SCHED_CYCLE (expr) = 0;
1682   EXPR_WAS_SUBSTITUTED (expr) = 0;
1683   EXPR_WAS_RENAMED (expr) = 0;
1684   EXPR_TARGET_AVAILABLE (expr) = 1;
1685   INSN_LIVE_VALID_P (insn) = false;
1686
1687   /* ??? If this expression is speculative, make its dependence
1688      as weak as possible.  We can filter this expression later
1689      in process_spec_exprs, because we do not distinguish
1690      between the status we got during compute_av_set and the
1691      existing status.  To be fixed.  */
1692   ds = EXPR_SPEC_DONE_DS (expr);
1693   if (ds)
1694     EXPR_SPEC_DONE_DS (expr) = ds_get_max_dep_weak (ds);
1695
1696   free_history_vect (&EXPR_HISTORY_OF_CHANGES (expr));
1697 }
1698
1699 /* Update target_available bits when merging exprs TO and FROM.  SPLIT_POINT
1700    is non-null when expressions are merged from different successors at
1701    a split point.  */
1702 static void
1703 update_target_availability (expr_t to, expr_t from, insn_t split_point)
1704 {
1705   if (EXPR_TARGET_AVAILABLE (to) < 0
1706       || EXPR_TARGET_AVAILABLE (from) < 0)
1707     EXPR_TARGET_AVAILABLE (to) = -1;
1708   else
1709     {
1710       /* We try to detect the case when one of the expressions
1711          can only be reached through another one.  In this case,
1712          we can do better.  */
1713       if (split_point == NULL)
1714         {
1715           int toind, fromind;
1716
1717           toind = EXPR_ORIG_BB_INDEX (to);
1718           fromind = EXPR_ORIG_BB_INDEX (from);
1719
1720           if (toind && toind == fromind)
1721             /* Do nothing -- everything is done in
1722                merge_with_other_exprs.  */
1723             ;
1724           else
1725             EXPR_TARGET_AVAILABLE (to) = -1;
1726         }
1727       else
1728         EXPR_TARGET_AVAILABLE (to) &= EXPR_TARGET_AVAILABLE (from);
1729     }
1730 }
1731
1732 /* Update speculation bits when merging exprs TO and FROM.  SPLIT_POINT
1733    is non-null when expressions are merged from different successors at
1734    a split point.  */
1735 static void
1736 update_speculative_bits (expr_t to, expr_t from, insn_t split_point)
1737 {
1738   ds_t old_to_ds, old_from_ds;
1739
1740   old_to_ds = EXPR_SPEC_DONE_DS (to);
1741   old_from_ds = EXPR_SPEC_DONE_DS (from);
1742
1743   EXPR_SPEC_DONE_DS (to) = ds_max_merge (old_to_ds, old_from_ds);
1744   EXPR_SPEC_TO_CHECK_DS (to) |= EXPR_SPEC_TO_CHECK_DS (from);
1745   EXPR_NEEDS_SPEC_CHECK_P (to) |= EXPR_NEEDS_SPEC_CHECK_P (from);
1746
1747   /* When merging e.g. control & data speculative exprs, or a control
1748      speculative with a control&data speculative one, we really have
1749      to change vinsn too.  Also, when speculative status is changed,
1750      we also need to record this as a transformation in expr's history.  */
1751   if ((old_to_ds & SPECULATIVE) || (old_from_ds & SPECULATIVE))
1752     {
1753       old_to_ds = ds_get_speculation_types (old_to_ds);
1754       old_from_ds = ds_get_speculation_types (old_from_ds);
1755
1756       if (old_to_ds != old_from_ds)
1757         {
1758           ds_t record_ds;
1759
1760           /* When both expressions are speculative, we need to change
1761              the vinsn first.  */
1762           if ((old_to_ds & SPECULATIVE) && (old_from_ds & SPECULATIVE))
1763             {
1764               int res;
1765
1766               res = speculate_expr (to, EXPR_SPEC_DONE_DS (to));
1767               gcc_assert (res >= 0);
1768             }
1769
1770           if (split_point != NULL)
1771             {
1772               /* Record the change with proper status.  */
1773               record_ds = EXPR_SPEC_DONE_DS (to) & SPECULATIVE;
1774               record_ds &= ~(old_to_ds & SPECULATIVE);
1775               record_ds &= ~(old_from_ds & SPECULATIVE);
1776
1777               insert_in_history_vect (&EXPR_HISTORY_OF_CHANGES (to),
1778                                       INSN_UID (split_point), TRANS_SPECULATION,
1779                                       EXPR_VINSN (from), EXPR_VINSN (to),
1780                                       record_ds);
1781             }
1782         }
1783     }
1784 }
1785
1786
1787 /* Merge bits of FROM expr to TO expr.  When SPLIT_POINT is not NULL,
1788    this is done along different paths.  */
1789 void
1790 merge_expr_data (expr_t to, expr_t from, insn_t split_point)
1791 {
1792   int i;
1793   expr_history_def *phist;
1794
1795   /* For now, we just set the spec of resulting expr to be minimum of the specs
1796      of merged exprs.  */
1797   if (EXPR_SPEC (to) > EXPR_SPEC (from))
1798     EXPR_SPEC (to) = EXPR_SPEC (from);
1799
1800   if (split_point)
1801     EXPR_USEFULNESS (to) += EXPR_USEFULNESS (from);
1802   else
1803     EXPR_USEFULNESS (to) = MAX (EXPR_USEFULNESS (to),
1804                                 EXPR_USEFULNESS (from));
1805
1806   if (EXPR_PRIORITY (to) < EXPR_PRIORITY (from))
1807     EXPR_PRIORITY (to) = EXPR_PRIORITY (from);
1808
1809   if (EXPR_SCHED_TIMES (to) > EXPR_SCHED_TIMES (from))
1810     EXPR_SCHED_TIMES (to) = EXPR_SCHED_TIMES (from);
1811
1812   if (EXPR_ORIG_BB_INDEX (to) != EXPR_ORIG_BB_INDEX (from))
1813     EXPR_ORIG_BB_INDEX (to) = 0;
1814
1815   EXPR_ORIG_SCHED_CYCLE (to) = MIN (EXPR_ORIG_SCHED_CYCLE (to),
1816                                     EXPR_ORIG_SCHED_CYCLE (from));
1817
1818   /* We keep this vector sorted.  */
1819   for (i = 0;
1820        VEC_iterate (expr_history_def, EXPR_HISTORY_OF_CHANGES (from),
1821                     i, phist);
1822        i++)
1823     insert_in_history_vect (&EXPR_HISTORY_OF_CHANGES (to),
1824                             phist->uid, phist->type,
1825                             phist->old_expr_vinsn, phist->new_expr_vinsn,
1826                             phist->spec_ds);
1827
1828   EXPR_WAS_SUBSTITUTED (to) |= EXPR_WAS_SUBSTITUTED (from);
1829   EXPR_WAS_RENAMED (to) |= EXPR_WAS_RENAMED (from);
1830   EXPR_CANT_MOVE (to) |= EXPR_CANT_MOVE (from);
1831
1832   update_target_availability (to, from, split_point);
1833   update_speculative_bits (to, from, split_point);
1834 }
1835
1836 /* Merge bits of FROM expr to TO expr.  Vinsns in the exprs should be equal
1837    in terms of vinsn_equal_p.  SPLIT_POINT is non-null when expressions
1838    are merged from different successors at a split point.  */
1839 void
1840 merge_expr (expr_t to, expr_t from, insn_t split_point)
1841 {
1842   vinsn_t to_vi = EXPR_VINSN (to);
1843   vinsn_t from_vi = EXPR_VINSN (from);
1844
1845   gcc_assert (vinsn_equal_p (to_vi, from_vi));
1846
1847   /* Make sure that speculative pattern is propagated into exprs that
1848      have non-speculative one.  This will provide us with consistent
1849      speculative bits and speculative patterns inside expr.  */
1850   if (EXPR_SPEC_DONE_DS (to) == 0
1851       && EXPR_SPEC_DONE_DS (from) != 0)
1852     change_vinsn_in_expr (to, EXPR_VINSN (from));
1853
1854   merge_expr_data (to, from, split_point);
1855   gcc_assert (EXPR_USEFULNESS (to) <= REG_BR_PROB_BASE);
1856 }
1857
1858 /* Clear the information of this EXPR.  */
1859 void
1860 clear_expr (expr_t expr)
1861 {
1862
1863   vinsn_detach (EXPR_VINSN (expr));
1864   EXPR_VINSN (expr) = NULL;
1865
1866   free_history_vect (&EXPR_HISTORY_OF_CHANGES (expr));
1867 }
1868
1869 /* For a given LV_SET, mark EXPR having unavailable target register.  */
1870 static void
1871 set_unavailable_target_for_expr (expr_t expr, regset lv_set)
1872 {
1873   if (EXPR_SEPARABLE_P (expr))
1874     {
1875       if (REG_P (EXPR_LHS (expr))
1876           && bitmap_bit_p (lv_set, REGNO (EXPR_LHS (expr))))
1877         {
1878           /* If it's an insn like r1 = use (r1, ...), and it exists in
1879              different forms in each of the av_sets being merged, we can't say
1880              whether original destination register is available or not.
1881              However, this still works if destination register is not used
1882              in the original expression: if the branch at which LV_SET we're
1883              looking here is not actually 'other branch' in sense that same
1884              expression is available through it (but it can't be determined
1885              at computation stage because of transformations on one of the
1886              branches), it still won't affect the availability.
1887              Liveness of a register somewhere on a code motion path means
1888              it's either read somewhere on a codemotion path, live on
1889              'other' branch, live at the point immediately following
1890              the original operation, or is read by the original operation.
1891              The latter case is filtered out in the condition below.
1892              It still doesn't cover the case when register is defined and used
1893              somewhere within the code motion path, and in this case we could
1894              miss a unifying code motion along both branches using a renamed
1895              register, but it won't affect a code correctness since upon
1896              an actual code motion a bookkeeping code would be generated.  */
1897           if (bitmap_bit_p (VINSN_REG_USES (EXPR_VINSN (expr)),
1898                             REGNO (EXPR_LHS (expr))))
1899             EXPR_TARGET_AVAILABLE (expr) = -1;
1900           else
1901             EXPR_TARGET_AVAILABLE (expr) = false;
1902         }
1903     }
1904   else
1905     {
1906       unsigned regno;
1907       reg_set_iterator rsi;
1908
1909       EXECUTE_IF_SET_IN_REG_SET (VINSN_REG_SETS (EXPR_VINSN (expr)),
1910                                  0, regno, rsi)
1911         if (bitmap_bit_p (lv_set, regno))
1912           {
1913             EXPR_TARGET_AVAILABLE (expr) = false;
1914             break;
1915           }
1916
1917       EXECUTE_IF_SET_IN_REG_SET (VINSN_REG_CLOBBERS (EXPR_VINSN (expr)),
1918                                  0, regno, rsi)
1919         if (bitmap_bit_p (lv_set, regno))
1920           {
1921             EXPR_TARGET_AVAILABLE (expr) = false;
1922             break;
1923           }
1924     }
1925 }
1926
1927 /* Try to make EXPR speculative.  Return 1 when EXPR's pattern
1928    or dependence status have changed, 2 when also the target register
1929    became unavailable, 0 if nothing had to be changed.  */
1930 int
1931 speculate_expr (expr_t expr, ds_t ds)
1932 {
1933   int res;
1934   rtx orig_insn_rtx;
1935   rtx spec_pat;
1936   ds_t target_ds, current_ds;
1937
1938   /* Obtain the status we need to put on EXPR.   */
1939   target_ds = (ds & SPECULATIVE);
1940   current_ds = EXPR_SPEC_DONE_DS (expr);
1941   ds = ds_full_merge (current_ds, target_ds, NULL_RTX, NULL_RTX);
1942
1943   orig_insn_rtx = EXPR_INSN_RTX (expr);
1944
1945   res = sched_speculate_insn (orig_insn_rtx, ds, &spec_pat);
1946
1947   switch (res)
1948     {
1949     case 0:
1950       EXPR_SPEC_DONE_DS (expr) = ds;
1951       return current_ds != ds ? 1 : 0;
1952
1953     case 1:
1954       {
1955         rtx spec_insn_rtx = create_insn_rtx_from_pattern (spec_pat, NULL_RTX);
1956         vinsn_t spec_vinsn = create_vinsn_from_insn_rtx (spec_insn_rtx, false);
1957
1958         change_vinsn_in_expr (expr, spec_vinsn);
1959         EXPR_SPEC_DONE_DS (expr) = ds;
1960         EXPR_NEEDS_SPEC_CHECK_P (expr) = true;
1961
1962         /* Do not allow clobbering the address register of speculative
1963            insns.  */
1964         if (bitmap_bit_p (VINSN_REG_USES (EXPR_VINSN (expr)),
1965                           expr_dest_regno (expr)))
1966           {
1967             EXPR_TARGET_AVAILABLE (expr) = false;
1968             return 2;
1969           }
1970
1971         return 1;
1972       }
1973
1974     case -1:
1975       return -1;
1976
1977     default:
1978       gcc_unreachable ();
1979       return -1;
1980     }
1981 }
1982
1983 /* Return a destination register, if any, of EXPR.  */
1984 rtx
1985 expr_dest_reg (expr_t expr)
1986 {
1987   rtx dest = VINSN_LHS (EXPR_VINSN (expr));
1988
1989   if (dest != NULL_RTX && REG_P (dest))
1990     return dest;
1991
1992   return NULL_RTX;
1993 }
1994
1995 /* Returns the REGNO of the R's destination.  */
1996 unsigned
1997 expr_dest_regno (expr_t expr)
1998 {
1999   rtx dest = expr_dest_reg (expr);
2000
2001   gcc_assert (dest != NULL_RTX);
2002   return REGNO (dest);
2003 }
2004
2005 /* For a given LV_SET, mark all expressions in JOIN_SET, but not present in
2006    AV_SET having unavailable target register.  */
2007 void
2008 mark_unavailable_targets (av_set_t join_set, av_set_t av_set, regset lv_set)
2009 {
2010   expr_t expr;
2011   av_set_iterator avi;
2012
2013   FOR_EACH_EXPR (expr, avi, join_set)
2014     if (av_set_lookup (av_set, EXPR_VINSN (expr)) == NULL)
2015       set_unavailable_target_for_expr (expr, lv_set);
2016 }
2017 \f
2018
2019 /* Av set functions.  */
2020
2021 /* Add a new element to av set SETP.
2022    Return the element added.  */
2023 static av_set_t
2024 av_set_add_element (av_set_t *setp)
2025 {
2026   /* Insert at the beginning of the list.  */
2027   _list_add (setp);
2028   return *setp;
2029 }
2030
2031 /* Add EXPR to SETP.  */
2032 void
2033 av_set_add (av_set_t *setp, expr_t expr)
2034 {
2035   av_set_t elem;
2036
2037   gcc_assert (!INSN_NOP_P (EXPR_INSN_RTX (expr)));
2038   elem = av_set_add_element (setp);
2039   copy_expr (_AV_SET_EXPR (elem), expr);
2040 }
2041
2042 /* Same, but do not copy EXPR.  */
2043 static void
2044 av_set_add_nocopy (av_set_t *setp, expr_t expr)
2045 {
2046   av_set_t elem;
2047
2048   elem = av_set_add_element (setp);
2049   *_AV_SET_EXPR (elem) = *expr;
2050 }
2051
2052 /* Remove expr pointed to by IP from the av_set.  */
2053 void
2054 av_set_iter_remove (av_set_iterator *ip)
2055 {
2056   clear_expr (_AV_SET_EXPR (*ip->lp));
2057   _list_iter_remove (ip);
2058 }
2059
2060 /* Search for an expr in SET, such that it's equivalent to SOUGHT_VINSN in the
2061    sense of vinsn_equal_p function. Return NULL if no such expr is
2062    in SET was found.  */
2063 expr_t
2064 av_set_lookup (av_set_t set, vinsn_t sought_vinsn)
2065 {
2066   expr_t expr;
2067   av_set_iterator i;
2068
2069   FOR_EACH_EXPR (expr, i, set)
2070     if (vinsn_equal_p (EXPR_VINSN (expr), sought_vinsn))
2071       return expr;
2072   return NULL;
2073 }
2074
2075 /* Same, but also remove the EXPR found.   */
2076 static expr_t
2077 av_set_lookup_and_remove (av_set_t *setp, vinsn_t sought_vinsn)
2078 {
2079   expr_t expr;
2080   av_set_iterator i;
2081
2082   FOR_EACH_EXPR_1 (expr, i, setp)
2083     if (vinsn_equal_p (EXPR_VINSN (expr), sought_vinsn))
2084       {
2085         _list_iter_remove_nofree (&i);
2086         return expr;
2087       }
2088   return NULL;
2089 }
2090
2091 /* Search for an expr in SET, such that it's equivalent to EXPR in the
2092    sense of vinsn_equal_p function of their vinsns, but not EXPR itself.
2093    Returns NULL if no such expr is in SET was found.  */
2094 static expr_t
2095 av_set_lookup_other_equiv_expr (av_set_t set, expr_t expr)
2096 {
2097   expr_t cur_expr;
2098   av_set_iterator i;
2099
2100   FOR_EACH_EXPR (cur_expr, i, set)
2101     {
2102       if (cur_expr == expr)
2103         continue;
2104       if (vinsn_equal_p (EXPR_VINSN (cur_expr), EXPR_VINSN (expr)))
2105         return cur_expr;
2106     }
2107
2108   return NULL;
2109 }
2110
2111 /* If other expression is already in AVP, remove one of them.  */
2112 expr_t
2113 merge_with_other_exprs (av_set_t *avp, av_set_iterator *ip, expr_t expr)
2114 {
2115   expr_t expr2;
2116
2117   expr2 = av_set_lookup_other_equiv_expr (*avp, expr);
2118   if (expr2 != NULL)
2119     {
2120       /* Reset target availability on merge, since taking it only from one
2121          of the exprs would be controversial for different code.  */
2122       EXPR_TARGET_AVAILABLE (expr2) = -1;
2123       EXPR_USEFULNESS (expr2) = 0;
2124
2125       merge_expr (expr2, expr, NULL);
2126
2127       /* Fix usefulness as it should be now REG_BR_PROB_BASE.  */
2128       EXPR_USEFULNESS (expr2) = REG_BR_PROB_BASE;
2129
2130       av_set_iter_remove (ip);
2131       return expr2;
2132     }
2133
2134   return expr;
2135 }
2136
2137 /* Return true if there is an expr that correlates to VI in SET.  */
2138 bool
2139 av_set_is_in_p (av_set_t set, vinsn_t vi)
2140 {
2141   return av_set_lookup (set, vi) != NULL;
2142 }
2143
2144 /* Return a copy of SET.  */
2145 av_set_t
2146 av_set_copy (av_set_t set)
2147 {
2148   expr_t expr;
2149   av_set_iterator i;
2150   av_set_t res = NULL;
2151
2152   FOR_EACH_EXPR (expr, i, set)
2153     av_set_add (&res, expr);
2154
2155   return res;
2156 }
2157
2158 /* Join two av sets that do not have common elements by attaching second set
2159    (pointed to by FROMP) to the end of first set (TO_TAILP must point to
2160    _AV_SET_NEXT of first set's last element).  */
2161 static void
2162 join_distinct_sets (av_set_t *to_tailp, av_set_t *fromp)
2163 {
2164   gcc_assert (*to_tailp == NULL);
2165   *to_tailp = *fromp;
2166   *fromp = NULL;
2167 }
2168
2169 /* Makes set pointed to by TO to be the union of TO and FROM.  Clear av_set
2170    pointed to by FROMP afterwards.  */
2171 void
2172 av_set_union_and_clear (av_set_t *top, av_set_t *fromp, insn_t insn)
2173 {
2174   expr_t expr1;
2175   av_set_iterator i;
2176
2177   /* Delete from TOP all exprs, that present in FROMP.  */
2178   FOR_EACH_EXPR_1 (expr1, i, top)
2179     {
2180       expr_t expr2 = av_set_lookup (*fromp, EXPR_VINSN (expr1));
2181
2182       if (expr2)
2183         {
2184           merge_expr (expr2, expr1, insn);
2185           av_set_iter_remove (&i);
2186         }
2187     }
2188
2189   join_distinct_sets (i.lp, fromp);
2190 }
2191
2192 /* Same as above, but also update availability of target register in
2193    TOP judging by TO_LV_SET and FROM_LV_SET.  */
2194 void
2195 av_set_union_and_live (av_set_t *top, av_set_t *fromp, regset to_lv_set,
2196                        regset from_lv_set, insn_t insn)
2197 {
2198   expr_t expr1;
2199   av_set_iterator i;
2200   av_set_t *to_tailp, in_both_set = NULL;
2201
2202   /* Delete from TOP all expres, that present in FROMP.  */
2203   FOR_EACH_EXPR_1 (expr1, i, top)
2204     {
2205       expr_t expr2 = av_set_lookup_and_remove (fromp, EXPR_VINSN (expr1));
2206
2207       if (expr2)
2208         {
2209           /* It may be that the expressions have different destination
2210              registers, in which case we need to check liveness here.  */
2211           if (EXPR_SEPARABLE_P (expr1))
2212             {
2213               int regno1 = (REG_P (EXPR_LHS (expr1))
2214                             ? (int) expr_dest_regno (expr1) : -1);
2215               int regno2 = (REG_P (EXPR_LHS (expr2))
2216                             ? (int) expr_dest_regno (expr2) : -1);
2217
2218               /* ??? We don't have a way to check restrictions for
2219                *other* register on the current path, we did it only
2220                for the current target register.  Give up.  */
2221               if (regno1 != regno2)
2222                 EXPR_TARGET_AVAILABLE (expr2) = -1;
2223             }
2224           else if (EXPR_INSN_RTX (expr1) != EXPR_INSN_RTX (expr2))
2225             EXPR_TARGET_AVAILABLE (expr2) = -1;
2226
2227           merge_expr (expr2, expr1, insn);
2228           av_set_add_nocopy (&in_both_set, expr2);
2229           av_set_iter_remove (&i);
2230         }
2231       else
2232         /* EXPR1 is present in TOP, but not in FROMP.  Check it on
2233            FROM_LV_SET.  */
2234         set_unavailable_target_for_expr (expr1, from_lv_set);
2235     }
2236   to_tailp = i.lp;
2237
2238   /* These expressions are not present in TOP.  Check liveness
2239      restrictions on TO_LV_SET.  */
2240   FOR_EACH_EXPR (expr1, i, *fromp)
2241     set_unavailable_target_for_expr (expr1, to_lv_set);
2242
2243   join_distinct_sets (i.lp, &in_both_set);
2244   join_distinct_sets (to_tailp, fromp);
2245 }
2246
2247 /* Clear av_set pointed to by SETP.  */
2248 void
2249 av_set_clear (av_set_t *setp)
2250 {
2251   expr_t expr;
2252   av_set_iterator i;
2253
2254   FOR_EACH_EXPR_1 (expr, i, setp)
2255     av_set_iter_remove (&i);
2256
2257   gcc_assert (*setp == NULL);
2258 }
2259
2260 /* Leave only one non-speculative element in the SETP.  */
2261 void
2262 av_set_leave_one_nonspec (av_set_t *setp)
2263 {
2264   expr_t expr;
2265   av_set_iterator i;
2266   bool has_one_nonspec = false;
2267
2268   /* Keep all speculative exprs, and leave one non-speculative
2269      (the first one).  */
2270   FOR_EACH_EXPR_1 (expr, i, setp)
2271     {
2272       if (!EXPR_SPEC_DONE_DS (expr))
2273         {
2274           if (has_one_nonspec)
2275             av_set_iter_remove (&i);
2276           else
2277             has_one_nonspec = true;
2278         }
2279     }
2280 }
2281
2282 /* Return the N'th element of the SET.  */
2283 expr_t
2284 av_set_element (av_set_t set, int n)
2285 {
2286   expr_t expr;
2287   av_set_iterator i;
2288
2289   FOR_EACH_EXPR (expr, i, set)
2290     if (n-- == 0)
2291       return expr;
2292
2293   gcc_unreachable ();
2294   return NULL;
2295 }
2296
2297 /* Deletes all expressions from AVP that are conditional branches (IFs).  */
2298 void
2299 av_set_substract_cond_branches (av_set_t *avp)
2300 {
2301   av_set_iterator i;
2302   expr_t expr;
2303
2304   FOR_EACH_EXPR_1 (expr, i, avp)
2305     if (vinsn_cond_branch_p (EXPR_VINSN (expr)))
2306       av_set_iter_remove (&i);
2307 }
2308
2309 /* Multiplies usefulness attribute of each member of av-set *AVP by
2310    value PROB / ALL_PROB.  */
2311 void
2312 av_set_split_usefulness (av_set_t av, int prob, int all_prob)
2313 {
2314   av_set_iterator i;
2315   expr_t expr;
2316
2317   FOR_EACH_EXPR (expr, i, av)
2318     EXPR_USEFULNESS (expr) = (all_prob
2319                               ? (EXPR_USEFULNESS (expr) * prob) / all_prob
2320                               : 0);
2321 }
2322
2323 /* Leave in AVP only those expressions, which are present in AV,
2324    and return it.  */
2325 void
2326 av_set_intersect (av_set_t *avp, av_set_t av)
2327 {
2328   av_set_iterator i;
2329   expr_t expr;
2330
2331   FOR_EACH_EXPR_1 (expr, i, avp)
2332     if (av_set_lookup (av, EXPR_VINSN (expr)) == NULL)
2333       av_set_iter_remove (&i);
2334 }
2335
2336 \f
2337
2338 /* Dependence hooks to initialize insn data.  */
2339
2340 /* This is used in hooks callable from dependence analysis when initializing
2341    instruction's data.  */
2342 static struct
2343 {
2344   /* Where the dependence was found (lhs/rhs).  */
2345   deps_where_t where;
2346
2347   /* The actual data object to initialize.  */
2348   idata_t id;
2349
2350   /* True when the insn should not be made clonable.  */
2351   bool force_unique_p;
2352
2353   /* True when insn should be treated as of type USE, i.e. never renamed.  */
2354   bool force_use_p;
2355 } deps_init_id_data;
2356
2357
2358 /* Setup ID for INSN.  FORCE_UNIQUE_P is true when INSN should not be
2359    clonable.  */
2360 static void
2361 setup_id_for_insn (idata_t id, insn_t insn, bool force_unique_p)
2362 {
2363   int type;
2364
2365   /* Determine whether INSN could be cloned and return appropriate vinsn type.
2366      That clonable insns which can be separated into lhs and rhs have type SET.
2367      Other clonable insns have type USE.  */
2368   type = GET_CODE (insn);
2369
2370   /* Only regular insns could be cloned.  */
2371   if (type == INSN && !force_unique_p)
2372     type = SET;
2373   else if (type == JUMP_INSN && simplejump_p (insn))
2374     type = PC;
2375   else if (type == DEBUG_INSN)
2376     type = !force_unique_p ? USE : INSN;
2377
2378   IDATA_TYPE (id) = type;
2379   IDATA_REG_SETS (id) = get_clear_regset_from_pool ();
2380   IDATA_REG_USES (id) = get_clear_regset_from_pool ();
2381   IDATA_REG_CLOBBERS (id) = get_clear_regset_from_pool ();
2382 }
2383
2384 /* Start initializing insn data.  */
2385 static void
2386 deps_init_id_start_insn (insn_t insn)
2387 {
2388   gcc_assert (deps_init_id_data.where == DEPS_IN_NOWHERE);
2389
2390   setup_id_for_insn (deps_init_id_data.id, insn,
2391                      deps_init_id_data.force_unique_p);
2392   deps_init_id_data.where = DEPS_IN_INSN;
2393 }
2394
2395 /* Start initializing lhs data.  */
2396 static void
2397 deps_init_id_start_lhs (rtx lhs)
2398 {
2399   gcc_assert (deps_init_id_data.where == DEPS_IN_INSN);
2400   gcc_assert (IDATA_LHS (deps_init_id_data.id) == NULL);
2401
2402   if (IDATA_TYPE (deps_init_id_data.id) == SET)
2403     {
2404       IDATA_LHS (deps_init_id_data.id) = lhs;
2405       deps_init_id_data.where = DEPS_IN_LHS;
2406     }
2407 }
2408
2409 /* Finish initializing lhs data.  */
2410 static void
2411 deps_init_id_finish_lhs (void)
2412 {
2413   deps_init_id_data.where = DEPS_IN_INSN;
2414 }
2415
2416 /* Note a set of REGNO.  */
2417 static void
2418 deps_init_id_note_reg_set (int regno)
2419 {
2420   haifa_note_reg_set (regno);
2421
2422   if (deps_init_id_data.where == DEPS_IN_RHS)
2423     deps_init_id_data.force_use_p = true;
2424
2425   if (IDATA_TYPE (deps_init_id_data.id) != PC)
2426     SET_REGNO_REG_SET (IDATA_REG_SETS (deps_init_id_data.id), regno);
2427
2428 #ifdef STACK_REGS
2429   /* Make instructions that set stack registers to be ineligible for
2430      renaming to avoid issues with find_used_regs.  */
2431   if (IN_RANGE (regno, FIRST_STACK_REG, LAST_STACK_REG))
2432     deps_init_id_data.force_use_p = true;
2433 #endif
2434 }
2435
2436 /* Note a clobber of REGNO.  */
2437 static void
2438 deps_init_id_note_reg_clobber (int regno)
2439 {
2440   haifa_note_reg_clobber (regno);
2441
2442   if (deps_init_id_data.where == DEPS_IN_RHS)
2443     deps_init_id_data.force_use_p = true;
2444
2445   if (IDATA_TYPE (deps_init_id_data.id) != PC)
2446     SET_REGNO_REG_SET (IDATA_REG_CLOBBERS (deps_init_id_data.id), regno);
2447 }
2448
2449 /* Note a use of REGNO.  */
2450 static void
2451 deps_init_id_note_reg_use (int regno)
2452 {
2453   haifa_note_reg_use (regno);
2454
2455   if (IDATA_TYPE (deps_init_id_data.id) != PC)
2456     SET_REGNO_REG_SET (IDATA_REG_USES (deps_init_id_data.id), regno);
2457 }
2458
2459 /* Start initializing rhs data.  */
2460 static void
2461 deps_init_id_start_rhs (rtx rhs)
2462 {
2463   gcc_assert (deps_init_id_data.where == DEPS_IN_INSN);
2464
2465   /* And there was no sel_deps_reset_to_insn ().  */
2466   if (IDATA_LHS (deps_init_id_data.id) != NULL)
2467     {
2468       IDATA_RHS (deps_init_id_data.id) = rhs;
2469       deps_init_id_data.where = DEPS_IN_RHS;
2470     }
2471 }
2472
2473 /* Finish initializing rhs data.  */
2474 static void
2475 deps_init_id_finish_rhs (void)
2476 {
2477   gcc_assert (deps_init_id_data.where == DEPS_IN_RHS
2478               || deps_init_id_data.where == DEPS_IN_INSN);
2479   deps_init_id_data.where = DEPS_IN_INSN;
2480 }
2481
2482 /* Finish initializing insn data.  */
2483 static void
2484 deps_init_id_finish_insn (void)
2485 {
2486   gcc_assert (deps_init_id_data.where == DEPS_IN_INSN);
2487
2488   if (IDATA_TYPE (deps_init_id_data.id) == SET)
2489     {
2490       rtx lhs = IDATA_LHS (deps_init_id_data.id);
2491       rtx rhs = IDATA_RHS (deps_init_id_data.id);
2492
2493       if (lhs == NULL || rhs == NULL || !lhs_and_rhs_separable_p (lhs, rhs)
2494           || deps_init_id_data.force_use_p)
2495         {
2496           /* This should be a USE, as we don't want to schedule its RHS
2497              separately.  However, we still want to have them recorded
2498              for the purposes of substitution.  That's why we don't
2499              simply call downgrade_to_use () here.  */
2500           gcc_assert (IDATA_TYPE (deps_init_id_data.id) == SET);
2501           gcc_assert (!lhs == !rhs);
2502
2503           IDATA_TYPE (deps_init_id_data.id) = USE;
2504         }
2505     }
2506
2507   deps_init_id_data.where = DEPS_IN_NOWHERE;
2508 }
2509
2510 /* This is dependence info used for initializing insn's data.  */
2511 static struct sched_deps_info_def deps_init_id_sched_deps_info;
2512
2513 /* This initializes most of the static part of the above structure.  */
2514 static const struct sched_deps_info_def const_deps_init_id_sched_deps_info =
2515   {
2516     NULL,
2517
2518     deps_init_id_start_insn,
2519     deps_init_id_finish_insn,
2520     deps_init_id_start_lhs,
2521     deps_init_id_finish_lhs,
2522     deps_init_id_start_rhs,
2523     deps_init_id_finish_rhs,
2524     deps_init_id_note_reg_set,
2525     deps_init_id_note_reg_clobber,
2526     deps_init_id_note_reg_use,
2527     NULL, /* note_mem_dep */
2528     NULL, /* note_dep */
2529
2530     0, /* use_cselib */
2531     0, /* use_deps_list */
2532     0 /* generate_spec_deps */
2533   };
2534
2535 /* Initialize INSN's lhs and rhs in ID.  When FORCE_UNIQUE_P is true,
2536    we don't actually need information about lhs and rhs.  */
2537 static void
2538 setup_id_lhs_rhs (idata_t id, insn_t insn, bool force_unique_p)
2539 {
2540   rtx pat = PATTERN (insn);
2541
2542   if (NONJUMP_INSN_P (insn)
2543       && GET_CODE (pat) == SET
2544       && !force_unique_p)
2545     {
2546       IDATA_RHS (id) = SET_SRC (pat);
2547       IDATA_LHS (id) = SET_DEST (pat);
2548     }
2549   else
2550     IDATA_LHS (id) = IDATA_RHS (id) = NULL;
2551 }
2552
2553 /* Possibly downgrade INSN to USE.  */
2554 static void
2555 maybe_downgrade_id_to_use (idata_t id, insn_t insn)
2556 {
2557   bool must_be_use = false;
2558   unsigned uid = INSN_UID (insn);
2559   df_ref *rec;
2560   rtx lhs = IDATA_LHS (id);
2561   rtx rhs = IDATA_RHS (id);
2562
2563   /* We downgrade only SETs.  */
2564   if (IDATA_TYPE (id) != SET)
2565     return;
2566
2567   if (!lhs || !lhs_and_rhs_separable_p (lhs, rhs))
2568     {
2569       IDATA_TYPE (id) = USE;
2570       return;
2571     }
2572
2573   for (rec = DF_INSN_UID_DEFS (uid); *rec; rec++)
2574     {
2575       df_ref def = *rec;
2576
2577       if (DF_REF_INSN (def)
2578           && DF_REF_FLAGS_IS_SET (def, DF_REF_PRE_POST_MODIFY)
2579           && loc_mentioned_in_p (DF_REF_LOC (def), IDATA_RHS (id)))
2580         {
2581           must_be_use = true;
2582           break;
2583         }
2584
2585 #ifdef STACK_REGS
2586       /* Make instructions that set stack registers to be ineligible for
2587          renaming to avoid issues with find_used_regs.  */
2588       if (IN_RANGE (DF_REF_REGNO (def), FIRST_STACK_REG, LAST_STACK_REG))
2589         {
2590           must_be_use = true;
2591           break;
2592         }
2593 #endif
2594     }
2595
2596   if (must_be_use)
2597     IDATA_TYPE (id) = USE;
2598 }
2599
2600 /* Setup register sets describing INSN in ID.  */
2601 static void
2602 setup_id_reg_sets (idata_t id, insn_t insn)
2603 {
2604   unsigned uid = INSN_UID (insn);
2605   df_ref *rec;
2606   regset tmp = get_clear_regset_from_pool ();
2607
2608   for (rec = DF_INSN_UID_DEFS (uid); *rec; rec++)
2609     {
2610       df_ref def = *rec;
2611       unsigned int regno = DF_REF_REGNO (def);
2612
2613       /* Post modifies are treated like clobbers by sched-deps.c.  */
2614       if (DF_REF_FLAGS_IS_SET (def, (DF_REF_MUST_CLOBBER
2615                                      | DF_REF_PRE_POST_MODIFY)))
2616         SET_REGNO_REG_SET (IDATA_REG_CLOBBERS (id), regno);
2617       else if (! DF_REF_FLAGS_IS_SET (def, DF_REF_MAY_CLOBBER))
2618         {
2619           SET_REGNO_REG_SET (IDATA_REG_SETS (id), regno);
2620
2621 #ifdef STACK_REGS
2622           /* For stack registers, treat writes to them as writes
2623              to the first one to be consistent with sched-deps.c.  */
2624           if (IN_RANGE (regno, FIRST_STACK_REG, LAST_STACK_REG))
2625             SET_REGNO_REG_SET (IDATA_REG_SETS (id), FIRST_STACK_REG);
2626 #endif
2627         }
2628       /* Mark special refs that generate read/write def pair.  */
2629       if (DF_REF_FLAGS_IS_SET (def, DF_REF_CONDITIONAL)
2630           || regno == STACK_POINTER_REGNUM)
2631         bitmap_set_bit (tmp, regno);
2632     }
2633
2634   for (rec = DF_INSN_UID_USES (uid); *rec; rec++)
2635     {
2636       df_ref use = *rec;
2637       unsigned int regno = DF_REF_REGNO (use);
2638
2639       /* When these refs are met for the first time, skip them, as
2640          these uses are just counterparts of some defs.  */
2641       if (bitmap_bit_p (tmp, regno))
2642         bitmap_clear_bit (tmp, regno);
2643       else if (! DF_REF_FLAGS_IS_SET (use, DF_REF_CALL_STACK_USAGE))
2644         {
2645           SET_REGNO_REG_SET (IDATA_REG_USES (id), regno);
2646
2647 #ifdef STACK_REGS
2648           /* For stack registers, treat reads from them as reads from
2649              the first one to be consistent with sched-deps.c.  */
2650           if (IN_RANGE (regno, FIRST_STACK_REG, LAST_STACK_REG))
2651             SET_REGNO_REG_SET (IDATA_REG_USES (id), FIRST_STACK_REG);
2652 #endif
2653         }
2654     }
2655
2656   return_regset_to_pool (tmp);
2657 }
2658
2659 /* Initialize instruction data for INSN in ID using DF's data.  */
2660 static void
2661 init_id_from_df (idata_t id, insn_t insn, bool force_unique_p)
2662 {
2663   gcc_assert (DF_INSN_UID_SAFE_GET (INSN_UID (insn)) != NULL);
2664
2665   setup_id_for_insn (id, insn, force_unique_p);
2666   setup_id_lhs_rhs (id, insn, force_unique_p);
2667
2668   if (INSN_NOP_P (insn))
2669     return;
2670
2671   maybe_downgrade_id_to_use (id, insn);
2672   setup_id_reg_sets (id, insn);
2673 }
2674
2675 /* Initialize instruction data for INSN in ID.  */
2676 static void
2677 deps_init_id (idata_t id, insn_t insn, bool force_unique_p)
2678 {
2679   struct deps_desc _dc, *dc = &_dc;
2680
2681   deps_init_id_data.where = DEPS_IN_NOWHERE;
2682   deps_init_id_data.id = id;
2683   deps_init_id_data.force_unique_p = force_unique_p;
2684   deps_init_id_data.force_use_p = false;
2685
2686   init_deps (dc, false);
2687
2688   memcpy (&deps_init_id_sched_deps_info,
2689           &const_deps_init_id_sched_deps_info,
2690           sizeof (deps_init_id_sched_deps_info));
2691
2692   if (spec_info != NULL)
2693     deps_init_id_sched_deps_info.generate_spec_deps = 1;
2694
2695   sched_deps_info = &deps_init_id_sched_deps_info;
2696
2697   deps_analyze_insn (dc, insn);
2698
2699   free_deps (dc);
2700
2701   deps_init_id_data.id = NULL;
2702 }
2703
2704 \f
2705
2706 /* Implement hooks for collecting fundamental insn properties like if insn is
2707    an ASM or is within a SCHED_GROUP.  */
2708
2709 /* True when a "one-time init" data for INSN was already inited.  */
2710 static bool
2711 first_time_insn_init (insn_t insn)
2712 {
2713   return INSN_LIVE (insn) == NULL;
2714 }
2715
2716 /* Hash an entry in a transformed_insns hashtable.  */
2717 static hashval_t
2718 hash_transformed_insns (const void *p)
2719 {
2720   return VINSN_HASH_RTX (((const struct transformed_insns *) p)->vinsn_old);
2721 }
2722
2723 /* Compare the entries in a transformed_insns hashtable.  */
2724 static int
2725 eq_transformed_insns (const void *p, const void *q)
2726 {
2727   rtx i1 = VINSN_INSN_RTX (((const struct transformed_insns *) p)->vinsn_old);
2728   rtx i2 = VINSN_INSN_RTX (((const struct transformed_insns *) q)->vinsn_old);
2729
2730   if (INSN_UID (i1) == INSN_UID (i2))
2731     return 1;
2732   return rtx_equal_p (PATTERN (i1), PATTERN (i2));
2733 }
2734
2735 /* Free an entry in a transformed_insns hashtable.  */
2736 static void
2737 free_transformed_insns (void *p)
2738 {
2739   struct transformed_insns *pti = (struct transformed_insns *) p;
2740
2741   vinsn_detach (pti->vinsn_old);
2742   vinsn_detach (pti->vinsn_new);
2743   free (pti);
2744 }
2745
2746 /* Init the s_i_d data for INSN which should be inited just once, when
2747    we first see the insn.  */
2748 static void
2749 init_first_time_insn_data (insn_t insn)
2750 {
2751   /* This should not be set if this is the first time we init data for
2752      insn.  */
2753   gcc_assert (first_time_insn_init (insn));
2754
2755   /* These are needed for nops too.  */
2756   INSN_LIVE (insn) = get_regset_from_pool ();
2757   INSN_LIVE_VALID_P (insn) = false;
2758
2759   if (!INSN_NOP_P (insn))
2760     {
2761       INSN_ANALYZED_DEPS (insn) = BITMAP_ALLOC (NULL);
2762       INSN_FOUND_DEPS (insn) = BITMAP_ALLOC (NULL);
2763       INSN_TRANSFORMED_INSNS (insn)
2764         = htab_create (16, hash_transformed_insns,
2765                        eq_transformed_insns, free_transformed_insns);
2766       init_deps (&INSN_DEPS_CONTEXT (insn), true);
2767     }
2768 }
2769
2770 /* Free almost all above data for INSN that is scheduled already.
2771    Used for extra-large basic blocks.  */
2772 void
2773 free_data_for_scheduled_insn (insn_t insn)
2774 {
2775   gcc_assert (! first_time_insn_init (insn));
2776
2777   if (! INSN_ANALYZED_DEPS (insn))
2778     return;
2779
2780   BITMAP_FREE (INSN_ANALYZED_DEPS (insn));
2781   BITMAP_FREE (INSN_FOUND_DEPS (insn));
2782   htab_delete (INSN_TRANSFORMED_INSNS (insn));
2783
2784   /* This is allocated only for bookkeeping insns.  */
2785   if (INSN_ORIGINATORS (insn))
2786     BITMAP_FREE (INSN_ORIGINATORS (insn));
2787   free_deps (&INSN_DEPS_CONTEXT (insn));
2788
2789   INSN_ANALYZED_DEPS (insn) = NULL;
2790
2791   /* Clear the readonly flag so we would ICE when trying to recalculate
2792      the deps context (as we believe that it should not happen).  */
2793   (&INSN_DEPS_CONTEXT (insn))->readonly = 0;
2794 }
2795
2796 /* Free the same data as above for INSN.  */
2797 static void
2798 free_first_time_insn_data (insn_t insn)
2799 {
2800   gcc_assert (! first_time_insn_init (insn));
2801
2802   free_data_for_scheduled_insn (insn);
2803   return_regset_to_pool (INSN_LIVE (insn));
2804   INSN_LIVE (insn) = NULL;
2805   INSN_LIVE_VALID_P (insn) = false;
2806 }
2807
2808 /* Initialize region-scope data structures for basic blocks.  */
2809 static void
2810 init_global_and_expr_for_bb (basic_block bb)
2811 {
2812   if (sel_bb_empty_p (bb))
2813     return;
2814
2815   invalidate_av_set (bb);
2816 }
2817
2818 /* Data for global dependency analysis (to initialize CANT_MOVE and
2819    SCHED_GROUP_P).  */
2820 static struct
2821 {
2822   /* Previous insn.  */
2823   insn_t prev_insn;
2824 } init_global_data;
2825
2826 /* Determine if INSN is in the sched_group, is an asm or should not be
2827    cloned.  After that initialize its expr.  */
2828 static void
2829 init_global_and_expr_for_insn (insn_t insn)
2830 {
2831   if (LABEL_P (insn))
2832     return;
2833
2834   if (NOTE_INSN_BASIC_BLOCK_P (insn))
2835     {
2836       init_global_data.prev_insn = NULL_RTX;
2837       return;
2838     }
2839
2840   gcc_assert (INSN_P (insn));
2841
2842   if (SCHED_GROUP_P (insn))
2843     /* Setup a sched_group.  */
2844     {
2845       insn_t prev_insn = init_global_data.prev_insn;
2846
2847       if (prev_insn)
2848         INSN_SCHED_NEXT (prev_insn) = insn;
2849
2850       init_global_data.prev_insn = insn;
2851     }
2852   else
2853     init_global_data.prev_insn = NULL_RTX;
2854
2855   if (GET_CODE (PATTERN (insn)) == ASM_INPUT
2856       || asm_noperands (PATTERN (insn)) >= 0)
2857     /* Mark INSN as an asm.  */
2858     INSN_ASM_P (insn) = true;
2859
2860   {
2861     bool force_unique_p;
2862     ds_t spec_done_ds;
2863
2864     /* Certain instructions cannot be cloned.  */
2865     if (CANT_MOVE (insn)
2866         || INSN_ASM_P (insn)
2867         || SCHED_GROUP_P (insn)
2868         || prologue_epilogue_contains (insn)
2869         /* Exception handling insns are always unique.  */
2870         || (cfun->can_throw_non_call_exceptions && can_throw_internal (insn))
2871         /* TRAP_IF though have an INSN code is control_flow_insn_p ().  */
2872         || control_flow_insn_p (insn))
2873       force_unique_p = true;
2874     else
2875       force_unique_p = false;
2876
2877     if (targetm.sched.get_insn_spec_ds)
2878       {
2879         spec_done_ds = targetm.sched.get_insn_spec_ds (insn);
2880         spec_done_ds = ds_get_max_dep_weak (spec_done_ds);
2881       }
2882     else
2883       spec_done_ds = 0;
2884
2885     /* Initialize INSN's expr.  */
2886     init_expr (INSN_EXPR (insn), vinsn_create (insn, force_unique_p), 0,
2887                REG_BR_PROB_BASE, INSN_PRIORITY (insn), 0, BLOCK_NUM (insn),
2888                spec_done_ds, 0, 0, NULL, true, false, false, false,
2889                CANT_MOVE (insn));
2890   }
2891
2892   init_first_time_insn_data (insn);
2893 }
2894
2895 /* Scan the region and initialize instruction data for basic blocks BBS.  */
2896 void
2897 sel_init_global_and_expr (bb_vec_t bbs)
2898 {
2899   /* ??? It would be nice to implement push / pop scheme for sched_infos.  */
2900   const struct sched_scan_info_def ssi =
2901     {
2902       NULL, /* extend_bb */
2903       init_global_and_expr_for_bb, /* init_bb */
2904       extend_insn_data, /* extend_insn */
2905       init_global_and_expr_for_insn /* init_insn */
2906     };
2907
2908   sched_scan (&ssi, bbs, NULL, NULL, NULL);
2909 }
2910
2911 /* Finalize region-scope data structures for basic blocks.  */
2912 static void
2913 finish_global_and_expr_for_bb (basic_block bb)
2914 {
2915   av_set_clear (&BB_AV_SET (bb));
2916   BB_AV_LEVEL (bb) = 0;
2917 }
2918
2919 /* Finalize INSN's data.  */
2920 static void
2921 finish_global_and_expr_insn (insn_t insn)
2922 {
2923   if (LABEL_P (insn) || NOTE_INSN_BASIC_BLOCK_P (insn))
2924     return;
2925
2926   gcc_assert (INSN_P (insn));
2927
2928   if (INSN_LUID (insn) > 0)
2929     {
2930       free_first_time_insn_data (insn);
2931       INSN_WS_LEVEL (insn) = 0;
2932       CANT_MOVE (insn) = 0;
2933
2934       /* We can no longer assert this, as vinsns of this insn could be
2935          easily live in other insn's caches.  This should be changed to
2936          a counter-like approach among all vinsns.  */
2937       gcc_assert (true || VINSN_COUNT (INSN_VINSN (insn)) == 1);
2938       clear_expr (INSN_EXPR (insn));
2939     }
2940 }
2941
2942 /* Finalize per instruction data for the whole region.  */
2943 void
2944 sel_finish_global_and_expr (void)
2945 {
2946   {
2947     bb_vec_t bbs;
2948     int i;
2949
2950     bbs = VEC_alloc (basic_block, heap, current_nr_blocks);
2951
2952     for (i = 0; i < current_nr_blocks; i++)
2953       VEC_quick_push (basic_block, bbs, BASIC_BLOCK (BB_TO_BLOCK (i)));
2954
2955     /* Clear AV_SETs and INSN_EXPRs.  */
2956     {
2957       const struct sched_scan_info_def ssi =
2958         {
2959           NULL, /* extend_bb */
2960           finish_global_and_expr_for_bb, /* init_bb */
2961           NULL, /* extend_insn */
2962           finish_global_and_expr_insn /* init_insn */
2963         };
2964
2965       sched_scan (&ssi, bbs, NULL, NULL, NULL);
2966     }
2967
2968     VEC_free (basic_block, heap, bbs);
2969   }
2970
2971   finish_insns ();
2972 }
2973 \f
2974
2975 /* In the below hooks, we merely calculate whether or not a dependence
2976    exists, and in what part of insn.  However, we will need more data
2977    when we'll start caching dependence requests.  */
2978
2979 /* Container to hold information for dependency analysis.  */
2980 static struct
2981 {
2982   deps_t dc;
2983
2984   /* A variable to track which part of rtx we are scanning in
2985      sched-deps.c: sched_analyze_insn ().  */
2986   deps_where_t where;
2987
2988   /* Current producer.  */
2989   insn_t pro;
2990
2991   /* Current consumer.  */
2992   vinsn_t con;
2993
2994   /* Is SEL_DEPS_HAS_DEP_P[DEPS_IN_X] is true, then X has a dependence.
2995      X is from { INSN, LHS, RHS }.  */
2996   ds_t has_dep_p[DEPS_IN_NOWHERE];
2997 } has_dependence_data;
2998
2999 /* Start analyzing dependencies of INSN.  */
3000 static void
3001 has_dependence_start_insn (insn_t insn ATTRIBUTE_UNUSED)
3002 {
3003   gcc_assert (has_dependence_data.where == DEPS_IN_NOWHERE);
3004
3005   has_dependence_data.where = DEPS_IN_INSN;
3006 }
3007
3008 /* Finish analyzing dependencies of an insn.  */
3009 static void
3010 has_dependence_finish_insn (void)
3011 {
3012   gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
3013
3014   has_dependence_data.where = DEPS_IN_NOWHERE;
3015 }
3016
3017 /* Start analyzing dependencies of LHS.  */
3018 static void
3019 has_dependence_start_lhs (rtx lhs ATTRIBUTE_UNUSED)
3020 {
3021   gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
3022
3023   if (VINSN_LHS (has_dependence_data.con) != NULL)
3024     has_dependence_data.where = DEPS_IN_LHS;
3025 }
3026
3027 /* Finish analyzing dependencies of an lhs.  */
3028 static void
3029 has_dependence_finish_lhs (void)
3030 {
3031   has_dependence_data.where = DEPS_IN_INSN;
3032 }
3033
3034 /* Start analyzing dependencies of RHS.  */
3035 static void
3036 has_dependence_start_rhs (rtx rhs ATTRIBUTE_UNUSED)
3037 {
3038   gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
3039
3040   if (VINSN_RHS (has_dependence_data.con) != NULL)
3041     has_dependence_data.where = DEPS_IN_RHS;
3042 }
3043
3044 /* Start analyzing dependencies of an rhs.  */
3045 static void
3046 has_dependence_finish_rhs (void)
3047 {
3048   gcc_assert (has_dependence_data.where == DEPS_IN_RHS
3049               || has_dependence_data.where == DEPS_IN_INSN);
3050
3051   has_dependence_data.where = DEPS_IN_INSN;
3052 }
3053
3054 /* Note a set of REGNO.  */
3055 static void
3056 has_dependence_note_reg_set (int regno)
3057 {
3058   struct deps_reg *reg_last = &has_dependence_data.dc->reg_last[regno];
3059
3060   if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
3061                                        VINSN_INSN_RTX
3062                                        (has_dependence_data.con)))
3063     {
3064       ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
3065
3066       if (reg_last->sets != NULL
3067           || reg_last->clobbers != NULL)
3068         *dsp = (*dsp & ~SPECULATIVE) | DEP_OUTPUT;
3069
3070       if (reg_last->uses)
3071         *dsp = (*dsp & ~SPECULATIVE) | DEP_ANTI;
3072     }
3073 }
3074
3075 /* Note a clobber of REGNO.  */
3076 static void
3077 has_dependence_note_reg_clobber (int regno)
3078 {
3079   struct deps_reg *reg_last = &has_dependence_data.dc->reg_last[regno];
3080
3081   if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
3082                                        VINSN_INSN_RTX
3083                                        (has_dependence_data.con)))
3084     {
3085       ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
3086
3087       if (reg_last->sets)
3088         *dsp = (*dsp & ~SPECULATIVE) | DEP_OUTPUT;
3089
3090       if (reg_last->uses)
3091         *dsp = (*dsp & ~SPECULATIVE) | DEP_ANTI;
3092     }
3093 }
3094
3095 /* Note a use of REGNO.  */
3096 static void
3097 has_dependence_note_reg_use (int regno)
3098 {
3099   struct deps_reg *reg_last = &has_dependence_data.dc->reg_last[regno];
3100
3101   if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
3102                                        VINSN_INSN_RTX
3103                                        (has_dependence_data.con)))
3104     {
3105       ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
3106
3107       if (reg_last->sets)
3108         *dsp = (*dsp & ~SPECULATIVE) | DEP_TRUE;
3109
3110       if (reg_last->clobbers)
3111         *dsp = (*dsp & ~SPECULATIVE) | DEP_ANTI;
3112
3113       /* Handle BE_IN_SPEC.  */
3114       if (reg_last->uses)
3115         {
3116           ds_t pro_spec_checked_ds;
3117
3118           pro_spec_checked_ds = INSN_SPEC_CHECKED_DS (has_dependence_data.pro);
3119           pro_spec_checked_ds = ds_get_max_dep_weak (pro_spec_checked_ds);
3120
3121           if (pro_spec_checked_ds != 0)
3122             /* Merge BE_IN_SPEC bits into *DSP.  */
3123             *dsp = ds_full_merge (*dsp, pro_spec_checked_ds,
3124                                   NULL_RTX, NULL_RTX);
3125         }
3126     }
3127 }
3128
3129 /* Note a memory dependence.  */
3130 static void
3131 has_dependence_note_mem_dep (rtx mem ATTRIBUTE_UNUSED,
3132                              rtx pending_mem ATTRIBUTE_UNUSED,
3133                              insn_t pending_insn ATTRIBUTE_UNUSED,
3134                              ds_t ds ATTRIBUTE_UNUSED)
3135 {
3136   if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
3137                                        VINSN_INSN_RTX (has_dependence_data.con)))
3138     {
3139       ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
3140
3141       *dsp = ds_full_merge (ds, *dsp, pending_mem, mem);
3142     }
3143 }
3144
3145 /* Note a dependence.  */
3146 static void
3147 has_dependence_note_dep (insn_t pro ATTRIBUTE_UNUSED,
3148                          ds_t ds ATTRIBUTE_UNUSED)
3149 {
3150   if (!sched_insns_conditions_mutex_p (has_dependence_data.pro,
3151                                        VINSN_INSN_RTX (has_dependence_data.con)))
3152     {
3153       ds_t *dsp = &has_dependence_data.has_dep_p[has_dependence_data.where];
3154
3155       *dsp = ds_full_merge (ds, *dsp, NULL_RTX, NULL_RTX);
3156     }
3157 }
3158
3159 /* Mark the insn as having a hard dependence that prevents speculation.  */
3160 void
3161 sel_mark_hard_insn (rtx insn)
3162 {
3163   int i;
3164
3165   /* Only work when we're in has_dependence_p mode.
3166      ??? This is a hack, this should actually be a hook.  */
3167   if (!has_dependence_data.dc || !has_dependence_data.pro)
3168     return;
3169
3170   gcc_assert (insn == VINSN_INSN_RTX (has_dependence_data.con));
3171   gcc_assert (has_dependence_data.where == DEPS_IN_INSN);
3172
3173   for (i = 0; i < DEPS_IN_NOWHERE; i++)
3174     has_dependence_data.has_dep_p[i] &= ~SPECULATIVE;
3175 }
3176
3177 /* This structure holds the hooks for the dependency analysis used when
3178    actually processing dependencies in the scheduler.  */
3179 static struct sched_deps_info_def has_dependence_sched_deps_info;
3180
3181 /* This initializes most of the fields of the above structure.  */
3182 static const struct sched_deps_info_def const_has_dependence_sched_deps_info =
3183   {
3184     NULL,
3185
3186     has_dependence_start_insn,
3187     has_dependence_finish_insn,
3188     has_dependence_start_lhs,
3189     has_dependence_finish_lhs,
3190     has_dependence_start_rhs,
3191     has_dependence_finish_rhs,
3192     has_dependence_note_reg_set,
3193     has_dependence_note_reg_clobber,
3194     has_dependence_note_reg_use,
3195     has_dependence_note_mem_dep,
3196     has_dependence_note_dep,
3197
3198     0, /* use_cselib */
3199     0, /* use_deps_list */
3200     0 /* generate_spec_deps */
3201   };
3202
3203 /* Initialize has_dependence_sched_deps_info with extra spec field.  */
3204 static void
3205 setup_has_dependence_sched_deps_info (void)
3206 {
3207   memcpy (&has_dependence_sched_deps_info,
3208           &const_has_dependence_sched_deps_info,
3209           sizeof (has_dependence_sched_deps_info));
3210
3211   if (spec_info != NULL)
3212     has_dependence_sched_deps_info.generate_spec_deps = 1;
3213
3214   sched_deps_info = &has_dependence_sched_deps_info;
3215 }
3216
3217 /* Remove all dependences found and recorded in has_dependence_data array.  */
3218 void
3219 sel_clear_has_dependence (void)
3220 {
3221   int i;
3222
3223   for (i = 0; i < DEPS_IN_NOWHERE; i++)
3224     has_dependence_data.has_dep_p[i] = 0;
3225 }
3226
3227 /* Return nonzero if EXPR has is dependent upon PRED.  Return the pointer
3228    to the dependence information array in HAS_DEP_PP.  */
3229 ds_t
3230 has_dependence_p (expr_t expr, insn_t pred, ds_t **has_dep_pp)
3231 {
3232   int i;
3233   ds_t ds;
3234   struct deps_desc *dc;
3235
3236   if (INSN_SIMPLEJUMP_P (pred))
3237     /* Unconditional jump is just a transfer of control flow.
3238        Ignore it.  */
3239     return false;
3240
3241   dc = &INSN_DEPS_CONTEXT (pred);
3242
3243   /* We init this field lazily.  */
3244   if (dc->reg_last == NULL)
3245     init_deps_reg_last (dc);
3246
3247   if (!dc->readonly)
3248     {
3249       has_dependence_data.pro = NULL;
3250       /* Initialize empty dep context with information about PRED.  */
3251       advance_deps_context (dc, pred);
3252       dc->readonly = 1;
3253     }
3254
3255   has_dependence_data.where = DEPS_IN_NOWHERE;
3256   has_dependence_data.pro = pred;
3257   has_dependence_data.con = EXPR_VINSN (expr);
3258   has_dependence_data.dc = dc;
3259
3260   sel_clear_has_dependence ();
3261
3262   /* Now catch all dependencies that would be generated between PRED and
3263      INSN.  */
3264   setup_has_dependence_sched_deps_info ();
3265   deps_analyze_insn (dc, EXPR_INSN_RTX (expr));
3266   has_dependence_data.dc = NULL;
3267
3268   /* When a barrier was found, set DEPS_IN_INSN bits.  */
3269   if (dc->last_reg_pending_barrier == TRUE_BARRIER)
3270     has_dependence_data.has_dep_p[DEPS_IN_INSN] = DEP_TRUE;
3271   else if (dc->last_reg_pending_barrier == MOVE_BARRIER)
3272     has_dependence_data.has_dep_p[DEPS_IN_INSN] = DEP_ANTI;
3273
3274   /* Do not allow stores to memory to move through checks.  Currently
3275      we don't move this to sched-deps.c as the check doesn't have
3276      obvious places to which this dependence can be attached.
3277      FIMXE: this should go to a hook.  */
3278   if (EXPR_LHS (expr)
3279       && MEM_P (EXPR_LHS (expr))
3280       && sel_insn_is_speculation_check (pred))
3281     has_dependence_data.has_dep_p[DEPS_IN_INSN] = DEP_ANTI;
3282
3283   *has_dep_pp = has_dependence_data.has_dep_p;
3284   ds = 0;
3285   for (i = 0; i < DEPS_IN_NOWHERE; i++)
3286     ds = ds_full_merge (ds, has_dependence_data.has_dep_p[i],
3287                         NULL_RTX, NULL_RTX);
3288
3289   return ds;
3290 }
3291 \f
3292
3293 /* Dependence hooks implementation that checks dependence latency constraints
3294    on the insns being scheduled.  The entry point for these routines is
3295    tick_check_p predicate.  */
3296
3297 static struct
3298 {
3299   /* An expr we are currently checking.  */
3300   expr_t expr;
3301
3302   /* A minimal cycle for its scheduling.  */
3303   int cycle;
3304
3305   /* Whether we have seen a true dependence while checking.  */
3306   bool seen_true_dep_p;
3307 } tick_check_data;
3308
3309 /* Update minimal scheduling cycle for tick_check_insn given that it depends
3310    on PRO with status DS and weight DW.  */
3311 static void
3312 tick_check_dep_with_dw (insn_t pro_insn, ds_t ds, dw_t dw)
3313 {
3314   expr_t con_expr = tick_check_data.expr;
3315   insn_t con_insn = EXPR_INSN_RTX (con_expr);
3316
3317   if (con_insn != pro_insn)
3318     {
3319       enum reg_note dt;
3320       int tick;
3321
3322       if (/* PROducer was removed from above due to pipelining.  */
3323           !INSN_IN_STREAM_P (pro_insn)
3324           /* Or PROducer was originally on the next iteration regarding the
3325              CONsumer.  */
3326           || (INSN_SCHED_TIMES (pro_insn)
3327               - EXPR_SCHED_TIMES (con_expr)) > 1)
3328         /* Don't count this dependence.  */
3329         return;
3330
3331       dt = ds_to_dt (ds);
3332       if (dt == REG_DEP_TRUE)
3333         tick_check_data.seen_true_dep_p = true;
3334
3335       gcc_assert (INSN_SCHED_CYCLE (pro_insn) > 0);
3336
3337       {
3338         dep_def _dep, *dep = &_dep;
3339
3340         init_dep (dep, pro_insn, con_insn, dt);
3341
3342         tick = INSN_SCHED_CYCLE (pro_insn) + dep_cost_1 (dep, dw);
3343       }
3344
3345       /* When there are several kinds of dependencies between pro and con,
3346          only REG_DEP_TRUE should be taken into account.  */
3347       if (tick > tick_check_data.cycle
3348           && (dt == REG_DEP_TRUE || !tick_check_data.seen_true_dep_p))
3349         tick_check_data.cycle = tick;
3350     }
3351 }
3352
3353 /* An implementation of note_dep hook.  */
3354 static void
3355 tick_check_note_dep (insn_t pro, ds_t ds)
3356 {
3357   tick_check_dep_with_dw (pro, ds, 0);
3358 }
3359
3360 /* An implementation of note_mem_dep hook.  */
3361 static void
3362 tick_check_note_mem_dep (rtx mem1, rtx mem2, insn_t pro, ds_t ds)
3363 {
3364   dw_t dw;
3365
3366   dw = (ds_to_dt (ds) == REG_DEP_TRUE
3367         ? estimate_dep_weak (mem1, mem2)
3368         : 0);
3369
3370   tick_check_dep_with_dw (pro, ds, dw);
3371 }
3372
3373 /* This structure contains hooks for dependence analysis used when determining
3374    whether an insn is ready for scheduling.  */
3375 static struct sched_deps_info_def tick_check_sched_deps_info =
3376   {
3377     NULL,
3378
3379     NULL,
3380     NULL,
3381     NULL,
3382     NULL,
3383     NULL,
3384     NULL,
3385     haifa_note_reg_set,
3386     haifa_note_reg_clobber,
3387     haifa_note_reg_use,
3388     tick_check_note_mem_dep,
3389     tick_check_note_dep,
3390
3391     0, 0, 0
3392   };
3393
3394 /* Estimate number of cycles from the current cycle of FENCE until EXPR can be
3395    scheduled.  Return 0 if all data from producers in DC is ready.  */
3396 int
3397 tick_check_p (expr_t expr, deps_t dc, fence_t fence)
3398 {
3399   int cycles_left;
3400   /* Initialize variables.  */
3401   tick_check_data.expr = expr;
3402   tick_check_data.cycle = 0;
3403   tick_check_data.seen_true_dep_p = false;
3404   sched_deps_info = &tick_check_sched_deps_info;
3405
3406   gcc_assert (!dc->readonly);
3407   dc->readonly = 1;
3408   deps_analyze_insn (dc, EXPR_INSN_RTX (expr));
3409   dc->readonly = 0;
3410
3411   cycles_left = tick_check_data.cycle - FENCE_CYCLE (fence);
3412
3413   return cycles_left >= 0 ? cycles_left : 0;
3414 }
3415 \f
3416
3417 /* Functions to work with insns.  */
3418
3419 /* Returns true if LHS of INSN is the same as DEST of an insn
3420    being moved.  */
3421 bool
3422 lhs_of_insn_equals_to_dest_p (insn_t insn, rtx dest)
3423 {
3424   rtx lhs = INSN_LHS (insn);
3425
3426   if (lhs == NULL || dest == NULL)
3427     return false;
3428
3429   return rtx_equal_p (lhs, dest);
3430 }
3431
3432 /* Return s_i_d entry of INSN.  Callable from debugger.  */
3433 sel_insn_data_def
3434 insn_sid (insn_t insn)
3435 {
3436   return *SID (insn);
3437 }
3438
3439 /* True when INSN is a speculative check.  We can tell this by looking
3440    at the data structures of the selective scheduler, not by examining
3441    the pattern.  */
3442 bool
3443 sel_insn_is_speculation_check (rtx insn)
3444 {
3445   return s_i_d && !! INSN_SPEC_CHECKED_DS (insn);
3446 }
3447
3448 /* Extracts machine mode MODE and destination location DST_LOC
3449    for given INSN.  */
3450 void
3451 get_dest_and_mode (rtx insn, rtx *dst_loc, enum machine_mode *mode)
3452 {
3453   rtx pat = PATTERN (insn);
3454
3455   gcc_assert (dst_loc);
3456   gcc_assert (GET_CODE (pat) == SET);
3457
3458   *dst_loc = SET_DEST (pat);
3459
3460   gcc_assert (*dst_loc);
3461   gcc_assert (MEM_P (*dst_loc) || REG_P (*dst_loc));
3462
3463   if (mode)
3464     *mode = GET_MODE (*dst_loc);
3465 }
3466
3467 /* Returns true when moving through JUMP will result in bookkeeping
3468    creation.  */
3469 bool
3470 bookkeeping_can_be_created_if_moved_through_p (insn_t jump)
3471 {
3472   insn_t succ;
3473   succ_iterator si;
3474
3475   FOR_EACH_SUCC (succ, si, jump)
3476     if (sel_num_cfg_preds_gt_1 (succ))
3477       return true;
3478
3479   return false;
3480 }
3481
3482 /* Return 'true' if INSN is the only one in its basic block.  */
3483 static bool
3484 insn_is_the_only_one_in_bb_p (insn_t insn)
3485 {
3486   return sel_bb_head_p (insn) && sel_bb_end_p (insn);
3487 }
3488
3489 #ifdef ENABLE_CHECKING
3490 /* Check that the region we're scheduling still has at most one
3491    backedge.  */
3492 static void
3493 verify_backedges (void)
3494 {
3495   if (pipelining_p)
3496     {
3497       int i, n = 0;
3498       edge e;
3499       edge_iterator ei;
3500
3501       for (i = 0; i < current_nr_blocks; i++)
3502         FOR_EACH_EDGE (e, ei, BASIC_BLOCK (BB_TO_BLOCK (i))->succs)
3503           if (in_current_region_p (e->dest)
3504               && BLOCK_TO_BB (e->dest->index) < i)
3505             n++;
3506
3507       gcc_assert (n <= 1);
3508     }
3509 }
3510 #endif
3511 \f
3512
3513 /* Functions to work with control flow.  */
3514
3515 /* Recompute BLOCK_TO_BB and BB_FOR_BLOCK for current region so that blocks
3516    are sorted in topological order (it might have been invalidated by
3517    redirecting an edge).  */
3518 static void
3519 sel_recompute_toporder (void)
3520 {
3521   int i, n, rgn;
3522   int *postorder, n_blocks;
3523
3524   postorder = XALLOCAVEC (int, n_basic_blocks);
3525   n_blocks = post_order_compute (postorder, false, false);
3526
3527   rgn = CONTAINING_RGN (BB_TO_BLOCK (0));
3528   for (n = 0, i = n_blocks - 1; i >= 0; i--)
3529     if (CONTAINING_RGN (postorder[i]) == rgn)
3530       {
3531         BLOCK_TO_BB (postorder[i]) = n;
3532         BB_TO_BLOCK (n) = postorder[i];
3533         n++;
3534       }
3535
3536   /* Assert that we updated info for all blocks.  We may miss some blocks if
3537      this function is called when redirecting an edge made a block
3538      unreachable, but that block is not deleted yet.  */
3539   gcc_assert (n == RGN_NR_BLOCKS (rgn));
3540 }
3541
3542 /* Tidy the possibly empty block BB.  */
3543 static bool
3544 maybe_tidy_empty_bb (basic_block bb, bool recompute_toporder_p)
3545 {
3546   basic_block succ_bb, pred_bb;
3547   edge e;
3548   edge_iterator ei;
3549   bool rescan_p;
3550
3551   /* Keep empty bb only if this block immediately precedes EXIT and
3552      has incoming non-fallthrough edge, or it has no predecessors or
3553      successors.  Otherwise remove it.  */
3554   if (!sel_bb_empty_p (bb)
3555       || (single_succ_p (bb)
3556           && single_succ (bb) == EXIT_BLOCK_PTR
3557           && (!single_pred_p (bb)
3558               || !(single_pred_edge (bb)->flags & EDGE_FALLTHRU)))
3559       || EDGE_COUNT (bb->preds) == 0
3560       || EDGE_COUNT (bb->succs) == 0)
3561     return false;
3562
3563   /* Do not attempt to redirect complex edges.  */
3564   FOR_EACH_EDGE (e, ei, bb->preds)
3565     if (e->flags & EDGE_COMPLEX)
3566       return false;
3567
3568   free_data_sets (bb);
3569
3570   /* Do not delete BB if it has more than one successor.
3571      That can occur when we moving a jump.  */
3572   if (!single_succ_p (bb))
3573     {
3574       gcc_assert (can_merge_blocks_p (bb->prev_bb, bb));
3575       sel_merge_blocks (bb->prev_bb, bb);
3576       return true;
3577     }
3578
3579   succ_bb = single_succ (bb);
3580   rescan_p = true;
3581   pred_bb = NULL;
3582
3583   /* Redirect all non-fallthru edges to the next bb.  */
3584   while (rescan_p)
3585     {
3586       rescan_p = false;
3587
3588       FOR_EACH_EDGE (e, ei, bb->preds)
3589         {
3590           pred_bb = e->src;
3591
3592           if (!(e->flags & EDGE_FALLTHRU))
3593             {
3594               recompute_toporder_p |= sel_redirect_edge_and_branch (e, succ_bb);
3595               rescan_p = true;
3596               break;
3597             }
3598         }
3599     }
3600
3601   /* If it is possible - merge BB with its predecessor.  */
3602   if (can_merge_blocks_p (bb->prev_bb, bb))
3603     sel_merge_blocks (bb->prev_bb, bb);
3604   else
3605     /* Otherwise this is a block without fallthru predecessor.
3606        Just delete it.  */
3607     {
3608       gcc_assert (pred_bb != NULL);
3609
3610       if (in_current_region_p (pred_bb))
3611         move_bb_info (pred_bb, bb);
3612       remove_empty_bb (bb, true);
3613     }
3614
3615   if (recompute_toporder_p)
3616     sel_recompute_toporder ();
3617
3618 #ifdef ENABLE_CHECKING
3619   verify_backedges ();
3620 #endif
3621
3622   return true;
3623 }
3624
3625 /* Tidy the control flow after we have removed original insn from
3626    XBB.  Return true if we have removed some blocks.  When FULL_TIDYING
3627    is true, also try to optimize control flow on non-empty blocks.  */
3628 bool
3629 tidy_control_flow (basic_block xbb, bool full_tidying)
3630 {
3631   bool changed = true;
3632   insn_t first, last;
3633
3634   /* First check whether XBB is empty.  */
3635   changed = maybe_tidy_empty_bb (xbb, false);
3636   if (changed || !full_tidying)
3637     return changed;
3638
3639   /* Check if there is a unnecessary jump after insn left.  */
3640   if (jump_leads_only_to_bb_p (BB_END (xbb), xbb->next_bb)
3641       && INSN_SCHED_TIMES (BB_END (xbb)) == 0
3642       && !IN_CURRENT_FENCE_P (BB_END (xbb)))
3643     {
3644       if (sel_remove_insn (BB_END (xbb), false, false))
3645         return true;
3646       tidy_fallthru_edge (EDGE_SUCC (xbb, 0));
3647     }
3648
3649   first = sel_bb_head (xbb);
3650   last = sel_bb_end (xbb);
3651   if (MAY_HAVE_DEBUG_INSNS)
3652     {
3653       if (first != last && DEBUG_INSN_P (first))
3654         do
3655           first = NEXT_INSN (first);
3656         while (first != last && (DEBUG_INSN_P (first) || NOTE_P (first)));
3657
3658       if (first != last && DEBUG_INSN_P (last))
3659         do
3660           last = PREV_INSN (last);
3661         while (first != last && (DEBUG_INSN_P (last) || NOTE_P (last)));
3662     }
3663   /* Check if there is an unnecessary jump in previous basic block leading
3664      to next basic block left after removing INSN from stream.
3665      If it is so, remove that jump and redirect edge to current
3666      basic block (where there was INSN before deletion).  This way
3667      when NOP will be deleted several instructions later with its
3668      basic block we will not get a jump to next instruction, which
3669      can be harmful.  */
3670   if (first == last
3671       && !sel_bb_empty_p (xbb)
3672       && INSN_NOP_P (last)
3673       /* Flow goes fallthru from current block to the next.  */
3674       && EDGE_COUNT (xbb->succs) == 1
3675       && (EDGE_SUCC (xbb, 0)->flags & EDGE_FALLTHRU)
3676       /* When successor is an EXIT block, it may not be the next block.  */
3677       && single_succ (xbb) != EXIT_BLOCK_PTR
3678       /* And unconditional jump in previous basic block leads to
3679          next basic block of XBB and this jump can be safely removed.  */
3680       && in_current_region_p (xbb->prev_bb)
3681       && jump_leads_only_to_bb_p (BB_END (xbb->prev_bb), xbb->next_bb)
3682       && INSN_SCHED_TIMES (BB_END (xbb->prev_bb)) == 0
3683       /* Also this jump is not at the scheduling boundary.  */
3684       && !IN_CURRENT_FENCE_P (BB_END (xbb->prev_bb)))
3685     {
3686       bool recompute_toporder_p;
3687       /* Clear data structures of jump - jump itself will be removed
3688          by sel_redirect_edge_and_branch.  */
3689       clear_expr (INSN_EXPR (BB_END (xbb->prev_bb)));
3690       recompute_toporder_p
3691         = sel_redirect_edge_and_branch (EDGE_SUCC (xbb->prev_bb, 0), xbb);
3692
3693       gcc_assert (EDGE_SUCC (xbb->prev_bb, 0)->flags & EDGE_FALLTHRU);
3694
3695       /* It can turn out that after removing unused jump, basic block
3696          that contained that jump, becomes empty too.  In such case
3697          remove it too.  */
3698       if (sel_bb_empty_p (xbb->prev_bb))
3699         changed = maybe_tidy_empty_bb (xbb->prev_bb, recompute_toporder_p);
3700       else if (recompute_toporder_p)
3701         sel_recompute_toporder ();
3702     }
3703
3704   return changed;
3705 }
3706
3707 /* Purge meaningless empty blocks in the middle of a region.  */
3708 void
3709 purge_empty_blocks (void)
3710 {
3711   /* Do not attempt to delete preheader.  */
3712   int i = sel_is_loop_preheader_p (BASIC_BLOCK (BB_TO_BLOCK (0))) ? 1 : 0;
3713
3714   while (i < current_nr_blocks)
3715     {
3716       basic_block b = BASIC_BLOCK (BB_TO_BLOCK (i));
3717
3718       if (maybe_tidy_empty_bb (b, false))
3719         continue;
3720
3721       i++;
3722     }
3723 }
3724
3725 /* Rip-off INSN from the insn stream.  When ONLY_DISCONNECT is true,
3726    do not delete insn's data, because it will be later re-emitted.
3727    Return true if we have removed some blocks afterwards.  */
3728 bool
3729 sel_remove_insn (insn_t insn, bool only_disconnect, bool full_tidying)
3730 {
3731   basic_block bb = BLOCK_FOR_INSN (insn);
3732
3733   gcc_assert (INSN_IN_STREAM_P (insn));
3734
3735   if (DEBUG_INSN_P (insn) && BB_AV_SET_VALID_P (bb))
3736     {
3737       expr_t expr;
3738       av_set_iterator i;
3739
3740       /* When we remove a debug insn that is head of a BB, it remains
3741          in the AV_SET of the block, but it shouldn't.  */
3742       FOR_EACH_EXPR_1 (expr, i, &BB_AV_SET (bb))
3743         if (EXPR_INSN_RTX (expr) == insn)
3744           {
3745             av_set_iter_remove (&i);
3746             break;
3747           }
3748     }
3749
3750   if (only_disconnect)
3751     {
3752       insn_t prev = PREV_INSN (insn);
3753       insn_t next = NEXT_INSN (insn);
3754       basic_block bb = BLOCK_FOR_INSN (insn);
3755
3756       NEXT_INSN (prev) = next;
3757       PREV_INSN (next) = prev;
3758
3759       if (BB_HEAD (bb) == insn)
3760         {
3761           gcc_assert (BLOCK_FOR_INSN (prev) == bb);
3762           BB_HEAD (bb) = prev;
3763         }
3764       if (BB_END (bb) == insn)
3765         BB_END (bb) = prev;
3766     }
3767   else
3768     {
3769       remove_insn (insn);
3770       clear_expr (INSN_EXPR (insn));
3771     }
3772
3773   /* It is necessary to null this fields before calling add_insn ().  */
3774   PREV_INSN (insn) = NULL_RTX;
3775   NEXT_INSN (insn) = NULL_RTX;
3776
3777   return tidy_control_flow (bb, full_tidying);
3778 }
3779
3780 /* Estimate number of the insns in BB.  */
3781 static int
3782 sel_estimate_number_of_insns (basic_block bb)
3783 {
3784   int res = 0;
3785   insn_t insn = NEXT_INSN (BB_HEAD (bb)), next_tail = NEXT_INSN (BB_END (bb));
3786
3787   for (; insn != next_tail; insn = NEXT_INSN (insn))
3788     if (NONDEBUG_INSN_P (insn))
3789       res++;
3790
3791   return res;
3792 }
3793
3794 /* We don't need separate luids for notes or labels.  */
3795 static int
3796 sel_luid_for_non_insn (rtx x)
3797 {
3798   gcc_assert (NOTE_P (x) || LABEL_P (x));
3799
3800   return -1;
3801 }
3802
3803 /* Return seqno of the only predecessor of INSN.  */
3804 static int
3805 get_seqno_of_a_pred (insn_t insn)
3806 {
3807   int seqno;
3808
3809   gcc_assert (INSN_SIMPLEJUMP_P (insn));
3810
3811   if (!sel_bb_head_p (insn))
3812     seqno = INSN_SEQNO (PREV_INSN (insn));
3813   else
3814     {
3815       basic_block bb = BLOCK_FOR_INSN (insn);
3816
3817       if (single_pred_p (bb)
3818           && !in_current_region_p (single_pred (bb)))
3819         {
3820           /* We can have preds outside a region when splitting edges
3821              for pipelining of an outer loop.  Use succ instead.
3822              There should be only one of them.  */
3823           insn_t succ = NULL;
3824           succ_iterator si;
3825           bool first = true;
3826
3827           gcc_assert (flag_sel_sched_pipelining_outer_loops
3828                       && current_loop_nest);
3829           FOR_EACH_SUCC_1 (succ, si, insn,
3830                            SUCCS_NORMAL | SUCCS_SKIP_TO_LOOP_EXITS)
3831             {
3832               gcc_assert (first);
3833               first = false;
3834             }
3835
3836           gcc_assert (succ != NULL);
3837           seqno = INSN_SEQNO (succ);
3838         }
3839       else
3840         {
3841           insn_t *preds;
3842           int n;
3843
3844           cfg_preds (BLOCK_FOR_INSN (insn), &preds, &n);
3845           gcc_assert (n == 1);
3846
3847           seqno = INSN_SEQNO (preds[0]);
3848
3849           free (preds);
3850         }
3851     }
3852
3853   return seqno;
3854 }
3855
3856 /*  Find the proper seqno for inserting at INSN.  Returns -1 if no predecessors
3857     with positive seqno exist.  */
3858 int
3859 get_seqno_by_preds (rtx insn)
3860 {
3861   basic_block bb = BLOCK_FOR_INSN (insn);
3862   rtx tmp = insn, head = BB_HEAD (bb);
3863   insn_t *preds;
3864   int n, i, seqno;
3865
3866   while (tmp != head)
3867     if (INSN_P (tmp))
3868       return INSN_SEQNO (tmp);
3869     else
3870       tmp = PREV_INSN (tmp);
3871
3872   cfg_preds (bb, &preds, &n);
3873   for (i = 0, seqno = -1; i < n; i++)
3874     seqno = MAX (seqno, INSN_SEQNO (preds[i]));
3875
3876   return seqno;
3877 }
3878
3879 \f
3880
3881 /* Extend pass-scope data structures for basic blocks.  */
3882 void
3883 sel_extend_global_bb_info (void)
3884 {
3885   VEC_safe_grow_cleared (sel_global_bb_info_def, heap, sel_global_bb_info,
3886                          last_basic_block);
3887 }
3888
3889 /* Extend region-scope data structures for basic blocks.  */
3890 static void
3891 extend_region_bb_info (void)
3892 {
3893   VEC_safe_grow_cleared (sel_region_bb_info_def, heap, sel_region_bb_info,
3894                          last_basic_block);
3895 }
3896
3897 /* Extend all data structures to fit for all basic blocks.  */
3898 static void
3899 extend_bb_info (void)
3900 {
3901   sel_extend_global_bb_info ();
3902   extend_region_bb_info ();
3903 }
3904
3905 /* Finalize pass-scope data structures for basic blocks.  */
3906 void
3907 sel_finish_global_bb_info (void)
3908 {
3909   VEC_free (sel_global_bb_info_def, heap, sel_global_bb_info);
3910 }
3911
3912 /* Finalize region-scope data structures for basic blocks.  */
3913 static void
3914 finish_region_bb_info (void)
3915 {
3916   VEC_free (sel_region_bb_info_def, heap, sel_region_bb_info);
3917 }
3918 \f
3919
3920 /* Data for each insn in current region.  */
3921 VEC (sel_insn_data_def, heap) *s_i_d = NULL;
3922
3923 /* A vector for the insns we've emitted.  */
3924 static insn_vec_t new_insns = NULL;
3925
3926 /* Extend data structures for insns from current region.  */
3927 static void
3928 extend_insn_data (void)
3929 {
3930   int reserve;
3931
3932   sched_extend_target ();
3933   sched_deps_init (false);
3934
3935   /* Extend data structures for insns from current region.  */
3936   reserve = (sched_max_luid + 1
3937              - VEC_length (sel_insn_data_def, s_i_d));
3938   if (reserve > 0
3939       && ! VEC_space (sel_insn_data_def, s_i_d, reserve))
3940     {
3941       int size;
3942
3943       if (sched_max_luid / 2 > 1024)
3944         size = sched_max_luid + 1024;
3945       else
3946         size = 3 * sched_max_luid / 2;
3947
3948
3949       VEC_safe_grow_cleared (sel_insn_data_def, heap, s_i_d, size);
3950     }
3951 }
3952
3953 /* Finalize data structures for insns from current region.  */
3954 static void
3955 finish_insns (void)
3956 {
3957   unsigned i;
3958
3959   /* Clear here all dependence contexts that may have left from insns that were
3960      removed during the scheduling.  */
3961   for (i = 0; i < VEC_length (sel_insn_data_def, s_i_d); i++)
3962     {
3963       sel_insn_data_def *sid_entry = VEC_index (sel_insn_data_def, s_i_d, i);
3964
3965       if (sid_entry->live)
3966         return_regset_to_pool (sid_entry->live);
3967       if (sid_entry->analyzed_deps)
3968         {
3969           BITMAP_FREE (sid_entry->analyzed_deps);
3970           BITMAP_FREE (sid_entry->found_deps);
3971           htab_delete (sid_entry->transformed_insns);
3972           free_deps (&sid_entry->deps_context);
3973         }
3974       if (EXPR_VINSN (&sid_entry->expr))
3975         {
3976           clear_expr (&sid_entry->expr);
3977
3978           /* Also, clear CANT_MOVE bit here, because we really don't want it
3979              to be passed to the next region.  */
3980           CANT_MOVE_BY_LUID (i) = 0;
3981         }
3982     }
3983
3984   VEC_free (sel_insn_data_def, heap, s_i_d);
3985 }
3986
3987 /* A proxy to pass initialization data to init_insn ().  */
3988 static sel_insn_data_def _insn_init_ssid;
3989 static sel_insn_data_t insn_init_ssid = &_insn_init_ssid;
3990
3991 /* If true create a new vinsn.  Otherwise use the one from EXPR.  */
3992 static bool insn_init_create_new_vinsn_p;
3993
3994 /* Set all necessary data for initialization of the new insn[s].  */
3995 static expr_t
3996 set_insn_init (expr_t expr, vinsn_t vi, int seqno)
3997 {
3998   expr_t x = &insn_init_ssid->expr;
3999
4000   copy_expr_onside (x, expr);
4001   if (vi != NULL)
4002     {
4003       insn_init_create_new_vinsn_p = false;
4004       change_vinsn_in_expr (x, vi);
4005     }
4006   else
4007     insn_init_create_new_vinsn_p = true;
4008
4009   insn_init_ssid->seqno = seqno;
4010   return x;
4011 }
4012
4013 /* Init data for INSN.  */
4014 static void
4015 init_insn_data (insn_t insn)
4016 {
4017   expr_t expr;
4018   sel_insn_data_t ssid = insn_init_ssid;
4019
4020   /* The fields mentioned below are special and hence are not being
4021      propagated to the new insns.  */
4022   gcc_assert (!ssid->asm_p && ssid->sched_next == NULL
4023               && !ssid->after_stall_p && ssid->sched_cycle == 0);
4024   gcc_assert (INSN_P (insn) && INSN_LUID (insn) > 0);
4025
4026   expr = INSN_EXPR (insn);
4027   copy_expr (expr, &ssid->expr);
4028   prepare_insn_expr (insn, ssid->seqno);
4029
4030   if (insn_init_create_new_vinsn_p)
4031     change_vinsn_in_expr (expr, vinsn_create (insn, init_insn_force_unique_p));
4032
4033   if (first_time_insn_init (insn))
4034     init_first_time_insn_data (insn);
4035 }
4036
4037 /* This is used to initialize spurious jumps generated by
4038    sel_redirect_edge ().  */
4039 static void
4040 init_simplejump_data (insn_t insn)
4041 {
4042   init_expr (INSN_EXPR (insn), vinsn_create (insn, false), 0,
4043              REG_BR_PROB_BASE, 0, 0, 0, 0, 0, 0, NULL, true, false, false,
4044              false, true);
4045   INSN_SEQNO (insn) = get_seqno_of_a_pred (insn);
4046   init_first_time_insn_data (insn);
4047 }
4048
4049 /* Perform deferred initialization of insns.  This is used to process
4050    a new jump that may be created by redirect_edge.  */
4051 void
4052 sel_init_new_insn (insn_t insn, int flags)
4053 {
4054   /* We create data structures for bb when the first insn is emitted in it.  */
4055   if (INSN_P (insn)
4056       && INSN_IN_STREAM_P (insn)
4057       && insn_is_the_only_one_in_bb_p (insn))
4058     {
4059       extend_bb_info ();
4060       create_initial_data_sets (BLOCK_FOR_INSN (insn));
4061     }
4062
4063   if (flags & INSN_INIT_TODO_LUID)
4064     sched_init_luids (NULL, NULL, NULL, insn);
4065
4066   if (flags & INSN_INIT_TODO_SSID)
4067     {
4068       extend_insn_data ();
4069       init_insn_data (insn);
4070       clear_expr (&insn_init_ssid->expr);
4071     }
4072
4073   if (flags & INSN_INIT_TODO_SIMPLEJUMP)
4074     {
4075       extend_insn_data ();
4076       init_simplejump_data (insn);
4077     }
4078
4079   gcc_assert (CONTAINING_RGN (BLOCK_NUM (insn))
4080               == CONTAINING_RGN (BB_TO_BLOCK (0)));
4081 }
4082 \f
4083
4084 /* Functions to init/finish work with lv sets.  */
4085
4086 /* Init BB_LV_SET of BB from DF_LR_IN set of BB.  */
4087 static void
4088 init_lv_set (basic_block bb)
4089 {
4090   gcc_assert (!BB_LV_SET_VALID_P (bb));
4091
4092   BB_LV_SET (bb) = get_regset_from_pool ();
4093   COPY_REG_SET (BB_LV_SET (bb), DF_LR_IN (bb));
4094   BB_LV_SET_VALID_P (bb) = true;
4095 }
4096
4097 /* Copy liveness information to BB from FROM_BB.  */
4098 static void
4099 copy_lv_set_from (basic_block bb, basic_block from_bb)
4100 {
4101   gcc_assert (!BB_LV_SET_VALID_P (bb));
4102
4103   COPY_REG_SET (BB_LV_SET (bb), BB_LV_SET (from_bb));
4104   BB_LV_SET_VALID_P (bb) = true;
4105 }
4106
4107 /* Initialize lv set of all bb headers.  */
4108 void
4109 init_lv_sets (void)
4110 {
4111   basic_block bb;
4112
4113   /* Initialize of LV sets.  */
4114   FOR_EACH_BB (bb)
4115     init_lv_set (bb);
4116
4117   /* Don't forget EXIT_BLOCK.  */
4118   init_lv_set (EXIT_BLOCK_PTR);
4119 }
4120
4121 /* Release lv set of HEAD.  */
4122 static void
4123 free_lv_set (basic_block bb)
4124 {
4125   gcc_assert (BB_LV_SET (bb) != NULL);
4126
4127   return_regset_to_pool (BB_LV_SET (bb));
4128   BB_LV_SET (bb) = NULL;
4129   BB_LV_SET_VALID_P (bb) = false;
4130 }
4131
4132 /* Finalize lv sets of all bb headers.  */
4133 void
4134 free_lv_sets (void)
4135 {
4136   basic_block bb;
4137
4138   /* Don't forget EXIT_BLOCK.  */
4139   free_lv_set (EXIT_BLOCK_PTR);
4140
4141   /* Free LV sets.  */
4142   FOR_EACH_BB (bb)
4143     if (BB_LV_SET (bb))
4144       free_lv_set (bb);
4145 }
4146
4147 /* Initialize an invalid AV_SET for BB.
4148    This set will be updated next time compute_av () process BB.  */
4149 static void
4150 invalidate_av_set (basic_block bb)
4151 {
4152   gcc_assert (BB_AV_LEVEL (bb) <= 0
4153               && BB_AV_SET (bb) == NULL);
4154
4155   BB_AV_LEVEL (bb) = -1;
4156 }
4157
4158 /* Create initial data sets for BB (they will be invalid).  */
4159 static void
4160 create_initial_data_sets (basic_block bb)
4161 {
4162   if (BB_LV_SET (bb))
4163     BB_LV_SET_VALID_P (bb) = false;
4164   else
4165     BB_LV_SET (bb) = get_regset_from_pool ();
4166   invalidate_av_set (bb);
4167 }
4168
4169 /* Free av set of BB.  */
4170 static void
4171 free_av_set (basic_block bb)
4172 {
4173   av_set_clear (&BB_AV_SET (bb));
4174   BB_AV_LEVEL (bb) = 0;
4175 }
4176
4177 /* Free data sets of BB.  */
4178 void
4179 free_data_sets (basic_block bb)
4180 {
4181   free_lv_set (bb);
4182   free_av_set (bb);
4183 }
4184
4185 /* Exchange lv sets of TO and FROM.  */
4186 static void
4187 exchange_lv_sets (basic_block to, basic_block from)
4188 {
4189   {
4190     regset to_lv_set = BB_LV_SET (to);
4191
4192     BB_LV_SET (to) = BB_LV_SET (from);
4193     BB_LV_SET (from) = to_lv_set;
4194   }
4195
4196   {
4197     bool to_lv_set_valid_p = BB_LV_SET_VALID_P (to);
4198
4199     BB_LV_SET_VALID_P (to) = BB_LV_SET_VALID_P (from);
4200     BB_LV_SET_VALID_P (from) = to_lv_set_valid_p;
4201   }
4202 }
4203
4204
4205 /* Exchange av sets of TO and FROM.  */
4206 static void
4207 exchange_av_sets (basic_block to, basic_block from)
4208 {
4209   {
4210     av_set_t to_av_set = BB_AV_SET (to);
4211
4212     BB_AV_SET (to) = BB_AV_SET (from);
4213     BB_AV_SET (from) = to_av_set;
4214   }
4215
4216   {
4217     int to_av_level = BB_AV_LEVEL (to);
4218
4219     BB_AV_LEVEL (to) = BB_AV_LEVEL (from);
4220     BB_AV_LEVEL (from) = to_av_level;
4221   }
4222 }
4223
4224 /* Exchange data sets of TO and FROM.  */
4225 void
4226 exchange_data_sets (basic_block to, basic_block from)
4227 {
4228   exchange_lv_sets (to, from);
4229   exchange_av_sets (to, from);
4230 }
4231
4232 /* Copy data sets of FROM to TO.  */
4233 void
4234 copy_data_sets (basic_block to, basic_block from)
4235 {
4236   gcc_assert (!BB_LV_SET_VALID_P (to) && !BB_AV_SET_VALID_P (to));
4237   gcc_assert (BB_AV_SET (to) == NULL);
4238
4239   BB_AV_LEVEL (to) = BB_AV_LEVEL (from);
4240   BB_LV_SET_VALID_P (to) = BB_LV_SET_VALID_P (from);
4241
4242   if (BB_AV_SET_VALID_P (from))
4243     {
4244       BB_AV_SET (to) = av_set_copy (BB_AV_SET (from));
4245     }
4246   if (BB_LV_SET_VALID_P (from))
4247     {
4248       gcc_assert (BB_LV_SET (to) != NULL);
4249       COPY_REG_SET (BB_LV_SET (to), BB_LV_SET (from));
4250     }
4251 }
4252
4253 /* Return an av set for INSN, if any.  */
4254 av_set_t
4255 get_av_set (insn_t insn)
4256 {
4257   av_set_t av_set;
4258
4259   gcc_assert (AV_SET_VALID_P (insn));
4260
4261   if (sel_bb_head_p (insn))
4262     av_set = BB_AV_SET (BLOCK_FOR_INSN (insn));
4263   else
4264     av_set = NULL;
4265
4266   return av_set;
4267 }
4268
4269 /* Implementation of AV_LEVEL () macro.  Return AV_LEVEL () of INSN.  */
4270 int
4271 get_av_level (insn_t insn)
4272 {
4273   int av_level;
4274
4275   gcc_assert (INSN_P (insn));
4276
4277   if (sel_bb_head_p (insn))
4278     av_level = BB_AV_LEVEL (BLOCK_FOR_INSN (insn));
4279   else
4280     av_level = INSN_WS_LEVEL (insn);
4281
4282   return av_level;
4283 }
4284
4285 \f
4286
4287 /* Variables to work with control-flow graph.  */
4288
4289 /* The basic block that already has been processed by the sched_data_update (),
4290    but hasn't been in sel_add_bb () yet.  */
4291 static VEC (basic_block, heap) *last_added_blocks = NULL;
4292
4293 /* A pool for allocating successor infos.  */
4294 static struct
4295 {
4296   /* A stack for saving succs_info structures.  */
4297   struct succs_info *stack;
4298
4299   /* Its size.  */
4300   int size;
4301
4302   /* Top of the stack.  */
4303   int top;
4304
4305   /* Maximal value of the top.  */
4306   int max_top;
4307 }  succs_info_pool;
4308
4309 /* Functions to work with control-flow graph.  */
4310
4311 /* Return basic block note of BB.  */
4312 insn_t
4313 sel_bb_head (basic_block bb)
4314 {
4315   insn_t head;
4316
4317   if (bb == EXIT_BLOCK_PTR)
4318     {
4319       gcc_assert (exit_insn != NULL_RTX);
4320       head = exit_insn;
4321     }
4322   else
4323     {
4324       insn_t note;
4325
4326       note = bb_note (bb);
4327       head = next_nonnote_insn (note);
4328
4329       if (head && (BARRIER_P (head) || BLOCK_FOR_INSN (head) != bb))
4330         head = NULL_RTX;
4331     }
4332
4333   return head;
4334 }
4335
4336 /* Return true if INSN is a basic block header.  */
4337 bool
4338 sel_bb_head_p (insn_t insn)
4339 {
4340   return sel_bb_head (BLOCK_FOR_INSN (insn)) == insn;
4341 }
4342
4343 /* Return last insn of BB.  */
4344 insn_t
4345 sel_bb_end (basic_block bb)
4346 {
4347   if (sel_bb_empty_p (bb))
4348     return NULL_RTX;
4349
4350   gcc_assert (bb != EXIT_BLOCK_PTR);
4351
4352   return BB_END (bb);
4353 }
4354
4355 /* Return true if INSN is the last insn in its basic block.  */
4356 bool
4357 sel_bb_end_p (insn_t insn)
4358 {
4359   return insn == sel_bb_end (BLOCK_FOR_INSN (insn));
4360 }
4361
4362 /* Return true if BB consist of single NOTE_INSN_BASIC_BLOCK.  */
4363 bool
4364 sel_bb_empty_p (basic_block bb)
4365 {
4366   return sel_bb_head (bb) == NULL;
4367 }
4368
4369 /* True when BB belongs to the current scheduling region.  */
4370 bool
4371 in_current_region_p (basic_block bb)
4372 {
4373   if (bb->index < NUM_FIXED_BLOCKS)
4374     return false;
4375
4376   return CONTAINING_RGN (bb->index) == CONTAINING_RGN (BB_TO_BLOCK (0));
4377 }
4378
4379 /* Return the block which is a fallthru bb of a conditional jump JUMP.  */
4380 basic_block
4381 fallthru_bb_of_jump (rtx jump)
4382 {
4383   if (!JUMP_P (jump))
4384     return NULL;
4385
4386   if (any_uncondjump_p (jump))
4387     return single_succ (BLOCK_FOR_INSN (jump));
4388
4389   if (!any_condjump_p (jump))
4390     return NULL;
4391
4392   /* A basic block that ends with a conditional jump may still have one successor
4393      (and be followed by a barrier), we are not interested.  */
4394   if (single_succ_p (BLOCK_FOR_INSN (jump)))
4395     return NULL;
4396
4397   return FALLTHRU_EDGE (BLOCK_FOR_INSN (jump))->dest;
4398 }
4399
4400 /* Remove all notes from BB.  */
4401 static void
4402 init_bb (basic_block bb)
4403 {
4404   remove_notes (bb_note (bb), BB_END (bb));
4405   BB_NOTE_LIST (bb) = note_list;
4406 }
4407
4408 void
4409 sel_init_bbs (bb_vec_t bbs, basic_block bb)
4410 {
4411   const struct sched_scan_info_def ssi =
4412     {
4413       extend_bb_info, /* extend_bb */
4414       init_bb, /* init_bb */
4415       NULL, /* extend_insn */
4416       NULL /* init_insn */
4417     };
4418
4419   sched_scan (&ssi, bbs, bb, new_insns, NULL);
4420 }
4421
4422 /* Restore notes for the whole region.  */
4423 static void
4424 sel_restore_notes (void)
4425 {
4426   int bb;
4427   insn_t insn;
4428
4429   for (bb = 0; bb < current_nr_blocks; bb++)
4430     {
4431       basic_block first, last;
4432
4433       first = EBB_FIRST_BB (bb);
4434       last = EBB_LAST_BB (bb)->next_bb;
4435
4436       do
4437         {
4438           note_list = BB_NOTE_LIST (first);
4439           restore_other_notes (NULL, first);
4440           BB_NOTE_LIST (first) = NULL_RTX;
4441
4442           FOR_BB_INSNS (first, insn)
4443             if (NONDEBUG_INSN_P (insn))
4444               reemit_notes (insn);
4445
4446           first = first->next_bb;
4447         }
4448       while (first != last);
4449     }
4450 }
4451
4452 /* Free per-bb data structures.  */
4453 void
4454 sel_finish_bbs (void)
4455 {
4456   sel_restore_notes ();
4457
4458   /* Remove current loop preheader from this loop.  */
4459   if (current_loop_nest)
4460     sel_remove_loop_preheader ();
4461
4462   finish_region_bb_info ();
4463 }
4464
4465 /* Return true if INSN has a single successor of type FLAGS.  */
4466 bool
4467 sel_insn_has_single_succ_p (insn_t insn, int flags)
4468 {
4469   insn_t succ;
4470   succ_iterator si;
4471   bool first_p = true;
4472
4473   FOR_EACH_SUCC_1 (succ, si, insn, flags)
4474     {
4475       if (first_p)
4476         first_p = false;
4477       else
4478         return false;
4479     }
4480
4481   return true;
4482 }
4483
4484 /* Allocate successor's info.  */
4485 static struct succs_info *
4486 alloc_succs_info (void)
4487 {
4488   if (succs_info_pool.top == succs_info_pool.max_top)
4489     {
4490       int i;
4491
4492       if (++succs_info_pool.max_top >= succs_info_pool.size)
4493         gcc_unreachable ();
4494
4495       i = ++succs_info_pool.top;
4496       succs_info_pool.stack[i].succs_ok = VEC_alloc (rtx, heap, 10);
4497       succs_info_pool.stack[i].succs_other = VEC_alloc (rtx, heap, 10);
4498       succs_info_pool.stack[i].probs_ok = VEC_alloc (int, heap, 10);
4499     }
4500   else
4501     succs_info_pool.top++;
4502
4503   return &succs_info_pool.stack[succs_info_pool.top];
4504 }
4505
4506 /* Free successor's info.  */
4507 void
4508 free_succs_info (struct succs_info * sinfo)
4509 {
4510   gcc_assert (succs_info_pool.top >= 0
4511               && &succs_info_pool.stack[succs_info_pool.top] == sinfo);
4512   succs_info_pool.top--;
4513
4514   /* Clear stale info.  */
4515   VEC_block_remove (rtx, sinfo->succs_ok,
4516                     0, VEC_length (rtx, sinfo->succs_ok));
4517   VEC_block_remove (rtx, sinfo->succs_other,
4518                     0, VEC_length (rtx, sinfo->succs_other));
4519   VEC_block_remove (int, sinfo->probs_ok,
4520                     0, VEC_length (int, sinfo->probs_ok));
4521   sinfo->all_prob = 0;
4522   sinfo->succs_ok_n = 0;
4523   sinfo->all_succs_n = 0;
4524 }
4525
4526 /* Compute successor info for INSN.  FLAGS are the flags passed
4527    to the FOR_EACH_SUCC_1 iterator.  */
4528 struct succs_info *
4529 compute_succs_info (insn_t insn, short flags)
4530 {
4531   succ_iterator si;
4532   insn_t succ;
4533   struct succs_info *sinfo = alloc_succs_info ();
4534
4535   /* Traverse *all* successors and decide what to do with each.  */
4536   FOR_EACH_SUCC_1 (succ, si, insn, SUCCS_ALL)
4537     {
4538       /* FIXME: this doesn't work for skipping to loop exits, as we don't
4539          perform code motion through inner loops.  */
4540       short current_flags = si.current_flags & ~SUCCS_SKIP_TO_LOOP_EXITS;
4541
4542       if (current_flags & flags)
4543         {
4544           VEC_safe_push (rtx, heap, sinfo->succs_ok, succ);
4545           VEC_safe_push (int, heap, sinfo->probs_ok,
4546                          /* FIXME: Improve calculation when skipping
4547                             inner loop to exits.  */
4548                          (si.bb_end
4549                           ? si.e1->probability
4550                           : REG_BR_PROB_BASE));
4551           sinfo->succs_ok_n++;
4552         }
4553       else
4554         VEC_safe_push (rtx, heap, sinfo->succs_other, succ);
4555
4556       /* Compute all_prob.  */
4557       if (!si.bb_end)
4558         sinfo->all_prob = REG_BR_PROB_BASE;
4559       else
4560         sinfo->all_prob += si.e1->probability;
4561
4562       sinfo->all_succs_n++;
4563     }
4564
4565   return sinfo;
4566 }
4567
4568 /* Return the predecessors of BB in PREDS and their number in N.
4569    Empty blocks are skipped.  SIZE is used to allocate PREDS.  */
4570 static void
4571 cfg_preds_1 (basic_block bb, insn_t **preds, int *n, int *size)
4572 {
4573   edge e;
4574   edge_iterator ei;
4575
4576   gcc_assert (BLOCK_TO_BB (bb->index) != 0);
4577
4578   FOR_EACH_EDGE (e, ei, bb->preds)
4579     {
4580       basic_block pred_bb = e->src;
4581       insn_t bb_end = BB_END (pred_bb);
4582
4583       /* ??? This code is not supposed to walk out of a region.  */
4584       gcc_assert (in_current_region_p (pred_bb));
4585
4586       if (sel_bb_empty_p (pred_bb))
4587         cfg_preds_1 (pred_bb, preds, n, size);
4588       else
4589         {
4590           if (*n == *size)
4591             *preds = XRESIZEVEC (insn_t, *preds,
4592                                  (*size = 2 * *size + 1));
4593           (*preds)[(*n)++] = bb_end;
4594         }
4595     }
4596
4597   gcc_assert (*n != 0);
4598 }
4599
4600 /* Find all predecessors of BB and record them in PREDS and their number
4601    in N.  Empty blocks are skipped, and only normal (forward in-region)
4602    edges are processed.  */
4603 static void
4604 cfg_preds (basic_block bb, insn_t **preds, int *n)
4605 {
4606   int size = 0;
4607
4608   *preds = NULL;
4609   *n = 0;
4610   cfg_preds_1 (bb, preds, n, &size);
4611 }
4612
4613 /* Returns true if we are moving INSN through join point.  */
4614 bool
4615 sel_num_cfg_preds_gt_1 (insn_t insn)
4616 {
4617   basic_block bb;
4618
4619   if (!sel_bb_head_p (insn) || INSN_BB (insn) == 0)
4620     return false;
4621
4622   bb = BLOCK_FOR_INSN (insn);
4623
4624   while (1)
4625     {
4626       if (EDGE_COUNT (bb->preds) > 1)
4627         return true;
4628
4629       gcc_assert (EDGE_PRED (bb, 0)->dest == bb);
4630       bb = EDGE_PRED (bb, 0)->src;
4631
4632       if (!sel_bb_empty_p (bb))
4633         break;
4634     }
4635
4636   return false;
4637 }
4638
4639 /* Returns true when BB should be the end of an ebb.  Adapted from the
4640    code in sched-ebb.c.  */
4641 bool
4642 bb_ends_ebb_p (basic_block bb)
4643 {
4644   basic_block next_bb = bb_next_bb (bb);
4645   edge e;
4646   edge_iterator ei;
4647
4648   if (next_bb == EXIT_BLOCK_PTR
4649       || bitmap_bit_p (forced_ebb_heads, next_bb->index)
4650       || (LABEL_P (BB_HEAD (next_bb))
4651           /* NB: LABEL_NUSES () is not maintained outside of jump.c.
4652              Work around that.  */
4653           && !single_pred_p (next_bb)))
4654     return true;
4655
4656   if (!in_current_region_p (next_bb))
4657     return true;
4658
4659   FOR_EACH_EDGE (e, ei, bb->succs)
4660     if ((e->flags & EDGE_FALLTHRU) != 0)
4661       {
4662         gcc_assert (e->dest == next_bb);
4663
4664         return false;
4665       }
4666
4667   return true;
4668 }
4669
4670 /* Returns true when INSN and SUCC are in the same EBB, given that SUCC is a
4671    successor of INSN.  */
4672 bool
4673 in_same_ebb_p (insn_t insn, insn_t succ)
4674 {
4675   basic_block ptr = BLOCK_FOR_INSN (insn);
4676
4677   for(;;)
4678     {
4679       if (ptr == BLOCK_FOR_INSN (succ))
4680         return true;
4681
4682       if (bb_ends_ebb_p (ptr))
4683         return false;
4684
4685       ptr = bb_next_bb (ptr);
4686     }
4687
4688   gcc_unreachable ();
4689   return false;
4690 }
4691
4692 /* Recomputes the reverse topological order for the function and
4693    saves it in REV_TOP_ORDER_INDEX.  REV_TOP_ORDER_INDEX_LEN is also
4694    modified appropriately.  */
4695 static void
4696 recompute_rev_top_order (void)
4697 {
4698   int *postorder;
4699   int n_blocks, i;
4700
4701   if (!rev_top_order_index || rev_top_order_index_len < last_basic_block)
4702     {
4703       rev_top_order_index_len = last_basic_block;
4704       rev_top_order_index = XRESIZEVEC (int, rev_top_order_index,
4705                                         rev_top_order_index_len);
4706     }
4707
4708   postorder = XNEWVEC (int, n_basic_blocks);
4709
4710   n_blocks = post_order_compute (postorder, true, false);
4711   gcc_assert (n_basic_blocks == n_blocks);
4712
4713   /* Build reverse function: for each basic block with BB->INDEX == K
4714      rev_top_order_index[K] is it's reverse topological sort number.  */
4715   for (i = 0; i < n_blocks; i++)
4716     {
4717       gcc_assert (postorder[i] < rev_top_order_index_len);
4718       rev_top_order_index[postorder[i]] = i;
4719     }
4720
4721   free (postorder);
4722 }
4723
4724 /* Clear all flags from insns in BB that could spoil its rescheduling.  */
4725 void
4726 clear_outdated_rtx_info (basic_block bb)
4727 {
4728   rtx insn;
4729
4730   FOR_BB_INSNS (bb, insn)
4731     if (INSN_P (insn))
4732       {
4733         SCHED_GROUP_P (insn) = 0;
4734         INSN_AFTER_STALL_P (insn) = 0;
4735         INSN_SCHED_TIMES (insn) = 0;
4736         EXPR_PRIORITY_ADJ (INSN_EXPR (insn)) = 0;
4737
4738         /* We cannot use the changed caches, as previously we could ignore
4739            the LHS dependence due to enabled renaming and transform
4740            the expression, and currently we'll be unable to do this.  */
4741         htab_empty (INSN_TRANSFORMED_INSNS (insn));
4742       }
4743 }
4744
4745 /* Add BB_NOTE to the pool of available basic block notes.  */
4746 static void
4747 return_bb_to_pool (basic_block bb)
4748 {
4749   rtx note = bb_note (bb);
4750
4751   gcc_assert (NOTE_BASIC_BLOCK (note) == bb
4752               && bb->aux == NULL);
4753
4754   /* It turns out that current cfg infrastructure does not support
4755      reuse of basic blocks.  Don't bother for now.  */
4756   /*VEC_safe_push (rtx, heap, bb_note_pool, note);*/
4757 }
4758
4759 /* Get a bb_note from pool or return NULL_RTX if pool is empty.  */
4760 static rtx
4761 get_bb_note_from_pool (void)
4762 {
4763   if (VEC_empty (rtx, bb_note_pool))
4764     return NULL_RTX;
4765   else
4766     {
4767       rtx note = VEC_pop (rtx, bb_note_pool);
4768
4769       PREV_INSN (note) = NULL_RTX;
4770       NEXT_INSN (note) = NULL_RTX;
4771
4772       return note;
4773     }
4774 }
4775
4776 /* Free bb_note_pool.  */
4777 void
4778 free_bb_note_pool (void)
4779 {
4780   VEC_free (rtx, heap, bb_note_pool);
4781 }
4782
4783 /* Setup scheduler pool and successor structure.  */
4784 void
4785 alloc_sched_pools (void)
4786 {
4787   int succs_size;
4788
4789   succs_size = MAX_WS + 1;
4790   succs_info_pool.stack = XCNEWVEC (struct succs_info, succs_size);
4791   succs_info_pool.size = succs_size;
4792   succs_info_pool.top = -1;
4793   succs_info_pool.max_top = -1;
4794
4795   sched_lists_pool = create_alloc_pool ("sel-sched-lists",
4796                                         sizeof (struct _list_node), 500);
4797 }
4798
4799 /* Free the pools.  */
4800 void
4801 free_sched_pools (void)
4802 {
4803   int i;
4804
4805   free_alloc_pool (sched_lists_pool);
4806   gcc_assert (succs_info_pool.top == -1);
4807   for (i = 0; i < succs_info_pool.max_top; i++)
4808     {
4809       VEC_free (rtx, heap, succs_info_pool.stack[i].succs_ok);
4810       VEC_free (rtx, heap, succs_info_pool.stack[i].succs_other);
4811       VEC_free (int, heap, succs_info_pool.stack[i].probs_ok);
4812     }
4813   free (succs_info_pool.stack);
4814 }
4815 \f
4816
4817 /* Returns a position in RGN where BB can be inserted retaining
4818    topological order.  */
4819 static int
4820 find_place_to_insert_bb (basic_block bb, int rgn)
4821 {
4822   bool has_preds_outside_rgn = false;
4823   edge e;
4824   edge_iterator ei;
4825
4826   /* Find whether we have preds outside the region.  */
4827   FOR_EACH_EDGE (e, ei, bb->preds)
4828     if (!in_current_region_p (e->src))
4829       {
4830         has_preds_outside_rgn = true;
4831         break;
4832       }
4833
4834   /* Recompute the top order -- needed when we have > 1 pred
4835      and in case we don't have preds outside.  */
4836   if (flag_sel_sched_pipelining_outer_loops
4837       && (has_preds_outside_rgn || EDGE_COUNT (bb->preds) > 1))
4838     {
4839       int i, bbi = bb->index, cur_bbi;
4840
4841       recompute_rev_top_order ();
4842       for (i = RGN_NR_BLOCKS (rgn) - 1; i >= 0; i--)
4843         {
4844           cur_bbi = BB_TO_BLOCK (i);
4845           if (rev_top_order_index[bbi]
4846               < rev_top_order_index[cur_bbi])
4847             break;
4848         }
4849
4850       /* We skipped the right block, so we increase i.  We accomodate
4851          it for increasing by step later, so we decrease i.  */
4852       return (i + 1) - 1;
4853     }
4854   else if (has_preds_outside_rgn)
4855     {
4856       /* This is the case when we generate an extra empty block
4857          to serve as region head during pipelining.  */
4858       e = EDGE_SUCC (bb, 0);
4859       gcc_assert (EDGE_COUNT (bb->succs) == 1
4860                   && in_current_region_p (EDGE_SUCC (bb, 0)->dest)
4861                   && (BLOCK_TO_BB (e->dest->index) == 0));
4862       return -1;
4863     }
4864
4865   /* We don't have preds outside the region.  We should have
4866      the only pred, because the multiple preds case comes from
4867      the pipelining of outer loops, and that is handled above.
4868      Just take the bbi of this single pred.  */
4869   if (EDGE_COUNT (bb->succs) > 0)
4870     {
4871       int pred_bbi;
4872
4873       gcc_assert (EDGE_COUNT (bb->preds) == 1);
4874
4875       pred_bbi = EDGE_PRED (bb, 0)->src->index;
4876       return BLOCK_TO_BB (pred_bbi);
4877     }
4878   else
4879     /* BB has no successors.  It is safe to put it in the end.  */
4880     return current_nr_blocks - 1;
4881 }
4882
4883 /* Deletes an empty basic block freeing its data.  */
4884 static void
4885 delete_and_free_basic_block (basic_block bb)
4886 {
4887   gcc_assert (sel_bb_empty_p (bb));
4888
4889   if (BB_LV_SET (bb))
4890     free_lv_set (bb);
4891
4892   bitmap_clear_bit (blocks_to_reschedule, bb->index);
4893
4894   /* Can't assert av_set properties because we use sel_aremove_bb
4895      when removing loop preheader from the region.  At the point of
4896      removing the preheader we already have deallocated sel_region_bb_info.  */
4897   gcc_assert (BB_LV_SET (bb) == NULL
4898               && !BB_LV_SET_VALID_P (bb)
4899               && BB_AV_LEVEL (bb) == 0
4900               && BB_AV_SET (bb) == NULL);
4901
4902   delete_basic_block (bb);
4903 }
4904
4905 /* Add BB to the current region and update the region data.  */
4906 static void
4907 add_block_to_current_region (basic_block bb)
4908 {
4909   int i, pos, bbi = -2, rgn;
4910
4911   rgn = CONTAINING_RGN (BB_TO_BLOCK (0));
4912   bbi = find_place_to_insert_bb (bb, rgn);
4913   bbi += 1;
4914   pos = RGN_BLOCKS (rgn) + bbi;
4915
4916   gcc_assert (RGN_HAS_REAL_EBB (rgn) == 0
4917               && ebb_head[bbi] == pos);
4918
4919   /* Make a place for the new block.  */
4920   extend_regions ();
4921
4922   for (i = RGN_BLOCKS (rgn + 1) - 1; i >= pos; i--)
4923     BLOCK_TO_BB (rgn_bb_table[i])++;
4924
4925   memmove (rgn_bb_table + pos + 1,
4926            rgn_bb_table + pos,
4927            (RGN_BLOCKS (nr_regions) - pos) * sizeof (*rgn_bb_table));
4928
4929   /* Initialize data for BB.  */
4930   rgn_bb_table[pos] = bb->index;
4931   BLOCK_TO_BB (bb->index) = bbi;
4932   CONTAINING_RGN (bb->index) = rgn;
4933
4934   RGN_NR_BLOCKS (rgn)++;
4935
4936   for (i = rgn + 1; i <= nr_regions; i++)
4937     RGN_BLOCKS (i)++;
4938 }
4939
4940 /* Remove BB from the current region and update the region data.  */
4941 static void
4942 remove_bb_from_region (basic_block bb)
4943 {
4944   int i, pos, bbi = -2, rgn;
4945
4946   rgn = CONTAINING_RGN (BB_TO_BLOCK (0));
4947   bbi = BLOCK_TO_BB (bb->index);
4948   pos = RGN_BLOCKS (rgn) + bbi;
4949
4950   gcc_assert (RGN_HAS_REAL_EBB (rgn) == 0
4951               && ebb_head[bbi] == pos);
4952
4953   for (i = RGN_BLOCKS (rgn + 1) - 1; i >= pos; i--)
4954     BLOCK_TO_BB (rgn_bb_table[i])--;
4955
4956   memmove (rgn_bb_table + pos,
4957            rgn_bb_table + pos + 1,
4958            (RGN_BLOCKS (nr_regions) - pos) * sizeof (*rgn_bb_table));
4959
4960   RGN_NR_BLOCKS (rgn)--;
4961   for (i = rgn + 1; i <= nr_regions; i++)
4962     RGN_BLOCKS (i)--;
4963 }
4964
4965 /* Add BB to the current region  and update all data.  If BB is NULL, add all
4966    blocks from last_added_blocks vector.  */
4967 static void
4968 sel_add_bb (basic_block bb)
4969 {
4970   /* Extend luids so that new notes will receive zero luids.  */
4971   sched_init_luids (NULL, NULL, NULL, NULL);
4972   sched_init_bbs ();
4973   sel_init_bbs (last_added_blocks, NULL);
4974
4975   /* When bb is passed explicitly, the vector should contain
4976      the only element that equals to bb; otherwise, the vector
4977      should not be NULL.  */
4978   gcc_assert (last_added_blocks != NULL);
4979
4980   if (bb != NULL)
4981     {
4982       gcc_assert (VEC_length (basic_block, last_added_blocks) == 1
4983                   && VEC_index (basic_block,
4984                                 last_added_blocks, 0) == bb);
4985       add_block_to_current_region (bb);
4986
4987       /* We associate creating/deleting data sets with the first insn
4988          appearing / disappearing in the bb.  */
4989       if (!sel_bb_empty_p (bb) && BB_LV_SET (bb) == NULL)
4990         create_initial_data_sets (bb);
4991
4992       VEC_free (basic_block, heap, last_added_blocks);
4993     }
4994   else
4995     /* BB is NULL - process LAST_ADDED_BLOCKS instead.  */
4996     {
4997       int i;
4998       basic_block temp_bb = NULL;
4999
5000       for (i = 0;
5001            VEC_iterate (basic_block, last_added_blocks, i, bb); i++)
5002         {
5003           add_block_to_current_region (bb);
5004           temp_bb = bb;
5005         }
5006
5007       /* We need to fetch at least one bb so we know the region
5008          to update.  */
5009       gcc_assert (temp_bb != NULL);
5010       bb = temp_bb;
5011
5012       VEC_free (basic_block, heap, last_added_blocks);
5013     }
5014
5015   rgn_setup_region (CONTAINING_RGN (bb->index));
5016 }
5017
5018 /* Remove BB from the current region and update all data.
5019    If REMOVE_FROM_CFG_PBB is true, also remove the block cfom cfg.  */
5020 static void
5021 sel_remove_bb (basic_block bb, bool remove_from_cfg_p)
5022 {
5023   gcc_assert (bb != NULL && BB_NOTE_LIST (bb) == NULL_RTX);
5024
5025   remove_bb_from_region (bb);
5026   return_bb_to_pool (bb);
5027   bitmap_clear_bit (blocks_to_reschedule, bb->index);
5028
5029   if (remove_from_cfg_p)
5030     delete_and_free_basic_block (bb);
5031
5032   rgn_setup_region (CONTAINING_RGN (bb->index));
5033 }
5034
5035 /* Concatenate info of EMPTY_BB to info of MERGE_BB.  */
5036 static void
5037 move_bb_info (basic_block merge_bb, basic_block empty_bb)
5038 {
5039   gcc_assert (in_current_region_p (merge_bb));
5040
5041   concat_note_lists (BB_NOTE_LIST (empty_bb),
5042                      &BB_NOTE_LIST (merge_bb));
5043   BB_NOTE_LIST (empty_bb) = NULL_RTX;
5044
5045 }
5046
5047 /* Remove an empty basic block EMPTY_BB.  When MERGE_UP_P is true, we put
5048    EMPTY_BB's note lists into its predecessor instead of putting them
5049    into the successor.  When REMOVE_FROM_CFG_P is true, also remove
5050    the empty block.  */
5051 void
5052 sel_remove_empty_bb (basic_block empty_bb, bool merge_up_p,
5053                      bool remove_from_cfg_p)
5054 {
5055   basic_block merge_bb;
5056
5057   gcc_assert (sel_bb_empty_p (empty_bb));
5058
5059   if (merge_up_p)
5060     {
5061       merge_bb = empty_bb->prev_bb;
5062       gcc_assert (EDGE_COUNT (empty_bb->preds) == 1
5063                   && EDGE_PRED (empty_bb, 0)->src == merge_bb);
5064     }
5065   else
5066     {
5067       edge e;
5068       edge_iterator ei;
5069
5070       merge_bb = bb_next_bb (empty_bb);
5071
5072       /* Redirect incoming edges (except fallthrough one) of EMPTY_BB to its
5073          successor block.  */
5074       for (ei = ei_start (empty_bb->preds);
5075            (e = ei_safe_edge (ei)); )
5076         {
5077           if (! (e->flags & EDGE_FALLTHRU))
5078             sel_redirect_edge_and_branch (e, merge_bb);
5079           else
5080             ei_next (&ei);
5081         }
5082
5083       gcc_assert (EDGE_COUNT (empty_bb->succs) == 1
5084                   && EDGE_SUCC (empty_bb, 0)->dest == merge_bb);
5085     }
5086
5087   move_bb_info (merge_bb, empty_bb);
5088   remove_empty_bb (empty_bb, remove_from_cfg_p);
5089 }
5090
5091 /* Remove EMPTY_BB.  If REMOVE_FROM_CFG_P is false, remove EMPTY_BB from
5092    region, but keep it in CFG.  */
5093 static void
5094 remove_empty_bb (basic_block empty_bb, bool remove_from_cfg_p)
5095 {
5096   /* The block should contain just a note or a label.
5097      We try to check whether it is unused below.  */
5098   gcc_assert (BB_HEAD (empty_bb) == BB_END (empty_bb)
5099               || LABEL_P (BB_HEAD (empty_bb)));
5100
5101   /* If basic block has predecessors or successors, redirect them.  */
5102   if (remove_from_cfg_p
5103       && (EDGE_COUNT (empty_bb->preds) > 0
5104           || EDGE_COUNT (empty_bb->succs) > 0))
5105     {
5106       basic_block pred;
5107       basic_block succ;
5108
5109       /* We need to init PRED and SUCC before redirecting edges.  */
5110       if (EDGE_COUNT (empty_bb->preds) > 0)
5111         {
5112           edge e;
5113
5114           gcc_assert (EDGE_COUNT (empty_bb->preds) == 1);
5115
5116           e = EDGE_PRED (empty_bb, 0);
5117           gcc_assert (e->src == empty_bb->prev_bb
5118                       && (e->flags & EDGE_FALLTHRU));
5119
5120           pred = empty_bb->prev_bb;
5121         }
5122       else
5123         pred = NULL;
5124
5125       if (EDGE_COUNT (empty_bb->succs) > 0)
5126         {
5127           /* We do not check fallthruness here as above, because
5128              after removing a jump the edge may actually be not fallthru.  */
5129           gcc_assert (EDGE_COUNT (empty_bb->succs) == 1);
5130           succ = EDGE_SUCC (empty_bb, 0)->dest;
5131         }
5132       else
5133         succ = NULL;
5134
5135       if (EDGE_COUNT (empty_bb->preds) > 0 && succ != NULL)
5136         {
5137           edge e = EDGE_PRED (empty_bb, 0);
5138
5139           if (e->flags & EDGE_FALLTHRU)
5140             redirect_edge_succ_nodup (e, succ);
5141           else
5142             sel_redirect_edge_and_branch (EDGE_PRED (empty_bb, 0), succ);
5143         }
5144
5145       if (EDGE_COUNT (empty_bb->succs) > 0 && pred != NULL)
5146         {
5147           edge e = EDGE_SUCC (empty_bb, 0);
5148
5149           if (find_edge (pred, e->dest) == NULL)
5150             redirect_edge_pred (e, pred);
5151         }
5152     }
5153
5154   /* Finish removing.  */
5155   sel_remove_bb (empty_bb, remove_from_cfg_p);
5156 }
5157
5158 /* An implementation of create_basic_block hook, which additionally updates
5159    per-bb data structures.  */
5160 static basic_block
5161 sel_create_basic_block (void *headp, void *endp, basic_block after)
5162 {
5163   basic_block new_bb;
5164   insn_t new_bb_note;
5165
5166   gcc_assert (flag_sel_sched_pipelining_outer_loops
5167               || last_added_blocks == NULL);
5168
5169   new_bb_note = get_bb_note_from_pool ();
5170
5171   if (new_bb_note == NULL_RTX)
5172     new_bb = orig_cfg_hooks.create_basic_block (headp, endp, after);
5173   else
5174     {
5175       new_bb = create_basic_block_structure ((rtx) headp, (rtx) endp,
5176                                              new_bb_note, after);
5177       new_bb->aux = NULL;
5178     }
5179
5180   VEC_safe_push (basic_block, heap, last_added_blocks, new_bb);
5181
5182   return new_bb;
5183 }
5184
5185 /* Implement sched_init_only_bb ().  */
5186 static void
5187 sel_init_only_bb (basic_block bb, basic_block after)
5188 {
5189   gcc_assert (after == NULL);
5190
5191   extend_regions ();
5192   rgn_make_new_region_out_of_new_block (bb);
5193 }
5194
5195 /* Update the latch when we've splitted or merged it from FROM block to TO.
5196    This should be checked for all outer loops, too.  */
5197 static void
5198 change_loops_latches (basic_block from, basic_block to)
5199 {
5200   gcc_assert (from != to);
5201
5202   if (current_loop_nest)
5203     {
5204       struct loop *loop;
5205
5206       for (loop = current_loop_nest; loop; loop = loop_outer (loop))
5207         if (considered_for_pipelining_p (loop) && loop->latch == from)
5208           {
5209             gcc_assert (loop == current_loop_nest);
5210             loop->latch = to;
5211             gcc_assert (loop_latch_edge (loop));
5212           }
5213     }
5214 }
5215
5216 /* Splits BB on two basic blocks, adding it to the region and extending
5217    per-bb data structures.  Returns the newly created bb.  */
5218 static basic_block
5219 sel_split_block (basic_block bb, rtx after)
5220 {
5221   basic_block new_bb;
5222   insn_t insn;
5223
5224   new_bb = sched_split_block_1 (bb, after);
5225   sel_add_bb (new_bb);
5226
5227   /* This should be called after sel_add_bb, because this uses
5228      CONTAINING_RGN for the new block, which is not yet initialized.
5229      FIXME: this function may be a no-op now.  */
5230   change_loops_latches (bb, new_bb);
5231
5232   /* Update ORIG_BB_INDEX for insns moved into the new block.  */
5233   FOR_BB_INSNS (new_bb, insn)
5234    if (INSN_P (insn))
5235      EXPR_ORIG_BB_INDEX (INSN_EXPR (insn)) = new_bb->index;
5236
5237   if (sel_bb_empty_p (bb))
5238     {
5239       gcc_assert (!sel_bb_empty_p (new_bb));
5240
5241       /* NEW_BB has data sets that need to be updated and BB holds
5242          data sets that should be removed.  Exchange these data sets
5243          so that we won't lose BB's valid data sets.  */
5244       exchange_data_sets (new_bb, bb);
5245       free_data_sets (bb);
5246     }
5247
5248   if (!sel_bb_empty_p (new_bb)
5249       && bitmap_bit_p (blocks_to_reschedule, bb->index))
5250     bitmap_set_bit (blocks_to_reschedule, new_bb->index);
5251
5252   return new_bb;
5253 }
5254
5255 /* If BB ends with a jump insn whose ID is bigger then PREV_MAX_UID, return it.
5256    Otherwise returns NULL.  */
5257 static rtx
5258 check_for_new_jump (basic_block bb, int prev_max_uid)
5259 {
5260   rtx end;
5261
5262   end = sel_bb_end (bb);
5263   if (end && INSN_UID (end) >= prev_max_uid)
5264     return end;
5265   return NULL;
5266 }
5267
5268 /* Look for a new jump either in FROM_BB block or in newly created JUMP_BB block.
5269    New means having UID at least equal to PREV_MAX_UID.  */
5270 static rtx
5271 find_new_jump (basic_block from, basic_block jump_bb, int prev_max_uid)
5272 {
5273   rtx jump;
5274
5275   /* Return immediately if no new insns were emitted.  */
5276   if (get_max_uid () == prev_max_uid)
5277     return NULL;
5278
5279   /* Now check both blocks for new jumps.  It will ever be only one.  */
5280   if ((jump = check_for_new_jump (from, prev_max_uid)))
5281     return jump;
5282
5283   if (jump_bb != NULL
5284       && (jump = check_for_new_jump (jump_bb, prev_max_uid)))
5285     return jump;
5286   return NULL;
5287 }
5288
5289 /* Splits E and adds the newly created basic block to the current region.
5290    Returns this basic block.  */
5291 basic_block
5292 sel_split_edge (edge e)
5293 {
5294   basic_block new_bb, src, other_bb = NULL;
5295   int prev_max_uid;
5296   rtx jump;
5297
5298   src = e->src;
5299   prev_max_uid = get_max_uid ();
5300   new_bb = split_edge (e);
5301
5302   if (flag_sel_sched_pipelining_outer_loops
5303       && current_loop_nest)
5304     {
5305       int i;
5306       basic_block bb;
5307
5308       /* Some of the basic blocks might not have been added to the loop.
5309          Add them here, until this is fixed in force_fallthru.  */
5310       for (i = 0;
5311            VEC_iterate (basic_block, last_added_blocks, i, bb); i++)
5312         if (!bb->loop_father)
5313           {
5314             add_bb_to_loop (bb, e->dest->loop_father);
5315
5316             gcc_assert (!other_bb && (new_bb->index != bb->index));
5317             other_bb = bb;
5318           }
5319     }
5320
5321   /* Add all last_added_blocks to the region.  */
5322   sel_add_bb (NULL);
5323
5324   jump = find_new_jump (src, new_bb, prev_max_uid);
5325   if (jump)
5326     sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
5327
5328   /* Put the correct lv set on this block.  */
5329   if (other_bb && !sel_bb_empty_p (other_bb))
5330     compute_live (sel_bb_head (other_bb));
5331
5332   return new_bb;
5333 }
5334
5335 /* Implement sched_create_empty_bb ().  */
5336 static basic_block
5337 sel_create_empty_bb (basic_block after)
5338 {
5339   basic_block new_bb;
5340
5341   new_bb = sched_create_empty_bb_1 (after);
5342
5343   /* We'll explicitly initialize NEW_BB via sel_init_only_bb () a bit
5344      later.  */
5345   gcc_assert (VEC_length (basic_block, last_added_blocks) == 1
5346               && VEC_index (basic_block, last_added_blocks, 0) == new_bb);
5347
5348   VEC_free (basic_block, heap, last_added_blocks);
5349   return new_bb;
5350 }
5351
5352 /* Implement sched_create_recovery_block.  ORIG_INSN is where block
5353    will be splitted to insert a check.  */
5354 basic_block
5355 sel_create_recovery_block (insn_t orig_insn)
5356 {
5357   basic_block first_bb, second_bb, recovery_block;
5358   basic_block before_recovery = NULL;
5359   rtx jump;
5360
5361   first_bb = BLOCK_FOR_INSN (orig_insn);
5362   if (sel_bb_end_p (orig_insn))
5363     {
5364       /* Avoid introducing an empty block while splitting.  */
5365       gcc_assert (single_succ_p (first_bb));
5366       second_bb = single_succ (first_bb);
5367     }
5368   else
5369     second_bb = sched_split_block (first_bb, orig_insn);
5370
5371   recovery_block = sched_create_recovery_block (&before_recovery);
5372   if (before_recovery)
5373     copy_lv_set_from (before_recovery, EXIT_BLOCK_PTR);
5374
5375   gcc_assert (sel_bb_empty_p (recovery_block));
5376   sched_create_recovery_edges (first_bb, recovery_block, second_bb);
5377   if (current_loops != NULL)
5378     add_bb_to_loop (recovery_block, first_bb->loop_father);
5379
5380   sel_add_bb (recovery_block);
5381
5382   jump = BB_END (recovery_block);
5383   gcc_assert (sel_bb_head (recovery_block) == jump);
5384   sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
5385
5386   return recovery_block;
5387 }
5388
5389 /* Merge basic block B into basic block A.  */
5390 void
5391 sel_merge_blocks (basic_block a, basic_block b)
5392 {
5393   sel_remove_empty_bb (b, true, false);
5394   merge_blocks (a, b);
5395
5396   change_loops_latches (b, a);
5397 }
5398
5399 /* A wrapper for redirect_edge_and_branch_force, which also initializes
5400    data structures for possibly created bb and insns.  Returns the newly
5401    added bb or NULL, when a bb was not needed.  */
5402 void
5403 sel_redirect_edge_and_branch_force (edge e, basic_block to)
5404 {
5405   basic_block jump_bb, src;
5406   int prev_max_uid;
5407   rtx jump;
5408
5409   gcc_assert (!sel_bb_empty_p (e->src));
5410
5411   src = e->src;
5412   prev_max_uid = get_max_uid ();
5413   jump_bb = redirect_edge_and_branch_force (e, to);
5414
5415   if (jump_bb != NULL)
5416     sel_add_bb (jump_bb);
5417
5418   /* This function could not be used to spoil the loop structure by now,
5419      thus we don't care to update anything.  But check it to be sure.  */
5420   if (current_loop_nest
5421       && pipelining_p)
5422     gcc_assert (loop_latch_edge (current_loop_nest));
5423
5424   jump = find_new_jump (src, jump_bb, prev_max_uid);
5425   if (jump)
5426     sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
5427 }
5428
5429 /* A wrapper for redirect_edge_and_branch.  Return TRUE if blocks connected by
5430    redirected edge are in reverse topological order.  */
5431 bool
5432 sel_redirect_edge_and_branch (edge e, basic_block to)
5433 {
5434   bool latch_edge_p;
5435   basic_block src;
5436   int prev_max_uid;
5437   rtx jump;
5438   edge redirected;
5439   bool recompute_toporder_p = false;
5440
5441   latch_edge_p = (pipelining_p
5442                   && current_loop_nest
5443                   && e == loop_latch_edge (current_loop_nest));
5444
5445   src = e->src;
5446   prev_max_uid = get_max_uid ();
5447
5448   redirected = redirect_edge_and_branch (e, to);
5449
5450   gcc_assert (redirected && last_added_blocks == NULL);
5451
5452   /* When we've redirected a latch edge, update the header.  */
5453   if (latch_edge_p)
5454     {
5455       current_loop_nest->header = to;
5456       gcc_assert (loop_latch_edge (current_loop_nest));
5457     }
5458
5459   /* In rare situations, the topological relation between the blocks connected
5460      by the redirected edge can change (see PR42245 for an example).  Update
5461      block_to_bb/bb_to_block.  */
5462   if (CONTAINING_RGN (e->src->index) == CONTAINING_RGN (to->index)
5463       && BLOCK_TO_BB (e->src->index) > BLOCK_TO_BB (to->index))
5464     recompute_toporder_p = true;
5465
5466   jump = find_new_jump (src, NULL, prev_max_uid);
5467   if (jump)
5468     sel_init_new_insn (jump, INSN_INIT_TODO_LUID | INSN_INIT_TODO_SIMPLEJUMP);
5469
5470   return recompute_toporder_p;
5471 }
5472
5473 /* This variable holds the cfg hooks used by the selective scheduler.  */
5474 static struct cfg_hooks sel_cfg_hooks;
5475
5476 /* Register sel-sched cfg hooks.  */
5477 void
5478 sel_register_cfg_hooks (void)
5479 {
5480   sched_split_block = sel_split_block;
5481
5482   orig_cfg_hooks = get_cfg_hooks ();
5483   sel_cfg_hooks = orig_cfg_hooks;
5484
5485   sel_cfg_hooks.create_basic_block = sel_create_basic_block;
5486
5487   set_cfg_hooks (sel_cfg_hooks);
5488
5489   sched_init_only_bb = sel_init_only_bb;
5490   sched_split_block = sel_split_block;
5491   sched_create_empty_bb = sel_create_empty_bb;
5492 }
5493
5494 /* Unregister sel-sched cfg hooks.  */
5495 void
5496 sel_unregister_cfg_hooks (void)
5497 {
5498   sched_create_empty_bb = NULL;
5499   sched_split_block = NULL;
5500   sched_init_only_bb = NULL;
5501
5502   set_cfg_hooks (orig_cfg_hooks);
5503 }
5504 \f
5505
5506 /* Emit an insn rtx based on PATTERN.  If a jump insn is wanted,
5507    LABEL is where this jump should be directed.  */
5508 rtx
5509 create_insn_rtx_from_pattern (rtx pattern, rtx label)
5510 {
5511   rtx insn_rtx;
5512
5513   gcc_assert (!INSN_P (pattern));
5514
5515   start_sequence ();
5516
5517   if (label == NULL_RTX)
5518     insn_rtx = emit_insn (pattern);
5519   else if (DEBUG_INSN_P (label))
5520     insn_rtx = emit_debug_insn (pattern);
5521   else
5522     {
5523       insn_rtx = emit_jump_insn (pattern);
5524       JUMP_LABEL (insn_rtx) = label;
5525       ++LABEL_NUSES (label);
5526     }
5527
5528   end_sequence ();
5529
5530   sched_init_luids (NULL, NULL, NULL, NULL);
5531   sched_extend_target ();
5532   sched_deps_init (false);
5533
5534   /* Initialize INSN_CODE now.  */
5535   recog_memoized (insn_rtx);
5536   return insn_rtx;
5537 }
5538
5539 /* Create a new vinsn for INSN_RTX.  FORCE_UNIQUE_P is true when the vinsn
5540    must not be clonable.  */
5541 vinsn_t
5542 create_vinsn_from_insn_rtx (rtx insn_rtx, bool force_unique_p)
5543 {
5544   gcc_assert (INSN_P (insn_rtx) && !INSN_IN_STREAM_P (insn_rtx));
5545
5546   /* If VINSN_TYPE is not USE, retain its uniqueness.  */
5547   return vinsn_create (insn_rtx, force_unique_p);
5548 }
5549
5550 /* Create a copy of INSN_RTX.  */
5551 rtx
5552 create_copy_of_insn_rtx (rtx insn_rtx)
5553 {
5554   rtx res;
5555
5556   if (DEBUG_INSN_P (insn_rtx))
5557     return create_insn_rtx_from_pattern (copy_rtx (PATTERN (insn_rtx)),
5558                                          insn_rtx);
5559
5560   gcc_assert (NONJUMP_INSN_P (insn_rtx));
5561
5562   res = create_insn_rtx_from_pattern (copy_rtx (PATTERN (insn_rtx)),
5563                                       NULL_RTX);
5564   return res;
5565 }
5566
5567 /* Change vinsn field of EXPR to hold NEW_VINSN.  */
5568 void
5569 change_vinsn_in_expr (expr_t expr, vinsn_t new_vinsn)
5570 {
5571   vinsn_detach (EXPR_VINSN (expr));
5572
5573   EXPR_VINSN (expr) = new_vinsn;
5574   vinsn_attach (new_vinsn);
5575 }
5576
5577 /* Helpers for global init.  */
5578 /* This structure is used to be able to call existing bundling mechanism
5579    and calculate insn priorities.  */
5580 static struct haifa_sched_info sched_sel_haifa_sched_info =
5581 {
5582   NULL, /* init_ready_list */
5583   NULL, /* can_schedule_ready_p */
5584   NULL, /* schedule_more_p */
5585   NULL, /* new_ready */
5586   NULL, /* rgn_rank */
5587   sel_print_insn, /* rgn_print_insn */
5588   contributes_to_priority,
5589   NULL, /* insn_finishes_block_p */
5590
5591   NULL, NULL,
5592   NULL, NULL,
5593   0, 0,
5594
5595   NULL, /* add_remove_insn */
5596   NULL, /* begin_schedule_ready */
5597   NULL, /* advance_target_bb */
5598   SEL_SCHED | NEW_BBS
5599 };
5600
5601 /* Setup special insns used in the scheduler.  */
5602 void
5603 setup_nop_and_exit_insns (void)
5604 {
5605   gcc_assert (nop_pattern == NULL_RTX
5606               && exit_insn == NULL_RTX);
5607
5608   nop_pattern = gen_nop ();
5609
5610   start_sequence ();
5611   emit_insn (nop_pattern);
5612   exit_insn = get_insns ();
5613   end_sequence ();
5614   set_block_for_insn (exit_insn, EXIT_BLOCK_PTR);
5615 }
5616
5617 /* Free special insns used in the scheduler.  */
5618 void
5619 free_nop_and_exit_insns (void)
5620 {
5621   exit_insn = NULL_RTX;
5622   nop_pattern = NULL_RTX;
5623 }
5624
5625 /* Setup a special vinsn used in new insns initialization.  */
5626 void
5627 setup_nop_vinsn (void)
5628 {
5629   nop_vinsn = vinsn_create (exit_insn, false);
5630   vinsn_attach (nop_vinsn);
5631 }
5632
5633 /* Free a special vinsn used in new insns initialization.  */
5634 void
5635 free_nop_vinsn (void)
5636 {
5637   gcc_assert (VINSN_COUNT (nop_vinsn) == 1);
5638   vinsn_detach (nop_vinsn);
5639   nop_vinsn = NULL;
5640 }
5641
5642 /* Call a set_sched_flags hook.  */
5643 void
5644 sel_set_sched_flags (void)
5645 {
5646   /* ??? This means that set_sched_flags were called, and we decided to
5647      support speculation.  However, set_sched_flags also modifies flags
5648      on current_sched_info, doing this only at global init.  And we
5649      sometimes change c_s_i later.  So put the correct flags again.  */
5650   if (spec_info && targetm.sched.set_sched_flags)
5651     targetm.sched.set_sched_flags (spec_info);
5652 }
5653
5654 /* Setup pointers to global sched info structures.  */
5655 void
5656 sel_setup_sched_infos (void)
5657 {
5658   rgn_setup_common_sched_info ();
5659
5660   memcpy (&sel_common_sched_info, common_sched_info,
5661           sizeof (sel_common_sched_info));
5662
5663   sel_common_sched_info.fix_recovery_cfg = NULL;
5664   sel_common_sched_info.add_block = NULL;
5665   sel_common_sched_info.estimate_number_of_insns
5666     = sel_estimate_number_of_insns;
5667   sel_common_sched_info.luid_for_non_insn = sel_luid_for_non_insn;
5668   sel_common_sched_info.sched_pass_id = SCHED_SEL_PASS;
5669
5670   common_sched_info = &sel_common_sched_info;
5671
5672   current_sched_info = &sched_sel_haifa_sched_info;
5673   current_sched_info->sched_max_insns_priority =
5674     get_rgn_sched_max_insns_priority ();
5675
5676   sel_set_sched_flags ();
5677 }
5678 \f
5679
5680 /* Adds basic block BB to region RGN at the position *BB_ORD_INDEX,
5681    *BB_ORD_INDEX after that is increased.  */
5682 static void
5683 sel_add_block_to_region (basic_block bb, int *bb_ord_index, int rgn)
5684 {
5685   RGN_NR_BLOCKS (rgn) += 1;
5686   RGN_DONT_CALC_DEPS (rgn) = 0;
5687   RGN_HAS_REAL_EBB (rgn) = 0;
5688   CONTAINING_RGN (bb->index) = rgn;
5689   BLOCK_TO_BB (bb->index) = *bb_ord_index;
5690   rgn_bb_table[RGN_BLOCKS (rgn) + *bb_ord_index] = bb->index;
5691   (*bb_ord_index)++;
5692
5693   /* FIXME: it is true only when not scheduling ebbs.  */
5694   RGN_BLOCKS (rgn + 1) = RGN_BLOCKS (rgn) + RGN_NR_BLOCKS (rgn);
5695 }
5696
5697 /* Functions to support pipelining of outer loops.  */
5698
5699 /* Creates a new empty region and returns it's number.  */
5700 static int
5701 sel_create_new_region (void)
5702 {
5703   int new_rgn_number = nr_regions;
5704
5705   RGN_NR_BLOCKS (new_rgn_number) = 0;
5706
5707   /* FIXME: This will work only when EBBs are not created.  */
5708   if (new_rgn_number != 0)
5709     RGN_BLOCKS (new_rgn_number) = RGN_BLOCKS (new_rgn_number - 1) +
5710       RGN_NR_BLOCKS (new_rgn_number - 1);
5711   else
5712     RGN_BLOCKS (new_rgn_number) = 0;
5713
5714   /* Set the blocks of the next region so the other functions may
5715      calculate the number of blocks in the region.  */
5716   RGN_BLOCKS (new_rgn_number + 1) = RGN_BLOCKS (new_rgn_number) +
5717     RGN_NR_BLOCKS (new_rgn_number);
5718
5719   nr_regions++;
5720
5721   return new_rgn_number;
5722 }
5723
5724 /* If X has a smaller topological sort number than Y, returns -1;
5725    if greater, returns 1.  */
5726 static int
5727 bb_top_order_comparator (const void *x, const void *y)
5728 {
5729   basic_block bb1 = *(const basic_block *) x;
5730   basic_block bb2 = *(const basic_block *) y;
5731
5732   gcc_assert (bb1 == bb2
5733               || rev_top_order_index[bb1->index]
5734                  != rev_top_order_index[bb2->index]);
5735
5736   /* It's a reverse topological order in REV_TOP_ORDER_INDEX, so
5737      bbs with greater number should go earlier.  */
5738   if (rev_top_order_index[bb1->index] > rev_top_order_index[bb2->index])
5739     return -1;
5740   else
5741     return 1;
5742 }
5743
5744 /* Create a region for LOOP and return its number.  If we don't want
5745    to pipeline LOOP, return -1.  */
5746 static int
5747 make_region_from_loop (struct loop *loop)
5748 {
5749   unsigned int i;
5750   int new_rgn_number = -1;
5751   struct loop *inner;
5752
5753   /* Basic block index, to be assigned to BLOCK_TO_BB.  */
5754   int bb_ord_index = 0;
5755   basic_block *loop_blocks;
5756   basic_block preheader_block;
5757
5758   if (loop->num_nodes
5759       > (unsigned) PARAM_VALUE (PARAM_MAX_PIPELINE_REGION_BLOCKS))
5760     return -1;
5761
5762   /* Don't pipeline loops whose latch belongs to some of its inner loops.  */
5763   for (inner = loop->inner; inner; inner = inner->inner)
5764     if (flow_bb_inside_loop_p (inner, loop->latch))
5765       return -1;
5766
5767   loop->ninsns = num_loop_insns (loop);
5768   if ((int) loop->ninsns > PARAM_VALUE (PARAM_MAX_PIPELINE_REGION_INSNS))
5769     return -1;
5770
5771   loop_blocks = get_loop_body_in_custom_order (loop, bb_top_order_comparator);
5772
5773   for (i = 0; i < loop->num_nodes; i++)
5774     if (loop_blocks[i]->flags & BB_IRREDUCIBLE_LOOP)
5775       {
5776         free (loop_blocks);
5777         return -1;
5778       }
5779
5780   preheader_block = loop_preheader_edge (loop)->src;
5781   gcc_assert (preheader_block);
5782   gcc_assert (loop_blocks[0] == loop->header);
5783
5784   new_rgn_number = sel_create_new_region ();
5785
5786   sel_add_block_to_region (preheader_block, &bb_ord_index, new_rgn_number);
5787   SET_BIT (bbs_in_loop_rgns, preheader_block->index);
5788
5789   for (i = 0; i < loop->num_nodes; i++)
5790     {
5791       /* Add only those blocks that haven't been scheduled in the inner loop.
5792          The exception is the basic blocks with bookkeeping code - they should
5793          be added to the region (and they actually don't belong to the loop
5794          body, but to the region containing that loop body).  */
5795
5796       gcc_assert (new_rgn_number >= 0);
5797
5798       if (! TEST_BIT (bbs_in_loop_rgns, loop_blocks[i]->index))
5799         {
5800           sel_add_block_to_region (loop_blocks[i], &bb_ord_index,
5801                                    new_rgn_number);
5802           SET_BIT (bbs_in_loop_rgns, loop_blocks[i]->index);
5803         }
5804     }
5805
5806   free (loop_blocks);
5807   MARK_LOOP_FOR_PIPELINING (loop);
5808
5809   return new_rgn_number;
5810 }
5811
5812 /* Create a new region from preheader blocks LOOP_BLOCKS.  */
5813 void
5814 make_region_from_loop_preheader (VEC(basic_block, heap) **loop_blocks)
5815 {
5816   unsigned int i;
5817   int new_rgn_number = -1;
5818   basic_block bb;
5819
5820   /* Basic block index, to be assigned to BLOCK_TO_BB.  */
5821   int bb_ord_index = 0;
5822
5823   new_rgn_number = sel_create_new_region ();
5824
5825   FOR_EACH_VEC_ELT (basic_block, *loop_blocks, i, bb)
5826     {
5827       gcc_assert (new_rgn_number >= 0);
5828
5829       sel_add_block_to_region (bb, &bb_ord_index, new_rgn_number);
5830     }
5831
5832   VEC_free (basic_block, heap, *loop_blocks);
5833   gcc_assert (*loop_blocks == NULL);
5834 }
5835
5836
5837 /* Create region(s) from loop nest LOOP, such that inner loops will be
5838    pipelined before outer loops.  Returns true when a region for LOOP
5839    is created.  */
5840 static bool
5841 make_regions_from_loop_nest (struct loop *loop)
5842 {
5843   struct loop *cur_loop;
5844   int rgn_number;
5845
5846   /* Traverse all inner nodes of the loop.  */
5847   for (cur_loop = loop->inner; cur_loop; cur_loop = cur_loop->next)
5848     if (! TEST_BIT (bbs_in_loop_rgns, cur_loop->header->index))
5849       return false;
5850
5851   /* At this moment all regular inner loops should have been pipelined.
5852      Try to create a region from this loop.  */
5853   rgn_number = make_region_from_loop (loop);
5854
5855   if (rgn_number < 0)
5856     return false;
5857
5858   VEC_safe_push (loop_p, heap, loop_nests, loop);
5859   return true;
5860 }
5861
5862 /* Initalize data structures needed.  */
5863 void
5864 sel_init_pipelining (void)
5865 {
5866   /* Collect loop information to be used in outer loops pipelining.  */
5867   loop_optimizer_init (LOOPS_HAVE_PREHEADERS
5868                        | LOOPS_HAVE_FALLTHRU_PREHEADERS
5869                        | LOOPS_HAVE_RECORDED_EXITS
5870                        | LOOPS_HAVE_MARKED_IRREDUCIBLE_REGIONS);
5871   current_loop_nest = NULL;
5872
5873   bbs_in_loop_rgns = sbitmap_alloc (last_basic_block);
5874   sbitmap_zero (bbs_in_loop_rgns);
5875
5876   recompute_rev_top_order ();
5877 }
5878
5879 /* Returns a struct loop for region RGN.  */
5880 loop_p
5881 get_loop_nest_for_rgn (unsigned int rgn)
5882 {
5883   /* Regions created with extend_rgns don't have corresponding loop nests,
5884      because they don't represent loops.  */
5885   if (rgn < VEC_length (loop_p, loop_nests))
5886     return VEC_index (loop_p, loop_nests, rgn);
5887   else
5888     return NULL;
5889 }
5890
5891 /* True when LOOP was included into pipelining regions.   */
5892 bool
5893 considered_for_pipelining_p (struct loop *loop)
5894 {
5895   if (loop_depth (loop) == 0)
5896     return false;
5897
5898   /* Now, the loop could be too large or irreducible.  Check whether its
5899      region is in LOOP_NESTS.
5900      We determine the region number of LOOP as the region number of its
5901      latch.  We can't use header here, because this header could be
5902      just removed preheader and it will give us the wrong region number.
5903      Latch can't be used because it could be in the inner loop too.  */
5904   if (LOOP_MARKED_FOR_PIPELINING_P (loop))
5905     {
5906       int rgn = CONTAINING_RGN (loop->latch->index);
5907
5908       gcc_assert ((unsigned) rgn < VEC_length (loop_p, loop_nests));
5909       return true;
5910     }
5911
5912   return false;
5913 }
5914
5915 /* Makes regions from the rest of the blocks, after loops are chosen
5916    for pipelining.  */
5917 static void
5918 make_regions_from_the_rest (void)
5919 {
5920   int cur_rgn_blocks;
5921   int *loop_hdr;
5922   int i;
5923
5924   basic_block bb;
5925   edge e;
5926   edge_iterator ei;
5927   int *degree;
5928
5929   /* Index in rgn_bb_table where to start allocating new regions.  */
5930   cur_rgn_blocks = nr_regions ? RGN_BLOCKS (nr_regions) : 0;
5931
5932   /* Make regions from all the rest basic blocks - those that don't belong to
5933      any loop or belong to irreducible loops.  Prepare the data structures
5934      for extend_rgns.  */
5935
5936   /* LOOP_HDR[I] == -1 if I-th bb doesn't belong to any loop,
5937      LOOP_HDR[I] == LOOP_HDR[J] iff basic blocks I and J reside within the same
5938      loop.  */
5939   loop_hdr = XNEWVEC (int, last_basic_block);
5940   degree = XCNEWVEC (int, last_basic_block);
5941
5942
5943   /* For each basic block that belongs to some loop assign the number
5944      of innermost loop it belongs to.  */
5945   for (i = 0; i < last_basic_block; i++)
5946     loop_hdr[i] = -1;
5947
5948   FOR_EACH_BB (bb)
5949     {
5950       if (bb->loop_father && !bb->loop_father->num == 0
5951           && !(bb->flags & BB_IRREDUCIBLE_LOOP))
5952         loop_hdr[bb->index] = bb->loop_father->num;
5953     }
5954
5955   /* For each basic block degree is calculated as the number of incoming
5956      edges, that are going out of bbs that are not yet scheduled.
5957      The basic blocks that are scheduled have degree value of zero.  */
5958   FOR_EACH_BB (bb)
5959     {
5960       degree[bb->index] = 0;
5961
5962       if (!TEST_BIT (bbs_in_loop_rgns, bb->index))
5963         {
5964           FOR_EACH_EDGE (e, ei, bb->preds)
5965             if (!TEST_BIT (bbs_in_loop_rgns, e->src->index))
5966               degree[bb->index]++;
5967         }
5968       else
5969         degree[bb->index] = -1;
5970     }
5971
5972   extend_rgns (degree, &cur_rgn_blocks, bbs_in_loop_rgns, loop_hdr);
5973
5974   /* Any block that did not end up in a region is placed into a region
5975      by itself.  */
5976   FOR_EACH_BB (bb)
5977     if (degree[bb->index] >= 0)
5978       {
5979         rgn_bb_table[cur_rgn_blocks] = bb->index;
5980         RGN_NR_BLOCKS (nr_regions) = 1;
5981         RGN_BLOCKS (nr_regions) = cur_rgn_blocks++;
5982         RGN_DONT_CALC_DEPS (nr_regions) = 0;
5983         RGN_HAS_REAL_EBB (nr_regions) = 0;
5984         CONTAINING_RGN (bb->index) = nr_regions++;
5985         BLOCK_TO_BB (bb->index) = 0;
5986       }
5987
5988   free (degree);
5989   free (loop_hdr);
5990 }
5991
5992 /* Free data structures used in pipelining of loops.  */
5993 void sel_finish_pipelining (void)
5994 {
5995   loop_iterator li;
5996   struct loop *loop;
5997
5998   /* Release aux fields so we don't free them later by mistake.  */
5999   FOR_EACH_LOOP (li, loop, 0)
6000     loop->aux = NULL;
6001
6002   loop_optimizer_finalize ();
6003
6004   VEC_free (loop_p, heap, loop_nests);
6005
6006   free (rev_top_order_index);
6007   rev_top_order_index = NULL;
6008 }
6009
6010 /* This function replaces the find_rgns when
6011    FLAG_SEL_SCHED_PIPELINING_OUTER_LOOPS is set.  */
6012 void
6013 sel_find_rgns (void)
6014 {
6015   sel_init_pipelining ();
6016   extend_regions ();
6017
6018   if (current_loops)
6019     {
6020       loop_p loop;
6021       loop_iterator li;
6022
6023       FOR_EACH_LOOP (li, loop, (flag_sel_sched_pipelining_outer_loops
6024                                 ? LI_FROM_INNERMOST
6025                                 : LI_ONLY_INNERMOST))
6026         make_regions_from_loop_nest (loop);
6027     }
6028
6029   /* Make regions from all the rest basic blocks and schedule them.
6030      These blocks include blocks that don't belong to any loop or belong
6031      to irreducible loops.  */
6032   make_regions_from_the_rest ();
6033
6034   /* We don't need bbs_in_loop_rgns anymore.  */
6035   sbitmap_free (bbs_in_loop_rgns);
6036   bbs_in_loop_rgns = NULL;
6037 }
6038
6039 /* Adds the preheader blocks from previous loop to current region taking
6040    it from LOOP_PREHEADER_BLOCKS (current_loop_nest).
6041    This function is only used with -fsel-sched-pipelining-outer-loops.  */
6042 void
6043 sel_add_loop_preheaders (void)
6044 {
6045   int i;
6046   basic_block bb;
6047   VEC(basic_block, heap) *preheader_blocks
6048     = LOOP_PREHEADER_BLOCKS (current_loop_nest);
6049
6050   for (i = 0;
6051        VEC_iterate (basic_block, preheader_blocks, i, bb);
6052        i++)
6053     {
6054       VEC_safe_push (basic_block, heap, last_added_blocks, bb);
6055       sel_add_bb (bb);
6056     }
6057
6058   VEC_free (basic_block, heap, preheader_blocks);
6059 }
6060
6061 /* While pipelining outer loops, returns TRUE if BB is a loop preheader.
6062    Please note that the function should also work when pipelining_p is
6063    false, because it is used when deciding whether we should or should
6064    not reschedule pipelined code.  */
6065 bool
6066 sel_is_loop_preheader_p (basic_block bb)
6067 {
6068   if (current_loop_nest)
6069     {
6070       struct loop *outer;
6071
6072       if (preheader_removed)
6073         return false;
6074
6075       /* Preheader is the first block in the region.  */
6076       if (BLOCK_TO_BB (bb->index) == 0)
6077         return true;
6078
6079       /* We used to find a preheader with the topological information.
6080          Check that the above code is equivalent to what we did before.  */
6081
6082       if (in_current_region_p (current_loop_nest->header))
6083         gcc_assert (!(BLOCK_TO_BB (bb->index)
6084                       < BLOCK_TO_BB (current_loop_nest->header->index)));
6085
6086       /* Support the situation when the latch block of outer loop
6087          could be from here.  */
6088       for (outer = loop_outer (current_loop_nest);
6089            outer;
6090            outer = loop_outer (outer))
6091         if (considered_for_pipelining_p (outer) && outer->latch == bb)
6092           gcc_unreachable ();
6093     }
6094
6095   return false;
6096 }
6097
6098 /* Checks whether JUMP leads to basic block DEST_BB and no other blocks.  */
6099 bool
6100 jump_leads_only_to_bb_p (insn_t jump, basic_block dest_bb)
6101 {
6102   basic_block jump_bb = BLOCK_FOR_INSN (jump);
6103
6104   /* It is not jump, jump with side-effects or jump can lead to several
6105      basic blocks.  */
6106   if (!onlyjump_p (jump)
6107       || !any_uncondjump_p (jump))
6108     return false;
6109
6110   /* Several outgoing edges, abnormal edge or destination of jump is
6111      not DEST_BB.  */
6112   if (EDGE_COUNT (jump_bb->succs) != 1
6113       || EDGE_SUCC (jump_bb, 0)->flags & EDGE_ABNORMAL
6114       || EDGE_SUCC (jump_bb, 0)->dest != dest_bb)
6115     return false;
6116
6117   /* If not anything of the upper.  */
6118   return true;
6119 }
6120
6121 /* Removes the loop preheader from the current region and saves it in
6122    PREHEADER_BLOCKS of the father loop, so they will be added later to
6123    region that represents an outer loop.  */
6124 static void
6125 sel_remove_loop_preheader (void)
6126 {
6127   int i, old_len;
6128   int cur_rgn = CONTAINING_RGN (BB_TO_BLOCK (0));
6129   basic_block bb;
6130   bool all_empty_p = true;
6131   VEC(basic_block, heap) *preheader_blocks
6132     = LOOP_PREHEADER_BLOCKS (loop_outer (current_loop_nest));
6133
6134   gcc_assert (current_loop_nest);
6135   old_len = VEC_length (basic_block, preheader_blocks);
6136
6137   /* Add blocks that aren't within the current loop to PREHEADER_BLOCKS.  */
6138   for (i = 0; i < RGN_NR_BLOCKS (cur_rgn); i++)
6139     {
6140       bb = BASIC_BLOCK (BB_TO_BLOCK (i));
6141
6142       /* If the basic block belongs to region, but doesn't belong to
6143          corresponding loop, then it should be a preheader.  */
6144       if (sel_is_loop_preheader_p (bb))
6145         {
6146           VEC_safe_push (basic_block, heap, preheader_blocks, bb);
6147           if (BB_END (bb) != bb_note (bb))
6148             all_empty_p = false;
6149         }
6150     }
6151
6152   /* Remove these blocks only after iterating over the whole region.  */
6153   for (i = VEC_length (basic_block, preheader_blocks) - 1;
6154        i >= old_len;
6155        i--)
6156     {
6157       bb =  VEC_index (basic_block, preheader_blocks, i);
6158       sel_remove_bb (bb, false);
6159     }
6160
6161   if (!considered_for_pipelining_p (loop_outer (current_loop_nest)))
6162     {
6163       if (!all_empty_p)
6164         /* Immediately create new region from preheader.  */
6165         make_region_from_loop_preheader (&preheader_blocks);
6166       else
6167         {
6168           /* If all preheader blocks are empty - dont create new empty region.
6169              Instead, remove them completely.  */
6170           FOR_EACH_VEC_ELT (basic_block, preheader_blocks, i, bb)
6171             {
6172               edge e;
6173               edge_iterator ei;
6174               basic_block prev_bb = bb->prev_bb, next_bb = bb->next_bb;
6175
6176               /* Redirect all incoming edges to next basic block.  */
6177               for (ei = ei_start (bb->preds); (e = ei_safe_edge (ei)); )
6178                 {
6179                   if (! (e->flags & EDGE_FALLTHRU))
6180                     redirect_edge_and_branch (e, bb->next_bb);
6181                   else
6182                     redirect_edge_succ (e, bb->next_bb);
6183                 }
6184               gcc_assert (BB_NOTE_LIST (bb) == NULL);
6185               delete_and_free_basic_block (bb);
6186
6187               /* Check if after deleting preheader there is a nonconditional
6188                  jump in PREV_BB that leads to the next basic block NEXT_BB.
6189                  If it is so - delete this jump and clear data sets of its
6190                  basic block if it becomes empty.  */
6191               if (next_bb->prev_bb == prev_bb
6192                   && prev_bb != ENTRY_BLOCK_PTR
6193                   && jump_leads_only_to_bb_p (BB_END (prev_bb), next_bb))
6194                 {
6195                   redirect_edge_and_branch (EDGE_SUCC (prev_bb, 0), next_bb);
6196                   if (BB_END (prev_bb) == bb_note (prev_bb))
6197                     free_data_sets (prev_bb);
6198                 }
6199             }
6200         }
6201       VEC_free (basic_block, heap, preheader_blocks);
6202     }
6203   else
6204     /* Store preheader within the father's loop structure.  */
6205     SET_LOOP_PREHEADER_BLOCKS (loop_outer (current_loop_nest),
6206                                preheader_blocks);
6207 }
6208 #endif