]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/tree-parloops.c
genattrtab.c (write_header): Include hash-set.h...
[thirdparty/gcc.git] / gcc / tree-parloops.c
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>.
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 "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"
78
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.
85
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).
96
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.
102
103 More info can also be found at http://gcc.gnu.org/wiki/AutoParInGCC */
104 /*
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.
108
109
110 parloop
111 {
112 int sum=1;
113
114 for (i = 0; i < N; i++)
115 {
116 x[i] = i + 3;
117 sum+=x[i];
118 }
119 }
120
121 gimple-like code:
122 header_bb:
123
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;
132
133
134 exit_bb:
135
136 # sum_21 = PHI <sum_11(4)>
137 printf (&"%d"[0], sum_21);
138
139
140 after reduction transformation (only relevant parts):
141
142 parloop
143 {
144
145 ....
146
147
148 # Storing the initial value given by the user. #
149
150 .paral_data_store.32.sum.27 = 1;
151
152 #pragma omp parallel num_threads(4)
153
154 #pragma omp for schedule(static)
155
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. #
159
160 # sum.27_29 = PHI <sum.27_11, 0>
161
162 sum.27_11 = D.1827_8 + sum.27_29;
163
164 GIMPLE_OMP_CONTINUE
165
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
169
170 # Creating the atomic operation is done at
171 create_call_for_reduction_1() #
172
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);
177
178 GIMPLE_OMP_RETURN
179
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. #
184
185
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;
189
190 exit bb:
191 # sum_21 = PHI <sum_43, sum_26>
192 printf (&"%d"[0], sum_21);
193
194 ...
195
196 }
197
198 */
199
200 /* Minimal number of iterations of a loop that should be executed in each
201 thread. */
202 #define MIN_PER_THREAD 100
203
204 /* Element of the hashtable, representing a
205 reduction in the current loop. */
206 struct reduction_info
207 {
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. */
222 };
223
224 /* Reduction info hashtable helpers. */
225
226 struct reduction_hasher : typed_free_remove <reduction_info>
227 {
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 *);
232 };
233
234 /* Equality and hash functions for hashtab code. */
235
236 inline bool
237 reduction_hasher::equal (const value_type *a, const compare_type *b)
238 {
239 return (a->reduc_phi == b->reduc_phi);
240 }
241
242 inline hashval_t
243 reduction_hasher::hash (const value_type *a)
244 {
245 return a->reduc_version;
246 }
247
248 typedef hash_table<reduction_hasher> reduction_info_table_type;
249
250
251 static struct reduction_info *
252 reduction_phi (reduction_info_table_type *reduction_list, gimple phi)
253 {
254 struct reduction_info tmpred, *red;
255
256 if (reduction_list->elements () == 0 || phi == NULL)
257 return NULL;
258
259 tmpred.reduc_phi = phi;
260 tmpred.reduc_version = gimple_uid (phi);
261 red = reduction_list->find (&tmpred);
262
263 return red;
264 }
265
266 /* Element of hashtable of names to copy. */
267
268 struct name_to_copy_elt
269 {
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. */
274 };
275
276 /* Name copies hashtable helpers. */
277
278 struct name_to_copy_hasher : typed_free_remove <name_to_copy_elt>
279 {
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 *);
284 };
285
286 /* Equality and hash functions for hashtab code. */
287
288 inline bool
289 name_to_copy_hasher::equal (const value_type *a, const compare_type *b)
290 {
291 return a->version == b->version;
292 }
293
294 inline hashval_t
295 name_to_copy_hasher::hash (const value_type *a)
296 {
297 return (hashval_t) a->version;
298 }
299
300 typedef hash_table<name_to_copy_hasher> name_to_copy_table_type;
301
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
306 {
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)
316
317 /* Allocate a new transformation matrix. */
318
319 static lambda_trans_matrix
320 lambda_trans_matrix_new (int colsize, int rowsize,
321 struct obstack * lambda_obstack)
322 {
323 lambda_trans_matrix ret;
324
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;
332 }
333
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. */
337
338 static void
339 lambda_matrix_vector_mult (lambda_matrix matrix, int m, int n,
340 lambda_vector vec, lambda_vector dest)
341 {
342 int i, j;
343
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];
348 }
349
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.
353
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. */
362
363 static bool
364 lambda_transform_legal_p (lambda_trans_matrix trans,
365 int nb_loops,
366 vec<ddr_p> dependence_relations)
367 {
368 unsigned int i, j;
369 lambda_vector distres;
370 struct data_dependence_relation *ddr;
371
372 gcc_assert (LTM_COLSIZE (trans) == nb_loops
373 && LTM_ROWSIZE (trans) == nb_loops);
374
375 /* When there are no dependences, the transformation is correct. */
376 if (dependence_relations.length () == 0)
377 return true;
378
379 ddr = dependence_relations[0];
380 if (ddr == NULL)
381 return true;
382
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;
387
388 distres = lambda_vector_new (nb_loops);
389
390 /* For each distance vector in the dependence graph. */
391 FOR_EACH_VEC_ELT (dependence_relations, i, ddr)
392 {
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;
399
400 /* Conservatively answer: "this transformation is not valid". */
401 if (DDR_ARE_DEPENDENT (ddr) == chrec_dont_know)
402 return false;
403
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;
408
409 /* Compute trans.dist_vect */
410 for (j = 0; j < DDR_NUM_DIST_VECTS (ddr); j++)
411 {
412 lambda_matrix_vector_mult (LTM_MATRIX (trans), nb_loops, nb_loops,
413 DDR_DIST_VECT (ddr, j), distres);
414
415 if (!lambda_vector_lexico_pos (distres, nb_loops))
416 return false;
417 }
418 }
419 return true;
420 }
421
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). */
425
426 static bool
427 loop_parallel_p (struct loop *loop, struct obstack * parloop_obstack)
428 {
429 vec<ddr_p> dependence_relations;
430 vec<data_reference_p> datarefs;
431 lambda_trans_matrix trans;
432 bool ret = false;
433
434 if (dump_file && (dump_flags & TDF_DETAILS))
435 {
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");
441 }
442
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))
450 {
451 if (dump_file && (dump_flags & TDF_DETAILS))
452 fprintf (dump_file, " FAILED: cannot analyze data dependencies\n");
453 ret = false;
454 goto end;
455 }
456 if (dump_file && (dump_flags & TDF_DETAILS))
457 dump_data_dependence_relations (dump_file, dependence_relations);
458
459 trans = lambda_trans_matrix_new (1, 1, parloop_obstack);
460 LTM_MATRIX (trans)[0][0] = -1;
461
462 if (lambda_transform_legal_p (trans, 1, dependence_relations))
463 {
464 ret = true;
465 if (dump_file && (dump_flags & TDF_DETAILS))
466 fprintf (dump_file, " SUCCESS: may be parallelized\n");
467 }
468 else if (dump_file && (dump_flags & TDF_DETAILS))
469 fprintf (dump_file,
470 " FAILED: data dependencies exist across iterations\n");
471
472 end:
473 free_dependence_relations (dependence_relations);
474 free_data_refs (datarefs);
475
476 return ret;
477 }
478
479 /* Return true when LOOP contains basic blocks marked with the
480 BB_IRREDUCIBLE_LOOP flag. */
481
482 static inline bool
483 loop_has_blocks_with_irreducible_flag (struct loop *loop)
484 {
485 unsigned i;
486 basic_block *bbs = get_loop_body_in_dom_order (loop);
487 bool res = true;
488
489 for (i = 0; i < loop->num_nodes; i++)
490 if (bbs[i]->flags & BB_IRREDUCIBLE_LOOP)
491 goto end;
492
493 res = false;
494 end:
495 free (bbs);
496 return res;
497 }
498
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. */
504
505 static tree
506 take_address_of (tree obj, tree type, edge entry,
507 int_tree_htab_type *decl_address, gimple_stmt_iterator *gsi)
508 {
509 int uid;
510 tree *var_p, name, addr;
511 gassign *stmt;
512 gimple_seq stmts;
513
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;
521
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));
525
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)
534 {
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);
546
547 slot->uid = uid;
548 slot->to = name;
549 }
550 else
551 name = slot->to;
552
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);
557
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);
562
563 if (!useless_type_conversion_p (type, TREE_TYPE (name)))
564 {
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);
569 }
570
571 return name;
572 }
573
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. */
577
578 int
579 initialize_reductions (reduction_info **slot, struct loop *loop)
580 {
581 tree init, c;
582 tree bvar, type, arg;
583 edge e;
584
585 struct reduction_info *const reduc = *slot;
586
587 /* Create initialization in preheader:
588 reduction_variable = initialization value of reduction. */
589
590 /* In the phi node at the header, replace the argument coming
591 from the preheader with the reduction initialization value. */
592
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");
596
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));
601
602 init = omp_reduction_init (c, TREE_TYPE (bvar));
603 reduc->init = init;
604
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. */
612
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. */
616
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;
621 }
622
623 struct elv_data
624 {
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;
631 };
632
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. */
638
639 static tree
640 eliminate_local_variables_1 (tree *tp, int *walk_subtrees, void *data)
641 {
642 struct elv_data *const dta = (struct elv_data *) data;
643 tree t = *tp, var, addr, addr_type, type, obj;
644
645 if (DECL_P (t))
646 {
647 *walk_subtrees = 0;
648
649 if (!SSA_VAR_P (t) || DECL_EXTERNAL (t))
650 return NULL_TREE;
651
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)
657 {
658 dta->reset = true;
659 return NULL_TREE;
660 }
661
662 *tp = build_simple_mem_ref (addr);
663
664 dta->changed = true;
665 return NULL_TREE;
666 }
667
668 if (TREE_CODE (t) == ADDR_EXPR)
669 {
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;
683
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;
689
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)
694 {
695 dta->reset = true;
696 return NULL_TREE;
697 }
698 *tp = addr;
699
700 dta->changed = true;
701 return NULL_TREE;
702 }
703
704 if (!EXPR_P (t))
705 *walk_subtrees = 0;
706
707 return NULL_TREE;
708 }
709
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. */
714
715 static void
716 eliminate_local_variables_stmt (edge entry, gimple_stmt_iterator *gsi,
717 int_tree_htab_type *decl_address)
718 {
719 struct elv_data dta;
720 gimple stmt = gsi_stmt (*gsi);
721
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;
727
728 if (gimple_debug_bind_p (stmt))
729 {
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)
734 {
735 gimple_debug_bind_reset_value (stmt);
736 dta.changed = true;
737 }
738 }
739 else if (gimple_clobber_p (stmt))
740 {
741 stmt = gimple_build_nop ();
742 gsi_replace (gsi, stmt, false);
743 dta.changed = true;
744 }
745 else
746 {
747 dta.gsi = gsi;
748 walk_gimple_op (stmt, eliminate_local_variables_1, &dta.info);
749 }
750
751 if (dta.changed)
752 update_stmt (stmt);
753 }
754
755 /* Eliminates the references to local variables from the single entry
756 single exit region between the ENTRY and EXIT edges.
757
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).
762
763 2) Dereferencing a local variable -- these are replaced with indirect
764 references. */
765
766 static void
767 eliminate_local_variables (edge entry, edge exit)
768 {
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;
777
778 gather_blocks_in_sese_region (entry_bb, exit_bb, &body);
779
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)))
784 {
785 if (gimple_debug_bind_p (gsi_stmt (gsi)))
786 has_debug_stmt = true;
787 }
788 else
789 eliminate_local_variables_stmt (entry, &gsi, &decl_address);
790
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);
797 }
798
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. */
801
802 static bool
803 expr_invariant_in_region_p (edge entry, edge exit, tree expr)
804 {
805 basic_block entry_bb = entry->src;
806 basic_block exit_bb = exit->dest;
807 basic_block def_bb;
808
809 if (is_gimple_min_invariant (expr))
810 return true;
811
812 if (TREE_CODE (expr) == SSA_NAME)
813 {
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;
819
820 return true;
821 }
822
823 return false;
824 }
825
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.
829
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. */
832
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)
837 {
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;
844
845 if (TREE_CODE (name) != SSA_NAME)
846 return name;
847
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;
854
855 if (copy_name_p)
856 {
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;
863 }
864 else
865 {
866 gcc_assert (!slot);
867 copy = name;
868 }
869
870 var = SSA_NAME_VAR (name);
871 if (!var)
872 return copy;
873
874 uid = DECL_UID (var);
875 ielt.uid = uid;
876 dslot = decl_copies->find_slot_with_hash (ielt, uid, INSERT);
877 if (!dslot->to)
878 {
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;
883
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;
892 }
893 else
894 var_copy = dslot->to;
895
896 replace_ssa_name_symbol (copy, var_copy);
897 return copy;
898 }
899
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. */
906
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)
911 {
912 use_operand_p use;
913 def_operand_p def;
914 ssa_op_iter oi;
915 tree name, copy;
916 bool copy_name_p;
917
918 FOR_EACH_PHI_OR_STMT_DEF (def, stmt, oi, SSA_OP_DEF)
919 {
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);
925 }
926
927 FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE)
928 {
929 name = USE_FROM_PTR (use);
930 if (TREE_CODE (name) != SSA_NAME)
931 continue;
932
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);
937 }
938 }
939
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. */
946
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)
951 {
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;
959
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);
977
978 FOR_EACH_PHI_OR_STMT_USE (use, stmt, oi, SSA_OP_USE)
979 {
980 name = USE_FROM_PTR (use);
981 if (TREE_CODE (name) != SSA_NAME)
982 continue;
983
984 elt.version = SSA_NAME_VERSION (name);
985 slot = name_copies->find_slot_with_hash (&elt, elt.version, NO_INSERT);
986 if (!slot)
987 {
988 gimple_debug_bind_reset_value (stmt);
989 update_stmt (stmt);
990 break;
991 }
992
993 SET_USE (use, (*slot)->new_name);
994 }
995
996 return false;
997 }
998
999 /* Callback for htab_traverse. Adds a field corresponding to the reduction
1000 specified in SLOT. The type is passed in DATA. */
1001
1002 int
1003 add_field_for_reduction (reduction_info **slot, tree type)
1004 {
1005
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));
1010
1011 insert_field_into_struct (type, field);
1012
1013 red->field = field;
1014
1015 return 1;
1016 }
1017
1018 /* Callback for htab_traverse. Adds a field corresponding to a ssa name
1019 described in SLOT. The type is passed in DATA. */
1020
1021 int
1022 add_field_for_name (name_to_copy_elt **slot, tree type)
1023 {
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));
1029
1030 insert_field_into_struct (type, field);
1031 elt->field = field;
1032
1033 return 1;
1034 }
1035
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. */
1042
1043 int
1044 create_phi_for_local_result (reduction_info **slot, struct loop *loop)
1045 {
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;
1052
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;
1057
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;
1074
1075 return 1;
1076 }
1077
1078 struct clsn_data
1079 {
1080 tree store;
1081 tree load;
1082
1083 basic_block store_bb;
1084 basic_block load_bb;
1085 };
1086
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. */
1091
1092 int
1093 create_call_for_reduction_1 (reduction_info **slot, struct clsn_data *clsn_data)
1094 {
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;
1105
1106 load_struct = build_simple_mem_ref (clsn_data->load);
1107 t = build3 (COMPONENT_REF, type, load_struct, reduc->field, NULL_TREE);
1108
1109 addr = build_addr (t, current_function_decl);
1110
1111 /* Create phi node. */
1112 bb = clsn_data->load_bb;
1113
1114 e = split_block (bb, t);
1115 new_bb = e->dest;
1116
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);
1123
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));
1131
1132 name = force_gimple_operand_gsi (&gsi, x, true, NULL_TREE, true,
1133 GSI_CONTINUE_LINKING);
1134
1135 gsi_insert_after (&gsi, gimple_build_omp_atomic_store (name), GSI_NEW_STMT);
1136 return 1;
1137 }
1138
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)
1147 {
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);
1153 }
1154
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. */
1157
1158 int
1159 create_loads_for_reductions (reduction_info **slot, struct clsn_data *clsn_data)
1160 {
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;
1168
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);
1173
1174 x = load_struct;
1175 name = PHI_RESULT (red->keep_res);
1176 stmt = gimple_build_assign (name, x);
1177
1178 gsi_insert_after (&gsi, stmt, GSI_NEW_STMT);
1179
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)
1183 {
1184 remove_phi_node (&gsi, false);
1185 return 1;
1186 }
1187 gcc_unreachable ();
1188 }
1189
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)
1196 {
1197 gimple_stmt_iterator gsi;
1198 tree t;
1199 gimple stmt;
1200
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);
1204
1205 gsi_insert_before (&gsi, stmt, GSI_NEW_STMT);
1206
1207 reduction_list
1208 ->traverse <struct clsn_data *, create_loads_for_reductions> (ld_st_data);
1209
1210 }
1211
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. */
1217
1218 int
1219 create_stores_for_reduction (reduction_info **slot, struct clsn_data *clsn_data)
1220 {
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));
1226
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);
1231
1232 return 1;
1233 }
1234
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. */
1238
1239 int
1240 create_loads_and_stores_for_name (name_to_copy_elt **slot,
1241 struct clsn_data *clsn_data)
1242 {
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;
1249
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);
1254
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);
1260
1261 return 1;
1262 }
1263
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
1267
1268 while (1)
1269 {
1270 use (a);
1271 use (b);
1272 }
1273
1274 is transformed this way:
1275
1276 bb0:
1277 old.a = a;
1278 old.b = b;
1279
1280 bb1:
1281 a' = new->a;
1282 b' = new->b;
1283 while (1)
1284 {
1285 use (a');
1286 use (b');
1287 }
1288
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. */
1297
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)
1303
1304 {
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;
1318
1319 entry = single_succ_edge (entry_bb);
1320 gather_blocks_in_sese_region (entry_bb, exit_bb, &body);
1321
1322 FOR_EACH_VEC_ELT (body, i, bb)
1323 {
1324 if (bb != entry_bb && bb != exit_bb)
1325 {
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);
1329
1330 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi); gsi_next (&gsi))
1331 {
1332 gimple stmt = gsi_stmt (gsi);
1333
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);
1339 }
1340 }
1341 }
1342
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)
1352 {
1353 for (gsi = gsi_start_bb (bb); !gsi_end_p (gsi);)
1354 {
1355 gimple stmt = gsi_stmt (gsi);
1356
1357 if (is_gimple_debug (stmt))
1358 {
1359 if (separate_decls_in_region_debug (stmt, &name_copies,
1360 &decl_copies))
1361 {
1362 gsi_remove (&gsi, true);
1363 continue;
1364 }
1365 }
1366
1367 gsi_next (&gsi);
1368 }
1369 }
1370
1371 if (name_copies.elements () == 0 && reduction_list->elements () == 0)
1372 {
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;
1377 }
1378 else
1379 {
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;
1386
1387 name_copies.traverse <tree, add_field_for_name> (type);
1388 if (reduction_list && reduction_list->elements () > 0)
1389 {
1390 /* Create the fields for reductions. */
1391 reduction_list->traverse <tree, add_field_for_reduction> (type);
1392 }
1393 layout_type (type);
1394
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);
1399
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;
1404
1405 name_copies
1406 .traverse <struct clsn_data *, create_loads_and_stores_for_name>
1407 (ld_st_data);
1408
1409 /* Load the calculation from memory (after the join of the threads). */
1410
1411 if (reduction_list && reduction_list->elements () > 0)
1412 {
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);
1420 }
1421 }
1422 }
1423
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. */
1427
1428 static GTY(()) bitmap parallelized_functions;
1429
1430 /* Returns true if FN was created by create_loop_fn. */
1431
1432 bool
1433 parallelized_function_p (tree fn)
1434 {
1435 if (!parallelized_functions || !DECL_ARTIFICIAL (fn))
1436 return false;
1437
1438 return bitmap_bit_p (parallelized_functions, DECL_UID (fn));
1439 }
1440
1441 /* Creates and returns an empty function that will receive the body of
1442 a parallelized loop. */
1443
1444 static tree
1445 create_loop_fn (location_t loc)
1446 {
1447 char buf[100];
1448 char *tname;
1449 tree decl, type, name, t;
1450 struct function *act_cfun = cfun;
1451 static unsigned loopfn_num;
1452
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);
1459
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));
1464
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);
1474
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;
1479
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;
1487
1488 allocate_struct_function (decl, false);
1489
1490 /* The call to allocate_struct_function clobbers CFUN, so we need to restore
1491 it. */
1492 set_cfun (act_cfun);
1493
1494 return decl;
1495 }
1496
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).
1501
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. */
1508
1509 static void
1510 transform_to_exit_first_loop (struct loop *loop,
1511 reduction_info_table_type *reduction_list,
1512 tree nit)
1513 {
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;
1523
1524 split_block_after_labels (loop->header);
1525 orig_header = single_succ (loop->header);
1526 hpred = single_succ_edge (loop->header);
1527
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);
1531
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))
1537 {
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);
1544
1545 if (res == control)
1546 {
1547 gimple_cond_set_lhs (cond_stmt, t);
1548 update_stmt (cond_stmt);
1549 control = t;
1550 }
1551 }
1552
1553 bbs = get_loop_body_in_dom_order (loop);
1554
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);
1564
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); )
1571 {
1572 phi = gsi.phi ();
1573 res = PHI_RESULT (phi);
1574 if (virtual_operand_p (res))
1575 {
1576 gsi_next (&gsi);
1577 continue;
1578 }
1579
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. */
1584
1585 if (reduction_list->elements () > 0)
1586 {
1587 struct reduction_info *red;
1588
1589 tree val = PHI_ARG_DEF_FROM_EDGE (phi, exit);
1590 red = reduction_phi (reduction_list, SSA_NAME_DEF_STMT (val));
1591 if (red)
1592 {
1593 red->keep_res = phi;
1594 gsi_next (&gsi);
1595 continue;
1596 }
1597 }
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);
1602 }
1603 gcc_assert (control_name != NULL_TREE);
1604
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);
1615 }
1616
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. */
1622
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)
1626 {
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;
1638
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);
1643
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);
1649
1650 gsi_insert_after (&gsi, omp_par_stmt, GSI_NEW_STMT);
1651
1652 /* Initialize NEW_DATA. */
1653 if (data)
1654 {
1655 gassign *assign_stmt;
1656
1657 gsi = gsi_after_labels (bb);
1658
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);
1662
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);
1666 }
1667
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);
1674
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));
1678
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));
1687
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);
1691
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));
1697
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))
1703 {
1704 source_location locus;
1705 tree def;
1706 gphi *phi = gpi.phi ();
1707 gphi *stmt;
1708
1709 stmt = as_a <gphi *> (
1710 SSA_NAME_DEF_STMT (PHI_ARG_DEF_FROM_EDGE (phi, exit)));
1711
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);
1716
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);
1720 }
1721 e = redirect_edge_and_branch (exit, nexit->dest);
1722 PENDING_STMT (e) = NULL;
1723
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;
1729
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)));
1739
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;
1743
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;
1750
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);
1756
1757 /* After the above dom info is hosed. Re-compute it. */
1758 free_dominance_info (CDI_DOMINATORS);
1759 calculate_dominance_info (CDI_DOMINATORS);
1760
1761 return paral_bb;
1762 }
1763
1764 /* Generates code to execute the iterations of LOOP in N_THREADS
1765 threads in parallel.
1766
1767 NITER describes number of iterations of LOOP.
1768 REDUCTION_LIST describes the reductions existent in the LOOP. */
1769
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)
1774 {
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;
1784
1785 /* From
1786
1787 ---------------------------------------------------------------------
1788 loop
1789 {
1790 IV = phi (INIT, IV + STEP)
1791 BODY1;
1792 if (COND)
1793 break;
1794 BODY2;
1795 }
1796 ---------------------------------------------------------------------
1797
1798 with # of iterations NITER (possibly with MAY_BE_ZERO assumption),
1799 we generate the following code:
1800
1801 ---------------------------------------------------------------------
1802
1803 if (MAY_BE_ZERO
1804 || NITER < MIN_PER_THREAD * N_THREADS)
1805 goto original;
1806
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;
1818
1819 original:
1820 loop
1821 {
1822 IV = phi (INIT, IV + STEP)
1823 BODY1;
1824 if (COND)
1825 break;
1826 BODY2;
1827 }
1828
1829 end:
1830
1831 */
1832
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. */
1837
1838 /* We should compute a better number-of-iterations value for outer loops.
1839 That is, if we have
1840
1841 for (i = 0; i < n; ++i)
1842 for (j = 0; j < m; ++j)
1843 ...
1844
1845 we should compute nit = n * m, not nit = n.
1846 Also may_be_zero handling would need to be adjusted. */
1847
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);
1853
1854 if (loop->inner)
1855 m_p_thread=2;
1856 else
1857 m_p_thread=MIN_PER_THREAD;
1858
1859 many_iterations_cond =
1860 fold_build2 (GE_EXPR, boolean_type_node,
1861 nit, build_int_cst (type, m_p_thread * n_threads));
1862
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))
1872 {
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);
1878 }
1879
1880 initialize_original_copy_tables ();
1881
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 ();
1888
1889 /* Base all the induction variables in LOOP on a single control one. */
1890 canonicalize_loop_ivs (loop, &nit, true);
1891
1892 /* Ensure that the exit condition is the first statement in the loop. */
1893 transform_to_exit_first_loop (loop, reduction_list, nit);
1894
1895 /* Generate initializations for reductions. */
1896 if (reduction_list->elements () > 0)
1897 reduction_list->traverse <struct loop *, initialize_reductions> (loop);
1898
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);
1903
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);
1909
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);
1919
1920 scev_reset ();
1921
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);
1925
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);
1930 }
1931
1932 /* Returns true when LOOP contains vector phi nodes. */
1933
1934 static bool
1935 loop_has_vector_phi_nodes (struct loop *loop ATTRIBUTE_UNUSED)
1936 {
1937 unsigned i;
1938 basic_block *bbs = get_loop_body_in_dom_order (loop);
1939 gphi_iterator gsi;
1940 bool res = true;
1941
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;
1946
1947 res = false;
1948 end:
1949 free (bbs);
1950 return res;
1951 }
1952
1953 /* Create a reduction_info struct, initialize it with REDUC_STMT
1954 and PHI, insert it to the REDUCTION_LIST. */
1955
1956 static void
1957 build_new_reduction (reduction_info_table_type *reduction_list,
1958 gimple reduc_stmt, gphi *phi)
1959 {
1960 reduction_info **slot;
1961 struct reduction_info *new_reduction;
1962
1963 gcc_assert (reduc_stmt);
1964
1965 if (dump_file && (dump_flags & TDF_DETAILS))
1966 {
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");
1971 }
1972
1973 new_reduction = XCNEW (struct reduction_info);
1974
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;
1981 }
1982
1983 /* Callback for htab_traverse. Sets gimple_uid of reduc_phi stmts. */
1984
1985 int
1986 set_reduc_phi_uids (reduction_info **slot, void *data ATTRIBUTE_UNUSED)
1987 {
1988 struct reduction_info *const red = *slot;
1989 gimple_set_uid (red->reduc_phi, red->reduc_version);
1990 return 1;
1991 }
1992
1993 /* Detect all reductions in the LOOP, insert them into REDUCTION_LIST. */
1994
1995 static void
1996 gather_scalar_reductions (loop_p loop, reduction_info_table_type *reduction_list)
1997 {
1998 gphi_iterator gsi;
1999 loop_vec_info simple_loop_info;
2000
2001 simple_loop_info = vect_analyze_loop_form (loop);
2002
2003 for (gsi = gsi_start_phis (loop->header); !gsi_end_p (gsi); gsi_next (&gsi))
2004 {
2005 gphi *phi = gsi.phi ();
2006 affine_iv iv;
2007 tree res = PHI_RESULT (phi);
2008 bool double_reduc;
2009
2010 if (virtual_operand_p (res))
2011 continue;
2012
2013 if (!simple_iv (loop, loop, res, &iv, true)
2014 && simple_loop_info)
2015 {
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);
2021 }
2022 }
2023 destroy_loop_vec_info (simple_loop_info, true);
2024
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);
2029 }
2030
2031 /* Try to initialize NITER for code generation part. */
2032
2033 static bool
2034 try_get_loop_niter (loop_p loop, struct tree_niter_desc *niter)
2035 {
2036 edge exit = single_dom_exit (loop);
2037
2038 gcc_assert (exit);
2039
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))
2044 {
2045 if (dump_file && (dump_flags & TDF_DETAILS))
2046 fprintf (dump_file, " FAILED: number of iterations not known\n");
2047 return false;
2048 }
2049
2050 return true;
2051 }
2052
2053 /* Try to initialize REDUCTION_LIST for code generation part.
2054 REDUCTION_LIST describes the reductions. */
2055
2056 static bool
2057 try_create_reduction_list (loop_p loop,
2058 reduction_info_table_type *reduction_list)
2059 {
2060 edge exit = single_dom_exit (loop);
2061 gphi_iterator gsi;
2062
2063 gcc_assert (exit);
2064
2065 gather_scalar_reductions (loop, reduction_list);
2066
2067
2068 for (gsi = gsi_start_phis (exit->dest); !gsi_end_p (gsi); gsi_next (&gsi))
2069 {
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);
2076
2077 if (!virtual_operand_p (val))
2078 {
2079 if (dump_file && (dump_flags & TDF_DETAILS))
2080 {
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");
2088 }
2089 if (reduction_list->elements () == 0)
2090 {
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;
2095 }
2096 reduc_phi = NULL;
2097 FOR_EACH_IMM_USE_FAST (use_p, imm_iter, val)
2098 {
2099 if (!gimple_debug_bind_p (USE_STMT (use_p))
2100 && flow_bb_inside_loop_p (loop, gimple_bb (USE_STMT (use_p))))
2101 {
2102 reduc_phi = USE_STMT (use_p);
2103 break;
2104 }
2105 }
2106 red = reduction_phi (reduction_list, reduc_phi);
2107 if (red == NULL)
2108 {
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;
2113 }
2114 if (dump_file && (dump_flags & TDF_DETAILS))
2115 {
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);
2120 }
2121 }
2122 }
2123
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))
2127 {
2128 gphi *phi = gsi.phi ();
2129 tree def = PHI_RESULT (phi);
2130 affine_iv iv;
2131
2132 if (!virtual_operand_p (def) && !simple_iv (loop, loop, def, &iv, true))
2133 {
2134 struct reduction_info *red;
2135
2136 red = reduction_phi (reduction_list, phi);
2137 if (red == NULL)
2138 {
2139 if (dump_file && (dump_flags & TDF_DETAILS))
2140 fprintf (dump_file,
2141 " FAILED: scalar dependency between iterations\n");
2142 return false;
2143 }
2144 }
2145 }
2146
2147
2148 return true;
2149 }
2150
2151 /* Detect parallel loops and generate parallel code using libgomp
2152 primitives. Returns true if some loop was parallelized, false
2153 otherwise. */
2154
2155 bool
2156 parallelize_loops (void)
2157 {
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;
2165
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;
2171
2172 gcc_obstack_init (&parloop_obstack);
2173 reduction_info_table_type reduction_list (10);
2174 init_stmt_vec_info_vec ();
2175
2176 FOR_EACH_LOOP (loop, 0)
2177 {
2178 reduction_list.empty ();
2179 if (dump_file && (dump_flags & TDF_DETAILS))
2180 {
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);
2186 }
2187
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)
2191 {
2192 if (dump_file && (dump_flags & TDF_DETAILS))
2193 fprintf (dump_file, "loop is not parallel according to graphite\n");
2194 continue;
2195 }
2196
2197 if (!single_dom_exit (loop))
2198 {
2199
2200 if (dump_file && (dump_flags & TDF_DETAILS))
2201 fprintf (dump_file, "loop is !single_dom_exit\n");
2202
2203 continue;
2204 }
2205
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;
2213
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;
2225
2226 if (!try_get_loop_niter (loop, &niter_desc))
2227 continue;
2228
2229 if (!try_create_reduction_list (loop, &reduction_list))
2230 continue;
2231
2232 if (!flag_loop_parallelize_all
2233 && !loop_parallel_p (loop, &parloop_obstack))
2234 continue;
2235
2236 changed = true;
2237 if (dump_file && (dump_flags & TDF_DETAILS))
2238 {
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));
2247 }
2248 gen_parallel_loop (loop, &reduction_list,
2249 n_threads, &niter_desc);
2250 }
2251
2252 free_stmt_vec_info_vec ();
2253 obstack_free (&parloop_obstack, NULL);
2254
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);
2260
2261 return changed;
2262 }
2263
2264 /* Parallelization. */
2265
2266 namespace {
2267
2268 const pass_data pass_data_parallelize_loops =
2269 {
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 */
2279 };
2280
2281 class pass_parallelize_loops : public gimple_opt_pass
2282 {
2283 public:
2284 pass_parallelize_loops (gcc::context *ctxt)
2285 : gimple_opt_pass (pass_data_parallelize_loops, ctxt)
2286 {}
2287
2288 /* opt_pass methods: */
2289 virtual bool gate (function *) { return flag_tree_parallelize_loops > 1; }
2290 virtual unsigned int execute (function *);
2291
2292 }; // class pass_parallelize_loops
2293
2294 unsigned
2295 pass_parallelize_loops::execute (function *fun)
2296 {
2297 if (number_of_loops (fun) <= 1)
2298 return 0;
2299
2300 if (parallelize_loops ())
2301 {
2302 fun->curr_properties &= ~(PROP_gimple_eomp);
2303 return TODO_update_ssa;
2304 }
2305
2306 return 0;
2307 }
2308
2309 } // anon namespace
2310
2311 gimple_opt_pass *
2312 make_pass_parallelize_loops (gcc::context *ctxt)
2313 {
2314 return new pass_parallelize_loops (ctxt);
2315 }
2316
2317
2318 #include "gt-tree-parloops.h"