OSDN Git Service

gcc:
[pf3gnuchains/gcc-fork.git] / gcc / tree-parloops.c
1 /* Loop autoparallelization.
2    Copyright (C) 2006, 2007, 2008, 2009, 2010
3    Free Software Foundation, Inc.
4    Contributed by Sebastian Pop <pop@cri.ensmp.fr> and
5    Zdenek Dvorak <dvorakz@suse.cz>.
6
7 This file is part of GCC.
8
9 GCC is free software; you can redistribute it and/or modify it under
10 the terms of the GNU General Public License as published by the Free
11 Software Foundation; either version 3, or (at your option) any later
12 version.
13
14 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
15 WARRANTY; without even the implied warranty of MERCHANTABILITY or
16 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
17 for more details.
18
19 You should have received a copy of the GNU General Public License
20 along with GCC; see the file COPYING3.  If not see
21 <http://www.gnu.org/licenses/>.  */
22
23 #include "config.h"
24 #include "system.h"
25 #include "coretypes.h"
26 #include "tm.h"
27 #include "tree.h"
28 #include "tree-flow.h"
29 #include "cfgloop.h"
30 #include "tree-data-ref.h"
31 #include "tree-pretty-print.h"
32 #include "gimple-pretty-print.h"
33 #include "tree-pass.h"
34 #include "tree-scalar-evolution.h"
35 #include "hashtab.h"
36 #include "langhooks.h"
37 #include "tree-vectorizer.h"
38
39 /* This pass tries to distribute iterations of loops into several threads.
40    The implementation is straightforward -- for each loop we test whether its
41    iterations are independent, and if it is the case (and some additional
42    conditions regarding profitability and correctness are satisfied), we
43    add GIMPLE_OMP_PARALLEL and GIMPLE_OMP_FOR codes and let omp expansion
44    machinery do its job.
45
46    The most of the complexity is in bringing the code into shape expected
47    by the omp expanders:
48    -- for GIMPLE_OMP_FOR, ensuring that the loop has only one induction
49       variable and that the exit test is at the start of the loop body
50    -- for GIMPLE_OMP_PARALLEL, replacing the references to local addressable
51       variables by accesses through pointers, and breaking up ssa chains
52       by storing the values incoming to the parallelized loop to a structure
53       passed to the new function as an argument (something similar is done
54       in omp gimplification, unfortunately only a small part of the code
55       can be shared).
56
57    TODO:
58    -- if there are several parallelizable loops in a function, it may be
59       possible to generate the threads just once (using synchronization to
60       ensure that cross-loop dependences are obeyed).
61    -- handling of common scalar dependence patterns (accumulation, ...)
62    -- handling of non-innermost loops  */
63
64 /*
65   Reduction handling:
66   currently we use vect_force_simple_reduction() to detect reduction patterns.
67   The code transformation will be introduced by an example.
68
69
70 parloop
71 {
72   int sum=1;
73
74   for (i = 0; i < N; i++)
75    {
76     x[i] = i + 3;
77     sum+=x[i];
78    }
79 }
80
81 gimple-like code:
82 header_bb:
83
84   # sum_29 = PHI <sum_11(5), 1(3)>
85   # i_28 = PHI <i_12(5), 0(3)>
86   D.1795_8 = i_28 + 3;
87   x[i_28] = D.1795_8;
88   sum_11 = D.1795_8 + sum_29;
89   i_12 = i_28 + 1;
90   if (N_6(D) > i_12)
91     goto header_bb;
92
93
94 exit_bb:
95
96   # sum_21 = PHI <sum_11(4)>
97   printf (&"%d"[0], sum_21);
98
99
100 after reduction transformation (only relevant parts):
101
102 parloop
103 {
104
105 ....
106
107
108   # Storing the initial value given by the user.  #
109
110   .paral_data_store.32.sum.27 = 1;
111
112   #pragma omp parallel num_threads(4)
113
114   #pragma omp for schedule(static)
115
116   # The neutral element corresponding to the particular
117   reduction's operation, e.g. 0 for PLUS_EXPR,
118   1 for MULT_EXPR, etc. replaces the user's initial value.  #
119
120   # sum.27_29 = PHI <sum.27_11, 0>
121
122   sum.27_11 = D.1827_8 + sum.27_29;
123
124   GIMPLE_OMP_CONTINUE
125
126   # Adding this reduction phi is done at create_phi_for_local_result() #
127   # sum.27_56 = PHI <sum.27_11, 0>
128   GIMPLE_OMP_RETURN
129
130   # Creating the atomic operation is done at
131   create_call_for_reduction_1()  #
132
133   #pragma omp atomic_load
134   D.1839_59 = *&.paral_data_load.33_51->reduction.23;
135   D.1840_60 = sum.27_56 + D.1839_59;
136   #pragma omp atomic_store (D.1840_60);
137
138   GIMPLE_OMP_RETURN
139
140  # collecting the result after the join of the threads is done at
141   create_loads_for_reductions().
142   The value computed by the threads is loaded from the
143   shared struct.  #
144
145
146   .paral_data_load.33_52 = &.paral_data_store.32;
147   sum_37 =  .paral_data_load.33_52->sum.27;
148   sum_43 = D.1795_41 + sum_37;
149
150   exit bb:
151   # sum_21 = PHI <sum_43, sum_26>
152   printf (&"%d"[0], sum_21);
153
154 ...
155
156 }
157
158 */
159
160 /* Minimal number of iterations of a loop that should be executed in each
161    thread.  */
162 #define MIN_PER_THREAD 100
163
164 /* Element of the hashtable, representing a
165    reduction in the current loop.  */
166 struct reduction_info
167 {
168   gimple reduc_stmt;            /* reduction statement.  */
169   gimple reduc_phi;             /* The phi node defining the reduction.  */
170   enum tree_code reduction_code;/* code for the reduction operation.  */
171   gimple keep_res;              /* The PHI_RESULT of this phi is the resulting value
172                                    of the reduction variable when existing the loop. */
173   tree initial_value;           /* The initial value of the reduction var before entering the loop.  */
174   tree field;                   /*  the name of the field in the parloop data structure intended for reduction.  */
175   tree init;                    /* reduction initialization value.  */
176   gimple new_phi;               /* (helper field) Newly created phi node whose result
177                                    will be passed to the atomic operation.  Represents
178                                    the local result each thread computed for the reduction
179                                    operation.  */
180 };
181
182 /* Equality and hash functions for hashtab code.  */
183
184 static int
185 reduction_info_eq (const void *aa, const void *bb)
186 {
187   const struct reduction_info *a = (const struct reduction_info *) aa;
188   const struct reduction_info *b = (const struct reduction_info *) bb;
189
190   return (a->reduc_phi == b->reduc_phi);
191 }
192
193 static hashval_t
194 reduction_info_hash (const void *aa)
195 {
196   const struct reduction_info *a = (const struct reduction_info *) aa;
197
198   return htab_hash_pointer (a->reduc_phi);
199 }
200
201 static struct reduction_info *
202 reduction_phi (htab_t reduction_list, gimple phi)
203 {
204   struct reduction_info tmpred, *red;
205
206   if (htab_elements (reduction_list) == 0)
207     return NULL;
208
209   tmpred.reduc_phi = phi;
210   red = (struct reduction_info *) htab_find (reduction_list, &tmpred);
211
212   return red;
213 }
214
215 /* Element of hashtable of names to copy.  */
216
217 struct name_to_copy_elt
218 {
219   unsigned version;     /* The version of the name to copy.  */
220   tree new_name;        /* The new name used in the copy.  */
221   tree field;           /* The field of the structure used to pass the
222                            value.  */
223 };
224
225 /* Equality and hash functions for hashtab code.  */
226
227 static int
228 name_to_copy_elt_eq (const void *aa, const void *bb)
229 {
230   const struct name_to_copy_elt *a = (const struct name_to_copy_elt *) aa;
231   const struct name_to_copy_elt *b = (const struct name_to_copy_elt *) bb;
232
233   return a->version == b->version;
234 }
235
236 static hashval_t
237 name_to_copy_elt_hash (const void *aa)
238 {
239   const struct name_to_copy_elt *a = (const struct name_to_copy_elt *) aa;
240
241   return (hashval_t) a->version;
242 }
243
244
245 /* Data dependency analysis. Returns true if the iterations of LOOP
246    are independent on each other (that is, if we can execute them
247    in parallel).  */
248
249 static bool
250 loop_parallel_p (struct loop *loop, struct obstack * parloop_obstack)
251 {
252   VEC (ddr_p, heap) * dependence_relations;
253   VEC (data_reference_p, heap) *datarefs;
254   lambda_trans_matrix trans;
255   bool ret = false;
256
257   if (dump_file && (dump_flags & TDF_DETAILS))
258   {
259     fprintf (dump_file, "Considering loop %d\n", loop->num);
260     if (!loop->inner)
261       fprintf (dump_file, "loop is innermost\n");
262     else
263       fprintf (dump_file, "loop NOT innermost\n");
264    }
265
266   /* Check for problems with dependences.  If the loop can be reversed,
267      the iterations are independent.  */
268   datarefs = VEC_alloc (data_reference_p, heap, 10);
269   dependence_relations = VEC_alloc (ddr_p, heap, 10 * 10);
270   compute_data_dependences_for_loop (loop, true, &datarefs,
271                                      &dependence_relations);
272   if (dump_file && (dump_flags & TDF_DETAILS))
273     dump_data_dependence_relations (dump_file, dependence_relations);
274
275   trans = lambda_trans_matrix_new (1, 1, parloop_obstack);
276   LTM_MATRIX (trans)[0][0] = -1;
277
278   if (lambda_transform_legal_p (trans, 1, dependence_relations))
279     {
280       ret = true;
281       if (dump_file && (dump_flags & TDF_DETAILS))
282         fprintf (dump_file, "  SUCCESS: may be parallelized\n");
283     }
284   else if (dump_file && (dump_flags & TDF_DETAILS))
285     fprintf (dump_file,
286              "  FAILED: data dependencies exist across iterations\n");
287
288   free_dependence_relations (dependence_relations);
289   free_data_refs (datarefs);
290
291   return ret;
292 }
293
294 /* Return true when LOOP contains basic blocks marked with the
295    BB_IRREDUCIBLE_LOOP flag.  */
296
297 static inline bool
298 loop_has_blocks_with_irreducible_flag (struct loop *loop)
299 {
300   unsigned i;
301   basic_block *bbs = get_loop_body_in_dom_order (loop);
302   bool res = true;
303
304   for (i = 0; i < loop->num_nodes; i++)
305     if (bbs[i]->flags & BB_IRREDUCIBLE_LOOP)
306       goto end;
307
308   res = false;
309  end:
310   free (bbs);
311   return res;
312 }
313
314 /* Assigns the address of OBJ in TYPE to an ssa name, and returns this name.
315    The assignment statement is placed on edge ENTRY.  DECL_ADDRESS maps decls
316    to their addresses that can be reused.  The address of OBJ is known to
317    be invariant in the whole function.  Other needed statements are placed
318    right before GSI.  */
319
320 static tree
321 take_address_of (tree obj, tree type, edge entry, htab_t decl_address,
322                  gimple_stmt_iterator *gsi)
323 {
324   int uid;
325   void **dslot;
326   struct int_tree_map ielt, *nielt;
327   tree *var_p, name, bvar, addr;
328   gimple stmt;
329   gimple_seq stmts;
330
331   /* Since the address of OBJ is invariant, the trees may be shared.
332      Avoid rewriting unrelated parts of the code.  */
333   obj = unshare_expr (obj);
334   for (var_p = &obj;
335        handled_component_p (*var_p);
336        var_p = &TREE_OPERAND (*var_p, 0))
337     continue;
338
339   /* Canonicalize the access to base on a MEM_REF.  */
340   if (DECL_P (*var_p))
341     *var_p = build_simple_mem_ref (build_fold_addr_expr (*var_p));
342
343   /* Assign a canonical SSA name to the address of the base decl used
344      in the address and share it for all accesses and addresses based
345      on it.  */
346   uid = DECL_UID (TREE_OPERAND (TREE_OPERAND (*var_p, 0), 0));
347   ielt.uid = uid;
348   dslot = htab_find_slot_with_hash (decl_address, &ielt, uid, INSERT);
349   if (!*dslot)
350     {
351       if (gsi == NULL)
352         return NULL;
353       addr = TREE_OPERAND (*var_p, 0);
354       bvar = create_tmp_var (TREE_TYPE (addr),
355                              get_name (TREE_OPERAND
356                                          (TREE_OPERAND (*var_p, 0), 0)));
357       add_referenced_var (bvar);
358       stmt = gimple_build_assign (bvar, addr);
359       name = make_ssa_name (bvar, stmt);
360       gimple_assign_set_lhs (stmt, name);
361       gsi_insert_on_edge_immediate (entry, stmt);
362
363       nielt = XNEW (struct int_tree_map);
364       nielt->uid = uid;
365       nielt->to = name;
366       *dslot = nielt;
367     }
368   else
369     name = ((struct int_tree_map *) *dslot)->to;
370
371   /* Express the address in terms of the canonical SSA name.  */
372   TREE_OPERAND (*var_p, 0) = name;
373   if (gsi == NULL)
374     return build_fold_addr_expr_with_type (obj, type);
375
376   name = force_gimple_operand (build_addr (obj, current_function_decl),
377                                &stmts, true, NULL_TREE);
378   if (!gimple_seq_empty_p (stmts))
379     gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
380
381   if (!useless_type_conversion_p (type, TREE_TYPE (name)))
382     {
383       name = force_gimple_operand (fold_convert (type, name), &stmts, true,
384                                    NULL_TREE);
385       if (!gimple_seq_empty_p (stmts))
386         gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
387     }
388
389   return name;
390 }
391
392 /* Callback for htab_traverse.  Create the initialization statement
393    for reduction described in SLOT, and place it at the preheader of
394    the loop described in DATA.  */
395
396 static int
397 initialize_reductions (void **slot, void *data)
398 {
399   tree init, c;
400   tree bvar, type, arg;
401   edge e;
402
403   struct reduction_info *const reduc = (struct reduction_info *) *slot;
404   struct loop *loop = (struct loop *) data;
405
406   /* Create initialization in preheader:
407      reduction_variable = initialization value of reduction.  */
408
409   /* In the phi node at the header, replace the argument coming
410      from the preheader with the reduction initialization value.  */
411
412   /* Create a new variable to initialize the reduction.  */
413   type = TREE_TYPE (PHI_RESULT (reduc->reduc_phi));
414   bvar = create_tmp_var (type, "reduction");
415   add_referenced_var (bvar);
416
417   c = build_omp_clause (gimple_location (reduc->reduc_stmt),
418                         OMP_CLAUSE_REDUCTION);
419   OMP_CLAUSE_REDUCTION_CODE (c) = reduc->reduction_code;
420   OMP_CLAUSE_DECL (c) = SSA_NAME_VAR (gimple_assign_lhs (reduc->reduc_stmt));
421
422   init = omp_reduction_init (c, TREE_TYPE (bvar));
423   reduc->init = init;
424
425   /* Replace the argument representing the initialization value
426      with the initialization value for the reduction (neutral
427      element for the particular operation, e.g. 0 for PLUS_EXPR,
428      1 for MULT_EXPR, etc).
429      Keep the old value in a new variable "reduction_initial",
430      that will be taken in consideration after the parallel
431      computing is done.  */
432
433   e = loop_preheader_edge (loop);
434   arg = PHI_ARG_DEF_FROM_EDGE (reduc->reduc_phi, e);
435   /* Create new variable to hold the initial value.  */
436
437   SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE
438            (reduc->reduc_phi, loop_preheader_edge (loop)), init);
439   reduc->initial_value = arg;
440   return 1;
441 }
442
443 struct elv_data
444 {
445   struct walk_stmt_info info;
446   edge entry;
447   htab_t decl_address;
448   gimple_stmt_iterator *gsi;
449   bool changed;
450   bool reset;
451 };
452
453 /* Eliminates references to local variables in *TP out of the single
454    entry single exit region starting at DTA->ENTRY.
455    DECL_ADDRESS contains addresses of the references that had their
456    address taken already.  If the expression is changed, CHANGED is
457    set to true.  Callback for walk_tree.  */
458
459 static tree
460 eliminate_local_variables_1 (tree *tp, int *walk_subtrees, void *data)
461 {
462   struct elv_data *const dta = (struct elv_data *) data;
463   tree t = *tp, var, addr, addr_type, type, obj;
464
465   if (DECL_P (t))
466     {
467       *walk_subtrees = 0;
468
469       if (!SSA_VAR_P (t) || DECL_EXTERNAL (t))
470         return NULL_TREE;
471
472       type = TREE_TYPE (t);
473       addr_type = build_pointer_type (type);
474       addr = take_address_of (t, addr_type, dta->entry, dta->decl_address,
475                               dta->gsi);
476       if (dta->gsi == NULL && addr == NULL_TREE)
477         {
478           dta->reset = true;
479           return NULL_TREE;
480         }
481
482       *tp = build_simple_mem_ref (addr);
483
484       dta->changed = true;
485       return NULL_TREE;
486     }
487
488   if (TREE_CODE (t) == ADDR_EXPR)
489     {
490       /* ADDR_EXPR may appear in two contexts:
491          -- as a gimple operand, when the address taken is a function invariant
492          -- as gimple rhs, when the resulting address in not a function
493             invariant
494          We do not need to do anything special in the latter case (the base of
495          the memory reference whose address is taken may be replaced in the
496          DECL_P case).  The former case is more complicated, as we need to
497          ensure that the new address is still a gimple operand.  Thus, it
498          is not sufficient to replace just the base of the memory reference --
499          we need to move the whole computation of the address out of the
500          loop.  */
501       if (!is_gimple_val (t))
502         return NULL_TREE;
503
504       *walk_subtrees = 0;
505       obj = TREE_OPERAND (t, 0);
506       var = get_base_address (obj);
507       if (!var || !SSA_VAR_P (var) || DECL_EXTERNAL (var))
508         return NULL_TREE;
509
510       addr_type = TREE_TYPE (t);
511       addr = take_address_of (obj, addr_type, dta->entry, dta->decl_address,
512                               dta->gsi);
513       if (dta->gsi == NULL && addr == NULL_TREE)
514         {
515           dta->reset = true;
516           return NULL_TREE;
517         }
518       *tp = addr;
519
520       dta->changed = true;
521       return NULL_TREE;
522     }
523
524   if (!EXPR_P (t))
525     *walk_subtrees = 0;
526
527   return NULL_TREE;
528 }
529
530 /* Moves the references to local variables in STMT at *GSI out of the single
531    entry single exit region starting at ENTRY.  DECL_ADDRESS contains
532    addresses of the references that had their address taken
533    already.  */
534
535 static void
536 eliminate_local_variables_stmt (edge entry, gimple_stmt_iterator *gsi,
537                                 htab_t decl_address)
538 {
539   struct elv_data dta;
540   gimple stmt = gsi_stmt (*gsi);
541
542   memset (&dta.info, '\0', sizeof (dta.info));
543   dta.entry = entry;
544   dta.decl_address = decl_address;
545   dta.changed = false;
546   dta.reset = false;
547
548   if (gimple_debug_bind_p (stmt))
549     {
550       dta.gsi = NULL;
551       walk_tree (gimple_debug_bind_get_value_ptr (stmt),
552                  eliminate_local_variables_1, &dta.info, NULL);
553       if (dta.reset)
554         {
555           gimple_debug_bind_reset_value (stmt);
556           dta.changed = true;
557         }
558     }
559   else
560     {
561       dta.gsi = gsi;
562       walk_gimple_op (stmt, eliminate_local_variables_1, &dta.info);
563     }
564
565   if (dta.changed)
566     update_stmt (stmt);
567 }
568
569 /* Eliminates the references to local variables from the single entry
570    single exit region between the ENTRY and EXIT edges.
571
572    This includes:
573    1) Taking address of a local variable -- these are moved out of the
574    region (and temporary variable is created to hold the address if
575    necessary).
576
577    2) Dereferencing a local variable -- these are replaced with indirect
578    references.  */
579
580 static void
581 eliminate_local_variables (edge entry, edge exit)
582 {
583   basic_block bb;
584   VEC (basic_block, heap) *body = VEC_alloc (basic_block, heap, 3);
585   unsigned i;
586   gimple_stmt_iterator gsi;
587   bool has_debug_stmt = false;
588   htab_t decl_address = htab_create (10, int_tree_map_hash, int_tree_map_eq,
589                                      free);
590   basic_block entry_bb = entry->src;
591   basic_block exit_bb = exit->dest;
592
593   gather_blocks_in_sese_region (entry_bb, exit_bb, &body);
594
595   FOR_EACH_VEC_ELT (basic_block, body, i, bb)
596     if (bb != entry_bb && bb != exit_bb)
597       for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
598         if (gimple_debug_bind_p (gsi_stmt (gsi)))
599           has_debug_stmt = true;
600         else
601           eliminate_local_variables_stmt (entry, &gsi, decl_address);
602
603   if (has_debug_stmt)
604     FOR_EACH_VEC_ELT (basic_block, body, i, bb)
605       if (bb != entry_bb && bb != exit_bb)
606         for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
607           if (gimple_debug_bind_p (gsi_stmt (gsi)))
608             eliminate_local_variables_stmt (entry, &gsi, decl_address);
609
610   htab_delete (decl_address);
611   VEC_free (basic_block, heap, body);
612 }
613
614 /* Returns true if expression EXPR is not defined between ENTRY and
615    EXIT, i.e. if all its operands are defined outside of the region.  */
616
617 static bool
618 expr_invariant_in_region_p (edge entry, edge exit, tree expr)
619 {
620   basic_block entry_bb = entry->src;
621   basic_block exit_bb = exit->dest;
622   basic_block def_bb;
623
624   if (is_gimple_min_invariant (expr))
625     return true;
626
627   if (TREE_CODE (expr) == SSA_NAME)
628     {
629       def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr));
630       if (def_bb
631           && dominated_by_p (CDI_DOMINATORS, def_bb, entry_bb)
632           && !dominated_by_p (CDI_DOMINATORS, def_bb, exit_bb))
633         return false;
634
635       return true;
636     }
637
638   return false;
639 }
640
641 /* If COPY_NAME_P is true, creates and returns a duplicate of NAME.
642    The copies are stored to NAME_COPIES, if NAME was already duplicated,
643    its duplicate stored in NAME_COPIES is returned.
644
645    Regardless of COPY_NAME_P, the decl used as a base of the ssa name is also
646    duplicated, storing the copies in DECL_COPIES.  */
647
648 static tree
649 separate_decls_in_region_name (tree name,
650                                htab_t name_copies, htab_t decl_copies,
651                                bool copy_name_p)
652 {
653   tree copy, var, var_copy;
654   unsigned idx, uid, nuid;
655   struct int_tree_map ielt, *nielt;
656   struct name_to_copy_elt elt, *nelt;
657   void **slot, **dslot;
658
659   if (TREE_CODE (name) != SSA_NAME)
660     return name;
661
662   idx = SSA_NAME_VERSION (name);
663   elt.version = idx;
664   slot = htab_find_slot_with_hash (name_copies, &elt, idx,
665                                    copy_name_p ? INSERT : NO_INSERT);
666   if (slot && *slot)
667     return ((struct name_to_copy_elt *) *slot)->new_name;
668
669   var = SSA_NAME_VAR (name);
670   uid = DECL_UID (var);
671   ielt.uid = uid;
672   dslot = htab_find_slot_with_hash (decl_copies, &ielt, uid, INSERT);
673   if (!*dslot)
674     {
675       var_copy = create_tmp_var (TREE_TYPE (var), get_name (var));
676       DECL_GIMPLE_REG_P (var_copy) = DECL_GIMPLE_REG_P (var);
677       add_referenced_var (var_copy);
678       nielt = XNEW (struct int_tree_map);
679       nielt->uid = uid;
680       nielt->to = var_copy;
681       *dslot = nielt;
682
683       /* Ensure that when we meet this decl next time, we won't duplicate
684          it again.  */
685       nuid = DECL_UID (var_copy);
686       ielt.uid = nuid;
687       dslot = htab_find_slot_with_hash (decl_copies, &ielt, nuid, INSERT);
688       gcc_assert (!*dslot);
689       nielt = XNEW (struct int_tree_map);
690       nielt->uid = nuid;
691       nielt->to = var_copy;
692       *dslot = nielt;
693     }
694   else
695     var_copy = ((struct int_tree_map *) *dslot)->to;
696
697   if (copy_name_p)
698     {
699       copy = duplicate_ssa_name (name, NULL);
700       nelt = XNEW (struct name_to_copy_elt);
701       nelt->version = idx;
702       nelt->new_name = copy;
703       nelt->field = NULL_TREE;
704       *slot = nelt;
705     }
706   else
707     {
708       gcc_assert (!slot);
709       copy = name;
710     }
711
712   SSA_NAME_VAR (copy) = var_copy;
713   return copy;
714 }
715
716 /* Finds the ssa names used in STMT that are defined outside the
717    region between ENTRY and EXIT and replaces such ssa names with
718    their duplicates.  The duplicates are stored to NAME_COPIES.  Base
719    decls of all ssa names used in STMT (including those defined in
720    LOOP) are replaced with the new temporary variables; the
721    replacement decls are stored in DECL_COPIES.  */
722
723 static void
724 separate_decls_in_region_stmt (edge entry, edge exit, gimple stmt,
725                                htab_t name_copies, htab_t decl_copies)
726 {
727   use_operand_p use;
728   def_operand_p def;
729   ssa_op_iter oi;
730   tree name, copy;
731   bool copy_name_p;
732
733   mark_virtual_ops_for_renaming (stmt);
734
735   FOR_EACH_PHI_OR_STMT_DEF (def, stmt, oi, SSA_OP_DEF)
736   {
737     name = DEF_FROM_PTR (def);
738     gcc_assert (TREE_CODE (name) == SSA_NAME);
739     copy = separate_decls_in_region_name (name, name_copies, decl_copies,
740                                           false);
741     gcc_assert (copy == name);
742   }
743
744   FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE)
745   {
746     name = USE_FROM_PTR (use);
747     if (TREE_CODE (name) != SSA_NAME)
748       continue;
749
750     copy_name_p = expr_invariant_in_region_p (entry, exit, name);
751     copy = separate_decls_in_region_name (name, name_copies, decl_copies,
752                                           copy_name_p);
753     SET_USE (use, copy);
754   }
755 }
756
757 /* Finds the ssa names used in STMT that are defined outside the
758    region between ENTRY and EXIT and replaces such ssa names with
759    their duplicates.  The duplicates are stored to NAME_COPIES.  Base
760    decls of all ssa names used in STMT (including those defined in
761    LOOP) are replaced with the new temporary variables; the
762    replacement decls are stored in DECL_COPIES.  */
763
764 static bool
765 separate_decls_in_region_debug_bind (gimple stmt,
766                                      htab_t name_copies, htab_t decl_copies)
767 {
768   use_operand_p use;
769   ssa_op_iter oi;
770   tree var, name;
771   struct int_tree_map ielt;
772   struct name_to_copy_elt elt;
773   void **slot, **dslot;
774
775   var = gimple_debug_bind_get_var (stmt);
776   if (TREE_CODE (var) == DEBUG_EXPR_DECL)
777     return true;
778   gcc_assert (DECL_P (var) && SSA_VAR_P (var));
779   ielt.uid = DECL_UID (var);
780   dslot = htab_find_slot_with_hash (decl_copies, &ielt, ielt.uid, NO_INSERT);
781   if (!dslot)
782     return true;
783   gimple_debug_bind_set_var (stmt, ((struct int_tree_map *) *dslot)->to);
784
785   FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE)
786   {
787     name = USE_FROM_PTR (use);
788     if (TREE_CODE (name) != SSA_NAME)
789       continue;
790
791     elt.version = SSA_NAME_VERSION (name);
792     slot = htab_find_slot_with_hash (name_copies, &elt, elt.version, NO_INSERT);
793     if (!slot)
794       {
795         gimple_debug_bind_reset_value (stmt);
796         update_stmt (stmt);
797         break;
798       }
799
800     SET_USE (use, ((struct name_to_copy_elt *) *slot)->new_name);
801   }
802
803   return false;
804 }
805
806 /* Callback for htab_traverse.  Adds a field corresponding to the reduction
807    specified in SLOT. The type is passed in DATA.  */
808
809 static int
810 add_field_for_reduction (void **slot, void *data)
811 {
812
813   struct reduction_info *const red = (struct reduction_info *) *slot;
814   tree const type = (tree) data;
815   tree var = SSA_NAME_VAR (gimple_assign_lhs (red->reduc_stmt));
816   tree field = build_decl (gimple_location (red->reduc_stmt),
817                            FIELD_DECL, DECL_NAME (var), TREE_TYPE (var));
818
819   insert_field_into_struct (type, field);
820
821   red->field = field;
822
823   return 1;
824 }
825
826 /* Callback for htab_traverse.  Adds a field corresponding to a ssa name
827    described in SLOT. The type is passed in DATA.  */
828
829 static int
830 add_field_for_name (void **slot, void *data)
831 {
832   struct name_to_copy_elt *const elt = (struct name_to_copy_elt *) *slot;
833   tree type = (tree) data;
834   tree name = ssa_name (elt->version);
835   tree var = SSA_NAME_VAR (name);
836   tree field = build_decl (DECL_SOURCE_LOCATION (var),
837                            FIELD_DECL, DECL_NAME (var), TREE_TYPE (var));
838
839   insert_field_into_struct (type, field);
840   elt->field = field;
841
842   return 1;
843 }
844
845 /* Callback for htab_traverse.  A local result is the intermediate result
846    computed by a single
847    thread, or the initial value in case no iteration was executed.
848    This function creates a phi node reflecting these values.
849    The phi's result will be stored in NEW_PHI field of the
850    reduction's data structure.  */
851
852 static int
853 create_phi_for_local_result (void **slot, void *data)
854 {
855   struct reduction_info *const reduc = (struct reduction_info *) *slot;
856   const struct loop *const loop = (const struct loop *) data;
857   edge e;
858   gimple new_phi;
859   basic_block store_bb;
860   tree local_res;
861   source_location locus;
862
863   /* STORE_BB is the block where the phi
864      should be stored.  It is the destination of the loop exit.
865      (Find the fallthru edge from GIMPLE_OMP_CONTINUE).  */
866   store_bb = FALLTHRU_EDGE (loop->latch)->dest;
867
868   /* STORE_BB has two predecessors.  One coming from  the loop
869      (the reduction's result is computed at the loop),
870      and another coming from a block preceding the loop,
871      when no iterations
872      are executed (the initial value should be taken).  */
873   if (EDGE_PRED (store_bb, 0) == FALLTHRU_EDGE (loop->latch))
874     e = EDGE_PRED (store_bb, 1);
875   else
876     e = EDGE_PRED (store_bb, 0);
877   local_res
878     = make_ssa_name (SSA_NAME_VAR (gimple_assign_lhs (reduc->reduc_stmt)),
879                      NULL);
880   locus = gimple_location (reduc->reduc_stmt);
881   new_phi = create_phi_node (local_res, store_bb);
882   SSA_NAME_DEF_STMT (local_res) = new_phi;
883   add_phi_arg (new_phi, reduc->init, e, locus);
884   add_phi_arg (new_phi, gimple_assign_lhs (reduc->reduc_stmt),
885                FALLTHRU_EDGE (loop->latch), locus);
886   reduc->new_phi = new_phi;
887
888   return 1;
889 }
890
891 struct clsn_data
892 {
893   tree store;
894   tree load;
895
896   basic_block store_bb;
897   basic_block load_bb;
898 };
899
900 /* Callback for htab_traverse.  Create an atomic instruction for the
901    reduction described in SLOT.
902    DATA annotates the place in memory the atomic operation relates to,
903    and the basic block it needs to be generated in.  */
904
905 static int
906 create_call_for_reduction_1 (void **slot, void *data)
907 {
908   struct reduction_info *const reduc = (struct reduction_info *) *slot;
909   struct clsn_data *const clsn_data = (struct clsn_data *) data;
910   gimple_stmt_iterator gsi;
911   tree type = TREE_TYPE (PHI_RESULT (reduc->reduc_phi));
912   tree load_struct;
913   basic_block bb;
914   basic_block new_bb;
915   edge e;
916   tree t, addr, ref, x;
917   tree tmp_load, name;
918   gimple load;
919
920   load_struct = build_simple_mem_ref (clsn_data->load);
921   t = build3 (COMPONENT_REF, type, load_struct, reduc->field, NULL_TREE);
922
923   addr = build_addr (t, current_function_decl);
924
925   /* Create phi node.  */
926   bb = clsn_data->load_bb;
927
928   e = split_block (bb, t);
929   new_bb = e->dest;
930
931   tmp_load = create_tmp_var (TREE_TYPE (TREE_TYPE (addr)), NULL);
932   add_referenced_var (tmp_load);
933   tmp_load = make_ssa_name (tmp_load, NULL);
934   load = gimple_build_omp_atomic_load (tmp_load, addr);
935   SSA_NAME_DEF_STMT (tmp_load) = load;
936   gsi = gsi_start_bb (new_bb);
937   gsi_insert_after (&gsi, load, GSI_NEW_STMT);
938
939   e = split_block (new_bb, load);
940   new_bb = e->dest;
941   gsi = gsi_start_bb (new_bb);
942   ref = tmp_load;
943   x = fold_build2 (reduc->reduction_code,
944                    TREE_TYPE (PHI_RESULT (reduc->new_phi)), ref,
945                    PHI_RESULT (reduc->new_phi));
946
947   name = force_gimple_operand_gsi (&gsi, x, true, NULL_TREE, true,
948                                    GSI_CONTINUE_LINKING);
949
950   gsi_insert_after (&gsi, gimple_build_omp_atomic_store (name), GSI_NEW_STMT);
951   return 1;
952 }
953
954 /* Create the atomic operation at the join point of the threads.
955    REDUCTION_LIST describes the reductions in the LOOP.
956    LD_ST_DATA describes the shared data structure where
957    shared data is stored in and loaded from.  */
958 static void
959 create_call_for_reduction (struct loop *loop, htab_t reduction_list,
960                            struct clsn_data *ld_st_data)
961 {
962   htab_traverse (reduction_list, create_phi_for_local_result, loop);
963   /* Find the fallthru edge from GIMPLE_OMP_CONTINUE.  */
964   ld_st_data->load_bb = FALLTHRU_EDGE (loop->latch)->dest;
965   htab_traverse (reduction_list, create_call_for_reduction_1, ld_st_data);
966 }
967
968 /* Callback for htab_traverse.  Loads the final reduction value at the
969    join point of all threads, and inserts it in the right place.  */
970
971 static int
972 create_loads_for_reductions (void **slot, void *data)
973 {
974   struct reduction_info *const red = (struct reduction_info *) *slot;
975   struct clsn_data *const clsn_data = (struct clsn_data *) data;
976   gimple stmt;
977   gimple_stmt_iterator gsi;
978   tree type = TREE_TYPE (gimple_assign_lhs (red->reduc_stmt));
979   tree load_struct;
980   tree name;
981   tree x;
982
983   gsi = gsi_after_labels (clsn_data->load_bb);
984   load_struct = build_simple_mem_ref (clsn_data->load);
985   load_struct = build3 (COMPONENT_REF, type, load_struct, red->field,
986                         NULL_TREE);
987
988   x = load_struct;
989   name = PHI_RESULT (red->keep_res);
990   stmt = gimple_build_assign (name, x);
991   SSA_NAME_DEF_STMT (name) = stmt;
992
993   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
994
995   for (gsi = gsi_start_phis (gimple_bb (red->keep_res));
996        !gsi_end_p (gsi); gsi_next (&gsi))
997     if (gsi_stmt (gsi) == red->keep_res)
998       {
999         remove_phi_node (&gsi, false);
1000         return 1;
1001       }
1002   gcc_unreachable ();
1003 }
1004
1005 /* Load the reduction result that was stored in LD_ST_DATA.
1006    REDUCTION_LIST describes the list of reductions that the
1007    loads should be generated for.  */
1008 static void
1009 create_final_loads_for_reduction (htab_t reduction_list,
1010                                   struct clsn_data *ld_st_data)
1011 {
1012   gimple_stmt_iterator gsi;
1013   tree t;
1014   gimple stmt;
1015
1016   gsi = gsi_after_labels (ld_st_data->load_bb);
1017   t = build_fold_addr_expr (ld_st_data->store);
1018   stmt = gimple_build_assign (ld_st_data->load, t);
1019
1020   gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
1021   SSA_NAME_DEF_STMT (ld_st_data->load) = stmt;
1022
1023   htab_traverse (reduction_list, create_loads_for_reductions, ld_st_data);
1024
1025 }
1026
1027 /* Callback for htab_traverse.  Store the neutral value for the
1028   particular reduction's operation, e.g. 0 for PLUS_EXPR,
1029   1 for MULT_EXPR, etc. into the reduction field.
1030   The reduction is specified in SLOT. The store information is
1031   passed in DATA.  */
1032
1033 static int
1034 create_stores_for_reduction (void **slot, void *data)
1035 {
1036   struct reduction_info *const red = (struct reduction_info *) *slot;
1037   struct clsn_data *const clsn_data = (struct clsn_data *) data;
1038   tree t;
1039   gimple stmt;
1040   gimple_stmt_iterator gsi;
1041   tree type = TREE_TYPE (gimple_assign_lhs (red->reduc_stmt));
1042
1043   gsi = gsi_last_bb (clsn_data->store_bb);
1044   t = build3 (COMPONENT_REF, type, clsn_data->store, red->field, NULL_TREE);
1045   stmt = gimple_build_assign (t, red->initial_value);
1046   mark_virtual_ops_for_renaming (stmt);
1047   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1048
1049   return 1;
1050 }
1051
1052 /* Callback for htab_traverse.  Creates loads to a field of LOAD in LOAD_BB and
1053    store to a field of STORE in STORE_BB for the ssa name and its duplicate
1054    specified in SLOT.  */
1055
1056 static int
1057 create_loads_and_stores_for_name (void **slot, void *data)
1058 {
1059   struct name_to_copy_elt *const elt = (struct name_to_copy_elt *) *slot;
1060   struct clsn_data *const clsn_data = (struct clsn_data *) data;
1061   tree t;
1062   gimple stmt;
1063   gimple_stmt_iterator gsi;
1064   tree type = TREE_TYPE (elt->new_name);
1065   tree load_struct;
1066
1067   gsi = gsi_last_bb (clsn_data->store_bb);
1068   t = build3 (COMPONENT_REF, type, clsn_data->store, elt->field, NULL_TREE);
1069   stmt = gimple_build_assign (t, ssa_name (elt->version));
1070   mark_virtual_ops_for_renaming (stmt);
1071   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1072
1073   gsi = gsi_last_bb (clsn_data->load_bb);
1074   load_struct = build_simple_mem_ref (clsn_data->load);
1075   t = build3 (COMPONENT_REF, type, load_struct, elt->field, NULL_TREE);
1076   stmt = gimple_build_assign (elt->new_name, t);
1077   SSA_NAME_DEF_STMT (elt->new_name) = stmt;
1078   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1079
1080   return 1;
1081 }
1082
1083 /* Moves all the variables used in LOOP and defined outside of it (including
1084    the initial values of loop phi nodes, and *PER_THREAD if it is a ssa
1085    name) to a structure created for this purpose.  The code
1086
1087    while (1)
1088      {
1089        use (a);
1090        use (b);
1091      }
1092
1093    is transformed this way:
1094
1095    bb0:
1096    old.a = a;
1097    old.b = b;
1098
1099    bb1:
1100    a' = new->a;
1101    b' = new->b;
1102    while (1)
1103      {
1104        use (a');
1105        use (b');
1106      }
1107
1108    `old' is stored to *ARG_STRUCT and `new' is stored to NEW_ARG_STRUCT.  The
1109    pointer `new' is intentionally not initialized (the loop will be split to a
1110    separate function later, and `new' will be initialized from its arguments).
1111    LD_ST_DATA holds information about the shared data structure used to pass
1112    information among the threads.  It is initialized here, and
1113    gen_parallel_loop will pass it to create_call_for_reduction that
1114    needs this information.  REDUCTION_LIST describes the reductions
1115    in LOOP.  */
1116
1117 static void
1118 separate_decls_in_region (edge entry, edge exit, htab_t reduction_list,
1119                           tree *arg_struct, tree *new_arg_struct,
1120                           struct clsn_data *ld_st_data)
1121
1122 {
1123   basic_block bb1 = split_edge (entry);
1124   basic_block bb0 = single_pred (bb1);
1125   htab_t name_copies = htab_create (10, name_to_copy_elt_hash,
1126                                     name_to_copy_elt_eq, free);
1127   htab_t decl_copies = htab_create (10, int_tree_map_hash, int_tree_map_eq,
1128                                     free);
1129   unsigned i;
1130   tree type, type_name, nvar;
1131   gimple_stmt_iterator gsi;
1132   struct clsn_data clsn_data;
1133   VEC (basic_block, heap) *body = VEC_alloc (basic_block, heap, 3);
1134   basic_block bb;
1135   basic_block entry_bb = bb1;
1136   basic_block exit_bb = exit->dest;
1137   bool has_debug_stmt = false;
1138
1139   entry = single_succ_edge (entry_bb);
1140   gather_blocks_in_sese_region (entry_bb, exit_bb, &body);
1141
1142   FOR_EACH_VEC_ELT (basic_block, body, i, bb)
1143     {
1144       if (bb != entry_bb && bb != exit_bb)
1145         {
1146           for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1147             separate_decls_in_region_stmt (entry, exit, gsi_stmt (gsi),
1148                                            name_copies, decl_copies);
1149
1150           for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1151             {
1152               gimple stmt = gsi_stmt (gsi);
1153
1154               if (is_gimple_debug (stmt))
1155                 has_debug_stmt = true;
1156               else
1157                 separate_decls_in_region_stmt (entry, exit, stmt,
1158                                                name_copies, decl_copies);
1159             }
1160         }
1161     }
1162
1163   /* Now process debug bind stmts.  We must not create decls while
1164      processing debug stmts, so we defer their processing so as to
1165      make sure we will have debug info for as many variables as
1166      possible (all of those that were dealt with in the loop above),
1167      and discard those for which we know there's nothing we can
1168      do.  */
1169   if (has_debug_stmt)
1170     FOR_EACH_VEC_ELT (basic_block, body, i, bb)
1171       if (bb != entry_bb && bb != exit_bb)
1172         {
1173           for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
1174             {
1175               gimple stmt = gsi_stmt (gsi);
1176
1177               if (gimple_debug_bind_p (stmt))
1178                 {
1179                   if (separate_decls_in_region_debug_bind (stmt,
1180                                                            name_copies,
1181                                                            decl_copies))
1182                     {
1183                       gsi_remove (&gsi, true);
1184                       continue;
1185                     }
1186                 }
1187
1188               gsi_next (&gsi);
1189             }
1190         }
1191
1192   VEC_free (basic_block, heap, body);
1193
1194   if (htab_elements (name_copies) == 0 && htab_elements (reduction_list) == 0)
1195     {
1196       /* It may happen that there is nothing to copy (if there are only
1197          loop carried and external variables in the loop).  */
1198       *arg_struct = NULL;
1199       *new_arg_struct = NULL;
1200     }
1201   else
1202     {
1203       /* Create the type for the structure to store the ssa names to.  */
1204       type = lang_hooks.types.make_type (RECORD_TYPE);
1205       type_name = build_decl (UNKNOWN_LOCATION,
1206                               TYPE_DECL, create_tmp_var_name (".paral_data"),
1207                               type);
1208       TYPE_NAME (type) = type_name;
1209
1210       htab_traverse (name_copies, add_field_for_name, type);
1211       if (reduction_list && htab_elements (reduction_list) > 0)
1212         {
1213           /* Create the fields for reductions.  */
1214           htab_traverse (reduction_list, add_field_for_reduction,
1215                          type);
1216         }
1217       layout_type (type);
1218
1219       /* Create the loads and stores.  */
1220       *arg_struct = create_tmp_var (type, ".paral_data_store");
1221       add_referenced_var (*arg_struct);
1222       nvar = create_tmp_var (build_pointer_type (type), ".paral_data_load");
1223       add_referenced_var (nvar);
1224       *new_arg_struct = make_ssa_name (nvar, NULL);
1225
1226       ld_st_data->store = *arg_struct;
1227       ld_st_data->load = *new_arg_struct;
1228       ld_st_data->store_bb = bb0;
1229       ld_st_data->load_bb = bb1;
1230
1231       htab_traverse (name_copies, create_loads_and_stores_for_name,
1232                      ld_st_data);
1233
1234       /* Load the calculation from memory (after the join of the threads).  */
1235
1236       if (reduction_list && htab_elements (reduction_list) > 0)
1237         {
1238           htab_traverse (reduction_list, create_stores_for_reduction,
1239                         ld_st_data);
1240           clsn_data.load = make_ssa_name (nvar, NULL);
1241           clsn_data.load_bb = exit->dest;
1242           clsn_data.store = ld_st_data->store;
1243           create_final_loads_for_reduction (reduction_list, &clsn_data);
1244         }
1245     }
1246
1247   htab_delete (decl_copies);
1248   htab_delete (name_copies);
1249 }
1250
1251 /* Bitmap containing uids of functions created by parallelization.  We cannot
1252    allocate it from the default obstack, as it must live across compilation
1253    of several functions; we make it gc allocated instead.  */
1254
1255 static GTY(()) bitmap parallelized_functions;
1256
1257 /* Returns true if FN was created by create_loop_fn.  */
1258
1259 static bool
1260 parallelized_function_p (tree fn)
1261 {
1262   if (!parallelized_functions || !DECL_ARTIFICIAL (fn))
1263     return false;
1264
1265   return bitmap_bit_p (parallelized_functions, DECL_UID (fn));
1266 }
1267
1268 /* Creates and returns an empty function that will receive the body of
1269    a parallelized loop.  */
1270
1271 static tree
1272 create_loop_fn (location_t loc)
1273 {
1274   char buf[100];
1275   char *tname;
1276   tree decl, type, name, t;
1277   struct function *act_cfun = cfun;
1278   static unsigned loopfn_num;
1279
1280   snprintf (buf, 100, "%s.$loopfn", current_function_name ());
1281   ASM_FORMAT_PRIVATE_NAME (tname, buf, loopfn_num++);
1282   clean_symbol_name (tname);
1283   name = get_identifier (tname);
1284   type = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE);
1285
1286   decl = build_decl (loc, FUNCTION_DECL, name, type);
1287   if (!parallelized_functions)
1288     parallelized_functions = BITMAP_GGC_ALLOC ();
1289   bitmap_set_bit (parallelized_functions, DECL_UID (decl));
1290
1291   TREE_STATIC (decl) = 1;
1292   TREE_USED (decl) = 1;
1293   DECL_ARTIFICIAL (decl) = 1;
1294   DECL_IGNORED_P (decl) = 0;
1295   TREE_PUBLIC (decl) = 0;
1296   DECL_UNINLINABLE (decl) = 1;
1297   DECL_EXTERNAL (decl) = 0;
1298   DECL_CONTEXT (decl) = NULL_TREE;
1299   DECL_INITIAL (decl) = make_node (BLOCK);
1300
1301   t = build_decl (loc, RESULT_DECL, NULL_TREE, void_type_node);
1302   DECL_ARTIFICIAL (t) = 1;
1303   DECL_IGNORED_P (t) = 1;
1304   DECL_RESULT (decl) = t;
1305
1306   t = build_decl (loc, PARM_DECL, get_identifier (".paral_data_param"),
1307                   ptr_type_node);
1308   DECL_ARTIFICIAL (t) = 1;
1309   DECL_ARG_TYPE (t) = ptr_type_node;
1310   DECL_CONTEXT (t) = decl;
1311   TREE_USED (t) = 1;
1312   DECL_ARGUMENTS (decl) = t;
1313
1314   allocate_struct_function (decl, false);
1315
1316   /* The call to allocate_struct_function clobbers CFUN, so we need to restore
1317      it.  */
1318   set_cfun (act_cfun);
1319
1320   return decl;
1321 }
1322
1323 /* Moves the exit condition of LOOP to the beginning of its header, and
1324    duplicates the part of the last iteration that gets disabled to the
1325    exit of the loop.  NIT is the number of iterations of the loop
1326    (used to initialize the variables in the duplicated part).
1327
1328    TODO: the common case is that latch of the loop is empty and immediately
1329    follows the loop exit.  In this case, it would be better not to copy the
1330    body of the loop, but only move the entry of the loop directly before the
1331    exit check and increase the number of iterations of the loop by one.
1332    This may need some additional preconditioning in case NIT = ~0.
1333    REDUCTION_LIST describes the reductions in LOOP.  */
1334
1335 static void
1336 transform_to_exit_first_loop (struct loop *loop, htab_t reduction_list, tree nit)
1337 {
1338   basic_block *bbs, *nbbs, ex_bb, orig_header;
1339   unsigned n;
1340   bool ok;
1341   edge exit = single_dom_exit (loop), hpred;
1342   tree control, control_name, res, t;
1343   gimple phi, nphi, cond_stmt, stmt, cond_nit;
1344   gimple_stmt_iterator gsi;
1345   tree nit_1;
1346
1347   split_block_after_labels (loop->header);
1348   orig_header = single_succ (loop->header);
1349   hpred = single_succ_edge (loop->header);
1350
1351   cond_stmt = last_stmt (exit->src);
1352   control = gimple_cond_lhs (cond_stmt);
1353   gcc_assert (gimple_cond_rhs (cond_stmt) == nit);
1354
1355   /* Make sure that we have phi nodes on exit for all loop header phis
1356      (create_parallel_loop requires that).  */
1357   for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
1358     {
1359       phi = gsi_stmt (gsi);
1360       res = PHI_RESULT (phi);
1361       t = make_ssa_name (SSA_NAME_VAR (res), phi);
1362       SET_PHI_RESULT (phi, t);
1363       nphi = create_phi_node (res, orig_header);
1364       SSA_NAME_DEF_STMT (res) = nphi;
1365       add_phi_arg (nphi, t, hpred, UNKNOWN_LOCATION);
1366
1367       if (res == control)
1368         {
1369           gimple_cond_set_lhs (cond_stmt, t);
1370           update_stmt (cond_stmt);
1371           control = t;
1372         }
1373     }
1374   bbs = get_loop_body_in_dom_order (loop);
1375
1376   for (n = 0; bbs[n] != loop->latch; n++)
1377     continue;
1378   nbbs = XNEWVEC (basic_block, n);
1379   ok = gimple_duplicate_sese_tail (single_succ_edge (loop->header), exit,
1380                                    bbs + 1, n, nbbs);
1381   gcc_assert (ok);
1382   free (bbs);
1383   ex_bb = nbbs[0];
1384   free (nbbs);
1385
1386   /* Other than reductions, the only gimple reg that should be copied
1387      out of the loop is the control variable.  */
1388
1389   control_name = NULL_TREE;
1390   for (gsi = gsi_start_phis (ex_bb); !gsi_end_p (gsi); )
1391     {
1392       phi = gsi_stmt (gsi);
1393       res = PHI_RESULT (phi);
1394       if (!is_gimple_reg (res))
1395         {
1396           gsi_next (&gsi);
1397           continue;
1398         }
1399
1400       /* Check if it is a part of reduction.  If it is,
1401          keep the phi at the reduction's keep_res field.  The
1402          PHI_RESULT of this phi is the resulting value of the reduction
1403          variable when exiting the loop.  */
1404
1405       exit = single_dom_exit (loop);
1406
1407       if (htab_elements (reduction_list) > 0)
1408         {
1409           struct reduction_info *red;
1410
1411           tree val = PHI_ARG_DEF_FROM_EDGE (phi, exit);
1412           red = reduction_phi (reduction_list, SSA_NAME_DEF_STMT (val));
1413           if (red)
1414             {
1415               red->keep_res = phi;
1416               gsi_next (&gsi);
1417               continue;
1418             }
1419         }
1420       gcc_assert (control_name == NULL_TREE
1421                   && SSA_NAME_VAR (res) == SSA_NAME_VAR (control));
1422       control_name = res;
1423       remove_phi_node (&gsi, false);
1424     }
1425   gcc_assert (control_name != NULL_TREE);
1426
1427   /* Initialize the control variable to number of iterations
1428      according to the rhs of the exit condition.  */
1429   gsi = gsi_after_labels (ex_bb);
1430   cond_nit = last_stmt (exit->src);
1431   nit_1 =  gimple_cond_rhs (cond_nit);
1432   nit_1 = force_gimple_operand_gsi (&gsi,
1433                                   fold_convert (TREE_TYPE (control_name), nit_1),
1434                                   false, NULL_TREE, false, GSI_SAME_STMT);
1435   stmt = gimple_build_assign (control_name, nit_1);
1436   gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
1437   SSA_NAME_DEF_STMT (control_name) = stmt;
1438 }
1439
1440 /* Create the parallel constructs for LOOP as described in gen_parallel_loop.
1441    LOOP_FN and DATA are the arguments of GIMPLE_OMP_PARALLEL.
1442    NEW_DATA is the variable that should be initialized from the argument
1443    of LOOP_FN.  N_THREADS is the requested number of threads.  Returns the
1444    basic block containing GIMPLE_OMP_PARALLEL tree.  */
1445
1446 static basic_block
1447 create_parallel_loop (struct loop *loop, tree loop_fn, tree data,
1448                       tree new_data, unsigned n_threads, location_t loc)
1449 {
1450   gimple_stmt_iterator gsi;
1451   basic_block bb, paral_bb, for_bb, ex_bb;
1452   tree t, param;
1453   gimple stmt, for_stmt, phi, cond_stmt;
1454   tree cvar, cvar_init, initvar, cvar_next, cvar_base, type;
1455   edge exit, nexit, guard, end, e;
1456
1457   /* Prepare the GIMPLE_OMP_PARALLEL statement.  */
1458   bb = loop_preheader_edge (loop)->src;
1459   paral_bb = single_pred (bb);
1460   gsi = gsi_last_bb (paral_bb);
1461
1462   t = build_omp_clause (loc, OMP_CLAUSE_NUM_THREADS);
1463   OMP_CLAUSE_NUM_THREADS_EXPR (t)
1464     = build_int_cst (integer_type_node, n_threads);
1465   stmt = gimple_build_omp_parallel (NULL, t, loop_fn, data);
1466   gimple_set_location (stmt, loc);
1467
1468   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1469
1470   /* Initialize NEW_DATA.  */
1471   if (data)
1472     {
1473       gsi = gsi_after_labels (bb);
1474
1475       param = make_ssa_name (DECL_ARGUMENTS (loop_fn), NULL);
1476       stmt = gimple_build_assign (param, build_fold_addr_expr (data));
1477       gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1478       SSA_NAME_DEF_STMT (param) = stmt;
1479
1480       stmt = gimple_build_assign (new_data,
1481                                   fold_convert (TREE_TYPE (new_data), param));
1482       gsi_insert_before (&gsi, stmt, GSI_SAME_STMT);
1483       SSA_NAME_DEF_STMT (new_data) = stmt;
1484     }
1485
1486   /* Emit GIMPLE_OMP_RETURN for GIMPLE_OMP_PARALLEL.  */
1487   bb = split_loop_exit_edge (single_dom_exit (loop));
1488   gsi = gsi_last_bb (bb);
1489   stmt = gimple_build_omp_return (false);
1490   gimple_set_location (stmt, loc);
1491   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1492
1493   /* Extract data for GIMPLE_OMP_FOR.  */
1494   gcc_assert (loop->header == single_dom_exit (loop)->src);
1495   cond_stmt = last_stmt (loop->header);
1496
1497   cvar = gimple_cond_lhs (cond_stmt);
1498   cvar_base = SSA_NAME_VAR (cvar);
1499   phi = SSA_NAME_DEF_STMT (cvar);
1500   cvar_init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1501   initvar = make_ssa_name (cvar_base, NULL);
1502   SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (phi, loop_preheader_edge (loop)),
1503            initvar);
1504   cvar_next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
1505
1506   gsi = gsi_last_nondebug_bb (loop->latch);
1507   gcc_assert (gsi_stmt (gsi) == SSA_NAME_DEF_STMT (cvar_next));
1508   gsi_remove (&gsi, true);
1509
1510   /* Prepare cfg.  */
1511   for_bb = split_edge (loop_preheader_edge (loop));
1512   ex_bb = split_loop_exit_edge (single_dom_exit (loop));
1513   extract_true_false_edges_from_block (loop->header, &nexit, &exit);
1514   gcc_assert (exit == single_dom_exit (loop));
1515
1516   guard = make_edge (for_bb, ex_bb, 0);
1517   single_succ_edge (loop->latch)->flags = 0;
1518   end = make_edge (loop->latch, ex_bb, EDGE_FALLTHRU);
1519   for (gsi = gsi_start_phis (ex_bb); !gsi_end_p (gsi); gsi_next (&gsi))
1520     {
1521       source_location locus;
1522       tree def;
1523       phi = gsi_stmt (gsi);
1524       stmt = SSA_NAME_DEF_STMT (PHI_ARG_DEF_FROM_EDGE (phi, exit));
1525
1526       def = PHI_ARG_DEF_FROM_EDGE (stmt, loop_preheader_edge (loop));
1527       locus = gimple_phi_arg_location_from_edge (stmt,
1528                                                  loop_preheader_edge (loop));
1529       add_phi_arg (phi, def, guard, locus);
1530
1531       def = PHI_ARG_DEF_FROM_EDGE (stmt, loop_latch_edge (loop));
1532       locus = gimple_phi_arg_location_from_edge (stmt, loop_latch_edge (loop));
1533       add_phi_arg (phi, def, end, locus);
1534     }
1535   e = redirect_edge_and_branch (exit, nexit->dest);
1536   PENDING_STMT (e) = NULL;
1537
1538   /* Emit GIMPLE_OMP_FOR.  */
1539   gimple_cond_set_lhs (cond_stmt, cvar_base);
1540   type = TREE_TYPE (cvar);
1541   t = build_omp_clause (loc, OMP_CLAUSE_SCHEDULE);
1542   OMP_CLAUSE_SCHEDULE_KIND (t) = OMP_CLAUSE_SCHEDULE_STATIC;
1543
1544   for_stmt = gimple_build_omp_for (NULL, t, 1, NULL);
1545   gimple_set_location (for_stmt, loc);
1546   gimple_omp_for_set_index (for_stmt, 0, initvar);
1547   gimple_omp_for_set_initial (for_stmt, 0, cvar_init);
1548   gimple_omp_for_set_final (for_stmt, 0, gimple_cond_rhs (cond_stmt));
1549   gimple_omp_for_set_cond (for_stmt, 0, gimple_cond_code (cond_stmt));
1550   gimple_omp_for_set_incr (for_stmt, 0, build2 (PLUS_EXPR, type,
1551                                                 cvar_base,
1552                                                 build_int_cst (type, 1)));
1553
1554   gsi = gsi_last_bb (for_bb);
1555   gsi_insert_after (&gsi, for_stmt, GSI_NEW_STMT);
1556   SSA_NAME_DEF_STMT (initvar) = for_stmt;
1557
1558   /* Emit GIMPLE_OMP_CONTINUE.  */
1559   gsi = gsi_last_bb (loop->latch);
1560   stmt = gimple_build_omp_continue (cvar_next, cvar);
1561   gimple_set_location (stmt, loc);
1562   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1563   SSA_NAME_DEF_STMT (cvar_next) = stmt;
1564
1565   /* Emit GIMPLE_OMP_RETURN for GIMPLE_OMP_FOR.  */
1566   gsi = gsi_last_bb (ex_bb);
1567   stmt = gimple_build_omp_return (true);
1568   gimple_set_location (stmt, loc);
1569   gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1570
1571   return paral_bb;
1572 }
1573
1574 /* Generates code to execute the iterations of LOOP in N_THREADS
1575    threads in parallel.
1576
1577    NITER describes number of iterations of LOOP.
1578    REDUCTION_LIST describes the reductions existent in the LOOP.  */
1579
1580 static void
1581 gen_parallel_loop (struct loop *loop, htab_t reduction_list,
1582                    unsigned n_threads, struct tree_niter_desc *niter)
1583 {
1584   loop_iterator li;
1585   tree many_iterations_cond, type, nit;
1586   tree arg_struct, new_arg_struct;
1587   gimple_seq stmts;
1588   basic_block parallel_head;
1589   edge entry, exit;
1590   struct clsn_data clsn_data;
1591   unsigned prob;
1592   location_t loc;
1593   gimple cond_stmt;
1594
1595   /* From
1596
1597      ---------------------------------------------------------------------
1598      loop
1599        {
1600          IV = phi (INIT, IV + STEP)
1601          BODY1;
1602          if (COND)
1603            break;
1604          BODY2;
1605        }
1606      ---------------------------------------------------------------------
1607
1608      with # of iterations NITER (possibly with MAY_BE_ZERO assumption),
1609      we generate the following code:
1610
1611      ---------------------------------------------------------------------
1612
1613      if (MAY_BE_ZERO
1614      || NITER < MIN_PER_THREAD * N_THREADS)
1615      goto original;
1616
1617      BODY1;
1618      store all local loop-invariant variables used in body of the loop to DATA.
1619      GIMPLE_OMP_PARALLEL (OMP_CLAUSE_NUM_THREADS (N_THREADS), LOOPFN, DATA);
1620      load the variables from DATA.
1621      GIMPLE_OMP_FOR (IV = INIT; COND; IV += STEP) (OMP_CLAUSE_SCHEDULE (static))
1622      BODY2;
1623      BODY1;
1624      GIMPLE_OMP_CONTINUE;
1625      GIMPLE_OMP_RETURN         -- GIMPLE_OMP_FOR
1626      GIMPLE_OMP_RETURN         -- GIMPLE_OMP_PARALLEL
1627      goto end;
1628
1629      original:
1630      loop
1631        {
1632          IV = phi (INIT, IV + STEP)
1633          BODY1;
1634          if (COND)
1635            break;
1636          BODY2;
1637        }
1638
1639      end:
1640
1641    */
1642
1643   /* Create two versions of the loop -- in the old one, we know that the
1644      number of iterations is large enough, and we will transform it into the
1645      loop that will be split to loop_fn, the new one will be used for the
1646      remaining iterations.  */
1647
1648   type = TREE_TYPE (niter->niter);
1649   nit = force_gimple_operand (unshare_expr (niter->niter), &stmts, true,
1650                               NULL_TREE);
1651   if (stmts)
1652     gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1653
1654   many_iterations_cond =
1655     fold_build2 (GE_EXPR, boolean_type_node,
1656                  nit, build_int_cst (type, MIN_PER_THREAD * n_threads));
1657   many_iterations_cond
1658     = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1659                    invert_truthvalue (unshare_expr (niter->may_be_zero)),
1660                    many_iterations_cond);
1661   many_iterations_cond
1662     = force_gimple_operand (many_iterations_cond, &stmts, false, NULL_TREE);
1663   if (stmts)
1664     gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1665   if (!is_gimple_condexpr (many_iterations_cond))
1666     {
1667       many_iterations_cond
1668         = force_gimple_operand (many_iterations_cond, &stmts,
1669                                 true, NULL_TREE);
1670       if (stmts)
1671         gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1672     }
1673
1674   initialize_original_copy_tables ();
1675
1676   /* We assume that the loop usually iterates a lot.  */
1677   prob = 4 * REG_BR_PROB_BASE / 5;
1678   loop_version (loop, many_iterations_cond, NULL,
1679                 prob, prob, REG_BR_PROB_BASE - prob, true);
1680   update_ssa (TODO_update_ssa);
1681   free_original_copy_tables ();
1682
1683   /* Base all the induction variables in LOOP on a single control one.  */
1684   canonicalize_loop_ivs (loop, &nit, true);
1685
1686   /* Ensure that the exit condition is the first statement in the loop.  */
1687   transform_to_exit_first_loop (loop, reduction_list, nit);
1688
1689   /* Generate initializations for reductions.  */
1690   if (htab_elements (reduction_list) > 0)
1691     htab_traverse (reduction_list, initialize_reductions, loop);
1692
1693   /* Eliminate the references to local variables from the loop.  */
1694   gcc_assert (single_exit (loop));
1695   entry = loop_preheader_edge (loop);
1696   exit = single_dom_exit (loop);
1697
1698   eliminate_local_variables (entry, exit);
1699   /* In the old loop, move all variables non-local to the loop to a structure
1700      and back, and create separate decls for the variables used in loop.  */
1701   separate_decls_in_region (entry, exit, reduction_list, &arg_struct,
1702                             &new_arg_struct, &clsn_data);
1703
1704   /* Create the parallel constructs.  */
1705   loc = UNKNOWN_LOCATION;
1706   cond_stmt = last_stmt (loop->header);
1707   if (cond_stmt)
1708     loc = gimple_location (cond_stmt);
1709   parallel_head = create_parallel_loop (loop, create_loop_fn (loc), arg_struct,
1710                                         new_arg_struct, n_threads, loc);
1711   if (htab_elements (reduction_list) > 0)
1712     create_call_for_reduction (loop, reduction_list, &clsn_data);
1713
1714   scev_reset ();
1715
1716   /* Cancel the loop (it is simpler to do it here rather than to teach the
1717      expander to do it).  */
1718   cancel_loop_tree (loop);
1719
1720   /* Free loop bound estimations that could contain references to
1721      removed statements.  */
1722   FOR_EACH_LOOP (li, loop, 0)
1723     free_numbers_of_iterations_estimates_loop (loop);
1724
1725   /* Expand the parallel constructs.  We do it directly here instead of running
1726      a separate expand_omp pass, since it is more efficient, and less likely to
1727      cause troubles with further analyses not being able to deal with the
1728      OMP trees.  */
1729
1730   omp_expand_local (parallel_head);
1731 }
1732
1733 /* Returns true when LOOP contains vector phi nodes.  */
1734
1735 static bool
1736 loop_has_vector_phi_nodes (struct loop *loop ATTRIBUTE_UNUSED)
1737 {
1738   unsigned i;
1739   basic_block *bbs = get_loop_body_in_dom_order (loop);
1740   gimple_stmt_iterator gsi;
1741   bool res = true;
1742
1743   for (i = 0; i < loop->num_nodes; i++)
1744     for (gsi = gsi_start_phis (bbs[i]); !gsi_end_p (gsi); gsi_next (&gsi))
1745       if (TREE_CODE (TREE_TYPE (PHI_RESULT (gsi_stmt (gsi)))) == VECTOR_TYPE)
1746         goto end;
1747
1748   res = false;
1749  end:
1750   free (bbs);
1751   return res;
1752 }
1753
1754 /* Create a reduction_info struct, initialize it with REDUC_STMT
1755    and PHI, insert it to the REDUCTION_LIST.  */
1756
1757 static void
1758 build_new_reduction (htab_t reduction_list, gimple reduc_stmt, gimple phi)
1759 {
1760   PTR *slot;
1761   struct reduction_info *new_reduction;
1762
1763   gcc_assert (reduc_stmt);
1764
1765   if (dump_file && (dump_flags & TDF_DETAILS))
1766     {
1767       fprintf (dump_file,
1768                "Detected reduction. reduction stmt is: \n");
1769       print_gimple_stmt (dump_file, reduc_stmt, 0, 0);
1770       fprintf (dump_file, "\n");
1771     }
1772
1773   new_reduction = XCNEW (struct reduction_info);
1774
1775   new_reduction->reduc_stmt = reduc_stmt;
1776   new_reduction->reduc_phi = phi;
1777   new_reduction->reduction_code = gimple_assign_rhs_code (reduc_stmt);
1778   slot = htab_find_slot (reduction_list, new_reduction, INSERT);
1779   *slot = new_reduction;
1780 }
1781
1782 /* Detect all reductions in the LOOP, insert them into REDUCTION_LIST.  */
1783
1784 static void
1785 gather_scalar_reductions (loop_p loop, htab_t reduction_list)
1786 {
1787   gimple_stmt_iterator gsi;
1788   loop_vec_info simple_loop_info;
1789
1790   vect_dump = NULL;
1791   simple_loop_info = vect_analyze_loop_form (loop);
1792
1793   for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
1794     {
1795       gimple phi = gsi_stmt (gsi);
1796       affine_iv iv;
1797       tree res = PHI_RESULT (phi);
1798       bool double_reduc;
1799
1800       if (!is_gimple_reg (res))
1801         continue;
1802
1803       if (!simple_iv (loop, loop, res, &iv, true)
1804         && simple_loop_info)
1805         {
1806            gimple reduc_stmt = vect_force_simple_reduction (simple_loop_info,
1807                                                             phi, true,
1808                                                             &double_reduc);
1809            if (reduc_stmt && !double_reduc)
1810               build_new_reduction (reduction_list, reduc_stmt, phi);
1811         }
1812     }
1813     destroy_loop_vec_info (simple_loop_info, true);
1814 }
1815
1816 /* Try to initialize NITER for code generation part.  */
1817
1818 static bool
1819 try_get_loop_niter (loop_p loop, struct tree_niter_desc *niter)
1820 {
1821   edge exit = single_dom_exit (loop);
1822
1823   gcc_assert (exit);
1824
1825   /* We need to know # of iterations, and there should be no uses of values
1826      defined inside loop outside of it, unless the values are invariants of
1827      the loop.  */
1828   if (!number_of_iterations_exit (loop, exit, niter, false))
1829     {
1830       if (dump_file && (dump_flags & TDF_DETAILS))
1831         fprintf (dump_file, "  FAILED: number of iterations not known\n");
1832       return false;
1833     }
1834
1835   return true;
1836 }
1837
1838 /* Try to initialize REDUCTION_LIST for code generation part.
1839    REDUCTION_LIST describes the reductions.  */
1840
1841 static bool
1842 try_create_reduction_list (loop_p loop, htab_t reduction_list)
1843 {
1844   edge exit = single_dom_exit (loop);
1845   gimple_stmt_iterator gsi;
1846
1847   gcc_assert (exit);
1848
1849   gather_scalar_reductions (loop, reduction_list);
1850
1851
1852   for (gsi = gsi_start_phis (exit->dest); !gsi_end_p (gsi); gsi_next (&gsi))
1853     {
1854       gimple phi = gsi_stmt (gsi);
1855       struct reduction_info *red;
1856       imm_use_iterator imm_iter;
1857       use_operand_p use_p;
1858       gimple reduc_phi;
1859       tree val = PHI_ARG_DEF_FROM_EDGE (phi, exit);
1860
1861       if (is_gimple_reg (val))
1862         {
1863           if (dump_file && (dump_flags & TDF_DETAILS))
1864             {
1865               fprintf (dump_file, "phi is ");
1866               print_gimple_stmt (dump_file, phi, 0, 0);
1867               fprintf (dump_file, "arg of phi to exit:   value ");
1868               print_generic_expr (dump_file, val, 0);
1869               fprintf (dump_file, " used outside loop\n");
1870               fprintf (dump_file,
1871                        "  checking if it a part of reduction pattern:  \n");
1872             }
1873           if (htab_elements (reduction_list) == 0)
1874             {
1875               if (dump_file && (dump_flags & TDF_DETAILS))
1876                 fprintf (dump_file,
1877                          "  FAILED: it is not a part of reduction.\n");
1878               return false;
1879             }
1880           reduc_phi = NULL;
1881           FOR_EACH_IMM_USE_FAST (use_p, imm_iter, val)
1882             {
1883               if (!gimple_debug_bind_p (USE_STMT (use_p))
1884                   && flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
1885                 {
1886                   reduc_phi = USE_STMT (use_p);
1887                   break;
1888                 }
1889             }
1890           red = reduction_phi (reduction_list, reduc_phi);
1891           if (red == NULL)
1892             {
1893               if (dump_file && (dump_flags & TDF_DETAILS))
1894                 fprintf (dump_file,
1895                          "  FAILED: it is not a part of reduction.\n");
1896               return false;
1897             }
1898           if (dump_file && (dump_flags & TDF_DETAILS))
1899             {
1900               fprintf (dump_file, "reduction phi is  ");
1901               print_gimple_stmt (dump_file, red->reduc_phi, 0, 0);
1902               fprintf (dump_file, "reduction stmt is  ");
1903               print_gimple_stmt (dump_file, red->reduc_stmt, 0, 0);
1904             }
1905         }
1906     }
1907
1908   /* The iterations of the loop may communicate only through bivs whose
1909      iteration space can be distributed efficiently.  */
1910   for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
1911     {
1912       gimple phi = gsi_stmt (gsi);
1913       tree def = PHI_RESULT (phi);
1914       affine_iv iv;
1915
1916       if (is_gimple_reg (def) && !simple_iv (loop, loop, def, &iv, true))
1917         {
1918           struct reduction_info *red;
1919
1920           red = reduction_phi (reduction_list, phi);
1921           if (red == NULL)
1922             {
1923               if (dump_file && (dump_flags & TDF_DETAILS))
1924                 fprintf (dump_file,
1925                          "  FAILED: scalar dependency between iterations\n");
1926               return false;
1927             }
1928         }
1929     }
1930
1931
1932   return true;
1933 }
1934
1935 /* Detect parallel loops and generate parallel code using libgomp
1936    primitives.  Returns true if some loop was parallelized, false
1937    otherwise.  */
1938
1939 bool
1940 parallelize_loops (void)
1941 {
1942   unsigned n_threads = flag_tree_parallelize_loops;
1943   bool changed = false;
1944   struct loop *loop;
1945   struct tree_niter_desc niter_desc;
1946   loop_iterator li;
1947   htab_t reduction_list;
1948   struct obstack parloop_obstack;
1949   HOST_WIDE_INT estimated;
1950   LOC loop_loc;
1951
1952   /* Do not parallelize loops in the functions created by parallelization.  */
1953   if (parallelized_function_p (cfun->decl))
1954     return false;
1955   if (cfun->has_nonlocal_label)
1956     return false;
1957
1958   gcc_obstack_init (&parloop_obstack);
1959   reduction_list = htab_create (10, reduction_info_hash,
1960                                      reduction_info_eq, free);
1961   init_stmt_vec_info_vec ();
1962
1963   FOR_EACH_LOOP (li, loop, 0)
1964     {
1965       htab_empty (reduction_list);
1966       if (dump_file && (dump_flags & TDF_DETAILS))
1967       {
1968         fprintf (dump_file, "Trying loop %d as candidate\n",loop->num);
1969         if (loop->inner)
1970           fprintf (dump_file, "loop %d is not innermost\n",loop->num);
1971         else
1972           fprintf (dump_file, "loop %d is innermost\n",loop->num);
1973       }
1974
1975       /* If we use autopar in graphite pass, we use its marked dependency
1976       checking results.  */
1977       if (flag_loop_parallelize_all && !loop->can_be_parallel)
1978       {
1979         if (dump_file && (dump_flags & TDF_DETAILS))
1980            fprintf (dump_file, "loop is not parallel according to graphite\n");
1981         continue;
1982       }
1983
1984       if (!single_dom_exit (loop))
1985       {
1986
1987         if (dump_file && (dump_flags & TDF_DETAILS))
1988           fprintf (dump_file, "loop is !single_dom_exit\n");
1989
1990         continue;
1991       }
1992
1993       if (/* And of course, the loop must be parallelizable.  */
1994           !can_duplicate_loop_p (loop)
1995           || loop_has_blocks_with_irreducible_flag (loop)
1996           || (loop_preheader_edge (loop)->src->flags & BB_IRREDUCIBLE_LOOP)
1997           /* FIXME: the check for vector phi nodes could be removed.  */
1998           || loop_has_vector_phi_nodes (loop))
1999         continue;
2000       estimated = estimated_loop_iterations_int (loop, false);
2001       /* FIXME: Bypass this check as graphite doesn't update the
2002       count and frequency correctly now.  */
2003       if (!flag_loop_parallelize_all
2004           && ((estimated !=-1 
2005              && estimated <= (HOST_WIDE_INT) n_threads * MIN_PER_THREAD)
2006               /* Do not bother with loops in cold areas.  */
2007               || optimize_loop_nest_for_size_p (loop)))
2008         continue;
2009
2010       if (!try_get_loop_niter (loop, &niter_desc))
2011         continue;
2012
2013       if (!try_create_reduction_list (loop, reduction_list))
2014         continue;
2015
2016       if (!flag_loop_parallelize_all
2017           && !loop_parallel_p (loop, &parloop_obstack))
2018         continue;
2019
2020       changed = true;
2021       if (dump_file && (dump_flags & TDF_DETAILS))
2022       {
2023         if (loop->inner)
2024           fprintf (dump_file, "parallelizing outer loop %d\n",loop->header->index);
2025         else
2026           fprintf (dump_file, "parallelizing inner loop %d\n",loop->header->index);
2027         loop_loc = find_loop_location (loop);
2028         if (loop_loc != UNKNOWN_LOC)
2029           fprintf (dump_file, "\nloop at %s:%d: ",
2030                    LOC_FILE (loop_loc), LOC_LINE (loop_loc));
2031       }
2032       gen_parallel_loop (loop, reduction_list,
2033                          n_threads, &niter_desc);
2034       verify_flow_info ();
2035       verify_dominators (CDI_DOMINATORS);
2036       verify_loop_structure ();
2037       verify_loop_closed_ssa (true);
2038     }
2039
2040   free_stmt_vec_info_vec ();
2041   htab_delete (reduction_list);
2042   obstack_free (&parloop_obstack, NULL);
2043
2044   /* Parallelization will cause new function calls to be inserted through
2045      which local variables will escape.  Reset the points-to solution
2046      for ESCAPED.  */
2047   if (changed)
2048     pt_solution_reset (&cfun->gimple_df->escaped);
2049
2050   return changed;
2051 }
2052
2053 #include "gt-tree-parloops.h"