[NDS32] Have shirnk-wrapping optimization to be performed on nds32 target.
[official-gcc.git] / gcc / tree-parloops.c
blob5f7c1bc360ab9f71e8039434aa7cb3b10c627418
1 /* Loop autoparallelization.
2 Copyright (C) 2006-2015 Free Software Foundation, Inc.
3 Contributed by Sebastian Pop <pop@cri.ensmp.fr>
4 Zdenek Dvorak <dvorakz@suse.cz> and Razya Ladelsky <razya@il.ibm.com>.
6 This file is part of GCC.
8 GCC is free software; you can redistribute it and/or modify it under
9 the terms of the GNU General Public License as published by the Free
10 Software Foundation; either version 3, or (at your option) any later
11 version.
13 GCC is distributed in the hope that it will be useful, but WITHOUT ANY
14 WARRANTY; without even the implied warranty of MERCHANTABILITY or
15 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
16 for more details.
18 You should have received a copy of the GNU General Public License
19 along with GCC; see the file COPYING3. If not see
20 <http://www.gnu.org/licenses/>. */
22 #include "config.h"
23 #include "system.h"
24 #include "coretypes.h"
25 #include "hash-set.h"
26 #include "machmode.h"
27 #include "vec.h"
28 #include "double-int.h"
29 #include "input.h"
30 #include "alias.h"
31 #include "symtab.h"
32 #include "options.h"
33 #include "wide-int.h"
34 #include "inchash.h"
35 #include "tree.h"
36 #include "fold-const.h"
37 #include "predict.h"
38 #include "tm.h"
39 #include "hard-reg-set.h"
40 #include "input.h"
41 #include "function.h"
42 #include "dominance.h"
43 #include "cfg.h"
44 #include "basic-block.h"
45 #include "tree-ssa-alias.h"
46 #include "internal-fn.h"
47 #include "gimple-expr.h"
48 #include "is-a.h"
49 #include "gimple.h"
50 #include "gimplify.h"
51 #include "gimple-iterator.h"
52 #include "gimplify-me.h"
53 #include "gimple-walk.h"
54 #include "stor-layout.h"
55 #include "tree-nested.h"
56 #include "gimple-ssa.h"
57 #include "tree-cfg.h"
58 #include "tree-phinodes.h"
59 #include "ssa-iterators.h"
60 #include "stringpool.h"
61 #include "tree-ssanames.h"
62 #include "tree-ssa-loop-ivopts.h"
63 #include "tree-ssa-loop-manip.h"
64 #include "tree-ssa-loop-niter.h"
65 #include "tree-ssa-loop.h"
66 #include "tree-into-ssa.h"
67 #include "cfgloop.h"
68 #include "tree-data-ref.h"
69 #include "tree-scalar-evolution.h"
70 #include "gimple-pretty-print.h"
71 #include "tree-pass.h"
72 #include "langhooks.h"
73 #include "tree-vectorizer.h"
74 #include "tree-hasher.h"
75 #include "tree-parloops.h"
76 #include "omp-low.h"
77 #include "tree-nested.h"
79 /* This pass tries to distribute iterations of loops into several threads.
80 The implementation is straightforward -- for each loop we test whether its
81 iterations are independent, and if it is the case (and some additional
82 conditions regarding profitability and correctness are satisfied), we
83 add GIMPLE_OMP_PARALLEL and GIMPLE_OMP_FOR codes and let omp expansion
84 machinery do its job.
86 The most of the complexity is in bringing the code into shape expected
87 by the omp expanders:
88 -- for GIMPLE_OMP_FOR, ensuring that the loop has only one induction
89 variable and that the exit test is at the start of the loop body
90 -- for GIMPLE_OMP_PARALLEL, replacing the references to local addressable
91 variables by accesses through pointers, and breaking up ssa chains
92 by storing the values incoming to the parallelized loop to a structure
93 passed to the new function as an argument (something similar is done
94 in omp gimplification, unfortunately only a small part of the code
95 can be shared).
97 TODO:
98 -- if there are several parallelizable loops in a function, it may be
99 possible to generate the threads just once (using synchronization to
100 ensure that cross-loop dependences are obeyed).
101 -- handling of common reduction patterns for outer loops.
103 More info can also be found at http://gcc.gnu.org/wiki/AutoParInGCC */
105 Reduction handling:
106 currently we use vect_force_simple_reduction() to detect reduction patterns.
107 The code transformation will be introduced by an example.
110 parloop
112 int sum=1;
114 for (i = 0; i < N; i++)
116 x[i] = i + 3;
117 sum+=x[i];
121 gimple-like code:
122 header_bb:
124 # sum_29 = PHI <sum_11(5), 1(3)>
125 # i_28 = PHI <i_12(5), 0(3)>
126 D.1795_8 = i_28 + 3;
127 x[i_28] = D.1795_8;
128 sum_11 = D.1795_8 + sum_29;
129 i_12 = i_28 + 1;
130 if (N_6(D) > i_12)
131 goto header_bb;
134 exit_bb:
136 # sum_21 = PHI <sum_11(4)>
137 printf (&"%d"[0], sum_21);
140 after reduction transformation (only relevant parts):
142 parloop
145 ....
148 # Storing the initial value given by the user. #
150 .paral_data_store.32.sum.27 = 1;
152 #pragma omp parallel num_threads(4)
154 #pragma omp for schedule(static)
156 # The neutral element corresponding to the particular
157 reduction's operation, e.g. 0 for PLUS_EXPR,
158 1 for MULT_EXPR, etc. replaces the user's initial value. #
160 # sum.27_29 = PHI <sum.27_11, 0>
162 sum.27_11 = D.1827_8 + sum.27_29;
164 GIMPLE_OMP_CONTINUE
166 # Adding this reduction phi is done at create_phi_for_local_result() #
167 # sum.27_56 = PHI <sum.27_11, 0>
168 GIMPLE_OMP_RETURN
170 # Creating the atomic operation is done at
171 create_call_for_reduction_1() #
173 #pragma omp atomic_load
174 D.1839_59 = *&.paral_data_load.33_51->reduction.23;
175 D.1840_60 = sum.27_56 + D.1839_59;
176 #pragma omp atomic_store (D.1840_60);
178 GIMPLE_OMP_RETURN
180 # collecting the result after the join of the threads is done at
181 create_loads_for_reductions().
182 The value computed by the threads is loaded from the
183 shared struct. #
186 .paral_data_load.33_52 = &.paral_data_store.32;
187 sum_37 = .paral_data_load.33_52->sum.27;
188 sum_43 = D.1795_41 + sum_37;
190 exit bb:
191 # sum_21 = PHI <sum_43, sum_26>
192 printf (&"%d"[0], sum_21);
200 /* Minimal number of iterations of a loop that should be executed in each
201 thread. */
202 #define MIN_PER_THREAD 100
204 /* Element of the hashtable, representing a
205 reduction in the current loop. */
206 struct reduction_info
208 gimple reduc_stmt; /* reduction statement. */
209 gimple reduc_phi; /* The phi node defining the reduction. */
210 enum tree_code reduction_code;/* code for the reduction operation. */
211 unsigned reduc_version; /* SSA_NAME_VERSION of original reduc_phi
212 result. */
213 gphi *keep_res; /* The PHI_RESULT of this phi is the resulting value
214 of the reduction variable when existing the loop. */
215 tree initial_value; /* The initial value of the reduction var before entering the loop. */
216 tree field; /* the name of the field in the parloop data structure intended for reduction. */
217 tree init; /* reduction initialization value. */
218 gphi *new_phi; /* (helper field) Newly created phi node whose result
219 will be passed to the atomic operation. Represents
220 the local result each thread computed for the reduction
221 operation. */
224 /* Reduction info hashtable helpers. */
226 struct reduction_hasher : typed_free_remove <reduction_info>
228 typedef reduction_info value_type;
229 typedef reduction_info compare_type;
230 static inline hashval_t hash (const value_type *);
231 static inline bool equal (const value_type *, const compare_type *);
234 /* Equality and hash functions for hashtab code. */
236 inline bool
237 reduction_hasher::equal (const value_type *a, const compare_type *b)
239 return (a->reduc_phi == b->reduc_phi);
242 inline hashval_t
243 reduction_hasher::hash (const value_type *a)
245 return a->reduc_version;
248 typedef hash_table<reduction_hasher> reduction_info_table_type;
251 static struct reduction_info *
252 reduction_phi (reduction_info_table_type *reduction_list, gimple phi)
254 struct reduction_info tmpred, *red;
256 if (reduction_list->elements () == 0 || phi == NULL)
257 return NULL;
259 tmpred.reduc_phi = phi;
260 tmpred.reduc_version = gimple_uid (phi);
261 red = reduction_list->find (&tmpred);
263 return red;
266 /* Element of hashtable of names to copy. */
268 struct name_to_copy_elt
270 unsigned version; /* The version of the name to copy. */
271 tree new_name; /* The new name used in the copy. */
272 tree field; /* The field of the structure used to pass the
273 value. */
276 /* Name copies hashtable helpers. */
278 struct name_to_copy_hasher : typed_free_remove <name_to_copy_elt>
280 typedef name_to_copy_elt value_type;
281 typedef name_to_copy_elt compare_type;
282 static inline hashval_t hash (const value_type *);
283 static inline bool equal (const value_type *, const compare_type *);
286 /* Equality and hash functions for hashtab code. */
288 inline bool
289 name_to_copy_hasher::equal (const value_type *a, const compare_type *b)
291 return a->version == b->version;
294 inline hashval_t
295 name_to_copy_hasher::hash (const value_type *a)
297 return (hashval_t) a->version;
300 typedef hash_table<name_to_copy_hasher> name_to_copy_table_type;
302 /* A transformation matrix, which is a self-contained ROWSIZE x COLSIZE
303 matrix. Rather than use floats, we simply keep a single DENOMINATOR that
304 represents the denominator for every element in the matrix. */
305 typedef struct lambda_trans_matrix_s
307 lambda_matrix matrix;
308 int rowsize;
309 int colsize;
310 int denominator;
311 } *lambda_trans_matrix;
312 #define LTM_MATRIX(T) ((T)->matrix)
313 #define LTM_ROWSIZE(T) ((T)->rowsize)
314 #define LTM_COLSIZE(T) ((T)->colsize)
315 #define LTM_DENOMINATOR(T) ((T)->denominator)
317 /* Allocate a new transformation matrix. */
319 static lambda_trans_matrix
320 lambda_trans_matrix_new (int colsize, int rowsize,
321 struct obstack * lambda_obstack)
323 lambda_trans_matrix ret;
325 ret = (lambda_trans_matrix)
326 obstack_alloc (lambda_obstack, sizeof (struct lambda_trans_matrix_s));
327 LTM_MATRIX (ret) = lambda_matrix_new (rowsize, colsize, lambda_obstack);
328 LTM_ROWSIZE (ret) = rowsize;
329 LTM_COLSIZE (ret) = colsize;
330 LTM_DENOMINATOR (ret) = 1;
331 return ret;
334 /* Multiply a vector VEC by a matrix MAT.
335 MAT is an M*N matrix, and VEC is a vector with length N. The result
336 is stored in DEST which must be a vector of length M. */
338 static void
339 lambda_matrix_vector_mult (lambda_matrix matrix, int m, int n,
340 lambda_vector vec, lambda_vector dest)
342 int i, j;
344 lambda_vector_clear (dest, m);
345 for (i = 0; i < m; i++)
346 for (j = 0; j < n; j++)
347 dest[i] += matrix[i][j] * vec[j];
350 /* Return true if TRANS is a legal transformation matrix that respects
351 the dependence vectors in DISTS and DIRS. The conservative answer
352 is false.
354 "Wolfe proves that a unimodular transformation represented by the
355 matrix T is legal when applied to a loop nest with a set of
356 lexicographically non-negative distance vectors RDG if and only if
357 for each vector d in RDG, (T.d >= 0) is lexicographically positive.
358 i.e.: if and only if it transforms the lexicographically positive
359 distance vectors to lexicographically positive vectors. Note that
360 a unimodular matrix must transform the zero vector (and only it) to
361 the zero vector." S.Muchnick. */
363 static bool
364 lambda_transform_legal_p (lambda_trans_matrix trans,
365 int nb_loops,
366 vec<ddr_p> dependence_relations)
368 unsigned int i, j;
369 lambda_vector distres;
370 struct data_dependence_relation *ddr;
372 gcc_assert (LTM_COLSIZE (trans) == nb_loops
373 && LTM_ROWSIZE (trans) == nb_loops);
375 /* When there are no dependences, the transformation is correct. */
376 if (dependence_relations.length () == 0)
377 return true;
379 ddr = dependence_relations[0];
380 if (ddr == NULL)
381 return true;
383 /* When there is an unknown relation in the dependence_relations, we
384 know that it is no worth looking at this loop nest: give up. */
385 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
386 return false;
388 distres = lambda_vector_new (nb_loops);
390 /* For each distance vector in the dependence graph. */
391 FOR_EACH_VEC_ELT (dependence_relations, i, ddr)
393 /* Don't care about relations for which we know that there is no
394 dependence, nor about read-read (aka. output-dependences):
395 these data accesses can happen in any order. */
396 if (DDR_ARE_DEPENDENT (ddr) == chrec_known
397 || (DR_IS_READ (DDR_A (ddr)) && DR_IS_READ (DDR_B (ddr))))
398 continue;
400 /* Conservatively answer: "this transformation is not valid". */
401 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
402 return false;
404 /* If the dependence could not be captured by a distance vector,
405 conservatively answer that the transform is not valid. */
406 if (DDR_NUM_DIST_VECTS (ddr) == 0)
407 return false;
409 /* Compute trans.dist_vect */
410 for (j = 0; j < DDR_NUM_DIST_VECTS (ddr); j++)
412 lambda_matrix_vector_mult (LTM_MATRIX (trans), nb_loops, nb_loops,
413 DDR_DIST_VECT (ddr, j), distres);
415 if (!lambda_vector_lexico_pos (distres, nb_loops))
416 return false;
419 return true;
422 /* Data dependency analysis. Returns true if the iterations of LOOP
423 are independent on each other (that is, if we can execute them
424 in parallel). */
426 static bool
427 loop_parallel_p (struct loop *loop, struct obstack * parloop_obstack)
429 vec<ddr_p> dependence_relations;
430 vec<data_reference_p> datarefs;
431 lambda_trans_matrix trans;
432 bool ret = false;
434 if (dump_file && (dump_flags & TDF_DETAILS))
436 fprintf (dump_file, "Considering loop %d\n", loop->num);
437 if (!loop->inner)
438 fprintf (dump_file, "loop is innermost\n");
439 else
440 fprintf (dump_file, "loop NOT innermost\n");
443 /* Check for problems with dependences. If the loop can be reversed,
444 the iterations are independent. */
445 auto_vec<loop_p, 3> loop_nest;
446 datarefs.create (10);
447 dependence_relations.create (100);
448 if (! compute_data_dependences_for_loop (loop, true, &loop_nest, &datarefs,
449 &dependence_relations))
451 if (dump_file && (dump_flags & TDF_DETAILS))
452 fprintf (dump_file, " FAILED: cannot analyze data dependencies\n");
453 ret = false;
454 goto end;
456 if (dump_file && (dump_flags & TDF_DETAILS))
457 dump_data_dependence_relations (dump_file, dependence_relations);
459 trans = lambda_trans_matrix_new (1, 1, parloop_obstack);
460 LTM_MATRIX (trans)[0][0] = -1;
462 if (lambda_transform_legal_p (trans, 1, dependence_relations))
464 ret = true;
465 if (dump_file && (dump_flags & TDF_DETAILS))
466 fprintf (dump_file, " SUCCESS: may be parallelized\n");
468 else if (dump_file && (dump_flags & TDF_DETAILS))
469 fprintf (dump_file,
470 " FAILED: data dependencies exist across iterations\n");
472 end:
473 free_dependence_relations (dependence_relations);
474 free_data_refs (datarefs);
476 return ret;
479 /* Return true when LOOP contains basic blocks marked with the
480 BB_IRREDUCIBLE_LOOP flag. */
482 static inline bool
483 loop_has_blocks_with_irreducible_flag (struct loop *loop)
485 unsigned i;
486 basic_block *bbs = get_loop_body_in_dom_order (loop);
487 bool res = true;
489 for (i = 0; i < loop->num_nodes; i++)
490 if (bbs[i]->flags & BB_IRREDUCIBLE_LOOP)
491 goto end;
493 res = false;
494 end:
495 free (bbs);
496 return res;
499 /* Assigns the address of OBJ in TYPE to an ssa name, and returns this name.
500 The assignment statement is placed on edge ENTRY. DECL_ADDRESS maps decls
501 to their addresses that can be reused. The address of OBJ is known to
502 be invariant in the whole function. Other needed statements are placed
503 right before GSI. */
505 static tree
506 take_address_of (tree obj, tree type, edge entry,
507 int_tree_htab_type *decl_address, gimple_stmt_iterator *gsi)
509 int uid;
510 tree *var_p, name, addr;
511 gassign *stmt;
512 gimple_seq stmts;
514 /* Since the address of OBJ is invariant, the trees may be shared.
515 Avoid rewriting unrelated parts of the code. */
516 obj = unshare_expr (obj);
517 for (var_p = &obj;
518 handled_component_p (*var_p);
519 var_p = &TREE_OPERAND (*var_p, 0))
520 continue;
522 /* Canonicalize the access to base on a MEM_REF. */
523 if (DECL_P (*var_p))
524 *var_p = build_simple_mem_ref (build_fold_addr_expr (*var_p));
526 /* Assign a canonical SSA name to the address of the base decl used
527 in the address and share it for all accesses and addresses based
528 on it. */
529 uid = DECL_UID (TREE_OPERAND (TREE_OPERAND (*var_p, 0), 0));
530 int_tree_map elt;
531 elt.uid = uid;
532 int_tree_map *slot = decl_address->find_slot (elt, INSERT);
533 if (!slot->to)
535 if (gsi == NULL)
536 return NULL;
537 addr = TREE_OPERAND (*var_p, 0);
538 const char *obj_name
539 = get_name (TREE_OPERAND (TREE_OPERAND (*var_p, 0), 0));
540 if (obj_name)
541 name = make_temp_ssa_name (TREE_TYPE (addr), NULL, obj_name);
542 else
543 name = make_ssa_name (TREE_TYPE (addr));
544 stmt = gimple_build_assign (name, addr);
545 gsi_insert_on_edge_immediate (entry, stmt);
547 slot->uid = uid;
548 slot->to = name;
550 else
551 name = slot->to;
553 /* Express the address in terms of the canonical SSA name. */
554 TREE_OPERAND (*var_p, 0) = name;
555 if (gsi == NULL)
556 return build_fold_addr_expr_with_type (obj, type);
558 name = force_gimple_operand (build_addr (obj, current_function_decl),
559 &stmts, true, NULL_TREE);
560 if (!gimple_seq_empty_p (stmts))
561 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
563 if (!useless_type_conversion_p (type, TREE_TYPE (name)))
565 name = force_gimple_operand (fold_convert (type, name), &stmts, true,
566 NULL_TREE);
567 if (!gimple_seq_empty_p (stmts))
568 gsi_insert_seq_before (gsi, stmts, GSI_SAME_STMT);
571 return name;
574 /* Callback for htab_traverse. Create the initialization statement
575 for reduction described in SLOT, and place it at the preheader of
576 the loop described in DATA. */
579 initialize_reductions (reduction_info **slot, struct loop *loop)
581 tree init, c;
582 tree bvar, type, arg;
583 edge e;
585 struct reduction_info *const reduc = *slot;
587 /* Create initialization in preheader:
588 reduction_variable = initialization value of reduction. */
590 /* In the phi node at the header, replace the argument coming
591 from the preheader with the reduction initialization value. */
593 /* Create a new variable to initialize the reduction. */
594 type = TREE_TYPE (PHI_RESULT (reduc->reduc_phi));
595 bvar = create_tmp_var (type, "reduction");
597 c = build_omp_clause (gimple_location (reduc->reduc_stmt),
598 OMP_CLAUSE_REDUCTION);
599 OMP_CLAUSE_REDUCTION_CODE (c) = reduc->reduction_code;
600 OMP_CLAUSE_DECL (c) = SSA_NAME_VAR (gimple_assign_lhs (reduc->reduc_stmt));
602 init = omp_reduction_init (c, TREE_TYPE (bvar));
603 reduc->init = init;
605 /* Replace the argument representing the initialization value
606 with the initialization value for the reduction (neutral
607 element for the particular operation, e.g. 0 for PLUS_EXPR,
608 1 for MULT_EXPR, etc).
609 Keep the old value in a new variable "reduction_initial",
610 that will be taken in consideration after the parallel
611 computing is done. */
613 e = loop_preheader_edge (loop);
614 arg = PHI_ARG_DEF_FROM_EDGE (reduc->reduc_phi, e);
615 /* Create new variable to hold the initial value. */
617 SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE
618 (reduc->reduc_phi, loop_preheader_edge (loop)), init);
619 reduc->initial_value = arg;
620 return 1;
623 struct elv_data
625 struct walk_stmt_info info;
626 edge entry;
627 int_tree_htab_type *decl_address;
628 gimple_stmt_iterator *gsi;
629 bool changed;
630 bool reset;
633 /* Eliminates references to local variables in *TP out of the single
634 entry single exit region starting at DTA->ENTRY.
635 DECL_ADDRESS contains addresses of the references that had their
636 address taken already. If the expression is changed, CHANGED is
637 set to true. Callback for walk_tree. */
639 static tree
640 eliminate_local_variables_1 (tree *tp, int *walk_subtrees, void *data)
642 struct elv_data *const dta = (struct elv_data *) data;
643 tree t = *tp, var, addr, addr_type, type, obj;
645 if (DECL_P (t))
647 *walk_subtrees = 0;
649 if (!SSA_VAR_P (t) || DECL_EXTERNAL (t))
650 return NULL_TREE;
652 type = TREE_TYPE (t);
653 addr_type = build_pointer_type (type);
654 addr = take_address_of (t, addr_type, dta->entry, dta->decl_address,
655 dta->gsi);
656 if (dta->gsi == NULL && addr == NULL_TREE)
658 dta->reset = true;
659 return NULL_TREE;
662 *tp = build_simple_mem_ref (addr);
664 dta->changed = true;
665 return NULL_TREE;
668 if (TREE_CODE (t) == ADDR_EXPR)
670 /* ADDR_EXPR may appear in two contexts:
671 -- as a gimple operand, when the address taken is a function invariant
672 -- as gimple rhs, when the resulting address in not a function
673 invariant
674 We do not need to do anything special in the latter case (the base of
675 the memory reference whose address is taken may be replaced in the
676 DECL_P case). The former case is more complicated, as we need to
677 ensure that the new address is still a gimple operand. Thus, it
678 is not sufficient to replace just the base of the memory reference --
679 we need to move the whole computation of the address out of the
680 loop. */
681 if (!is_gimple_val (t))
682 return NULL_TREE;
684 *walk_subtrees = 0;
685 obj = TREE_OPERAND (t, 0);
686 var = get_base_address (obj);
687 if (!var || !SSA_VAR_P (var) || DECL_EXTERNAL (var))
688 return NULL_TREE;
690 addr_type = TREE_TYPE (t);
691 addr = take_address_of (obj, addr_type, dta->entry, dta->decl_address,
692 dta->gsi);
693 if (dta->gsi == NULL && addr == NULL_TREE)
695 dta->reset = true;
696 return NULL_TREE;
698 *tp = addr;
700 dta->changed = true;
701 return NULL_TREE;
704 if (!EXPR_P (t))
705 *walk_subtrees = 0;
707 return NULL_TREE;
710 /* Moves the references to local variables in STMT at *GSI out of the single
711 entry single exit region starting at ENTRY. DECL_ADDRESS contains
712 addresses of the references that had their address taken
713 already. */
715 static void
716 eliminate_local_variables_stmt (edge entry, gimple_stmt_iterator *gsi,
717 int_tree_htab_type *decl_address)
719 struct elv_data dta;
720 gimple stmt = gsi_stmt (*gsi);
722 memset (&dta.info, '\0', sizeof (dta.info));
723 dta.entry = entry;
724 dta.decl_address = decl_address;
725 dta.changed = false;
726 dta.reset = false;
728 if (gimple_debug_bind_p (stmt))
730 dta.gsi = NULL;
731 walk_tree (gimple_debug_bind_get_value_ptr (stmt),
732 eliminate_local_variables_1, &dta.info, NULL);
733 if (dta.reset)
735 gimple_debug_bind_reset_value (stmt);
736 dta.changed = true;
739 else if (gimple_clobber_p (stmt))
741 stmt = gimple_build_nop ();
742 gsi_replace (gsi, stmt, false);
743 dta.changed = true;
745 else
747 dta.gsi = gsi;
748 walk_gimple_op (stmt, eliminate_local_variables_1, &dta.info);
751 if (dta.changed)
752 update_stmt (stmt);
755 /* Eliminates the references to local variables from the single entry
756 single exit region between the ENTRY and EXIT edges.
758 This includes:
759 1) Taking address of a local variable -- these are moved out of the
760 region (and temporary variable is created to hold the address if
761 necessary).
763 2) Dereferencing a local variable -- these are replaced with indirect
764 references. */
766 static void
767 eliminate_local_variables (edge entry, edge exit)
769 basic_block bb;
770 auto_vec<basic_block, 3> body;
771 unsigned i;
772 gimple_stmt_iterator gsi;
773 bool has_debug_stmt = false;
774 int_tree_htab_type decl_address (10);
775 basic_block entry_bb = entry->src;
776 basic_block exit_bb = exit->dest;
778 gather_blocks_in_sese_region (entry_bb, exit_bb, &body);
780 FOR_EACH_VEC_ELT (body, i, bb)
781 if (bb != entry_bb && bb != exit_bb)
782 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
783 if (is_gimple_debug (gsi_stmt (gsi)))
785 if (gimple_debug_bind_p (gsi_stmt (gsi)))
786 has_debug_stmt = true;
788 else
789 eliminate_local_variables_stmt (entry, &gsi, &decl_address);
791 if (has_debug_stmt)
792 FOR_EACH_VEC_ELT (body, i, bb)
793 if (bb != entry_bb && bb != exit_bb)
794 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
795 if (gimple_debug_bind_p (gsi_stmt (gsi)))
796 eliminate_local_variables_stmt (entry, &gsi, &decl_address);
799 /* Returns true if expression EXPR is not defined between ENTRY and
800 EXIT, i.e. if all its operands are defined outside of the region. */
802 static bool
803 expr_invariant_in_region_p (edge entry, edge exit, tree expr)
805 basic_block entry_bb = entry->src;
806 basic_block exit_bb = exit->dest;
807 basic_block def_bb;
809 if (is_gimple_min_invariant (expr))
810 return true;
812 if (TREE_CODE (expr) == SSA_NAME)
814 def_bb = gimple_bb (SSA_NAME_DEF_STMT (expr));
815 if (def_bb
816 && dominated_by_p (CDI_DOMINATORS, def_bb, entry_bb)
817 && !dominated_by_p (CDI_DOMINATORS, def_bb, exit_bb))
818 return false;
820 return true;
823 return false;
826 /* If COPY_NAME_P is true, creates and returns a duplicate of NAME.
827 The copies are stored to NAME_COPIES, if NAME was already duplicated,
828 its duplicate stored in NAME_COPIES is returned.
830 Regardless of COPY_NAME_P, the decl used as a base of the ssa name is also
831 duplicated, storing the copies in DECL_COPIES. */
833 static tree
834 separate_decls_in_region_name (tree name, name_to_copy_table_type *name_copies,
835 int_tree_htab_type *decl_copies,
836 bool copy_name_p)
838 tree copy, var, var_copy;
839 unsigned idx, uid, nuid;
840 struct int_tree_map ielt;
841 struct name_to_copy_elt elt, *nelt;
842 name_to_copy_elt **slot;
843 int_tree_map *dslot;
845 if (TREE_CODE (name) != SSA_NAME)
846 return name;
848 idx = SSA_NAME_VERSION (name);
849 elt.version = idx;
850 slot = name_copies->find_slot_with_hash (&elt, idx,
851 copy_name_p ? INSERT : NO_INSERT);
852 if (slot && *slot)
853 return (*slot)->new_name;
855 if (copy_name_p)
857 copy = duplicate_ssa_name (name, NULL);
858 nelt = XNEW (struct name_to_copy_elt);
859 nelt->version = idx;
860 nelt->new_name = copy;
861 nelt->field = NULL_TREE;
862 *slot = nelt;
864 else
866 gcc_assert (!slot);
867 copy = name;
870 var = SSA_NAME_VAR (name);
871 if (!var)
872 return copy;
874 uid = DECL_UID (var);
875 ielt.uid = uid;
876 dslot = decl_copies->find_slot_with_hash (ielt, uid, INSERT);
877 if (!dslot->to)
879 var_copy = create_tmp_var (TREE_TYPE (var), get_name (var));
880 DECL_GIMPLE_REG_P (var_copy) = DECL_GIMPLE_REG_P (var);
881 dslot->uid = uid;
882 dslot->to = var_copy;
884 /* Ensure that when we meet this decl next time, we won't duplicate
885 it again. */
886 nuid = DECL_UID (var_copy);
887 ielt.uid = nuid;
888 dslot = decl_copies->find_slot_with_hash (ielt, nuid, INSERT);
889 gcc_assert (!dslot->to);
890 dslot->uid = nuid;
891 dslot->to = var_copy;
893 else
894 var_copy = dslot->to;
896 replace_ssa_name_symbol (copy, var_copy);
897 return copy;
900 /* Finds the ssa names used in STMT that are defined outside the
901 region between ENTRY and EXIT and replaces such ssa names with
902 their duplicates. The duplicates are stored to NAME_COPIES. Base
903 decls of all ssa names used in STMT (including those defined in
904 LOOP) are replaced with the new temporary variables; the
905 replacement decls are stored in DECL_COPIES. */
907 static void
908 separate_decls_in_region_stmt (edge entry, edge exit, gimple stmt,
909 name_to_copy_table_type *name_copies,
910 int_tree_htab_type *decl_copies)
912 use_operand_p use;
913 def_operand_p def;
914 ssa_op_iter oi;
915 tree name, copy;
916 bool copy_name_p;
918 FOR_EACH_PHI_OR_STMT_DEF (def, stmt, oi, SSA_OP_DEF)
920 name = DEF_FROM_PTR (def);
921 gcc_assert (TREE_CODE (name) == SSA_NAME);
922 copy = separate_decls_in_region_name (name, name_copies, decl_copies,
923 false);
924 gcc_assert (copy == name);
927 FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE)
929 name = USE_FROM_PTR (use);
930 if (TREE_CODE (name) != SSA_NAME)
931 continue;
933 copy_name_p = expr_invariant_in_region_p (entry, exit, name);
934 copy = separate_decls_in_region_name (name, name_copies, decl_copies,
935 copy_name_p);
936 SET_USE (use, copy);
940 /* Finds the ssa names used in STMT that are defined outside the
941 region between ENTRY and EXIT and replaces such ssa names with
942 their duplicates. The duplicates are stored to NAME_COPIES. Base
943 decls of all ssa names used in STMT (including those defined in
944 LOOP) are replaced with the new temporary variables; the
945 replacement decls are stored in DECL_COPIES. */
947 static bool
948 separate_decls_in_region_debug (gimple stmt,
949 name_to_copy_table_type *name_copies,
950 int_tree_htab_type *decl_copies)
952 use_operand_p use;
953 ssa_op_iter oi;
954 tree var, name;
955 struct int_tree_map ielt;
956 struct name_to_copy_elt elt;
957 name_to_copy_elt **slot;
958 int_tree_map *dslot;
960 if (gimple_debug_bind_p (stmt))
961 var = gimple_debug_bind_get_var (stmt);
962 else if (gimple_debug_source_bind_p (stmt))
963 var = gimple_debug_source_bind_get_var (stmt);
964 else
965 return true;
966 if (TREE_CODE (var) == DEBUG_EXPR_DECL || TREE_CODE (var) == LABEL_DECL)
967 return true;
968 gcc_assert (DECL_P (var) && SSA_VAR_P (var));
969 ielt.uid = DECL_UID (var);
970 dslot = decl_copies->find_slot_with_hash (ielt, ielt.uid, NO_INSERT);
971 if (!dslot)
972 return true;
973 if (gimple_debug_bind_p (stmt))
974 gimple_debug_bind_set_var (stmt, dslot->to);
975 else if (gimple_debug_source_bind_p (stmt))
976 gimple_debug_source_bind_set_var (stmt, dslot->to);
978 FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE)
980 name = USE_FROM_PTR (use);
981 if (TREE_CODE (name) != SSA_NAME)
982 continue;
984 elt.version = SSA_NAME_VERSION (name);
985 slot = name_copies->find_slot_with_hash (&elt, elt.version, NO_INSERT);
986 if (!slot)
988 gimple_debug_bind_reset_value (stmt);
989 update_stmt (stmt);
990 break;
993 SET_USE (use, (*slot)->new_name);
996 return false;
999 /* Callback for htab_traverse. Adds a field corresponding to the reduction
1000 specified in SLOT. The type is passed in DATA. */
1003 add_field_for_reduction (reduction_info **slot, tree type)
1006 struct reduction_info *const red = *slot;
1007 tree var = gimple_assign_lhs (red->reduc_stmt);
1008 tree field = build_decl (gimple_location (red->reduc_stmt), FIELD_DECL,
1009 SSA_NAME_IDENTIFIER (var), TREE_TYPE (var));
1011 insert_field_into_struct (type, field);
1013 red->field = field;
1015 return 1;
1018 /* Callback for htab_traverse. Adds a field corresponding to a ssa name
1019 described in SLOT. The type is passed in DATA. */
1022 add_field_for_name (name_to_copy_elt **slot, tree type)
1024 struct name_to_copy_elt *const elt = *slot;
1025 tree name = ssa_name (elt->version);
1026 tree field = build_decl (UNKNOWN_LOCATION,
1027 FIELD_DECL, SSA_NAME_IDENTIFIER (name),
1028 TREE_TYPE (name));
1030 insert_field_into_struct (type, field);
1031 elt->field = field;
1033 return 1;
1036 /* Callback for htab_traverse. A local result is the intermediate result
1037 computed by a single
1038 thread, or the initial value in case no iteration was executed.
1039 This function creates a phi node reflecting these values.
1040 The phi's result will be stored in NEW_PHI field of the
1041 reduction's data structure. */
1044 create_phi_for_local_result (reduction_info **slot, struct loop *loop)
1046 struct reduction_info *const reduc = *slot;
1047 edge e;
1048 gphi *new_phi;
1049 basic_block store_bb;
1050 tree local_res;
1051 source_location locus;
1053 /* STORE_BB is the block where the phi
1054 should be stored. It is the destination of the loop exit.
1055 (Find the fallthru edge from GIMPLE_OMP_CONTINUE). */
1056 store_bb = FALLTHRU_EDGE (loop->latch)->dest;
1058 /* STORE_BB has two predecessors. One coming from the loop
1059 (the reduction's result is computed at the loop),
1060 and another coming from a block preceding the loop,
1061 when no iterations
1062 are executed (the initial value should be taken). */
1063 if (EDGE_PRED (store_bb, 0) == FALLTHRU_EDGE (loop->latch))
1064 e = EDGE_PRED (store_bb, 1);
1065 else
1066 e = EDGE_PRED (store_bb, 0);
1067 local_res = copy_ssa_name (gimple_assign_lhs (reduc->reduc_stmt));
1068 locus = gimple_location (reduc->reduc_stmt);
1069 new_phi = create_phi_node (local_res, store_bb);
1070 add_phi_arg (new_phi, reduc->init, e, locus);
1071 add_phi_arg (new_phi, gimple_assign_lhs (reduc->reduc_stmt),
1072 FALLTHRU_EDGE (loop->latch), locus);
1073 reduc->new_phi = new_phi;
1075 return 1;
1078 struct clsn_data
1080 tree store;
1081 tree load;
1083 basic_block store_bb;
1084 basic_block load_bb;
1087 /* Callback for htab_traverse. Create an atomic instruction for the
1088 reduction described in SLOT.
1089 DATA annotates the place in memory the atomic operation relates to,
1090 and the basic block it needs to be generated in. */
1093 create_call_for_reduction_1 (reduction_info **slot, struct clsn_data *clsn_data)
1095 struct reduction_info *const reduc = *slot;
1096 gimple_stmt_iterator gsi;
1097 tree type = TREE_TYPE (PHI_RESULT (reduc->reduc_phi));
1098 tree load_struct;
1099 basic_block bb;
1100 basic_block new_bb;
1101 edge e;
1102 tree t, addr, ref, x;
1103 tree tmp_load, name;
1104 gimple load;
1106 load_struct = build_simple_mem_ref (clsn_data->load);
1107 t = build3 (COMPONENT_REF, type, load_struct, reduc->field, NULL_TREE);
1109 addr = build_addr (t, current_function_decl);
1111 /* Create phi node. */
1112 bb = clsn_data->load_bb;
1114 e = split_block (bb, t);
1115 new_bb = e->dest;
1117 tmp_load = create_tmp_var (TREE_TYPE (TREE_TYPE (addr)));
1118 tmp_load = make_ssa_name (tmp_load);
1119 load = gimple_build_omp_atomic_load (tmp_load, addr);
1120 SSA_NAME_DEF_STMT (tmp_load) = load;
1121 gsi = gsi_start_bb (new_bb);
1122 gsi_insert_after (&gsi, load, GSI_NEW_STMT);
1124 e = split_block (new_bb, load);
1125 new_bb = e->dest;
1126 gsi = gsi_start_bb (new_bb);
1127 ref = tmp_load;
1128 x = fold_build2 (reduc->reduction_code,
1129 TREE_TYPE (PHI_RESULT (reduc->new_phi)), ref,
1130 PHI_RESULT (reduc->new_phi));
1132 name = force_gimple_operand_gsi (&gsi, x, true, NULL_TREE, true,
1133 GSI_CONTINUE_LINKING);
1135 gsi_insert_after (&gsi, gimple_build_omp_atomic_store (name), GSI_NEW_STMT);
1136 return 1;
1139 /* Create the atomic operation at the join point of the threads.
1140 REDUCTION_LIST describes the reductions in the LOOP.
1141 LD_ST_DATA describes the shared data structure where
1142 shared data is stored in and loaded from. */
1143 static void
1144 create_call_for_reduction (struct loop *loop,
1145 reduction_info_table_type *reduction_list,
1146 struct clsn_data *ld_st_data)
1148 reduction_list->traverse <struct loop *, create_phi_for_local_result> (loop);
1149 /* Find the fallthru edge from GIMPLE_OMP_CONTINUE. */
1150 ld_st_data->load_bb = FALLTHRU_EDGE (loop->latch)->dest;
1151 reduction_list
1152 ->traverse <struct clsn_data *, create_call_for_reduction_1> (ld_st_data);
1155 /* Callback for htab_traverse. Loads the final reduction value at the
1156 join point of all threads, and inserts it in the right place. */
1159 create_loads_for_reductions (reduction_info **slot, struct clsn_data *clsn_data)
1161 struct reduction_info *const red = *slot;
1162 gimple stmt;
1163 gimple_stmt_iterator gsi;
1164 tree type = TREE_TYPE (gimple_assign_lhs (red->reduc_stmt));
1165 tree load_struct;
1166 tree name;
1167 tree x;
1169 gsi = gsi_after_labels (clsn_data->load_bb);
1170 load_struct = build_simple_mem_ref (clsn_data->load);
1171 load_struct = build3 (COMPONENT_REF, type, load_struct, red->field,
1172 NULL_TREE);
1174 x = load_struct;
1175 name = PHI_RESULT (red->keep_res);
1176 stmt = gimple_build_assign (name, x);
1178 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1180 for (gsi = gsi_start_phis (gimple_bb (red->keep_res));
1181 !gsi_end_p (gsi); gsi_next (&gsi))
1182 if (gsi_stmt (gsi) == red->keep_res)
1184 remove_phi_node (&gsi, false);
1185 return 1;
1187 gcc_unreachable ();
1190 /* Load the reduction result that was stored in LD_ST_DATA.
1191 REDUCTION_LIST describes the list of reductions that the
1192 loads should be generated for. */
1193 static void
1194 create_final_loads_for_reduction (reduction_info_table_type *reduction_list,
1195 struct clsn_data *ld_st_data)
1197 gimple_stmt_iterator gsi;
1198 tree t;
1199 gimple stmt;
1201 gsi = gsi_after_labels (ld_st_data->load_bb);
1202 t = build_fold_addr_expr (ld_st_data->store);
1203 stmt = gimple_build_assign (ld_st_data->load, t);
1205 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
1207 reduction_list
1208 ->traverse <struct clsn_data *, create_loads_for_reductions> (ld_st_data);
1212 /* Callback for htab_traverse. Store the neutral value for the
1213 particular reduction's operation, e.g. 0 for PLUS_EXPR,
1214 1 for MULT_EXPR, etc. into the reduction field.
1215 The reduction is specified in SLOT. The store information is
1216 passed in DATA. */
1219 create_stores_for_reduction (reduction_info **slot, struct clsn_data *clsn_data)
1221 struct reduction_info *const red = *slot;
1222 tree t;
1223 gimple stmt;
1224 gimple_stmt_iterator gsi;
1225 tree type = TREE_TYPE (gimple_assign_lhs (red->reduc_stmt));
1227 gsi = gsi_last_bb (clsn_data->store_bb);
1228 t = build3 (COMPONENT_REF, type, clsn_data->store, red->field, NULL_TREE);
1229 stmt = gimple_build_assign (t, red->initial_value);
1230 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1232 return 1;
1235 /* Callback for htab_traverse. Creates loads to a field of LOAD in LOAD_BB and
1236 store to a field of STORE in STORE_BB for the ssa name and its duplicate
1237 specified in SLOT. */
1240 create_loads_and_stores_for_name (name_to_copy_elt **slot,
1241 struct clsn_data *clsn_data)
1243 struct name_to_copy_elt *const elt = *slot;
1244 tree t;
1245 gimple stmt;
1246 gimple_stmt_iterator gsi;
1247 tree type = TREE_TYPE (elt->new_name);
1248 tree load_struct;
1250 gsi = gsi_last_bb (clsn_data->store_bb);
1251 t = build3 (COMPONENT_REF, type, clsn_data->store, elt->field, NULL_TREE);
1252 stmt = gimple_build_assign (t, ssa_name (elt->version));
1253 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1255 gsi = gsi_last_bb (clsn_data->load_bb);
1256 load_struct = build_simple_mem_ref (clsn_data->load);
1257 t = build3 (COMPONENT_REF, type, load_struct, elt->field, NULL_TREE);
1258 stmt = gimple_build_assign (elt->new_name, t);
1259 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1261 return 1;
1264 /* Moves all the variables used in LOOP and defined outside of it (including
1265 the initial values of loop phi nodes, and *PER_THREAD if it is a ssa
1266 name) to a structure created for this purpose. The code
1268 while (1)
1270 use (a);
1271 use (b);
1274 is transformed this way:
1276 bb0:
1277 old.a = a;
1278 old.b = b;
1280 bb1:
1281 a' = new->a;
1282 b' = new->b;
1283 while (1)
1285 use (a');
1286 use (b');
1289 `old' is stored to *ARG_STRUCT and `new' is stored to NEW_ARG_STRUCT. The
1290 pointer `new' is intentionally not initialized (the loop will be split to a
1291 separate function later, and `new' will be initialized from its arguments).
1292 LD_ST_DATA holds information about the shared data structure used to pass
1293 information among the threads. It is initialized here, and
1294 gen_parallel_loop will pass it to create_call_for_reduction that
1295 needs this information. REDUCTION_LIST describes the reductions
1296 in LOOP. */
1298 static void
1299 separate_decls_in_region (edge entry, edge exit,
1300 reduction_info_table_type *reduction_list,
1301 tree *arg_struct, tree *new_arg_struct,
1302 struct clsn_data *ld_st_data)
1305 basic_block bb1 = split_edge (entry);
1306 basic_block bb0 = single_pred (bb1);
1307 name_to_copy_table_type name_copies (10);
1308 int_tree_htab_type decl_copies (10);
1309 unsigned i;
1310 tree type, type_name, nvar;
1311 gimple_stmt_iterator gsi;
1312 struct clsn_data clsn_data;
1313 auto_vec<basic_block, 3> body;
1314 basic_block bb;
1315 basic_block entry_bb = bb1;
1316 basic_block exit_bb = exit->dest;
1317 bool has_debug_stmt = false;
1319 entry = single_succ_edge (entry_bb);
1320 gather_blocks_in_sese_region (entry_bb, exit_bb, &body);
1322 FOR_EACH_VEC_ELT (body, i, bb)
1324 if (bb != entry_bb && bb != exit_bb)
1326 for (gsi = gsi_start_phis (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1327 separate_decls_in_region_stmt (entry, exit, gsi_stmt (gsi),
1328 &name_copies, &decl_copies);
1330 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1332 gimple stmt = gsi_stmt (gsi);
1334 if (is_gimple_debug (stmt))
1335 has_debug_stmt = true;
1336 else
1337 separate_decls_in_region_stmt (entry, exit, stmt,
1338 &name_copies, &decl_copies);
1343 /* Now process debug bind stmts. We must not create decls while
1344 processing debug stmts, so we defer their processing so as to
1345 make sure we will have debug info for as many variables as
1346 possible (all of those that were dealt with in the loop above),
1347 and discard those for which we know there's nothing we can
1348 do. */
1349 if (has_debug_stmt)
1350 FOR_EACH_VEC_ELT (body, i, bb)
1351 if (bb != entry_bb && bb != exit_bb)
1353 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
1355 gimple stmt = gsi_stmt (gsi);
1357 if (is_gimple_debug (stmt))
1359 if (separate_decls_in_region_debug (stmt, &name_copies,
1360 &decl_copies))
1362 gsi_remove (&gsi, true);
1363 continue;
1367 gsi_next (&gsi);
1371 if (name_copies.elements () == 0 && reduction_list->elements () == 0)
1373 /* It may happen that there is nothing to copy (if there are only
1374 loop carried and external variables in the loop). */
1375 *arg_struct = NULL;
1376 *new_arg_struct = NULL;
1378 else
1380 /* Create the type for the structure to store the ssa names to. */
1381 type = lang_hooks.types.make_type (RECORD_TYPE);
1382 type_name = build_decl (UNKNOWN_LOCATION,
1383 TYPE_DECL, create_tmp_var_name (".paral_data"),
1384 type);
1385 TYPE_NAME (type) = type_name;
1387 name_copies.traverse <tree, add_field_for_name> (type);
1388 if (reduction_list && reduction_list->elements () > 0)
1390 /* Create the fields for reductions. */
1391 reduction_list->traverse <tree, add_field_for_reduction> (type);
1393 layout_type (type);
1395 /* Create the loads and stores. */
1396 *arg_struct = create_tmp_var (type, ".paral_data_store");
1397 nvar = create_tmp_var (build_pointer_type (type), ".paral_data_load");
1398 *new_arg_struct = make_ssa_name (nvar);
1400 ld_st_data->store = *arg_struct;
1401 ld_st_data->load = *new_arg_struct;
1402 ld_st_data->store_bb = bb0;
1403 ld_st_data->load_bb = bb1;
1405 name_copies
1406 .traverse <struct clsn_data *, create_loads_and_stores_for_name>
1407 (ld_st_data);
1409 /* Load the calculation from memory (after the join of the threads). */
1411 if (reduction_list && reduction_list->elements () > 0)
1413 reduction_list
1414 ->traverse <struct clsn_data *, create_stores_for_reduction>
1415 (ld_st_data);
1416 clsn_data.load = make_ssa_name (nvar);
1417 clsn_data.load_bb = exit->dest;
1418 clsn_data.store = ld_st_data->store;
1419 create_final_loads_for_reduction (reduction_list, &clsn_data);
1424 /* Bitmap containing uids of functions created by parallelization. We cannot
1425 allocate it from the default obstack, as it must live across compilation
1426 of several functions; we make it gc allocated instead. */
1428 static GTY(()) bitmap parallelized_functions;
1430 /* Returns true if FN was created by create_loop_fn. */
1432 bool
1433 parallelized_function_p (tree fn)
1435 if (!parallelized_functions || !DECL_ARTIFICIAL (fn))
1436 return false;
1438 return bitmap_bit_p (parallelized_functions, DECL_UID (fn));
1441 /* Creates and returns an empty function that will receive the body of
1442 a parallelized loop. */
1444 static tree
1445 create_loop_fn (location_t loc)
1447 char buf[100];
1448 char *tname;
1449 tree decl, type, name, t;
1450 struct function *act_cfun = cfun;
1451 static unsigned loopfn_num;
1453 loc = LOCATION_LOCUS (loc);
1454 snprintf (buf, 100, "%s.$loopfn", current_function_name ());
1455 ASM_FORMAT_PRIVATE_NAME (tname, buf, loopfn_num++);
1456 clean_symbol_name (tname);
1457 name = get_identifier (tname);
1458 type = build_function_type_list (void_type_node, ptr_type_node, NULL_TREE);
1460 decl = build_decl (loc, FUNCTION_DECL, name, type);
1461 if (!parallelized_functions)
1462 parallelized_functions = BITMAP_GGC_ALLOC ();
1463 bitmap_set_bit (parallelized_functions, DECL_UID (decl));
1465 TREE_STATIC (decl) = 1;
1466 TREE_USED (decl) = 1;
1467 DECL_ARTIFICIAL (decl) = 1;
1468 DECL_IGNORED_P (decl) = 0;
1469 TREE_PUBLIC (decl) = 0;
1470 DECL_UNINLINABLE (decl) = 1;
1471 DECL_EXTERNAL (decl) = 0;
1472 DECL_CONTEXT (decl) = NULL_TREE;
1473 DECL_INITIAL (decl) = make_node (BLOCK);
1475 t = build_decl (loc, RESULT_DECL, NULL_TREE, void_type_node);
1476 DECL_ARTIFICIAL (t) = 1;
1477 DECL_IGNORED_P (t) = 1;
1478 DECL_RESULT (decl) = t;
1480 t = build_decl (loc, PARM_DECL, get_identifier (".paral_data_param"),
1481 ptr_type_node);
1482 DECL_ARTIFICIAL (t) = 1;
1483 DECL_ARG_TYPE (t) = ptr_type_node;
1484 DECL_CONTEXT (t) = decl;
1485 TREE_USED (t) = 1;
1486 DECL_ARGUMENTS (decl) = t;
1488 allocate_struct_function (decl, false);
1490 /* The call to allocate_struct_function clobbers CFUN, so we need to restore
1491 it. */
1492 set_cfun (act_cfun);
1494 return decl;
1497 /* Moves the exit condition of LOOP to the beginning of its header, and
1498 duplicates the part of the last iteration that gets disabled to the
1499 exit of the loop. NIT is the number of iterations of the loop
1500 (used to initialize the variables in the duplicated part).
1502 TODO: the common case is that latch of the loop is empty and immediately
1503 follows the loop exit. In this case, it would be better not to copy the
1504 body of the loop, but only move the entry of the loop directly before the
1505 exit check and increase the number of iterations of the loop by one.
1506 This may need some additional preconditioning in case NIT = ~0.
1507 REDUCTION_LIST describes the reductions in LOOP. */
1509 static void
1510 transform_to_exit_first_loop (struct loop *loop,
1511 reduction_info_table_type *reduction_list,
1512 tree nit)
1514 basic_block *bbs, *nbbs, ex_bb, orig_header;
1515 unsigned n;
1516 bool ok;
1517 edge exit = single_dom_exit (loop), hpred;
1518 tree control, control_name, res, t;
1519 gphi *phi, *nphi;
1520 gassign *stmt;
1521 gcond *cond_stmt, *cond_nit;
1522 tree nit_1;
1524 split_block_after_labels (loop->header);
1525 orig_header = single_succ (loop->header);
1526 hpred = single_succ_edge (loop->header);
1528 cond_stmt = as_a <gcond *> (last_stmt (exit->src));
1529 control = gimple_cond_lhs (cond_stmt);
1530 gcc_assert (gimple_cond_rhs (cond_stmt) == nit);
1532 /* Make sure that we have phi nodes on exit for all loop header phis
1533 (create_parallel_loop requires that). */
1534 for (gphi_iterator gsi = gsi_start_phis (loop->header);
1535 !gsi_end_p (gsi);
1536 gsi_next (&gsi))
1538 phi = gsi.phi ();
1539 res = PHI_RESULT (phi);
1540 t = copy_ssa_name (res, phi);
1541 SET_PHI_RESULT (phi, t);
1542 nphi = create_phi_node (res, orig_header);
1543 add_phi_arg (nphi, t, hpred, UNKNOWN_LOCATION);
1545 if (res == control)
1547 gimple_cond_set_lhs (cond_stmt, t);
1548 update_stmt (cond_stmt);
1549 control = t;
1553 bbs = get_loop_body_in_dom_order (loop);
1555 for (n = 0; bbs[n] != exit->src; n++)
1556 continue;
1557 nbbs = XNEWVEC (basic_block, n);
1558 ok = gimple_duplicate_sese_tail (single_succ_edge (loop->header), exit,
1559 bbs + 1, n, nbbs);
1560 gcc_assert (ok);
1561 free (bbs);
1562 ex_bb = nbbs[0];
1563 free (nbbs);
1565 /* Other than reductions, the only gimple reg that should be copied
1566 out of the loop is the control variable. */
1567 exit = single_dom_exit (loop);
1568 control_name = NULL_TREE;
1569 for (gphi_iterator gsi = gsi_start_phis (ex_bb);
1570 !gsi_end_p (gsi); )
1572 phi = gsi.phi ();
1573 res = PHI_RESULT (phi);
1574 if (virtual_operand_p (res))
1576 gsi_next (&gsi);
1577 continue;
1580 /* Check if it is a part of reduction. If it is,
1581 keep the phi at the reduction's keep_res field. The
1582 PHI_RESULT of this phi is the resulting value of the reduction
1583 variable when exiting the loop. */
1585 if (reduction_list->elements () > 0)
1587 struct reduction_info *red;
1589 tree val = PHI_ARG_DEF_FROM_EDGE (phi, exit);
1590 red = reduction_phi (reduction_list, SSA_NAME_DEF_STMT (val));
1591 if (red)
1593 red->keep_res = phi;
1594 gsi_next (&gsi);
1595 continue;
1598 gcc_assert (control_name == NULL_TREE
1599 && SSA_NAME_VAR (res) == SSA_NAME_VAR (control));
1600 control_name = res;
1601 remove_phi_node (&gsi, false);
1603 gcc_assert (control_name != NULL_TREE);
1605 /* Initialize the control variable to number of iterations
1606 according to the rhs of the exit condition. */
1607 gimple_stmt_iterator gsi = gsi_after_labels (ex_bb);
1608 cond_nit = as_a <gcond *> (last_stmt (exit->src));
1609 nit_1 = gimple_cond_rhs (cond_nit);
1610 nit_1 = force_gimple_operand_gsi (&gsi,
1611 fold_convert (TREE_TYPE (control_name), nit_1),
1612 false, NULL_TREE, false, GSI_SAME_STMT);
1613 stmt = gimple_build_assign (control_name, nit_1);
1614 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
1617 /* Create the parallel constructs for LOOP as described in gen_parallel_loop.
1618 LOOP_FN and DATA are the arguments of GIMPLE_OMP_PARALLEL.
1619 NEW_DATA is the variable that should be initialized from the argument
1620 of LOOP_FN. N_THREADS is the requested number of threads. Returns the
1621 basic block containing GIMPLE_OMP_PARALLEL tree. */
1623 static basic_block
1624 create_parallel_loop (struct loop *loop, tree loop_fn, tree data,
1625 tree new_data, unsigned n_threads, location_t loc)
1627 gimple_stmt_iterator gsi;
1628 basic_block bb, paral_bb, for_bb, ex_bb;
1629 tree t, param;
1630 gomp_parallel *omp_par_stmt;
1631 gimple omp_return_stmt1, omp_return_stmt2;
1632 gimple phi;
1633 gcond *cond_stmt;
1634 gomp_for *for_stmt;
1635 gomp_continue *omp_cont_stmt;
1636 tree cvar, cvar_init, initvar, cvar_next, cvar_base, type;
1637 edge exit, nexit, guard, end, e;
1639 /* Prepare the GIMPLE_OMP_PARALLEL statement. */
1640 bb = loop_preheader_edge (loop)->src;
1641 paral_bb = single_pred (bb);
1642 gsi = gsi_last_bb (paral_bb);
1644 t = build_omp_clause (loc, OMP_CLAUSE_NUM_THREADS);
1645 OMP_CLAUSE_NUM_THREADS_EXPR (t)
1646 = build_int_cst (integer_type_node, n_threads);
1647 omp_par_stmt = gimple_build_omp_parallel (NULL, t, loop_fn, data);
1648 gimple_set_location (omp_par_stmt, loc);
1650 gsi_insert_after (&gsi, omp_par_stmt, GSI_NEW_STMT);
1652 /* Initialize NEW_DATA. */
1653 if (data)
1655 gassign *assign_stmt;
1657 gsi = gsi_after_labels (bb);
1659 param = make_ssa_name (DECL_ARGUMENTS (loop_fn));
1660 assign_stmt = gimple_build_assign (param, build_fold_addr_expr (data));
1661 gsi_insert_before (&gsi, assign_stmt, GSI_SAME_STMT);
1663 assign_stmt = gimple_build_assign (new_data,
1664 fold_convert (TREE_TYPE (new_data), param));
1665 gsi_insert_before (&gsi, assign_stmt, GSI_SAME_STMT);
1668 /* Emit GIMPLE_OMP_RETURN for GIMPLE_OMP_PARALLEL. */
1669 bb = split_loop_exit_edge (single_dom_exit (loop));
1670 gsi = gsi_last_bb (bb);
1671 omp_return_stmt1 = gimple_build_omp_return (false);
1672 gimple_set_location (omp_return_stmt1, loc);
1673 gsi_insert_after (&gsi, omp_return_stmt1, GSI_NEW_STMT);
1675 /* Extract data for GIMPLE_OMP_FOR. */
1676 gcc_assert (loop->header == single_dom_exit (loop)->src);
1677 cond_stmt = as_a <gcond *> (last_stmt (loop->header));
1679 cvar = gimple_cond_lhs (cond_stmt);
1680 cvar_base = SSA_NAME_VAR (cvar);
1681 phi = SSA_NAME_DEF_STMT (cvar);
1682 cvar_init = PHI_ARG_DEF_FROM_EDGE (phi, loop_preheader_edge (loop));
1683 initvar = copy_ssa_name (cvar);
1684 SET_USE (PHI_ARG_DEF_PTR_FROM_EDGE (phi, loop_preheader_edge (loop)),
1685 initvar);
1686 cvar_next = PHI_ARG_DEF_FROM_EDGE (phi, loop_latch_edge (loop));
1688 gsi = gsi_last_nondebug_bb (loop->latch);
1689 gcc_assert (gsi_stmt (gsi) == SSA_NAME_DEF_STMT (cvar_next));
1690 gsi_remove (&gsi, true);
1692 /* Prepare cfg. */
1693 for_bb = split_edge (loop_preheader_edge (loop));
1694 ex_bb = split_loop_exit_edge (single_dom_exit (loop));
1695 extract_true_false_edges_from_block (loop->header, &nexit, &exit);
1696 gcc_assert (exit == single_dom_exit (loop));
1698 guard = make_edge (for_bb, ex_bb, 0);
1699 single_succ_edge (loop->latch)->flags = 0;
1700 end = make_edge (loop->latch, ex_bb, EDGE_FALLTHRU);
1701 for (gphi_iterator gpi = gsi_start_phis (ex_bb);
1702 !gsi_end_p (gpi); gsi_next (&gpi))
1704 source_location locus;
1705 tree def;
1706 gphi *phi = gpi.phi ();
1707 gphi *stmt;
1709 stmt = as_a <gphi *> (
1710 SSA_NAME_DEF_STMT (PHI_ARG_DEF_FROM_EDGE (phi, exit)));
1712 def = PHI_ARG_DEF_FROM_EDGE (stmt, loop_preheader_edge (loop));
1713 locus = gimple_phi_arg_location_from_edge (stmt,
1714 loop_preheader_edge (loop));
1715 add_phi_arg (phi, def, guard, locus);
1717 def = PHI_ARG_DEF_FROM_EDGE (stmt, loop_latch_edge (loop));
1718 locus = gimple_phi_arg_location_from_edge (stmt, loop_latch_edge (loop));
1719 add_phi_arg (phi, def, end, locus);
1721 e = redirect_edge_and_branch (exit, nexit->dest);
1722 PENDING_STMT (e) = NULL;
1724 /* Emit GIMPLE_OMP_FOR. */
1725 gimple_cond_set_lhs (cond_stmt, cvar_base);
1726 type = TREE_TYPE (cvar);
1727 t = build_omp_clause (loc, OMP_CLAUSE_SCHEDULE);
1728 OMP_CLAUSE_SCHEDULE_KIND (t) = OMP_CLAUSE_SCHEDULE_STATIC;
1730 for_stmt = gimple_build_omp_for (NULL, GF_OMP_FOR_KIND_FOR, t, 1, NULL);
1731 gimple_set_location (for_stmt, loc);
1732 gimple_omp_for_set_index (for_stmt, 0, initvar);
1733 gimple_omp_for_set_initial (for_stmt, 0, cvar_init);
1734 gimple_omp_for_set_final (for_stmt, 0, gimple_cond_rhs (cond_stmt));
1735 gimple_omp_for_set_cond (for_stmt, 0, gimple_cond_code (cond_stmt));
1736 gimple_omp_for_set_incr (for_stmt, 0, build2 (PLUS_EXPR, type,
1737 cvar_base,
1738 build_int_cst (type, 1)));
1740 gsi = gsi_last_bb (for_bb);
1741 gsi_insert_after (&gsi, for_stmt, GSI_NEW_STMT);
1742 SSA_NAME_DEF_STMT (initvar) = for_stmt;
1744 /* Emit GIMPLE_OMP_CONTINUE. */
1745 gsi = gsi_last_bb (loop->latch);
1746 omp_cont_stmt = gimple_build_omp_continue (cvar_next, cvar);
1747 gimple_set_location (omp_cont_stmt, loc);
1748 gsi_insert_after (&gsi, omp_cont_stmt, GSI_NEW_STMT);
1749 SSA_NAME_DEF_STMT (cvar_next) = omp_cont_stmt;
1751 /* Emit GIMPLE_OMP_RETURN for GIMPLE_OMP_FOR. */
1752 gsi = gsi_last_bb (ex_bb);
1753 omp_return_stmt2 = gimple_build_omp_return (true);
1754 gimple_set_location (omp_return_stmt2, loc);
1755 gsi_insert_after (&gsi, omp_return_stmt2, GSI_NEW_STMT);
1757 /* After the above dom info is hosed. Re-compute it. */
1758 free_dominance_info (CDI_DOMINATORS);
1759 calculate_dominance_info (CDI_DOMINATORS);
1761 return paral_bb;
1764 /* Generates code to execute the iterations of LOOP in N_THREADS
1765 threads in parallel.
1767 NITER describes number of iterations of LOOP.
1768 REDUCTION_LIST describes the reductions existent in the LOOP. */
1770 static void
1771 gen_parallel_loop (struct loop *loop,
1772 reduction_info_table_type *reduction_list,
1773 unsigned n_threads, struct tree_niter_desc *niter)
1775 tree many_iterations_cond, type, nit;
1776 tree arg_struct, new_arg_struct;
1777 gimple_seq stmts;
1778 edge entry, exit;
1779 struct clsn_data clsn_data;
1780 unsigned prob;
1781 location_t loc;
1782 gimple cond_stmt;
1783 unsigned int m_p_thread=2;
1785 /* From
1787 ---------------------------------------------------------------------
1788 loop
1790 IV = phi (INIT, IV + STEP)
1791 BODY1;
1792 if (COND)
1793 break;
1794 BODY2;
1796 ---------------------------------------------------------------------
1798 with # of iterations NITER (possibly with MAY_BE_ZERO assumption),
1799 we generate the following code:
1801 ---------------------------------------------------------------------
1803 if (MAY_BE_ZERO
1804 || NITER < MIN_PER_THREAD * N_THREADS)
1805 goto original;
1807 BODY1;
1808 store all local loop-invariant variables used in body of the loop to DATA.
1809 GIMPLE_OMP_PARALLEL (OMP_CLAUSE_NUM_THREADS (N_THREADS), LOOPFN, DATA);
1810 load the variables from DATA.
1811 GIMPLE_OMP_FOR (IV = INIT; COND; IV += STEP) (OMP_CLAUSE_SCHEDULE (static))
1812 BODY2;
1813 BODY1;
1814 GIMPLE_OMP_CONTINUE;
1815 GIMPLE_OMP_RETURN -- GIMPLE_OMP_FOR
1816 GIMPLE_OMP_RETURN -- GIMPLE_OMP_PARALLEL
1817 goto end;
1819 original:
1820 loop
1822 IV = phi (INIT, IV + STEP)
1823 BODY1;
1824 if (COND)
1825 break;
1826 BODY2;
1829 end:
1833 /* Create two versions of the loop -- in the old one, we know that the
1834 number of iterations is large enough, and we will transform it into the
1835 loop that will be split to loop_fn, the new one will be used for the
1836 remaining iterations. */
1838 /* We should compute a better number-of-iterations value for outer loops.
1839 That is, if we have
1841 for (i = 0; i < n; ++i)
1842 for (j = 0; j < m; ++j)
1845 we should compute nit = n * m, not nit = n.
1846 Also may_be_zero handling would need to be adjusted. */
1848 type = TREE_TYPE (niter->niter);
1849 nit = force_gimple_operand (unshare_expr (niter->niter), &stmts, true,
1850 NULL_TREE);
1851 if (stmts)
1852 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1854 if (loop->inner)
1855 m_p_thread=2;
1856 else
1857 m_p_thread=MIN_PER_THREAD;
1859 many_iterations_cond =
1860 fold_build2 (GE_EXPR, boolean_type_node,
1861 nit, build_int_cst (type, m_p_thread * n_threads));
1863 many_iterations_cond
1864 = fold_build2 (TRUTH_AND_EXPR, boolean_type_node,
1865 invert_truthvalue (unshare_expr (niter->may_be_zero)),
1866 many_iterations_cond);
1867 many_iterations_cond
1868 = force_gimple_operand (many_iterations_cond, &stmts, false, NULL_TREE);
1869 if (stmts)
1870 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1871 if (!is_gimple_condexpr (many_iterations_cond))
1873 many_iterations_cond
1874 = force_gimple_operand (many_iterations_cond, &stmts,
1875 true, NULL_TREE);
1876 if (stmts)
1877 gsi_insert_seq_on_edge_immediate (loop_preheader_edge (loop), stmts);
1880 initialize_original_copy_tables ();
1882 /* We assume that the loop usually iterates a lot. */
1883 prob = 4 * REG_BR_PROB_BASE / 5;
1884 loop_version (loop, many_iterations_cond, NULL,
1885 prob, prob, REG_BR_PROB_BASE - prob, true);
1886 update_ssa (TODO_update_ssa);
1887 free_original_copy_tables ();
1889 /* Base all the induction variables in LOOP on a single control one. */
1890 canonicalize_loop_ivs (loop, &nit, true);
1892 /* Ensure that the exit condition is the first statement in the loop. */
1893 transform_to_exit_first_loop (loop, reduction_list, nit);
1895 /* Generate initializations for reductions. */
1896 if (reduction_list->elements () > 0)
1897 reduction_list->traverse <struct loop *, initialize_reductions> (loop);
1899 /* Eliminate the references to local variables from the loop. */
1900 gcc_assert (single_exit (loop));
1901 entry = loop_preheader_edge (loop);
1902 exit = single_dom_exit (loop);
1904 eliminate_local_variables (entry, exit);
1905 /* In the old loop, move all variables non-local to the loop to a structure
1906 and back, and create separate decls for the variables used in loop. */
1907 separate_decls_in_region (entry, exit, reduction_list, &arg_struct,
1908 &new_arg_struct, &clsn_data);
1910 /* Create the parallel constructs. */
1911 loc = UNKNOWN_LOCATION;
1912 cond_stmt = last_stmt (loop->header);
1913 if (cond_stmt)
1914 loc = gimple_location (cond_stmt);
1915 create_parallel_loop (loop, create_loop_fn (loc), arg_struct,
1916 new_arg_struct, n_threads, loc);
1917 if (reduction_list->elements () > 0)
1918 create_call_for_reduction (loop, reduction_list, &clsn_data);
1920 scev_reset ();
1922 /* Cancel the loop (it is simpler to do it here rather than to teach the
1923 expander to do it). */
1924 cancel_loop_tree (loop);
1926 /* Free loop bound estimations that could contain references to
1927 removed statements. */
1928 FOR_EACH_LOOP (loop, 0)
1929 free_numbers_of_iterations_estimates_loop (loop);
1932 /* Returns true when LOOP contains vector phi nodes. */
1934 static bool
1935 loop_has_vector_phi_nodes (struct loop *loop ATTRIBUTE_UNUSED)
1937 unsigned i;
1938 basic_block *bbs = get_loop_body_in_dom_order (loop);
1939 gphi_iterator gsi;
1940 bool res = true;
1942 for (i = 0; i < loop->num_nodes; i++)
1943 for (gsi = gsi_start_phis (bbs[i]); !gsi_end_p (gsi); gsi_next (&gsi))
1944 if (TREE_CODE (TREE_TYPE (PHI_RESULT (gsi.phi ()))) == VECTOR_TYPE)
1945 goto end;
1947 res = false;
1948 end:
1949 free (bbs);
1950 return res;
1953 /* Create a reduction_info struct, initialize it with REDUC_STMT
1954 and PHI, insert it to the REDUCTION_LIST. */
1956 static void
1957 build_new_reduction (reduction_info_table_type *reduction_list,
1958 gimple reduc_stmt, gphi *phi)
1960 reduction_info **slot;
1961 struct reduction_info *new_reduction;
1963 gcc_assert (reduc_stmt);
1965 if (dump_file && (dump_flags & TDF_DETAILS))
1967 fprintf (dump_file,
1968 "Detected reduction. reduction stmt is: \n");
1969 print_gimple_stmt (dump_file, reduc_stmt, 0, 0);
1970 fprintf (dump_file, "\n");
1973 new_reduction = XCNEW (struct reduction_info);
1975 new_reduction->reduc_stmt = reduc_stmt;
1976 new_reduction->reduc_phi = phi;
1977 new_reduction->reduc_version = SSA_NAME_VERSION (gimple_phi_result (phi));
1978 new_reduction->reduction_code = gimple_assign_rhs_code (reduc_stmt);
1979 slot = reduction_list->find_slot (new_reduction, INSERT);
1980 *slot = new_reduction;
1983 /* Callback for htab_traverse. Sets gimple_uid of reduc_phi stmts. */
1986 set_reduc_phi_uids (reduction_info **slot, void *data ATTRIBUTE_UNUSED)
1988 struct reduction_info *const red = *slot;
1989 gimple_set_uid (red->reduc_phi, red->reduc_version);
1990 return 1;
1993 /* Detect all reductions in the LOOP, insert them into REDUCTION_LIST. */
1995 static void
1996 gather_scalar_reductions (loop_p loop, reduction_info_table_type *reduction_list)
1998 gphi_iterator gsi;
1999 loop_vec_info simple_loop_info;
2001 simple_loop_info = vect_analyze_loop_form (loop);
2003 for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
2005 gphi *phi = gsi.phi ();
2006 affine_iv iv;
2007 tree res = PHI_RESULT (phi);
2008 bool double_reduc;
2010 if (virtual_operand_p (res))
2011 continue;
2013 if (!simple_iv (loop, loop, res, &iv, true)
2014 && simple_loop_info)
2016 gimple reduc_stmt = vect_force_simple_reduction (simple_loop_info,
2017 phi, true,
2018 &double_reduc);
2019 if (reduc_stmt && !double_reduc)
2020 build_new_reduction (reduction_list, reduc_stmt, phi);
2023 destroy_loop_vec_info (simple_loop_info, true);
2025 /* As gimple_uid is used by the vectorizer in between vect_analyze_loop_form
2026 and destroy_loop_vec_info, we can set gimple_uid of reduc_phi stmts
2027 only now. */
2028 reduction_list->traverse <void *, set_reduc_phi_uids> (NULL);
2031 /* Try to initialize NITER for code generation part. */
2033 static bool
2034 try_get_loop_niter (loop_p loop, struct tree_niter_desc *niter)
2036 edge exit = single_dom_exit (loop);
2038 gcc_assert (exit);
2040 /* We need to know # of iterations, and there should be no uses of values
2041 defined inside loop outside of it, unless the values are invariants of
2042 the loop. */
2043 if (!number_of_iterations_exit (loop, exit, niter, false))
2045 if (dump_file && (dump_flags & TDF_DETAILS))
2046 fprintf (dump_file, " FAILED: number of iterations not known\n");
2047 return false;
2050 return true;
2053 /* Try to initialize REDUCTION_LIST for code generation part.
2054 REDUCTION_LIST describes the reductions. */
2056 static bool
2057 try_create_reduction_list (loop_p loop,
2058 reduction_info_table_type *reduction_list)
2060 edge exit = single_dom_exit (loop);
2061 gphi_iterator gsi;
2063 gcc_assert (exit);
2065 gather_scalar_reductions (loop, reduction_list);
2068 for (gsi = gsi_start_phis (exit->dest); !gsi_end_p (gsi); gsi_next (&gsi))
2070 gphi *phi = gsi.phi ();
2071 struct reduction_info *red;
2072 imm_use_iterator imm_iter;
2073 use_operand_p use_p;
2074 gimple reduc_phi;
2075 tree val = PHI_ARG_DEF_FROM_EDGE (phi, exit);
2077 if (!virtual_operand_p (val))
2079 if (dump_file && (dump_flags & TDF_DETAILS))
2081 fprintf (dump_file, "phi is ");
2082 print_gimple_stmt (dump_file, phi, 0, 0);
2083 fprintf (dump_file, "arg of phi to exit: value ");
2084 print_generic_expr (dump_file, val, 0);
2085 fprintf (dump_file, " used outside loop\n");
2086 fprintf (dump_file,
2087 " checking if it a part of reduction pattern: \n");
2089 if (reduction_list->elements () == 0)
2091 if (dump_file && (dump_flags & TDF_DETAILS))
2092 fprintf (dump_file,
2093 " FAILED: it is not a part of reduction.\n");
2094 return false;
2096 reduc_phi = NULL;
2097 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, val)
2099 if (!gimple_debug_bind_p (USE_STMT (use_p))
2100 && flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
2102 reduc_phi = USE_STMT (use_p);
2103 break;
2106 red = reduction_phi (reduction_list, reduc_phi);
2107 if (red == NULL)
2109 if (dump_file && (dump_flags & TDF_DETAILS))
2110 fprintf (dump_file,
2111 " FAILED: it is not a part of reduction.\n");
2112 return false;
2114 if (dump_file && (dump_flags & TDF_DETAILS))
2116 fprintf (dump_file, "reduction phi is ");
2117 print_gimple_stmt (dump_file, red->reduc_phi, 0, 0);
2118 fprintf (dump_file, "reduction stmt is ");
2119 print_gimple_stmt (dump_file, red->reduc_stmt, 0, 0);
2124 /* The iterations of the loop may communicate only through bivs whose
2125 iteration space can be distributed efficiently. */
2126 for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
2128 gphi *phi = gsi.phi ();
2129 tree def = PHI_RESULT (phi);
2130 affine_iv iv;
2132 if (!virtual_operand_p (def) && !simple_iv (loop, loop, def, &iv, true))
2134 struct reduction_info *red;
2136 red = reduction_phi (reduction_list, phi);
2137 if (red == NULL)
2139 if (dump_file && (dump_flags & TDF_DETAILS))
2140 fprintf (dump_file,
2141 " FAILED: scalar dependency between iterations\n");
2142 return false;
2148 return true;
2151 /* Detect parallel loops and generate parallel code using libgomp
2152 primitives. Returns true if some loop was parallelized, false
2153 otherwise. */
2155 bool
2156 parallelize_loops (void)
2158 unsigned n_threads = flag_tree_parallelize_loops;
2159 bool changed = false;
2160 struct loop *loop;
2161 struct tree_niter_desc niter_desc;
2162 struct obstack parloop_obstack;
2163 HOST_WIDE_INT estimated;
2164 source_location loop_loc;
2166 /* Do not parallelize loops in the functions created by parallelization. */
2167 if (parallelized_function_p (cfun->decl))
2168 return false;
2169 if (cfun->has_nonlocal_label)
2170 return false;
2172 gcc_obstack_init (&parloop_obstack);
2173 reduction_info_table_type reduction_list (10);
2174 init_stmt_vec_info_vec ();
2176 FOR_EACH_LOOP (loop, 0)
2178 reduction_list.empty ();
2179 if (dump_file && (dump_flags & TDF_DETAILS))
2181 fprintf (dump_file, "Trying loop %d as candidate\n",loop->num);
2182 if (loop->inner)
2183 fprintf (dump_file, "loop %d is not innermost\n",loop->num);
2184 else
2185 fprintf (dump_file, "loop %d is innermost\n",loop->num);
2188 /* If we use autopar in graphite pass, we use its marked dependency
2189 checking results. */
2190 if (flag_loop_parallelize_all && !loop->can_be_parallel)
2192 if (dump_file && (dump_flags & TDF_DETAILS))
2193 fprintf (dump_file, "loop is not parallel according to graphite\n");
2194 continue;
2197 if (!single_dom_exit (loop))
2200 if (dump_file && (dump_flags & TDF_DETAILS))
2201 fprintf (dump_file, "loop is !single_dom_exit\n");
2203 continue;
2206 if (/* And of course, the loop must be parallelizable. */
2207 !can_duplicate_loop_p (loop)
2208 || loop_has_blocks_with_irreducible_flag (loop)
2209 || (loop_preheader_edge (loop)->src->flags & BB_IRREDUCIBLE_LOOP)
2210 /* FIXME: the check for vector phi nodes could be removed. */
2211 || loop_has_vector_phi_nodes (loop))
2212 continue;
2214 estimated = estimated_stmt_executions_int (loop);
2215 if (estimated == -1)
2216 estimated = max_stmt_executions_int (loop);
2217 /* FIXME: Bypass this check as graphite doesn't update the
2218 count and frequency correctly now. */
2219 if (!flag_loop_parallelize_all
2220 && ((estimated != -1
2221 && estimated <= (HOST_WIDE_INT) n_threads * MIN_PER_THREAD)
2222 /* Do not bother with loops in cold areas. */
2223 || optimize_loop_nest_for_size_p (loop)))
2224 continue;
2226 if (!try_get_loop_niter (loop, &niter_desc))
2227 continue;
2229 if (!try_create_reduction_list (loop, &reduction_list))
2230 continue;
2232 if (!flag_loop_parallelize_all
2233 && !loop_parallel_p (loop, &parloop_obstack))
2234 continue;
2236 changed = true;
2237 if (dump_file && (dump_flags & TDF_DETAILS))
2239 if (loop->inner)
2240 fprintf (dump_file, "parallelizing outer loop %d\n",loop->header->index);
2241 else
2242 fprintf (dump_file, "parallelizing inner loop %d\n",loop->header->index);
2243 loop_loc = find_loop_location (loop);
2244 if (loop_loc != UNKNOWN_LOCATION)
2245 fprintf (dump_file, "\nloop at %s:%d: ",
2246 LOCATION_FILE (loop_loc), LOCATION_LINE (loop_loc));
2248 gen_parallel_loop (loop, &reduction_list,
2249 n_threads, &niter_desc);
2252 free_stmt_vec_info_vec ();
2253 obstack_free (&parloop_obstack, NULL);
2255 /* Parallelization will cause new function calls to be inserted through
2256 which local variables will escape. Reset the points-to solution
2257 for ESCAPED. */
2258 if (changed)
2259 pt_solution_reset (&cfun->gimple_df->escaped);
2261 return changed;
2264 /* Parallelization. */
2266 namespace {
2268 const pass_data pass_data_parallelize_loops =
2270 GIMPLE_PASS, /* type */
2271 "parloops", /* name */
2272 OPTGROUP_LOOP, /* optinfo_flags */
2273 TV_TREE_PARALLELIZE_LOOPS, /* tv_id */
2274 ( PROP_cfg | PROP_ssa ), /* properties_required */
2275 0, /* properties_provided */
2276 0, /* properties_destroyed */
2277 0, /* todo_flags_start */
2278 0, /* todo_flags_finish */
2281 class pass_parallelize_loops : public gimple_opt_pass
2283 public:
2284 pass_parallelize_loops (gcc::context *ctxt)
2285 : gimple_opt_pass (pass_data_parallelize_loops, ctxt)
2288 /* opt_pass methods: */
2289 virtual bool gate (function *) { return flag_tree_parallelize_loops > 1; }
2290 virtual unsigned int execute (function *);
2292 }; // class pass_parallelize_loops
2294 unsigned
2295 pass_parallelize_loops::execute (function *fun)
2297 if (number_of_loops (fun) <= 1)
2298 return 0;
2300 if (parallelize_loops ())
2302 fun->curr_properties &= ~(PROP_gimple_eomp);
2303 return TODO_update_ssa;
2306 return 0;
2309 } // anon namespace
2311 gimple_opt_pass *
2312 make_pass_parallelize_loops (gcc::context *ctxt)
2314 return new pass_parallelize_loops (ctxt);
2318 #include "gt-tree-parloops.h"