OSDN Git Service

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