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