genattrtab.c (write_header): Include hash-set.h...
[gcc.git] / gcc / tree-ssa-loop-prefetch.c
1 /* Array prefetching.
2 Copyright (C) 2005-2015 Free Software Foundation, Inc.
3
4 This file is part of GCC.
5
6 GCC is free software; you can redistribute it and/or modify it
7 under the terms of the GNU General Public License as published by the
8 Free Software Foundation; either version 3, or (at your option) any
9 later version.
10
11 GCC is distributed in the hope that it will be useful, but WITHOUT
12 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13 FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
14 for more details.
15
16 You should have received a copy of the GNU General Public License
17 along with GCC; see the file COPYING3. If not see
18 <http://www.gnu.org/licenses/>. */
19
20 #include "config.h"
21 #include "system.h"
22 #include "coretypes.h"
23 #include "tm.h"
24 #include "hash-set.h"
25 #include "machmode.h"
26 #include "vec.h"
27 #include "double-int.h"
28 #include "input.h"
29 #include "alias.h"
30 #include "symtab.h"
31 #include "wide-int.h"
32 #include "inchash.h"
33 #include "tree.h"
34 #include "fold-const.h"
35 #include "stor-layout.h"
36 #include "tm_p.h"
37 #include "predict.h"
38 #include "hard-reg-set.h"
39 #include "input.h"
40 #include "function.h"
41 #include "dominance.h"
42 #include "cfg.h"
43 #include "basic-block.h"
44 #include "tree-pretty-print.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-ssa.h"
54 #include "tree-ssa-loop-ivopts.h"
55 #include "tree-ssa-loop-manip.h"
56 #include "tree-ssa-loop-niter.h"
57 #include "tree-ssa-loop.h"
58 #include "tree-into-ssa.h"
59 #include "cfgloop.h"
60 #include "tree-pass.h"
61 #include "insn-config.h"
62 #include "tree-chrec.h"
63 #include "tree-scalar-evolution.h"
64 #include "diagnostic-core.h"
65 #include "params.h"
66 #include "langhooks.h"
67 #include "tree-inline.h"
68 #include "tree-data-ref.h"
69
70
71 /* FIXME: Needed for optabs, but this should all be moved to a TBD interface
72 between the GIMPLE and RTL worlds. */
73 #include "expr.h"
74 #include "insn-codes.h"
75 #include "optabs.h"
76 #include "recog.h"
77
78 /* This pass inserts prefetch instructions to optimize cache usage during
79 accesses to arrays in loops. It processes loops sequentially and:
80
81 1) Gathers all memory references in the single loop.
82 2) For each of the references it decides when it is profitable to prefetch
83 it. To do it, we evaluate the reuse among the accesses, and determines
84 two values: PREFETCH_BEFORE (meaning that it only makes sense to do
85 prefetching in the first PREFETCH_BEFORE iterations of the loop) and
86 PREFETCH_MOD (meaning that it only makes sense to prefetch in the
87 iterations of the loop that are zero modulo PREFETCH_MOD). For example
88 (assuming cache line size is 64 bytes, char has size 1 byte and there
89 is no hardware sequential prefetch):
90
91 char *a;
92 for (i = 0; i < max; i++)
93 {
94 a[255] = ...; (0)
95 a[i] = ...; (1)
96 a[i + 64] = ...; (2)
97 a[16*i] = ...; (3)
98 a[187*i] = ...; (4)
99 a[187*i + 50] = ...; (5)
100 }
101
102 (0) obviously has PREFETCH_BEFORE 1
103 (1) has PREFETCH_BEFORE 64, since (2) accesses the same memory
104 location 64 iterations before it, and PREFETCH_MOD 64 (since
105 it hits the same cache line otherwise).
106 (2) has PREFETCH_MOD 64
107 (3) has PREFETCH_MOD 4
108 (4) has PREFETCH_MOD 1. We do not set PREFETCH_BEFORE here, since
109 the cache line accessed by (5) is the same with probability only
110 7/32.
111 (5) has PREFETCH_MOD 1 as well.
112
113 Additionally, we use data dependence analysis to determine for each
114 reference the distance till the first reuse; this information is used
115 to determine the temporality of the issued prefetch instruction.
116
117 3) We determine how much ahead we need to prefetch. The number of
118 iterations needed is time to fetch / time spent in one iteration of
119 the loop. The problem is that we do not know either of these values,
120 so we just make a heuristic guess based on a magic (possibly)
121 target-specific constant and size of the loop.
122
123 4) Determine which of the references we prefetch. We take into account
124 that there is a maximum number of simultaneous prefetches (provided
125 by machine description). We prefetch as many prefetches as possible
126 while still within this bound (starting with those with lowest
127 prefetch_mod, since they are responsible for most of the cache
128 misses).
129
130 5) We unroll and peel loops so that we are able to satisfy PREFETCH_MOD
131 and PREFETCH_BEFORE requirements (within some bounds), and to avoid
132 prefetching nonaccessed memory.
133 TODO -- actually implement peeling.
134
135 6) We actually emit the prefetch instructions. ??? Perhaps emit the
136 prefetch instructions with guards in cases where 5) was not sufficient
137 to satisfy the constraints?
138
139 A cost model is implemented to determine whether or not prefetching is
140 profitable for a given loop. The cost model has three heuristics:
141
142 1. Function trip_count_to_ahead_ratio_too_small_p implements a
143 heuristic that determines whether or not the loop has too few
144 iterations (compared to ahead). Prefetching is not likely to be
145 beneficial if the trip count to ahead ratio is below a certain
146 minimum.
147
148 2. Function mem_ref_count_reasonable_p implements a heuristic that
149 determines whether the given loop has enough CPU ops that can be
150 overlapped with cache missing memory ops. If not, the loop
151 won't benefit from prefetching. In the implementation,
152 prefetching is not considered beneficial if the ratio between
153 the instruction count and the mem ref count is below a certain
154 minimum.
155
156 3. Function insn_to_prefetch_ratio_too_small_p implements a
157 heuristic that disables prefetching in a loop if the prefetching
158 cost is above a certain limit. The relative prefetching cost is
159 estimated by taking the ratio between the prefetch count and the
160 total intruction count (this models the I-cache cost).
161
162 The limits used in these heuristics are defined as parameters with
163 reasonable default values. Machine-specific default values will be
164 added later.
165
166 Some other TODO:
167 -- write and use more general reuse analysis (that could be also used
168 in other cache aimed loop optimizations)
169 -- make it behave sanely together with the prefetches given by user
170 (now we just ignore them; at the very least we should avoid
171 optimizing loops in that user put his own prefetches)
172 -- we assume cache line size alignment of arrays; this could be
173 improved. */
174
175 /* Magic constants follow. These should be replaced by machine specific
176 numbers. */
177
178 /* True if write can be prefetched by a read prefetch. */
179
180 #ifndef WRITE_CAN_USE_READ_PREFETCH
181 #define WRITE_CAN_USE_READ_PREFETCH 1
182 #endif
183
184 /* True if read can be prefetched by a write prefetch. */
185
186 #ifndef READ_CAN_USE_WRITE_PREFETCH
187 #define READ_CAN_USE_WRITE_PREFETCH 0
188 #endif
189
190 /* The size of the block loaded by a single prefetch. Usually, this is
191 the same as cache line size (at the moment, we only consider one level
192 of cache hierarchy). */
193
194 #ifndef PREFETCH_BLOCK
195 #define PREFETCH_BLOCK L1_CACHE_LINE_SIZE
196 #endif
197
198 /* Do we have a forward hardware sequential prefetching? */
199
200 #ifndef HAVE_FORWARD_PREFETCH
201 #define HAVE_FORWARD_PREFETCH 0
202 #endif
203
204 /* Do we have a backward hardware sequential prefetching? */
205
206 #ifndef HAVE_BACKWARD_PREFETCH
207 #define HAVE_BACKWARD_PREFETCH 0
208 #endif
209
210 /* In some cases we are only able to determine that there is a certain
211 probability that the two accesses hit the same cache line. In this
212 case, we issue the prefetches for both of them if this probability
213 is less then (1000 - ACCEPTABLE_MISS_RATE) per thousand. */
214
215 #ifndef ACCEPTABLE_MISS_RATE
216 #define ACCEPTABLE_MISS_RATE 50
217 #endif
218
219 #ifndef HAVE_prefetch
220 #define HAVE_prefetch 0
221 #endif
222
223 #define L1_CACHE_SIZE_BYTES ((unsigned) (L1_CACHE_SIZE * 1024))
224 #define L2_CACHE_SIZE_BYTES ((unsigned) (L2_CACHE_SIZE * 1024))
225
226 /* We consider a memory access nontemporal if it is not reused sooner than
227 after L2_CACHE_SIZE_BYTES of memory are accessed. However, we ignore
228 accesses closer than L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION,
229 so that we use nontemporal prefetches e.g. if single memory location
230 is accessed several times in a single iteration of the loop. */
231 #define NONTEMPORAL_FRACTION 16
232
233 /* In case we have to emit a memory fence instruction after the loop that
234 uses nontemporal stores, this defines the builtin to use. */
235
236 #ifndef FENCE_FOLLOWING_MOVNT
237 #define FENCE_FOLLOWING_MOVNT NULL_TREE
238 #endif
239
240 /* It is not profitable to prefetch when the trip count is not at
241 least TRIP_COUNT_TO_AHEAD_RATIO times the prefetch ahead distance.
242 For example, in a loop with a prefetch ahead distance of 10,
243 supposing that TRIP_COUNT_TO_AHEAD_RATIO is equal to 4, it is
244 profitable to prefetch when the trip count is greater or equal to
245 40. In that case, 30 out of the 40 iterations will benefit from
246 prefetching. */
247
248 #ifndef TRIP_COUNT_TO_AHEAD_RATIO
249 #define TRIP_COUNT_TO_AHEAD_RATIO 4
250 #endif
251
252 /* The group of references between that reuse may occur. */
253
254 struct mem_ref_group
255 {
256 tree base; /* Base of the reference. */
257 tree step; /* Step of the reference. */
258 struct mem_ref *refs; /* References in the group. */
259 struct mem_ref_group *next; /* Next group of references. */
260 };
261
262 /* Assigned to PREFETCH_BEFORE when all iterations are to be prefetched. */
263
264 #define PREFETCH_ALL (~(unsigned HOST_WIDE_INT) 0)
265
266 /* Do not generate a prefetch if the unroll factor is significantly less
267 than what is required by the prefetch. This is to avoid redundant
268 prefetches. For example, when prefetch_mod is 16 and unroll_factor is
269 2, prefetching requires unrolling the loop 16 times, but
270 the loop is actually unrolled twice. In this case (ratio = 8),
271 prefetching is not likely to be beneficial. */
272
273 #ifndef PREFETCH_MOD_TO_UNROLL_FACTOR_RATIO
274 #define PREFETCH_MOD_TO_UNROLL_FACTOR_RATIO 4
275 #endif
276
277 /* Some of the prefetch computations have quadratic complexity. We want to
278 avoid huge compile times and, therefore, want to limit the amount of
279 memory references per loop where we consider prefetching. */
280
281 #ifndef PREFETCH_MAX_MEM_REFS_PER_LOOP
282 #define PREFETCH_MAX_MEM_REFS_PER_LOOP 200
283 #endif
284
285 /* The memory reference. */
286
287 struct mem_ref
288 {
289 gimple stmt; /* Statement in that the reference appears. */
290 tree mem; /* The reference. */
291 HOST_WIDE_INT delta; /* Constant offset of the reference. */
292 struct mem_ref_group *group; /* The group of references it belongs to. */
293 unsigned HOST_WIDE_INT prefetch_mod;
294 /* Prefetch only each PREFETCH_MOD-th
295 iteration. */
296 unsigned HOST_WIDE_INT prefetch_before;
297 /* Prefetch only first PREFETCH_BEFORE
298 iterations. */
299 unsigned reuse_distance; /* The amount of data accessed before the first
300 reuse of this value. */
301 struct mem_ref *next; /* The next reference in the group. */
302 unsigned write_p : 1; /* Is it a write? */
303 unsigned independent_p : 1; /* True if the reference is independent on
304 all other references inside the loop. */
305 unsigned issue_prefetch_p : 1; /* Should we really issue the prefetch? */
306 unsigned storent_p : 1; /* True if we changed the store to a
307 nontemporal one. */
308 };
309
310 /* Dumps information about memory reference */
311 static void
312 dump_mem_details (FILE *file, tree base, tree step,
313 HOST_WIDE_INT delta, bool write_p)
314 {
315 fprintf (file, "(base ");
316 print_generic_expr (file, base, TDF_SLIM);
317 fprintf (file, ", step ");
318 if (cst_and_fits_in_hwi (step))
319 fprintf (file, HOST_WIDE_INT_PRINT_DEC, int_cst_value (step));
320 else
321 print_generic_expr (file, step, TDF_TREE);
322 fprintf (file, ")\n");
323 fprintf (file, " delta ");
324 fprintf (file, HOST_WIDE_INT_PRINT_DEC, delta);
325 fprintf (file, "\n");
326 fprintf (file, " %s\n", write_p ? "write" : "read");
327 fprintf (file, "\n");
328 }
329
330 /* Dumps information about reference REF to FILE. */
331
332 static void
333 dump_mem_ref (FILE *file, struct mem_ref *ref)
334 {
335 fprintf (file, "Reference %p:\n", (void *) ref);
336
337 fprintf (file, " group %p ", (void *) ref->group);
338
339 dump_mem_details (file, ref->group->base, ref->group->step, ref->delta,
340 ref->write_p);
341 }
342
343 /* Finds a group with BASE and STEP in GROUPS, or creates one if it does not
344 exist. */
345
346 static struct mem_ref_group *
347 find_or_create_group (struct mem_ref_group **groups, tree base, tree step)
348 {
349 struct mem_ref_group *group;
350
351 for (; *groups; groups = &(*groups)->next)
352 {
353 if (operand_equal_p ((*groups)->step, step, 0)
354 && operand_equal_p ((*groups)->base, base, 0))
355 return *groups;
356
357 /* If step is an integer constant, keep the list of groups sorted
358 by decreasing step. */
359 if (cst_and_fits_in_hwi ((*groups)->step) && cst_and_fits_in_hwi (step)
360 && int_cst_value ((*groups)->step) < int_cst_value (step))
361 break;
362 }
363
364 group = XNEW (struct mem_ref_group);
365 group->base = base;
366 group->step = step;
367 group->refs = NULL;
368 group->next = *groups;
369 *groups = group;
370
371 return group;
372 }
373
374 /* Records a memory reference MEM in GROUP with offset DELTA and write status
375 WRITE_P. The reference occurs in statement STMT. */
376
377 static void
378 record_ref (struct mem_ref_group *group, gimple stmt, tree mem,
379 HOST_WIDE_INT delta, bool write_p)
380 {
381 struct mem_ref **aref;
382
383 /* Do not record the same address twice. */
384 for (aref = &group->refs; *aref; aref = &(*aref)->next)
385 {
386 /* It does not have to be possible for write reference to reuse the read
387 prefetch, or vice versa. */
388 if (!WRITE_CAN_USE_READ_PREFETCH
389 && write_p
390 && !(*aref)->write_p)
391 continue;
392 if (!READ_CAN_USE_WRITE_PREFETCH
393 && !write_p
394 && (*aref)->write_p)
395 continue;
396
397 if ((*aref)->delta == delta)
398 return;
399 }
400
401 (*aref) = XNEW (struct mem_ref);
402 (*aref)->stmt = stmt;
403 (*aref)->mem = mem;
404 (*aref)->delta = delta;
405 (*aref)->write_p = write_p;
406 (*aref)->prefetch_before = PREFETCH_ALL;
407 (*aref)->prefetch_mod = 1;
408 (*aref)->reuse_distance = 0;
409 (*aref)->issue_prefetch_p = false;
410 (*aref)->group = group;
411 (*aref)->next = NULL;
412 (*aref)->independent_p = false;
413 (*aref)->storent_p = false;
414
415 if (dump_file && (dump_flags & TDF_DETAILS))
416 dump_mem_ref (dump_file, *aref);
417 }
418
419 /* Release memory references in GROUPS. */
420
421 static void
422 release_mem_refs (struct mem_ref_group *groups)
423 {
424 struct mem_ref_group *next_g;
425 struct mem_ref *ref, *next_r;
426
427 for (; groups; groups = next_g)
428 {
429 next_g = groups->next;
430 for (ref = groups->refs; ref; ref = next_r)
431 {
432 next_r = ref->next;
433 free (ref);
434 }
435 free (groups);
436 }
437 }
438
439 /* A structure used to pass arguments to idx_analyze_ref. */
440
441 struct ar_data
442 {
443 struct loop *loop; /* Loop of the reference. */
444 gimple stmt; /* Statement of the reference. */
445 tree *step; /* Step of the memory reference. */
446 HOST_WIDE_INT *delta; /* Offset of the memory reference. */
447 };
448
449 /* Analyzes a single INDEX of a memory reference to obtain information
450 described at analyze_ref. Callback for for_each_index. */
451
452 static bool
453 idx_analyze_ref (tree base, tree *index, void *data)
454 {
455 struct ar_data *ar_data = (struct ar_data *) data;
456 tree ibase, step, stepsize;
457 HOST_WIDE_INT idelta = 0, imult = 1;
458 affine_iv iv;
459
460 if (!simple_iv (ar_data->loop, loop_containing_stmt (ar_data->stmt),
461 *index, &iv, true))
462 return false;
463 ibase = iv.base;
464 step = iv.step;
465
466 if (TREE_CODE (ibase) == POINTER_PLUS_EXPR
467 && cst_and_fits_in_hwi (TREE_OPERAND (ibase, 1)))
468 {
469 idelta = int_cst_value (TREE_OPERAND (ibase, 1));
470 ibase = TREE_OPERAND (ibase, 0);
471 }
472 if (cst_and_fits_in_hwi (ibase))
473 {
474 idelta += int_cst_value (ibase);
475 ibase = build_int_cst (TREE_TYPE (ibase), 0);
476 }
477
478 if (TREE_CODE (base) == ARRAY_REF)
479 {
480 stepsize = array_ref_element_size (base);
481 if (!cst_and_fits_in_hwi (stepsize))
482 return false;
483 imult = int_cst_value (stepsize);
484 step = fold_build2 (MULT_EXPR, sizetype,
485 fold_convert (sizetype, step),
486 fold_convert (sizetype, stepsize));
487 idelta *= imult;
488 }
489
490 if (*ar_data->step == NULL_TREE)
491 *ar_data->step = step;
492 else
493 *ar_data->step = fold_build2 (PLUS_EXPR, sizetype,
494 fold_convert (sizetype, *ar_data->step),
495 fold_convert (sizetype, step));
496 *ar_data->delta += idelta;
497 *index = ibase;
498
499 return true;
500 }
501
502 /* Tries to express REF_P in shape &BASE + STEP * iter + DELTA, where DELTA and
503 STEP are integer constants and iter is number of iterations of LOOP. The
504 reference occurs in statement STMT. Strips nonaddressable component
505 references from REF_P. */
506
507 static bool
508 analyze_ref (struct loop *loop, tree *ref_p, tree *base,
509 tree *step, HOST_WIDE_INT *delta,
510 gimple stmt)
511 {
512 struct ar_data ar_data;
513 tree off;
514 HOST_WIDE_INT bit_offset;
515 tree ref = *ref_p;
516
517 *step = NULL_TREE;
518 *delta = 0;
519
520 /* First strip off the component references. Ignore bitfields.
521 Also strip off the real and imagine parts of a complex, so that
522 they can have the same base. */
523 if (TREE_CODE (ref) == REALPART_EXPR
524 || TREE_CODE (ref) == IMAGPART_EXPR
525 || (TREE_CODE (ref) == COMPONENT_REF
526 && DECL_NONADDRESSABLE_P (TREE_OPERAND (ref, 1))))
527 {
528 if (TREE_CODE (ref) == IMAGPART_EXPR)
529 *delta += int_size_in_bytes (TREE_TYPE (ref));
530 ref = TREE_OPERAND (ref, 0);
531 }
532
533 *ref_p = ref;
534
535 for (; TREE_CODE (ref) == COMPONENT_REF; ref = TREE_OPERAND (ref, 0))
536 {
537 off = DECL_FIELD_BIT_OFFSET (TREE_OPERAND (ref, 1));
538 bit_offset = TREE_INT_CST_LOW (off);
539 gcc_assert (bit_offset % BITS_PER_UNIT == 0);
540
541 *delta += bit_offset / BITS_PER_UNIT;
542 }
543
544 *base = unshare_expr (ref);
545 ar_data.loop = loop;
546 ar_data.stmt = stmt;
547 ar_data.step = step;
548 ar_data.delta = delta;
549 return for_each_index (base, idx_analyze_ref, &ar_data);
550 }
551
552 /* Record a memory reference REF to the list REFS. The reference occurs in
553 LOOP in statement STMT and it is write if WRITE_P. Returns true if the
554 reference was recorded, false otherwise. */
555
556 static bool
557 gather_memory_references_ref (struct loop *loop, struct mem_ref_group **refs,
558 tree ref, bool write_p, gimple stmt)
559 {
560 tree base, step;
561 HOST_WIDE_INT delta;
562 struct mem_ref_group *agrp;
563
564 if (get_base_address (ref) == NULL)
565 return false;
566
567 if (!analyze_ref (loop, &ref, &base, &step, &delta, stmt))
568 return false;
569 /* If analyze_ref fails the default is a NULL_TREE. We can stop here. */
570 if (step == NULL_TREE)
571 return false;
572
573 /* Stop if the address of BASE could not be taken. */
574 if (may_be_nonaddressable_p (base))
575 return false;
576
577 /* Limit non-constant step prefetching only to the innermost loops and
578 only when the step is loop invariant in the entire loop nest. */
579 if (!cst_and_fits_in_hwi (step))
580 {
581 if (loop->inner != NULL)
582 {
583 if (dump_file && (dump_flags & TDF_DETAILS))
584 {
585 fprintf (dump_file, "Memory expression %p\n",(void *) ref );
586 print_generic_expr (dump_file, ref, TDF_TREE);
587 fprintf (dump_file,":");
588 dump_mem_details (dump_file, base, step, delta, write_p);
589 fprintf (dump_file,
590 "Ignoring %p, non-constant step prefetching is "
591 "limited to inner most loops \n",
592 (void *) ref);
593 }
594 return false;
595 }
596 else
597 {
598 if (!expr_invariant_in_loop_p (loop_outermost (loop), step))
599 {
600 if (dump_file && (dump_flags & TDF_DETAILS))
601 {
602 fprintf (dump_file, "Memory expression %p\n",(void *) ref );
603 print_generic_expr (dump_file, ref, TDF_TREE);
604 fprintf (dump_file,":");
605 dump_mem_details (dump_file, base, step, delta, write_p);
606 fprintf (dump_file,
607 "Not prefetching, ignoring %p due to "
608 "loop variant step\n",
609 (void *) ref);
610 }
611 return false;
612 }
613 }
614 }
615
616 /* Now we know that REF = &BASE + STEP * iter + DELTA, where DELTA and STEP
617 are integer constants. */
618 agrp = find_or_create_group (refs, base, step);
619 record_ref (agrp, stmt, ref, delta, write_p);
620
621 return true;
622 }
623
624 /* Record the suitable memory references in LOOP. NO_OTHER_REFS is set to
625 true if there are no other memory references inside the loop. */
626
627 static struct mem_ref_group *
628 gather_memory_references (struct loop *loop, bool *no_other_refs, unsigned *ref_count)
629 {
630 basic_block *body = get_loop_body_in_dom_order (loop);
631 basic_block bb;
632 unsigned i;
633 gimple_stmt_iterator bsi;
634 gimple stmt;
635 tree lhs, rhs;
636 struct mem_ref_group *refs = NULL;
637
638 *no_other_refs = true;
639 *ref_count = 0;
640
641 /* Scan the loop body in order, so that the former references precede the
642 later ones. */
643 for (i = 0; i < loop->num_nodes; i++)
644 {
645 bb = body[i];
646 if (bb->loop_father != loop)
647 continue;
648
649 for (bsi = gsi_start_bb (bb); !gsi_end_p (bsi); gsi_next (&bsi))
650 {
651 stmt = gsi_stmt (bsi);
652
653 if (gimple_code (stmt) != GIMPLE_ASSIGN)
654 {
655 if (gimple_vuse (stmt)
656 || (is_gimple_call (stmt)
657 && !(gimple_call_flags (stmt) & ECF_CONST)))
658 *no_other_refs = false;
659 continue;
660 }
661
662 lhs = gimple_assign_lhs (stmt);
663 rhs = gimple_assign_rhs1 (stmt);
664
665 if (REFERENCE_CLASS_P (rhs))
666 {
667 *no_other_refs &= gather_memory_references_ref (loop, &refs,
668 rhs, false, stmt);
669 *ref_count += 1;
670 }
671 if (REFERENCE_CLASS_P (lhs))
672 {
673 *no_other_refs &= gather_memory_references_ref (loop, &refs,
674 lhs, true, stmt);
675 *ref_count += 1;
676 }
677 }
678 }
679 free (body);
680
681 return refs;
682 }
683
684 /* Prune the prefetch candidate REF using the self-reuse. */
685
686 static void
687 prune_ref_by_self_reuse (struct mem_ref *ref)
688 {
689 HOST_WIDE_INT step;
690 bool backward;
691
692 /* If the step size is non constant, we cannot calculate prefetch_mod. */
693 if (!cst_and_fits_in_hwi (ref->group->step))
694 return;
695
696 step = int_cst_value (ref->group->step);
697
698 backward = step < 0;
699
700 if (step == 0)
701 {
702 /* Prefetch references to invariant address just once. */
703 ref->prefetch_before = 1;
704 return;
705 }
706
707 if (backward)
708 step = -step;
709
710 if (step > PREFETCH_BLOCK)
711 return;
712
713 if ((backward && HAVE_BACKWARD_PREFETCH)
714 || (!backward && HAVE_FORWARD_PREFETCH))
715 {
716 ref->prefetch_before = 1;
717 return;
718 }
719
720 ref->prefetch_mod = PREFETCH_BLOCK / step;
721 }
722
723 /* Divides X by BY, rounding down. */
724
725 static HOST_WIDE_INT
726 ddown (HOST_WIDE_INT x, unsigned HOST_WIDE_INT by)
727 {
728 gcc_assert (by > 0);
729
730 if (x >= 0)
731 return x / by;
732 else
733 return (x + by - 1) / by;
734 }
735
736 /* Given a CACHE_LINE_SIZE and two inductive memory references
737 with a common STEP greater than CACHE_LINE_SIZE and an address
738 difference DELTA, compute the probability that they will fall
739 in different cache lines. Return true if the computed miss rate
740 is not greater than the ACCEPTABLE_MISS_RATE. DISTINCT_ITERS is the
741 number of distinct iterations after which the pattern repeats itself.
742 ALIGN_UNIT is the unit of alignment in bytes. */
743
744 static bool
745 is_miss_rate_acceptable (unsigned HOST_WIDE_INT cache_line_size,
746 HOST_WIDE_INT step, HOST_WIDE_INT delta,
747 unsigned HOST_WIDE_INT distinct_iters,
748 int align_unit)
749 {
750 unsigned align, iter;
751 int total_positions, miss_positions, max_allowed_miss_positions;
752 int address1, address2, cache_line1, cache_line2;
753
754 /* It always misses if delta is greater than or equal to the cache
755 line size. */
756 if (delta >= (HOST_WIDE_INT) cache_line_size)
757 return false;
758
759 miss_positions = 0;
760 total_positions = (cache_line_size / align_unit) * distinct_iters;
761 max_allowed_miss_positions = (ACCEPTABLE_MISS_RATE * total_positions) / 1000;
762
763 /* Iterate through all possible alignments of the first
764 memory reference within its cache line. */
765 for (align = 0; align < cache_line_size; align += align_unit)
766
767 /* Iterate through all distinct iterations. */
768 for (iter = 0; iter < distinct_iters; iter++)
769 {
770 address1 = align + step * iter;
771 address2 = address1 + delta;
772 cache_line1 = address1 / cache_line_size;
773 cache_line2 = address2 / cache_line_size;
774 if (cache_line1 != cache_line2)
775 {
776 miss_positions += 1;
777 if (miss_positions > max_allowed_miss_positions)
778 return false;
779 }
780 }
781 return true;
782 }
783
784 /* Prune the prefetch candidate REF using the reuse with BY.
785 If BY_IS_BEFORE is true, BY is before REF in the loop. */
786
787 static void
788 prune_ref_by_group_reuse (struct mem_ref *ref, struct mem_ref *by,
789 bool by_is_before)
790 {
791 HOST_WIDE_INT step;
792 bool backward;
793 HOST_WIDE_INT delta_r = ref->delta, delta_b = by->delta;
794 HOST_WIDE_INT delta = delta_b - delta_r;
795 HOST_WIDE_INT hit_from;
796 unsigned HOST_WIDE_INT prefetch_before, prefetch_block;
797 HOST_WIDE_INT reduced_step;
798 unsigned HOST_WIDE_INT reduced_prefetch_block;
799 tree ref_type;
800 int align_unit;
801
802 /* If the step is non constant we cannot calculate prefetch_before. */
803 if (!cst_and_fits_in_hwi (ref->group->step)) {
804 return;
805 }
806
807 step = int_cst_value (ref->group->step);
808
809 backward = step < 0;
810
811
812 if (delta == 0)
813 {
814 /* If the references has the same address, only prefetch the
815 former. */
816 if (by_is_before)
817 ref->prefetch_before = 0;
818
819 return;
820 }
821
822 if (!step)
823 {
824 /* If the reference addresses are invariant and fall into the
825 same cache line, prefetch just the first one. */
826 if (!by_is_before)
827 return;
828
829 if (ddown (ref->delta, PREFETCH_BLOCK)
830 != ddown (by->delta, PREFETCH_BLOCK))
831 return;
832
833 ref->prefetch_before = 0;
834 return;
835 }
836
837 /* Only prune the reference that is behind in the array. */
838 if (backward)
839 {
840 if (delta > 0)
841 return;
842
843 /* Transform the data so that we may assume that the accesses
844 are forward. */
845 delta = - delta;
846 step = -step;
847 delta_r = PREFETCH_BLOCK - 1 - delta_r;
848 delta_b = PREFETCH_BLOCK - 1 - delta_b;
849 }
850 else
851 {
852 if (delta < 0)
853 return;
854 }
855
856 /* Check whether the two references are likely to hit the same cache
857 line, and how distant the iterations in that it occurs are from
858 each other. */
859
860 if (step <= PREFETCH_BLOCK)
861 {
862 /* The accesses are sure to meet. Let us check when. */
863 hit_from = ddown (delta_b, PREFETCH_BLOCK) * PREFETCH_BLOCK;
864 prefetch_before = (hit_from - delta_r + step - 1) / step;
865
866 /* Do not reduce prefetch_before if we meet beyond cache size. */
867 if (prefetch_before > absu_hwi (L2_CACHE_SIZE_BYTES / step))
868 prefetch_before = PREFETCH_ALL;
869 if (prefetch_before < ref->prefetch_before)
870 ref->prefetch_before = prefetch_before;
871
872 return;
873 }
874
875 /* A more complicated case with step > prefetch_block. First reduce
876 the ratio between the step and the cache line size to its simplest
877 terms. The resulting denominator will then represent the number of
878 distinct iterations after which each address will go back to its
879 initial location within the cache line. This computation assumes
880 that PREFETCH_BLOCK is a power of two. */
881 prefetch_block = PREFETCH_BLOCK;
882 reduced_prefetch_block = prefetch_block;
883 reduced_step = step;
884 while ((reduced_step & 1) == 0
885 && reduced_prefetch_block > 1)
886 {
887 reduced_step >>= 1;
888 reduced_prefetch_block >>= 1;
889 }
890
891 prefetch_before = delta / step;
892 delta %= step;
893 ref_type = TREE_TYPE (ref->mem);
894 align_unit = TYPE_ALIGN (ref_type) / 8;
895 if (is_miss_rate_acceptable (prefetch_block, step, delta,
896 reduced_prefetch_block, align_unit))
897 {
898 /* Do not reduce prefetch_before if we meet beyond cache size. */
899 if (prefetch_before > L2_CACHE_SIZE_BYTES / PREFETCH_BLOCK)
900 prefetch_before = PREFETCH_ALL;
901 if (prefetch_before < ref->prefetch_before)
902 ref->prefetch_before = prefetch_before;
903
904 return;
905 }
906
907 /* Try also the following iteration. */
908 prefetch_before++;
909 delta = step - delta;
910 if (is_miss_rate_acceptable (prefetch_block, step, delta,
911 reduced_prefetch_block, align_unit))
912 {
913 if (prefetch_before < ref->prefetch_before)
914 ref->prefetch_before = prefetch_before;
915
916 return;
917 }
918
919 /* The ref probably does not reuse by. */
920 return;
921 }
922
923 /* Prune the prefetch candidate REF using the reuses with other references
924 in REFS. */
925
926 static void
927 prune_ref_by_reuse (struct mem_ref *ref, struct mem_ref *refs)
928 {
929 struct mem_ref *prune_by;
930 bool before = true;
931
932 prune_ref_by_self_reuse (ref);
933
934 for (prune_by = refs; prune_by; prune_by = prune_by->next)
935 {
936 if (prune_by == ref)
937 {
938 before = false;
939 continue;
940 }
941
942 if (!WRITE_CAN_USE_READ_PREFETCH
943 && ref->write_p
944 && !prune_by->write_p)
945 continue;
946 if (!READ_CAN_USE_WRITE_PREFETCH
947 && !ref->write_p
948 && prune_by->write_p)
949 continue;
950
951 prune_ref_by_group_reuse (ref, prune_by, before);
952 }
953 }
954
955 /* Prune the prefetch candidates in GROUP using the reuse analysis. */
956
957 static void
958 prune_group_by_reuse (struct mem_ref_group *group)
959 {
960 struct mem_ref *ref_pruned;
961
962 for (ref_pruned = group->refs; ref_pruned; ref_pruned = ref_pruned->next)
963 {
964 prune_ref_by_reuse (ref_pruned, group->refs);
965
966 if (dump_file && (dump_flags & TDF_DETAILS))
967 {
968 fprintf (dump_file, "Reference %p:", (void *) ref_pruned);
969
970 if (ref_pruned->prefetch_before == PREFETCH_ALL
971 && ref_pruned->prefetch_mod == 1)
972 fprintf (dump_file, " no restrictions");
973 else if (ref_pruned->prefetch_before == 0)
974 fprintf (dump_file, " do not prefetch");
975 else if (ref_pruned->prefetch_before <= ref_pruned->prefetch_mod)
976 fprintf (dump_file, " prefetch once");
977 else
978 {
979 if (ref_pruned->prefetch_before != PREFETCH_ALL)
980 {
981 fprintf (dump_file, " prefetch before ");
982 fprintf (dump_file, HOST_WIDE_INT_PRINT_DEC,
983 ref_pruned->prefetch_before);
984 }
985 if (ref_pruned->prefetch_mod != 1)
986 {
987 fprintf (dump_file, " prefetch mod ");
988 fprintf (dump_file, HOST_WIDE_INT_PRINT_DEC,
989 ref_pruned->prefetch_mod);
990 }
991 }
992 fprintf (dump_file, "\n");
993 }
994 }
995 }
996
997 /* Prune the list of prefetch candidates GROUPS using the reuse analysis. */
998
999 static void
1000 prune_by_reuse (struct mem_ref_group *groups)
1001 {
1002 for (; groups; groups = groups->next)
1003 prune_group_by_reuse (groups);
1004 }
1005
1006 /* Returns true if we should issue prefetch for REF. */
1007
1008 static bool
1009 should_issue_prefetch_p (struct mem_ref *ref)
1010 {
1011 /* For now do not issue prefetches for only first few of the
1012 iterations. */
1013 if (ref->prefetch_before != PREFETCH_ALL)
1014 {
1015 if (dump_file && (dump_flags & TDF_DETAILS))
1016 fprintf (dump_file, "Ignoring %p due to prefetch_before\n",
1017 (void *) ref);
1018 return false;
1019 }
1020
1021 /* Do not prefetch nontemporal stores. */
1022 if (ref->storent_p)
1023 {
1024 if (dump_file && (dump_flags & TDF_DETAILS))
1025 fprintf (dump_file, "Ignoring nontemporal store %p\n", (void *) ref);
1026 return false;
1027 }
1028
1029 return true;
1030 }
1031
1032 /* Decide which of the prefetch candidates in GROUPS to prefetch.
1033 AHEAD is the number of iterations to prefetch ahead (which corresponds
1034 to the number of simultaneous instances of one prefetch running at a
1035 time). UNROLL_FACTOR is the factor by that the loop is going to be
1036 unrolled. Returns true if there is anything to prefetch. */
1037
1038 static bool
1039 schedule_prefetches (struct mem_ref_group *groups, unsigned unroll_factor,
1040 unsigned ahead)
1041 {
1042 unsigned remaining_prefetch_slots, n_prefetches, prefetch_slots;
1043 unsigned slots_per_prefetch;
1044 struct mem_ref *ref;
1045 bool any = false;
1046
1047 /* At most SIMULTANEOUS_PREFETCHES should be running at the same time. */
1048 remaining_prefetch_slots = SIMULTANEOUS_PREFETCHES;
1049
1050 /* The prefetch will run for AHEAD iterations of the original loop, i.e.,
1051 AHEAD / UNROLL_FACTOR iterations of the unrolled loop. In each iteration,
1052 it will need a prefetch slot. */
1053 slots_per_prefetch = (ahead + unroll_factor / 2) / unroll_factor;
1054 if (dump_file && (dump_flags & TDF_DETAILS))
1055 fprintf (dump_file, "Each prefetch instruction takes %u prefetch slots.\n",
1056 slots_per_prefetch);
1057
1058 /* For now we just take memory references one by one and issue
1059 prefetches for as many as possible. The groups are sorted
1060 starting with the largest step, since the references with
1061 large step are more likely to cause many cache misses. */
1062
1063 for (; groups; groups = groups->next)
1064 for (ref = groups->refs; ref; ref = ref->next)
1065 {
1066 if (!should_issue_prefetch_p (ref))
1067 continue;
1068
1069 /* The loop is far from being sufficiently unrolled for this
1070 prefetch. Do not generate prefetch to avoid many redudant
1071 prefetches. */
1072 if (ref->prefetch_mod / unroll_factor > PREFETCH_MOD_TO_UNROLL_FACTOR_RATIO)
1073 continue;
1074
1075 /* If we need to prefetch the reference each PREFETCH_MOD iterations,
1076 and we unroll the loop UNROLL_FACTOR times, we need to insert
1077 ceil (UNROLL_FACTOR / PREFETCH_MOD) instructions in each
1078 iteration. */
1079 n_prefetches = ((unroll_factor + ref->prefetch_mod - 1)
1080 / ref->prefetch_mod);
1081 prefetch_slots = n_prefetches * slots_per_prefetch;
1082
1083 /* If more than half of the prefetches would be lost anyway, do not
1084 issue the prefetch. */
1085 if (2 * remaining_prefetch_slots < prefetch_slots)
1086 continue;
1087
1088 ref->issue_prefetch_p = true;
1089
1090 if (remaining_prefetch_slots <= prefetch_slots)
1091 return true;
1092 remaining_prefetch_slots -= prefetch_slots;
1093 any = true;
1094 }
1095
1096 return any;
1097 }
1098
1099 /* Return TRUE if no prefetch is going to be generated in the given
1100 GROUPS. */
1101
1102 static bool
1103 nothing_to_prefetch_p (struct mem_ref_group *groups)
1104 {
1105 struct mem_ref *ref;
1106
1107 for (; groups; groups = groups->next)
1108 for (ref = groups->refs; ref; ref = ref->next)
1109 if (should_issue_prefetch_p (ref))
1110 return false;
1111
1112 return true;
1113 }
1114
1115 /* Estimate the number of prefetches in the given GROUPS.
1116 UNROLL_FACTOR is the factor by which LOOP was unrolled. */
1117
1118 static int
1119 estimate_prefetch_count (struct mem_ref_group *groups, unsigned unroll_factor)
1120 {
1121 struct mem_ref *ref;
1122 unsigned n_prefetches;
1123 int prefetch_count = 0;
1124
1125 for (; groups; groups = groups->next)
1126 for (ref = groups->refs; ref; ref = ref->next)
1127 if (should_issue_prefetch_p (ref))
1128 {
1129 n_prefetches = ((unroll_factor + ref->prefetch_mod - 1)
1130 / ref->prefetch_mod);
1131 prefetch_count += n_prefetches;
1132 }
1133
1134 return prefetch_count;
1135 }
1136
1137 /* Issue prefetches for the reference REF into loop as decided before.
1138 HEAD is the number of iterations to prefetch ahead. UNROLL_FACTOR
1139 is the factor by which LOOP was unrolled. */
1140
1141 static void
1142 issue_prefetch_ref (struct mem_ref *ref, unsigned unroll_factor, unsigned ahead)
1143 {
1144 HOST_WIDE_INT delta;
1145 tree addr, addr_base, write_p, local, forward;
1146 gcall *prefetch;
1147 gimple_stmt_iterator bsi;
1148 unsigned n_prefetches, ap;
1149 bool nontemporal = ref->reuse_distance >= L2_CACHE_SIZE_BYTES;
1150
1151 if (dump_file && (dump_flags & TDF_DETAILS))
1152 fprintf (dump_file, "Issued%s prefetch for %p.\n",
1153 nontemporal ? " nontemporal" : "",
1154 (void *) ref);
1155
1156 bsi = gsi_for_stmt (ref->stmt);
1157
1158 n_prefetches = ((unroll_factor + ref->prefetch_mod - 1)
1159 / ref->prefetch_mod);
1160 addr_base = build_fold_addr_expr_with_type (ref->mem, ptr_type_node);
1161 addr_base = force_gimple_operand_gsi (&bsi, unshare_expr (addr_base),
1162 true, NULL, true, GSI_SAME_STMT);
1163 write_p = ref->write_p ? integer_one_node : integer_zero_node;
1164 local = nontemporal ? integer_zero_node : integer_three_node;
1165
1166 for (ap = 0; ap < n_prefetches; ap++)
1167 {
1168 if (cst_and_fits_in_hwi (ref->group->step))
1169 {
1170 /* Determine the address to prefetch. */
1171 delta = (ahead + ap * ref->prefetch_mod) *
1172 int_cst_value (ref->group->step);
1173 addr = fold_build_pointer_plus_hwi (addr_base, delta);
1174 addr = force_gimple_operand_gsi (&bsi, unshare_expr (addr), true, NULL,
1175 true, GSI_SAME_STMT);
1176 }
1177 else
1178 {
1179 /* The step size is non-constant but loop-invariant. We use the
1180 heuristic to simply prefetch ahead iterations ahead. */
1181 forward = fold_build2 (MULT_EXPR, sizetype,
1182 fold_convert (sizetype, ref->group->step),
1183 fold_convert (sizetype, size_int (ahead)));
1184 addr = fold_build_pointer_plus (addr_base, forward);
1185 addr = force_gimple_operand_gsi (&bsi, unshare_expr (addr), true,
1186 NULL, true, GSI_SAME_STMT);
1187 }
1188 /* Create the prefetch instruction. */
1189 prefetch = gimple_build_call (builtin_decl_explicit (BUILT_IN_PREFETCH),
1190 3, addr, write_p, local);
1191 gsi_insert_before (&bsi, prefetch, GSI_SAME_STMT);
1192 }
1193 }
1194
1195 /* Issue prefetches for the references in GROUPS into loop as decided before.
1196 HEAD is the number of iterations to prefetch ahead. UNROLL_FACTOR is the
1197 factor by that LOOP was unrolled. */
1198
1199 static void
1200 issue_prefetches (struct mem_ref_group *groups,
1201 unsigned unroll_factor, unsigned ahead)
1202 {
1203 struct mem_ref *ref;
1204
1205 for (; groups; groups = groups->next)
1206 for (ref = groups->refs; ref; ref = ref->next)
1207 if (ref->issue_prefetch_p)
1208 issue_prefetch_ref (ref, unroll_factor, ahead);
1209 }
1210
1211 /* Returns true if REF is a memory write for that a nontemporal store insn
1212 can be used. */
1213
1214 static bool
1215 nontemporal_store_p (struct mem_ref *ref)
1216 {
1217 machine_mode mode;
1218 enum insn_code code;
1219
1220 /* REF must be a write that is not reused. We require it to be independent
1221 on all other memory references in the loop, as the nontemporal stores may
1222 be reordered with respect to other memory references. */
1223 if (!ref->write_p
1224 || !ref->independent_p
1225 || ref->reuse_distance < L2_CACHE_SIZE_BYTES)
1226 return false;
1227
1228 /* Check that we have the storent instruction for the mode. */
1229 mode = TYPE_MODE (TREE_TYPE (ref->mem));
1230 if (mode == BLKmode)
1231 return false;
1232
1233 code = optab_handler (storent_optab, mode);
1234 return code != CODE_FOR_nothing;
1235 }
1236
1237 /* If REF is a nontemporal store, we mark the corresponding modify statement
1238 and return true. Otherwise, we return false. */
1239
1240 static bool
1241 mark_nontemporal_store (struct mem_ref *ref)
1242 {
1243 if (!nontemporal_store_p (ref))
1244 return false;
1245
1246 if (dump_file && (dump_flags & TDF_DETAILS))
1247 fprintf (dump_file, "Marked reference %p as a nontemporal store.\n",
1248 (void *) ref);
1249
1250 gimple_assign_set_nontemporal_move (ref->stmt, true);
1251 ref->storent_p = true;
1252
1253 return true;
1254 }
1255
1256 /* Issue a memory fence instruction after LOOP. */
1257
1258 static void
1259 emit_mfence_after_loop (struct loop *loop)
1260 {
1261 vec<edge> exits = get_loop_exit_edges (loop);
1262 edge exit;
1263 gcall *call;
1264 gimple_stmt_iterator bsi;
1265 unsigned i;
1266
1267 FOR_EACH_VEC_ELT (exits, i, exit)
1268 {
1269 call = gimple_build_call (FENCE_FOLLOWING_MOVNT, 0);
1270
1271 if (!single_pred_p (exit->dest)
1272 /* If possible, we prefer not to insert the fence on other paths
1273 in cfg. */
1274 && !(exit->flags & EDGE_ABNORMAL))
1275 split_loop_exit_edge (exit);
1276 bsi = gsi_after_labels (exit->dest);
1277
1278 gsi_insert_before (&bsi, call, GSI_NEW_STMT);
1279 }
1280
1281 exits.release ();
1282 update_ssa (TODO_update_ssa_only_virtuals);
1283 }
1284
1285 /* Returns true if we can use storent in loop, false otherwise. */
1286
1287 static bool
1288 may_use_storent_in_loop_p (struct loop *loop)
1289 {
1290 bool ret = true;
1291
1292 if (loop->inner != NULL)
1293 return false;
1294
1295 /* If we must issue a mfence insn after using storent, check that there
1296 is a suitable place for it at each of the loop exits. */
1297 if (FENCE_FOLLOWING_MOVNT != NULL_TREE)
1298 {
1299 vec<edge> exits = get_loop_exit_edges (loop);
1300 unsigned i;
1301 edge exit;
1302
1303 FOR_EACH_VEC_ELT (exits, i, exit)
1304 if ((exit->flags & EDGE_ABNORMAL)
1305 && exit->dest == EXIT_BLOCK_PTR_FOR_FN (cfun))
1306 ret = false;
1307
1308 exits.release ();
1309 }
1310
1311 return ret;
1312 }
1313
1314 /* Marks nontemporal stores in LOOP. GROUPS contains the description of memory
1315 references in the loop. */
1316
1317 static void
1318 mark_nontemporal_stores (struct loop *loop, struct mem_ref_group *groups)
1319 {
1320 struct mem_ref *ref;
1321 bool any = false;
1322
1323 if (!may_use_storent_in_loop_p (loop))
1324 return;
1325
1326 for (; groups; groups = groups->next)
1327 for (ref = groups->refs; ref; ref = ref->next)
1328 any |= mark_nontemporal_store (ref);
1329
1330 if (any && FENCE_FOLLOWING_MOVNT != NULL_TREE)
1331 emit_mfence_after_loop (loop);
1332 }
1333
1334 /* Determines whether we can profitably unroll LOOP FACTOR times, and if
1335 this is the case, fill in DESC by the description of number of
1336 iterations. */
1337
1338 static bool
1339 should_unroll_loop_p (struct loop *loop, struct tree_niter_desc *desc,
1340 unsigned factor)
1341 {
1342 if (!can_unroll_loop_p (loop, factor, desc))
1343 return false;
1344
1345 /* We only consider loops without control flow for unrolling. This is not
1346 a hard restriction -- tree_unroll_loop works with arbitrary loops
1347 as well; but the unrolling/prefetching is usually more profitable for
1348 loops consisting of a single basic block, and we want to limit the
1349 code growth. */
1350 if (loop->num_nodes > 2)
1351 return false;
1352
1353 return true;
1354 }
1355
1356 /* Determine the coefficient by that unroll LOOP, from the information
1357 contained in the list of memory references REFS. Description of
1358 umber of iterations of LOOP is stored to DESC. NINSNS is the number of
1359 insns of the LOOP. EST_NITER is the estimated number of iterations of
1360 the loop, or -1 if no estimate is available. */
1361
1362 static unsigned
1363 determine_unroll_factor (struct loop *loop, struct mem_ref_group *refs,
1364 unsigned ninsns, struct tree_niter_desc *desc,
1365 HOST_WIDE_INT est_niter)
1366 {
1367 unsigned upper_bound;
1368 unsigned nfactor, factor, mod_constraint;
1369 struct mem_ref_group *agp;
1370 struct mem_ref *ref;
1371
1372 /* First check whether the loop is not too large to unroll. We ignore
1373 PARAM_MAX_UNROLL_TIMES, because for small loops, it prevented us
1374 from unrolling them enough to make exactly one cache line covered by each
1375 iteration. Also, the goal of PARAM_MAX_UNROLL_TIMES is to prevent
1376 us from unrolling the loops too many times in cases where we only expect
1377 gains from better scheduling and decreasing loop overhead, which is not
1378 the case here. */
1379 upper_bound = PARAM_VALUE (PARAM_MAX_UNROLLED_INSNS) / ninsns;
1380
1381 /* If we unrolled the loop more times than it iterates, the unrolled version
1382 of the loop would be never entered. */
1383 if (est_niter >= 0 && est_niter < (HOST_WIDE_INT) upper_bound)
1384 upper_bound = est_niter;
1385
1386 if (upper_bound <= 1)
1387 return 1;
1388
1389 /* Choose the factor so that we may prefetch each cache just once,
1390 but bound the unrolling by UPPER_BOUND. */
1391 factor = 1;
1392 for (agp = refs; agp; agp = agp->next)
1393 for (ref = agp->refs; ref; ref = ref->next)
1394 if (should_issue_prefetch_p (ref))
1395 {
1396 mod_constraint = ref->prefetch_mod;
1397 nfactor = least_common_multiple (mod_constraint, factor);
1398 if (nfactor <= upper_bound)
1399 factor = nfactor;
1400 }
1401
1402 if (!should_unroll_loop_p (loop, desc, factor))
1403 return 1;
1404
1405 return factor;
1406 }
1407
1408 /* Returns the total volume of the memory references REFS, taking into account
1409 reuses in the innermost loop and cache line size. TODO -- we should also
1410 take into account reuses across the iterations of the loops in the loop
1411 nest. */
1412
1413 static unsigned
1414 volume_of_references (struct mem_ref_group *refs)
1415 {
1416 unsigned volume = 0;
1417 struct mem_ref_group *gr;
1418 struct mem_ref *ref;
1419
1420 for (gr = refs; gr; gr = gr->next)
1421 for (ref = gr->refs; ref; ref = ref->next)
1422 {
1423 /* Almost always reuses another value? */
1424 if (ref->prefetch_before != PREFETCH_ALL)
1425 continue;
1426
1427 /* If several iterations access the same cache line, use the size of
1428 the line divided by this number. Otherwise, a cache line is
1429 accessed in each iteration. TODO -- in the latter case, we should
1430 take the size of the reference into account, rounding it up on cache
1431 line size multiple. */
1432 volume += L1_CACHE_LINE_SIZE / ref->prefetch_mod;
1433 }
1434 return volume;
1435 }
1436
1437 /* Returns the volume of memory references accessed across VEC iterations of
1438 loops, whose sizes are described in the LOOP_SIZES array. N is the number
1439 of the loops in the nest (length of VEC and LOOP_SIZES vectors). */
1440
1441 static unsigned
1442 volume_of_dist_vector (lambda_vector vec, unsigned *loop_sizes, unsigned n)
1443 {
1444 unsigned i;
1445
1446 for (i = 0; i < n; i++)
1447 if (vec[i] != 0)
1448 break;
1449
1450 if (i == n)
1451 return 0;
1452
1453 gcc_assert (vec[i] > 0);
1454
1455 /* We ignore the parts of the distance vector in subloops, since usually
1456 the numbers of iterations are much smaller. */
1457 return loop_sizes[i] * vec[i];
1458 }
1459
1460 /* Add the steps of ACCESS_FN multiplied by STRIDE to the array STRIDE
1461 at the position corresponding to the loop of the step. N is the depth
1462 of the considered loop nest, and, LOOP is its innermost loop. */
1463
1464 static void
1465 add_subscript_strides (tree access_fn, unsigned stride,
1466 HOST_WIDE_INT *strides, unsigned n, struct loop *loop)
1467 {
1468 struct loop *aloop;
1469 tree step;
1470 HOST_WIDE_INT astep;
1471 unsigned min_depth = loop_depth (loop) - n;
1472
1473 while (TREE_CODE (access_fn) == POLYNOMIAL_CHREC)
1474 {
1475 aloop = get_chrec_loop (access_fn);
1476 step = CHREC_RIGHT (access_fn);
1477 access_fn = CHREC_LEFT (access_fn);
1478
1479 if ((unsigned) loop_depth (aloop) <= min_depth)
1480 continue;
1481
1482 if (tree_fits_shwi_p (step))
1483 astep = tree_to_shwi (step);
1484 else
1485 astep = L1_CACHE_LINE_SIZE;
1486
1487 strides[n - 1 - loop_depth (loop) + loop_depth (aloop)] += astep * stride;
1488
1489 }
1490 }
1491
1492 /* Returns the volume of memory references accessed between two consecutive
1493 self-reuses of the reference DR. We consider the subscripts of DR in N
1494 loops, and LOOP_SIZES contains the volumes of accesses in each of the
1495 loops. LOOP is the innermost loop of the current loop nest. */
1496
1497 static unsigned
1498 self_reuse_distance (data_reference_p dr, unsigned *loop_sizes, unsigned n,
1499 struct loop *loop)
1500 {
1501 tree stride, access_fn;
1502 HOST_WIDE_INT *strides, astride;
1503 vec<tree> access_fns;
1504 tree ref = DR_REF (dr);
1505 unsigned i, ret = ~0u;
1506
1507 /* In the following example:
1508
1509 for (i = 0; i < N; i++)
1510 for (j = 0; j < N; j++)
1511 use (a[j][i]);
1512 the same cache line is accessed each N steps (except if the change from
1513 i to i + 1 crosses the boundary of the cache line). Thus, for self-reuse,
1514 we cannot rely purely on the results of the data dependence analysis.
1515
1516 Instead, we compute the stride of the reference in each loop, and consider
1517 the innermost loop in that the stride is less than cache size. */
1518
1519 strides = XCNEWVEC (HOST_WIDE_INT, n);
1520 access_fns = DR_ACCESS_FNS (dr);
1521
1522 FOR_EACH_VEC_ELT (access_fns, i, access_fn)
1523 {
1524 /* Keep track of the reference corresponding to the subscript, so that we
1525 know its stride. */
1526 while (handled_component_p (ref) && TREE_CODE (ref) != ARRAY_REF)
1527 ref = TREE_OPERAND (ref, 0);
1528
1529 if (TREE_CODE (ref) == ARRAY_REF)
1530 {
1531 stride = TYPE_SIZE_UNIT (TREE_TYPE (ref));
1532 if (tree_fits_uhwi_p (stride))
1533 astride = tree_to_uhwi (stride);
1534 else
1535 astride = L1_CACHE_LINE_SIZE;
1536
1537 ref = TREE_OPERAND (ref, 0);
1538 }
1539 else
1540 astride = 1;
1541
1542 add_subscript_strides (access_fn, astride, strides, n, loop);
1543 }
1544
1545 for (i = n; i-- > 0; )
1546 {
1547 unsigned HOST_WIDE_INT s;
1548
1549 s = strides[i] < 0 ? -strides[i] : strides[i];
1550
1551 if (s < (unsigned) L1_CACHE_LINE_SIZE
1552 && (loop_sizes[i]
1553 > (unsigned) (L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION)))
1554 {
1555 ret = loop_sizes[i];
1556 break;
1557 }
1558 }
1559
1560 free (strides);
1561 return ret;
1562 }
1563
1564 /* Determines the distance till the first reuse of each reference in REFS
1565 in the loop nest of LOOP. NO_OTHER_REFS is true if there are no other
1566 memory references in the loop. Return false if the analysis fails. */
1567
1568 static bool
1569 determine_loop_nest_reuse (struct loop *loop, struct mem_ref_group *refs,
1570 bool no_other_refs)
1571 {
1572 struct loop *nest, *aloop;
1573 vec<data_reference_p> datarefs = vNULL;
1574 vec<ddr_p> dependences = vNULL;
1575 struct mem_ref_group *gr;
1576 struct mem_ref *ref, *refb;
1577 vec<loop_p> vloops = vNULL;
1578 unsigned *loop_data_size;
1579 unsigned i, j, n;
1580 unsigned volume, dist, adist;
1581 HOST_WIDE_INT vol;
1582 data_reference_p dr;
1583 ddr_p dep;
1584
1585 if (loop->inner)
1586 return true;
1587
1588 /* Find the outermost loop of the loop nest of loop (we require that
1589 there are no sibling loops inside the nest). */
1590 nest = loop;
1591 while (1)
1592 {
1593 aloop = loop_outer (nest);
1594
1595 if (aloop == current_loops->tree_root
1596 || aloop->inner->next)
1597 break;
1598
1599 nest = aloop;
1600 }
1601
1602 /* For each loop, determine the amount of data accessed in each iteration.
1603 We use this to estimate whether the reference is evicted from the
1604 cache before its reuse. */
1605 find_loop_nest (nest, &vloops);
1606 n = vloops.length ();
1607 loop_data_size = XNEWVEC (unsigned, n);
1608 volume = volume_of_references (refs);
1609 i = n;
1610 while (i-- != 0)
1611 {
1612 loop_data_size[i] = volume;
1613 /* Bound the volume by the L2 cache size, since above this bound,
1614 all dependence distances are equivalent. */
1615 if (volume > L2_CACHE_SIZE_BYTES)
1616 continue;
1617
1618 aloop = vloops[i];
1619 vol = estimated_stmt_executions_int (aloop);
1620 if (vol == -1)
1621 vol = expected_loop_iterations (aloop);
1622 volume *= vol;
1623 }
1624
1625 /* Prepare the references in the form suitable for data dependence
1626 analysis. We ignore unanalyzable data references (the results
1627 are used just as a heuristics to estimate temporality of the
1628 references, hence we do not need to worry about correctness). */
1629 for (gr = refs; gr; gr = gr->next)
1630 for (ref = gr->refs; ref; ref = ref->next)
1631 {
1632 dr = create_data_ref (nest, loop_containing_stmt (ref->stmt),
1633 ref->mem, ref->stmt, !ref->write_p);
1634
1635 if (dr)
1636 {
1637 ref->reuse_distance = volume;
1638 dr->aux = ref;
1639 datarefs.safe_push (dr);
1640 }
1641 else
1642 no_other_refs = false;
1643 }
1644
1645 FOR_EACH_VEC_ELT (datarefs, i, dr)
1646 {
1647 dist = self_reuse_distance (dr, loop_data_size, n, loop);
1648 ref = (struct mem_ref *) dr->aux;
1649 if (ref->reuse_distance > dist)
1650 ref->reuse_distance = dist;
1651
1652 if (no_other_refs)
1653 ref->independent_p = true;
1654 }
1655
1656 if (!compute_all_dependences (datarefs, &dependences, vloops, true))
1657 return false;
1658
1659 FOR_EACH_VEC_ELT (dependences, i, dep)
1660 {
1661 if (DDR_ARE_DEPENDENT (dep) == chrec_known)
1662 continue;
1663
1664 ref = (struct mem_ref *) DDR_A (dep)->aux;
1665 refb = (struct mem_ref *) DDR_B (dep)->aux;
1666
1667 if (DDR_ARE_DEPENDENT (dep) == chrec_dont_know
1668 || DDR_NUM_DIST_VECTS (dep) == 0)
1669 {
1670 /* If the dependence cannot be analyzed, assume that there might be
1671 a reuse. */
1672 dist = 0;
1673
1674 ref->independent_p = false;
1675 refb->independent_p = false;
1676 }
1677 else
1678 {
1679 /* The distance vectors are normalized to be always lexicographically
1680 positive, hence we cannot tell just from them whether DDR_A comes
1681 before DDR_B or vice versa. However, it is not important,
1682 anyway -- if DDR_A is close to DDR_B, then it is either reused in
1683 DDR_B (and it is not nontemporal), or it reuses the value of DDR_B
1684 in cache (and marking it as nontemporal would not affect
1685 anything). */
1686
1687 dist = volume;
1688 for (j = 0; j < DDR_NUM_DIST_VECTS (dep); j++)
1689 {
1690 adist = volume_of_dist_vector (DDR_DIST_VECT (dep, j),
1691 loop_data_size, n);
1692
1693 /* If this is a dependence in the innermost loop (i.e., the
1694 distances in all superloops are zero) and it is not
1695 the trivial self-dependence with distance zero, record that
1696 the references are not completely independent. */
1697 if (lambda_vector_zerop (DDR_DIST_VECT (dep, j), n - 1)
1698 && (ref != refb
1699 || DDR_DIST_VECT (dep, j)[n-1] != 0))
1700 {
1701 ref->independent_p = false;
1702 refb->independent_p = false;
1703 }
1704
1705 /* Ignore accesses closer than
1706 L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION,
1707 so that we use nontemporal prefetches e.g. if single memory
1708 location is accessed several times in a single iteration of
1709 the loop. */
1710 if (adist < L1_CACHE_SIZE_BYTES / NONTEMPORAL_FRACTION)
1711 continue;
1712
1713 if (adist < dist)
1714 dist = adist;
1715 }
1716 }
1717
1718 if (ref->reuse_distance > dist)
1719 ref->reuse_distance = dist;
1720 if (refb->reuse_distance > dist)
1721 refb->reuse_distance = dist;
1722 }
1723
1724 free_dependence_relations (dependences);
1725 free_data_refs (datarefs);
1726 free (loop_data_size);
1727
1728 if (dump_file && (dump_flags & TDF_DETAILS))
1729 {
1730 fprintf (dump_file, "Reuse distances:\n");
1731 for (gr = refs; gr; gr = gr->next)
1732 for (ref = gr->refs; ref; ref = ref->next)
1733 fprintf (dump_file, " ref %p distance %u\n",
1734 (void *) ref, ref->reuse_distance);
1735 }
1736
1737 return true;
1738 }
1739
1740 /* Determine whether or not the trip count to ahead ratio is too small based
1741 on prefitablility consideration.
1742 AHEAD: the iteration ahead distance,
1743 EST_NITER: the estimated trip count. */
1744
1745 static bool
1746 trip_count_to_ahead_ratio_too_small_p (unsigned ahead, HOST_WIDE_INT est_niter)
1747 {
1748 /* Assume trip count to ahead ratio is big enough if the trip count could not
1749 be estimated at compile time. */
1750 if (est_niter < 0)
1751 return false;
1752
1753 if (est_niter < (HOST_WIDE_INT) (TRIP_COUNT_TO_AHEAD_RATIO * ahead))
1754 {
1755 if (dump_file && (dump_flags & TDF_DETAILS))
1756 fprintf (dump_file,
1757 "Not prefetching -- loop estimated to roll only %d times\n",
1758 (int) est_niter);
1759 return true;
1760 }
1761
1762 return false;
1763 }
1764
1765 /* Determine whether or not the number of memory references in the loop is
1766 reasonable based on the profitablity and compilation time considerations.
1767 NINSNS: estimated number of instructions in the loop,
1768 MEM_REF_COUNT: total number of memory references in the loop. */
1769
1770 static bool
1771 mem_ref_count_reasonable_p (unsigned ninsns, unsigned mem_ref_count)
1772 {
1773 int insn_to_mem_ratio;
1774
1775 if (mem_ref_count == 0)
1776 return false;
1777
1778 /* Miss rate computation (is_miss_rate_acceptable) and dependence analysis
1779 (compute_all_dependences) have high costs based on quadratic complexity.
1780 To avoid huge compilation time, we give up prefetching if mem_ref_count
1781 is too large. */
1782 if (mem_ref_count > PREFETCH_MAX_MEM_REFS_PER_LOOP)
1783 return false;
1784
1785 /* Prefetching improves performance by overlapping cache missing
1786 memory accesses with CPU operations. If the loop does not have
1787 enough CPU operations to overlap with memory operations, prefetching
1788 won't give a significant benefit. One approximate way of checking
1789 this is to require the ratio of instructions to memory references to
1790 be above a certain limit. This approximation works well in practice.
1791 TODO: Implement a more precise computation by estimating the time
1792 for each CPU or memory op in the loop. Time estimates for memory ops
1793 should account for cache misses. */
1794 insn_to_mem_ratio = ninsns / mem_ref_count;
1795
1796 if (insn_to_mem_ratio < PREFETCH_MIN_INSN_TO_MEM_RATIO)
1797 {
1798 if (dump_file && (dump_flags & TDF_DETAILS))
1799 fprintf (dump_file,
1800 "Not prefetching -- instruction to memory reference ratio (%d) too small\n",
1801 insn_to_mem_ratio);
1802 return false;
1803 }
1804
1805 return true;
1806 }
1807
1808 /* Determine whether or not the instruction to prefetch ratio in the loop is
1809 too small based on the profitablity consideration.
1810 NINSNS: estimated number of instructions in the loop,
1811 PREFETCH_COUNT: an estimate of the number of prefetches,
1812 UNROLL_FACTOR: the factor to unroll the loop if prefetching. */
1813
1814 static bool
1815 insn_to_prefetch_ratio_too_small_p (unsigned ninsns, unsigned prefetch_count,
1816 unsigned unroll_factor)
1817 {
1818 int insn_to_prefetch_ratio;
1819
1820 /* Prefetching most likely causes performance degradation when the instruction
1821 to prefetch ratio is too small. Too many prefetch instructions in a loop
1822 may reduce the I-cache performance.
1823 (unroll_factor * ninsns) is used to estimate the number of instructions in
1824 the unrolled loop. This implementation is a bit simplistic -- the number
1825 of issued prefetch instructions is also affected by unrolling. So,
1826 prefetch_mod and the unroll factor should be taken into account when
1827 determining prefetch_count. Also, the number of insns of the unrolled
1828 loop will usually be significantly smaller than the number of insns of the
1829 original loop * unroll_factor (at least the induction variable increases
1830 and the exit branches will get eliminated), so it might be better to use
1831 tree_estimate_loop_size + estimated_unrolled_size. */
1832 insn_to_prefetch_ratio = (unroll_factor * ninsns) / prefetch_count;
1833 if (insn_to_prefetch_ratio < MIN_INSN_TO_PREFETCH_RATIO)
1834 {
1835 if (dump_file && (dump_flags & TDF_DETAILS))
1836 fprintf (dump_file,
1837 "Not prefetching -- instruction to prefetch ratio (%d) too small\n",
1838 insn_to_prefetch_ratio);
1839 return true;
1840 }
1841
1842 return false;
1843 }
1844
1845
1846 /* Issue prefetch instructions for array references in LOOP. Returns
1847 true if the LOOP was unrolled. */
1848
1849 static bool
1850 loop_prefetch_arrays (struct loop *loop)
1851 {
1852 struct mem_ref_group *refs;
1853 unsigned ahead, ninsns, time, unroll_factor;
1854 HOST_WIDE_INT est_niter;
1855 struct tree_niter_desc desc;
1856 bool unrolled = false, no_other_refs;
1857 unsigned prefetch_count;
1858 unsigned mem_ref_count;
1859
1860 if (optimize_loop_nest_for_size_p (loop))
1861 {
1862 if (dump_file && (dump_flags & TDF_DETAILS))
1863 fprintf (dump_file, " ignored (cold area)\n");
1864 return false;
1865 }
1866
1867 /* FIXME: the time should be weighted by the probabilities of the blocks in
1868 the loop body. */
1869 time = tree_num_loop_insns (loop, &eni_time_weights);
1870 if (time == 0)
1871 return false;
1872
1873 ahead = (PREFETCH_LATENCY + time - 1) / time;
1874 est_niter = estimated_stmt_executions_int (loop);
1875 if (est_niter == -1)
1876 est_niter = max_stmt_executions_int (loop);
1877
1878 /* Prefetching is not likely to be profitable if the trip count to ahead
1879 ratio is too small. */
1880 if (trip_count_to_ahead_ratio_too_small_p (ahead, est_niter))
1881 return false;
1882
1883 ninsns = tree_num_loop_insns (loop, &eni_size_weights);
1884
1885 /* Step 1: gather the memory references. */
1886 refs = gather_memory_references (loop, &no_other_refs, &mem_ref_count);
1887
1888 /* Give up prefetching if the number of memory references in the
1889 loop is not reasonable based on profitablity and compilation time
1890 considerations. */
1891 if (!mem_ref_count_reasonable_p (ninsns, mem_ref_count))
1892 goto fail;
1893
1894 /* Step 2: estimate the reuse effects. */
1895 prune_by_reuse (refs);
1896
1897 if (nothing_to_prefetch_p (refs))
1898 goto fail;
1899
1900 if (!determine_loop_nest_reuse (loop, refs, no_other_refs))
1901 goto fail;
1902
1903 /* Step 3: determine unroll factor. */
1904 unroll_factor = determine_unroll_factor (loop, refs, ninsns, &desc,
1905 est_niter);
1906
1907 /* Estimate prefetch count for the unrolled loop. */
1908 prefetch_count = estimate_prefetch_count (refs, unroll_factor);
1909 if (prefetch_count == 0)
1910 goto fail;
1911
1912 if (dump_file && (dump_flags & TDF_DETAILS))
1913 fprintf (dump_file, "Ahead %d, unroll factor %d, trip count "
1914 HOST_WIDE_INT_PRINT_DEC "\n"
1915 "insn count %d, mem ref count %d, prefetch count %d\n",
1916 ahead, unroll_factor, est_niter,
1917 ninsns, mem_ref_count, prefetch_count);
1918
1919 /* Prefetching is not likely to be profitable if the instruction to prefetch
1920 ratio is too small. */
1921 if (insn_to_prefetch_ratio_too_small_p (ninsns, prefetch_count,
1922 unroll_factor))
1923 goto fail;
1924
1925 mark_nontemporal_stores (loop, refs);
1926
1927 /* Step 4: what to prefetch? */
1928 if (!schedule_prefetches (refs, unroll_factor, ahead))
1929 goto fail;
1930
1931 /* Step 5: unroll the loop. TODO -- peeling of first and last few
1932 iterations so that we do not issue superfluous prefetches. */
1933 if (unroll_factor != 1)
1934 {
1935 tree_unroll_loop (loop, unroll_factor,
1936 single_dom_exit (loop), &desc);
1937 unrolled = true;
1938 }
1939
1940 /* Step 6: issue the prefetches. */
1941 issue_prefetches (refs, unroll_factor, ahead);
1942
1943 fail:
1944 release_mem_refs (refs);
1945 return unrolled;
1946 }
1947
1948 /* Issue prefetch instructions for array references in loops. */
1949
1950 unsigned int
1951 tree_ssa_prefetch_arrays (void)
1952 {
1953 struct loop *loop;
1954 bool unrolled = false;
1955 int todo_flags = 0;
1956
1957 if (!HAVE_prefetch
1958 /* It is possible to ask compiler for say -mtune=i486 -march=pentium4.
1959 -mtune=i486 causes us having PREFETCH_BLOCK 0, since this is part
1960 of processor costs and i486 does not have prefetch, but
1961 -march=pentium4 causes HAVE_prefetch to be true. Ugh. */
1962 || PREFETCH_BLOCK == 0)
1963 return 0;
1964
1965 if (dump_file && (dump_flags & TDF_DETAILS))
1966 {
1967 fprintf (dump_file, "Prefetching parameters:\n");
1968 fprintf (dump_file, " simultaneous prefetches: %d\n",
1969 SIMULTANEOUS_PREFETCHES);
1970 fprintf (dump_file, " prefetch latency: %d\n", PREFETCH_LATENCY);
1971 fprintf (dump_file, " prefetch block size: %d\n", PREFETCH_BLOCK);
1972 fprintf (dump_file, " L1 cache size: %d lines, %d kB\n",
1973 L1_CACHE_SIZE_BYTES / L1_CACHE_LINE_SIZE, L1_CACHE_SIZE);
1974 fprintf (dump_file, " L1 cache line size: %d\n", L1_CACHE_LINE_SIZE);
1975 fprintf (dump_file, " L2 cache size: %d kB\n", L2_CACHE_SIZE);
1976 fprintf (dump_file, " min insn-to-prefetch ratio: %d \n",
1977 MIN_INSN_TO_PREFETCH_RATIO);
1978 fprintf (dump_file, " min insn-to-mem ratio: %d \n",
1979 PREFETCH_MIN_INSN_TO_MEM_RATIO);
1980 fprintf (dump_file, "\n");
1981 }
1982
1983 initialize_original_copy_tables ();
1984
1985 if (!builtin_decl_explicit_p (BUILT_IN_PREFETCH))
1986 {
1987 tree type = build_function_type_list (void_type_node,
1988 const_ptr_type_node, NULL_TREE);
1989 tree decl = add_builtin_function ("__builtin_prefetch", type,
1990 BUILT_IN_PREFETCH, BUILT_IN_NORMAL,
1991 NULL, NULL_TREE);
1992 DECL_IS_NOVOPS (decl) = true;
1993 set_builtin_decl (BUILT_IN_PREFETCH, decl, false);
1994 }
1995
1996 /* We assume that size of cache line is a power of two, so verify this
1997 here. */
1998 gcc_assert ((PREFETCH_BLOCK & (PREFETCH_BLOCK - 1)) == 0);
1999
2000 FOR_EACH_LOOP (loop, LI_FROM_INNERMOST)
2001 {
2002 if (dump_file && (dump_flags & TDF_DETAILS))
2003 fprintf (dump_file, "Processing loop %d:\n", loop->num);
2004
2005 unrolled |= loop_prefetch_arrays (loop);
2006
2007 if (dump_file && (dump_flags & TDF_DETAILS))
2008 fprintf (dump_file, "\n\n");
2009 }
2010
2011 if (unrolled)
2012 {
2013 scev_reset ();
2014 todo_flags |= TODO_cleanup_cfg;
2015 }
2016
2017 free_original_copy_tables ();
2018 return todo_flags;
2019 }
2020
2021 /* Prefetching. */
2022
2023 namespace {
2024
2025 const pass_data pass_data_loop_prefetch =
2026 {
2027 GIMPLE_PASS, /* type */
2028 "aprefetch", /* name */
2029 OPTGROUP_LOOP, /* optinfo_flags */
2030 TV_TREE_PREFETCH, /* tv_id */
2031 ( PROP_cfg | PROP_ssa ), /* properties_required */
2032 0, /* properties_provided */
2033 0, /* properties_destroyed */
2034 0, /* todo_flags_start */
2035 0, /* todo_flags_finish */
2036 };
2037
2038 class pass_loop_prefetch : public gimple_opt_pass
2039 {
2040 public:
2041 pass_loop_prefetch (gcc::context *ctxt)
2042 : gimple_opt_pass (pass_data_loop_prefetch, ctxt)
2043 {}
2044
2045 /* opt_pass methods: */
2046 virtual bool gate (function *) { return flag_prefetch_loop_arrays > 0; }
2047 virtual unsigned int execute (function *);
2048
2049 }; // class pass_loop_prefetch
2050
2051 unsigned int
2052 pass_loop_prefetch::execute (function *fun)
2053 {
2054 if (number_of_loops (fun) <= 1)
2055 return 0;
2056
2057 return tree_ssa_prefetch_arrays ();
2058 }
2059
2060 } // anon namespace
2061
2062 gimple_opt_pass *
2063 make_pass_loop_prefetch (gcc::context *ctxt)
2064 {
2065 return new pass_loop_prefetch (ctxt);
2066 }
2067
2068