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