blob: 3770953b1a576226a2f1b11575a6455567c95f89 [file] [log] [blame]
Michael Kruse138a3fb2017-08-04 22:51:23 +00001//===------ ZoneAlgo.cpp ----------------------------------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Derive information about array elements between statements ("Zones").
11//
12// The algorithms here work on the scatter space - the image space of the
13// schedule returned by Scop::getSchedule(). We call an element in that space a
14// "timepoint". Timepoints are lexicographically ordered such that we can
15// defined ranges in the scatter space. We use two flavors of such ranges:
16// Timepoint sets and zones. A timepoint set is simply a subset of the scatter
17// space and is directly stored as isl_set.
18//
19// Zones are used to describe the space between timepoints as open sets, i.e.
20// they do not contain the extrema. Using isl rational sets to express these
21// would be overkill. We also cannot store them as the integer timepoints they
22// contain; the (nonempty) zone between 1 and 2 would be empty and
23// indistinguishable from e.g. the zone between 3 and 4. Also, we cannot store
24// the integer set including the extrema; the set ]1,2[ + ]3,4[ could be
25// coalesced to ]1,3[, although we defined the range [2,3] to be not in the set.
26// Instead, we store the "half-open" integer extrema, including the lower bound,
27// but excluding the upper bound. Examples:
28//
29// * The set { [i] : 1 <= i <= 3 } represents the zone ]0,3[ (which contains the
30// integer points 1 and 2, but not 0 or 3)
31//
32// * { [1] } represents the zone ]0,1[
33//
34// * { [i] : i = 1 or i = 3 } represents the zone ]0,1[ + ]2,3[
35//
36// Therefore, an integer i in the set represents the zone ]i-1,i[, i.e. strictly
37// speaking the integer points never belong to the zone. However, depending an
38// the interpretation, one might want to include them. Part of the
39// interpretation may not be known when the zone is constructed.
40//
41// Reads are assumed to always take place before writes, hence we can think of
42// reads taking place at the beginning of a timepoint and writes at the end.
43//
44// Let's assume that the zone represents the lifetime of a variable. That is,
45// the zone begins with a write that defines the value during its lifetime and
46// ends with the last read of that value. In the following we consider whether a
47// read/write at the beginning/ending of the lifetime zone should be within the
48// zone or outside of it.
49//
50// * A read at the timepoint that starts the live-range loads the previous
51// value. Hence, exclude the timepoint starting the zone.
52//
53// * A write at the timepoint that starts the live-range is not defined whether
54// it occurs before or after the write that starts the lifetime. We do not
55// allow this situation to occur. Hence, we include the timepoint starting the
56// zone to determine whether they are conflicting.
57//
58// * A read at the timepoint that ends the live-range reads the same variable.
59// We include the timepoint at the end of the zone to include that read into
60// the live-range. Doing otherwise would mean that the two reads access
61// different values, which would mean that the value they read are both alive
62// at the same time but occupy the same variable.
63//
64// * A write at the timepoint that ends the live-range starts a new live-range.
65// It must not be included in the live-range of the previous definition.
66//
67// All combinations of reads and writes at the endpoints are possible, but most
68// of the time only the write->read (for instance, a live-range from definition
69// to last use) and read->write (for instance, an unused range from last use to
70// overwrite) and combinations are interesting (half-open ranges). write->write
71// zones might be useful as well in some context to represent
72// output-dependencies.
73//
74// @see convertZoneToTimepoints
75//
76//
77// The code makes use of maps and sets in many different spaces. To not loose
78// track in which space a set or map is expected to be in, variables holding an
79// isl reference are usually annotated in the comments. They roughly follow isl
80// syntax for spaces, but only the tuples, not the dimensions. The tuples have a
81// meaning as follows:
82//
83// * Space[] - An unspecified tuple. Used for function parameters such that the
84// function caller can use it for anything they like.
85//
86// * Domain[] - A statement instance as returned by ScopStmt::getDomain()
87// isl_id_get_name: Stmt_<NameOfBasicBlock>
88// isl_id_get_user: Pointer to ScopStmt
89//
90// * Element[] - An array element as in the range part of
91// MemoryAccess::getAccessRelation()
92// isl_id_get_name: MemRef_<NameOfArrayVariable>
93// isl_id_get_user: Pointer to ScopArrayInfo
94//
95// * Scatter[] - Scatter space or space of timepoints
96// Has no tuple id
97//
98// * Zone[] - Range between timepoints as described above
99// Has no tuple id
100//
101// * ValInst[] - An llvm::Value as defined at a specific timepoint.
102//
103// A ValInst[] itself can be structured as one of:
104//
105// * [] - An unknown value.
106// Always zero dimensions
107// Has no tuple id
108//
109// * Value[] - An llvm::Value that is read-only in the SCoP, i.e. its
110// runtime content does not depend on the timepoint.
111// Always zero dimensions
112// isl_id_get_name: Val_<NameOfValue>
113// isl_id_get_user: A pointer to an llvm::Value
114//
115// * SCEV[...] - A synthesizable llvm::SCEV Expression.
116// In contrast to a Value[] is has at least one dimension per
117// SCEVAddRecExpr in the SCEV.
118//
119// * [Domain[] -> Value[]] - An llvm::Value that may change during the
120// Scop's execution.
121// The tuple itself has no id, but it wraps a map space holding a
122// statement instance which defines the llvm::Value as the map's domain
123// and llvm::Value itself as range.
124//
125// @see makeValInst()
126//
127// An annotation "{ Domain[] -> Scatter[] }" therefore means: A map from a
128// statement instance to a timepoint, aka a schedule. There is only one scatter
129// space, but most of the time multiple statements are processed in one set.
130// This is why most of the time isl_union_map has to be used.
131//
132// The basic algorithm works as follows:
133// At first we verify that the SCoP is compatible with this technique. For
134// instance, two writes cannot write to the same location at the same statement
135// instance because we cannot determine within the polyhedral model which one
136// comes first. Once this was verified, we compute zones at which an array
137// element is unused. This computation can fail if it takes too long. Then the
138// main algorithm is executed. Because every store potentially trails an unused
139// zone, we start at stores. We search for a scalar (MemoryKind::Value or
140// MemoryKind::PHI) that we can map to the array element overwritten by the
141// store, preferably one that is used by the store or at least the ScopStmt.
142// When it does not conflict with the lifetime of the values in the array
143// element, the map is applied and the unused zone updated as it is now used. We
144// continue to try to map scalars to the array element until there are no more
145// candidates to map. The algorithm is greedy in the sense that the first scalar
146// not conflicting will be mapped. Other scalars processed later that could have
147// fit the same unused zone will be rejected. As such the result depends on the
148// processing order.
149//
150//===----------------------------------------------------------------------===//
151
152#include "polly/ZoneAlgo.h"
153#include "polly/ScopInfo.h"
154#include "polly/Support/GICHelper.h"
155#include "polly/Support/ISLTools.h"
156#include "polly/Support/VirtualInstruction.h"
Michael Kruse47281842017-08-28 20:39:07 +0000157#include "llvm/ADT/Statistic.h"
Zhaoshi Zhengceec1752017-11-17 22:05:19 +0000158#include "llvm/Support/raw_ostream.h"
Michael Kruse138a3fb2017-08-04 22:51:23 +0000159
160#define DEBUG_TYPE "polly-zone"
161
Michael Kruse47281842017-08-28 20:39:07 +0000162STATISTIC(NumIncompatibleArrays, "Number of not zone-analyzable arrays");
163STATISTIC(NumCompatibleArrays, "Number of zone-analyzable arrays");
Michael Kruse68821a82017-10-31 16:11:46 +0000164STATISTIC(NumRecursivePHIs, "Number of recursive PHIs");
165STATISTIC(NumNormalizablePHIs, "Number of normalizable PHIs");
166STATISTIC(NumPHINormialization, "Number of PHI executed normalizations");
Michael Kruse47281842017-08-28 20:39:07 +0000167
Michael Kruse138a3fb2017-08-04 22:51:23 +0000168using namespace polly;
169using namespace llvm;
170
171static isl::union_map computeReachingDefinition(isl::union_map Schedule,
172 isl::union_map Writes,
173 bool InclDef, bool InclRedef) {
174 return computeReachingWrite(Schedule, Writes, false, InclDef, InclRedef);
175}
176
177/// Compute the reaching definition of a scalar.
178///
179/// Compared to computeReachingDefinition, there is just one element which is
180/// accessed and therefore only a set if instances that accesses that element is
181/// required.
182///
183/// @param Schedule { DomainWrite[] -> Scatter[] }
184/// @param Writes { DomainWrite[] }
185/// @param InclDef Include the timepoint of the definition to the result.
186/// @param InclRedef Include the timepoint of the overwrite into the result.
187///
188/// @return { Scatter[] -> DomainWrite[] }
189static isl::union_map computeScalarReachingDefinition(isl::union_map Schedule,
190 isl::union_set Writes,
191 bool InclDef,
192 bool InclRedef) {
Michael Kruse138a3fb2017-08-04 22:51:23 +0000193 // { DomainWrite[] -> Element[] }
Tobias Grosser0dd42512017-08-21 14:19:40 +0000194 isl::union_map Defs = isl::union_map::from_domain(Writes);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000195
196 // { [Element[] -> Scatter[]] -> DomainWrite[] }
197 auto ReachDefs =
198 computeReachingDefinition(Schedule, Defs, InclDef, InclRedef);
199
200 // { Scatter[] -> DomainWrite[] }
Tobias Grosser0dd42512017-08-21 14:19:40 +0000201 return ReachDefs.curry().range().unwrap();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000202}
203
204/// Compute the reaching definition of a scalar.
205///
206/// This overload accepts only a single writing statement as an isl_map,
207/// consequently the result also is only a single isl_map.
208///
209/// @param Schedule { DomainWrite[] -> Scatter[] }
210/// @param Writes { DomainWrite[] }
211/// @param InclDef Include the timepoint of the definition to the result.
212/// @param InclRedef Include the timepoint of the overwrite into the result.
213///
214/// @return { Scatter[] -> DomainWrite[] }
215static isl::map computeScalarReachingDefinition(isl::union_map Schedule,
216 isl::set Writes, bool InclDef,
217 bool InclRedef) {
Tobias Grosser0dd42512017-08-21 14:19:40 +0000218 isl::space DomainSpace = Writes.get_space();
219 isl::space ScatterSpace = getScatterSpace(Schedule);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000220
221 // { Scatter[] -> DomainWrite[] }
Tobias Grosser0dd42512017-08-21 14:19:40 +0000222 isl::union_map UMap = computeScalarReachingDefinition(
223 Schedule, isl::union_set(Writes), InclDef, InclRedef);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000224
Tobias Grosser0dd42512017-08-21 14:19:40 +0000225 isl::space ResultSpace = ScatterSpace.map_from_domain_and_range(DomainSpace);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000226 return singleton(UMap, ResultSpace);
227}
228
229isl::union_map polly::makeUnknownForDomain(isl::union_set Domain) {
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000230 return isl::union_map::from_domain(Domain);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000231}
232
233/// Create a domain-to-unknown value mapping.
234///
235/// @see makeUnknownForDomain(isl::union_set)
236///
237/// @param Domain { Domain[] }
238///
239/// @return { Domain[] -> ValInst[] }
240static isl::map makeUnknownForDomain(isl::set Domain) {
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000241 return isl::map::from_domain(Domain);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000242}
243
Michael Kruse70af4f52017-08-07 18:40:29 +0000244/// Return whether @p Map maps to an unknown value.
245///
246/// @param { [] -> ValInst[] }
247static bool isMapToUnknown(const isl::map &Map) {
248 isl::space Space = Map.get_space().range();
249 return Space.has_tuple_id(isl::dim::set).is_false() &&
250 Space.is_wrapping().is_false() && Space.dim(isl::dim::set) == 0;
251}
252
Michael Krusece673582017-08-08 17:00:27 +0000253isl::union_map polly::filterKnownValInst(const isl::union_map &UMap) {
Michael Kruse70af4f52017-08-07 18:40:29 +0000254 isl::union_map Result = isl::union_map::empty(UMap.get_space());
Michael Kruse630fc7b2017-08-09 11:21:40 +0000255 isl::stat Success = UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
Michael Kruse70af4f52017-08-07 18:40:29 +0000256 if (!isMapToUnknown(Map))
257 Result = Result.add_map(Map);
258 return isl::stat::ok;
259 });
Michael Kruse630fc7b2017-08-09 11:21:40 +0000260 if (Success != isl::stat::ok)
261 return {};
Michael Kruse70af4f52017-08-07 18:40:29 +0000262 return Result;
263}
264
Michael Kruse138a3fb2017-08-04 22:51:23 +0000265ZoneAlgorithm::ZoneAlgorithm(const char *PassName, Scop *S, LoopInfo *LI)
266 : PassName(PassName), IslCtx(S->getSharedIslCtx()), S(S), LI(LI),
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000267 Schedule(S->getSchedule()) {
Tobias Grosser31df6f32017-08-06 21:42:25 +0000268 auto Domains = S->getDomains();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000269
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000270 Schedule = Schedule.intersect_domain(Domains);
271 ParamSpace = Schedule.get_space();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000272 ScatterSpace = getScatterSpace(Schedule);
273}
274
Tobias Grosser2ef37812017-08-07 22:01:29 +0000275/// Check if all stores in @p Stmt store the very same value.
276///
Michael Kruse8756b3f2017-08-09 09:29:15 +0000277/// This covers a special situation occurring in Polybench's
278/// covariance/correlation (which is typical for algorithms that cover symmetric
279/// matrices):
280///
281/// for (int i = 0; i < n; i += 1)
282/// for (int j = 0; j <= i; j += 1) {
283/// double x = ...;
284/// C[i][j] = x;
285/// C[j][i] = x;
286/// }
287///
288/// For i == j, the same value is written twice to the same element.Double
289/// writes to the same element are not allowed in DeLICM because its algorithm
290/// does not see which of the writes is effective.But if its the same value
291/// anyway, it doesn't matter.
292///
293/// LLVM passes, however, cannot simplify this because the write is necessary
294/// for i != j (unless it would add a condition for one of the writes to occur
295/// only if i != j).
296///
Tobias Grosser2ef37812017-08-07 22:01:29 +0000297/// TODO: In the future we may want to extent this to make the checks
298/// specific to different memory locations.
299static bool onlySameValueWrites(ScopStmt *Stmt) {
300 Value *V = nullptr;
301
302 for (auto *MA : *Stmt) {
303 if (!MA->isLatestArrayKind() || !MA->isMustWrite() ||
304 !MA->isOriginalArrayKind())
305 continue;
306
307 if (!V) {
308 V = MA->getAccessValue();
309 continue;
310 }
311
312 if (V != MA->getAccessValue())
313 return false;
314 }
315 return true;
316}
317
Michael Kruse47281842017-08-28 20:39:07 +0000318void ZoneAlgorithm::collectIncompatibleElts(ScopStmt *Stmt,
319 isl::union_set &IncompatibleElts,
320 isl::union_set &AllElts) {
Michael Kruse138a3fb2017-08-04 22:51:23 +0000321 auto Stores = makeEmptyUnionMap();
322 auto Loads = makeEmptyUnionMap();
323
324 // This assumes that the MemoryKind::Array MemoryAccesses are iterated in
325 // order.
326 for (auto *MA : *Stmt) {
Michael Kruseff426d92017-10-31 12:50:25 +0000327 if (!MA->isOriginalArrayKind())
Michael Kruse138a3fb2017-08-04 22:51:23 +0000328 continue;
329
Michael Kruse47281842017-08-28 20:39:07 +0000330 isl::map AccRelMap = getAccessRelationFor(MA);
331 isl::union_map AccRel = AccRelMap;
332
333 // To avoid solving any ILP problems, always add entire arrays instead of
334 // just the elements that are accessed.
335 auto ArrayElts = isl::set::universe(AccRelMap.get_space().range());
336 AllElts = AllElts.add_set(ArrayElts);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000337
338 if (MA->isRead()) {
339 // Reject load after store to same location.
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +0000340 if (!Stores.is_disjoint(AccRel)) {
Michael Krusee983e6b2017-08-28 11:22:23 +0000341 DEBUG(dbgs() << "Load after store of same element in same statement\n");
Michael Kruse138a3fb2017-08-04 22:51:23 +0000342 OptimizationRemarkMissed R(PassName, "LoadAfterStore",
343 MA->getAccessInstruction());
344 R << "load after store of same element in same statement";
345 R << " (previous stores: " << Stores;
346 R << ", loading: " << AccRel << ")";
347 S->getFunction().getContext().diagnose(R);
Michael Kruse47281842017-08-28 20:39:07 +0000348
349 IncompatibleElts = IncompatibleElts.add_set(ArrayElts);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000350 }
351
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000352 Loads = Loads.unite(AccRel);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000353
354 continue;
355 }
356
Michael Kruse138a3fb2017-08-04 22:51:23 +0000357 // In region statements the order is less clear, eg. the load and store
358 // might be in a boxed loop.
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +0000359 if (Stmt->isRegionStmt() && !Loads.is_disjoint(AccRel)) {
Michael Krusee983e6b2017-08-28 11:22:23 +0000360 DEBUG(dbgs() << "WRITE in non-affine subregion not supported\n");
Michael Kruse138a3fb2017-08-04 22:51:23 +0000361 OptimizationRemarkMissed R(PassName, "StoreInSubregion",
362 MA->getAccessInstruction());
363 R << "store is in a non-affine subregion";
364 S->getFunction().getContext().diagnose(R);
Michael Kruse47281842017-08-28 20:39:07 +0000365
366 IncompatibleElts = IncompatibleElts.add_set(ArrayElts);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000367 }
368
369 // Do not allow more than one store to the same location.
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +0000370 if (!Stores.is_disjoint(AccRel) && !onlySameValueWrites(Stmt)) {
Michael Krusee983e6b2017-08-28 11:22:23 +0000371 DEBUG(dbgs() << "WRITE after WRITE to same element\n");
Michael Kruse138a3fb2017-08-04 22:51:23 +0000372 OptimizationRemarkMissed R(PassName, "StoreAfterStore",
373 MA->getAccessInstruction());
Michael Krusea9033aa2017-08-09 09:29:09 +0000374 R << "store after store of same element in same statement";
375 R << " (previous stores: " << Stores;
376 R << ", storing: " << AccRel << ")";
377 S->getFunction().getContext().diagnose(R);
Michael Kruse47281842017-08-28 20:39:07 +0000378
379 IncompatibleElts = IncompatibleElts.add_set(ArrayElts);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000380 }
381
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000382 Stores = Stores.unite(AccRel);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000383 }
Michael Kruse138a3fb2017-08-04 22:51:23 +0000384}
385
386void ZoneAlgorithm::addArrayReadAccess(MemoryAccess *MA) {
387 assert(MA->isLatestArrayKind());
388 assert(MA->isRead());
Michael Kruse70af4f52017-08-07 18:40:29 +0000389 ScopStmt *Stmt = MA->getStatement();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000390
391 // { DomainRead[] -> Element[] }
Michael Kruse47281842017-08-28 20:39:07 +0000392 auto AccRel = intersectRange(getAccessRelationFor(MA), CompatibleElts);
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000393 AllReads = AllReads.add_map(AccRel);
Michael Kruse70af4f52017-08-07 18:40:29 +0000394
395 if (LoadInst *Load = dyn_cast_or_null<LoadInst>(MA->getAccessInstruction())) {
396 // { DomainRead[] -> ValInst[] }
397 isl::map LoadValInst = makeValInst(
398 Load, Stmt, LI->getLoopFor(Load->getParent()), Stmt->isBlockStmt());
399
400 // { DomainRead[] -> [Element[] -> DomainRead[]] }
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000401 isl::map IncludeElement = AccRel.domain_map().curry();
Michael Kruse70af4f52017-08-07 18:40:29 +0000402
403 // { [Element[] -> DomainRead[]] -> ValInst[] }
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000404 isl::map EltLoadValInst = LoadValInst.apply_domain(IncludeElement);
Michael Kruse70af4f52017-08-07 18:40:29 +0000405
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000406 AllReadValInst = AllReadValInst.add_map(EltLoadValInst);
Michael Kruse70af4f52017-08-07 18:40:29 +0000407 }
Michael Kruse138a3fb2017-08-04 22:51:23 +0000408}
409
Michael Kruse68821a82017-10-31 16:11:46 +0000410isl::union_map ZoneAlgorithm::getWrittenValue(MemoryAccess *MA,
411 isl::map AccRel) {
Michael Krusebd84ce82017-09-06 12:40:55 +0000412 if (!MA->isMustWrite())
413 return {};
414
415 Value *AccVal = MA->getAccessValue();
416 ScopStmt *Stmt = MA->getStatement();
417 Instruction *AccInst = MA->getAccessInstruction();
418
419 // Write a value to a single element.
420 auto L = MA->isOriginalArrayKind() ? LI->getLoopFor(AccInst->getParent())
421 : Stmt->getSurroundingLoop();
422 if (AccVal &&
423 AccVal->getType() == MA->getLatestScopArrayInfo()->getElementType() &&
Michael Kruseef8325b2017-09-18 17:43:50 +0000424 AccRel.is_single_valued().is_true())
Michael Kruse68821a82017-10-31 16:11:46 +0000425 return makeNormalizedValInst(AccVal, Stmt, L);
Michael Krusebd84ce82017-09-06 12:40:55 +0000426
427 // memset(_, '0', ) is equivalent to writing the null value to all touched
428 // elements. isMustWrite() ensures that all of an element's bytes are
429 // overwritten.
430 if (auto *Memset = dyn_cast<MemSetInst>(AccInst)) {
431 auto *WrittenConstant = dyn_cast<Constant>(Memset->getValue());
432 Type *Ty = MA->getLatestScopArrayInfo()->getElementType();
433 if (WrittenConstant && WrittenConstant->isZeroValue()) {
434 Constant *Zero = Constant::getNullValue(Ty);
Michael Kruse68821a82017-10-31 16:11:46 +0000435 return makeNormalizedValInst(Zero, Stmt, L);
Michael Krusebd84ce82017-09-06 12:40:55 +0000436 }
437 }
438
439 return {};
440}
441
Michael Kruse138a3fb2017-08-04 22:51:23 +0000442void ZoneAlgorithm::addArrayWriteAccess(MemoryAccess *MA) {
443 assert(MA->isLatestArrayKind());
444 assert(MA->isWrite());
445 auto *Stmt = MA->getStatement();
446
447 // { Domain[] -> Element[] }
Michael Kruse983fa9b2017-10-24 16:40:34 +0000448 isl::map AccRel = intersectRange(getAccessRelationFor(MA), CompatibleElts);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000449
450 if (MA->isMustWrite())
Michael Kruse983fa9b2017-10-24 16:40:34 +0000451 AllMustWrites = AllMustWrites.add_map(AccRel);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000452
453 if (MA->isMayWrite())
Michael Kruse983fa9b2017-10-24 16:40:34 +0000454 AllMayWrites = AllMayWrites.add_map(AccRel);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000455
456 // { Domain[] -> ValInst[] }
Michael Kruse68821a82017-10-31 16:11:46 +0000457 isl::union_map WriteValInstance = getWrittenValue(MA, AccRel);
Michael Krusebd84ce82017-09-06 12:40:55 +0000458 if (!WriteValInstance)
459 WriteValInstance = makeUnknownForDomain(Stmt);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000460
461 // { Domain[] -> [Element[] -> Domain[]] }
Michael Kruse983fa9b2017-10-24 16:40:34 +0000462 isl::map IncludeElement = AccRel.domain_map().curry();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000463
464 // { [Element[] -> DomainWrite[]] -> ValInst[] }
Michael Kruse68821a82017-10-31 16:11:46 +0000465 isl::union_map EltWriteValInst =
466 WriteValInstance.apply_domain(IncludeElement);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000467
Michael Kruse68821a82017-10-31 16:11:46 +0000468 AllWriteValInst = AllWriteValInst.unite(EltWriteValInst);
469}
470
471/// Return whether @p PHI refers (also transitively through other PHIs) to
472/// itself.
473///
474/// loop:
475/// %phi1 = phi [0, %preheader], [%phi1, %loop]
476/// br i1 %c, label %loop, label %exit
477///
478/// exit:
479/// %phi2 = phi [%phi1, %bb]
480///
481/// In this example, %phi1 is recursive, but %phi2 is not.
482static bool isRecursivePHI(const PHINode *PHI) {
483 SmallVector<const PHINode *, 8> Worklist;
484 SmallPtrSet<const PHINode *, 8> Visited;
485 Worklist.push_back(PHI);
486
487 while (!Worklist.empty()) {
488 const PHINode *Cur = Worklist.pop_back_val();
489
490 if (Visited.count(Cur))
491 continue;
492 Visited.insert(Cur);
493
494 for (const Use &Incoming : Cur->incoming_values()) {
495 Value *IncomingVal = Incoming.get();
496 auto *IncomingPHI = dyn_cast<PHINode>(IncomingVal);
497 if (!IncomingPHI)
498 continue;
499
500 if (IncomingPHI == PHI)
501 return true;
502 Worklist.push_back(IncomingPHI);
503 }
504 }
505 return false;
506}
507
508isl::union_map ZoneAlgorithm::computePerPHI(const ScopArrayInfo *SAI) {
509 // TODO: If the PHI has an incoming block from before the SCoP, it is not
510 // represented in any ScopStmt.
511
512 auto *PHI = cast<PHINode>(SAI->getBasePtr());
513 auto It = PerPHIMaps.find(PHI);
514 if (It != PerPHIMaps.end())
515 return It->second;
516
517 assert(SAI->isPHIKind());
518
519 // { DomainPHIWrite[] -> Scatter[] }
520 isl::union_map PHIWriteScatter = makeEmptyUnionMap();
521
522 // Collect all incoming block timepoints.
523 for (MemoryAccess *MA : S->getPHIIncomings(SAI)) {
524 isl::map Scatter = getScatterFor(MA);
525 PHIWriteScatter = PHIWriteScatter.add_map(Scatter);
526 }
527
528 // { DomainPHIRead[] -> Scatter[] }
529 isl::map PHIReadScatter = getScatterFor(S->getPHIRead(SAI));
530
531 // { DomainPHIRead[] -> Scatter[] }
532 isl::map BeforeRead = beforeScatter(PHIReadScatter, true);
533
534 // { Scatter[] }
535 isl::set WriteTimes = singleton(PHIWriteScatter.range(), ScatterSpace);
536
537 // { DomainPHIRead[] -> Scatter[] }
538 isl::map PHIWriteTimes = BeforeRead.intersect_range(WriteTimes);
539 isl::map LastPerPHIWrites = PHIWriteTimes.lexmax();
540
541 // { DomainPHIRead[] -> DomainPHIWrite[] }
542 isl::union_map Result =
543 isl::union_map(LastPerPHIWrites).apply_range(PHIWriteScatter.reverse());
544 assert(!Result.is_single_valued().is_false());
545 assert(!Result.is_injective().is_false());
546
547 PerPHIMaps.insert({PHI, Result});
548 return Result;
Michael Kruse138a3fb2017-08-04 22:51:23 +0000549}
550
551isl::union_set ZoneAlgorithm::makeEmptyUnionSet() const {
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000552 return isl::union_set::empty(ParamSpace);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000553}
554
555isl::union_map ZoneAlgorithm::makeEmptyUnionMap() const {
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000556 return isl::union_map::empty(ParamSpace);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000557}
558
Michael Kruse47281842017-08-28 20:39:07 +0000559void ZoneAlgorithm::collectCompatibleElts() {
560 // First find all the incompatible elements, then take the complement.
561 // We compile the list of compatible (rather than incompatible) elements so
562 // users can intersect with the list, not requiring a subtract operation. It
563 // also allows us to define a 'universe' of all elements and makes it more
564 // explicit in which array elements can be used.
565 isl::union_set AllElts = makeEmptyUnionSet();
566 isl::union_set IncompatibleElts = makeEmptyUnionSet();
567
568 for (auto &Stmt : *S)
569 collectIncompatibleElts(&Stmt, IncompatibleElts, AllElts);
570
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +0000571 NumIncompatibleArrays += isl_union_set_n_set(IncompatibleElts.get());
Michael Kruse47281842017-08-28 20:39:07 +0000572 CompatibleElts = AllElts.subtract(IncompatibleElts);
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +0000573 NumCompatibleArrays += isl_union_set_n_set(CompatibleElts.get());
Michael Kruse138a3fb2017-08-04 22:51:23 +0000574}
575
576isl::map ZoneAlgorithm::getScatterFor(ScopStmt *Stmt) const {
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000577 isl::space ResultSpace =
578 Stmt->getDomainSpace().map_from_domain_and_range(ScatterSpace);
579 return Schedule.extract_map(ResultSpace);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000580}
581
582isl::map ZoneAlgorithm::getScatterFor(MemoryAccess *MA) const {
583 return getScatterFor(MA->getStatement());
584}
585
586isl::union_map ZoneAlgorithm::getScatterFor(isl::union_set Domain) const {
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000587 return Schedule.intersect_domain(Domain);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000588}
589
590isl::map ZoneAlgorithm::getScatterFor(isl::set Domain) const {
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000591 auto ResultSpace = Domain.get_space().map_from_domain_and_range(ScatterSpace);
592 auto UDomain = isl::union_set(Domain);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000593 auto UResult = getScatterFor(std::move(UDomain));
594 auto Result = singleton(std::move(UResult), std::move(ResultSpace));
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000595 assert(!Result || Result.domain().is_equal(Domain) == isl_bool_true);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000596 return Result;
597}
598
599isl::set ZoneAlgorithm::getDomainFor(ScopStmt *Stmt) const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000600 return Stmt->getDomain().remove_redundancies();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000601}
602
603isl::set ZoneAlgorithm::getDomainFor(MemoryAccess *MA) const {
604 return getDomainFor(MA->getStatement());
605}
606
607isl::map ZoneAlgorithm::getAccessRelationFor(MemoryAccess *MA) const {
608 auto Domain = getDomainFor(MA);
609 auto AccRel = MA->getLatestAccessRelation();
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000610 return AccRel.intersect_domain(Domain);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000611}
612
613isl::map ZoneAlgorithm::getScalarReachingDefinition(ScopStmt *Stmt) {
614 auto &Result = ScalarReachDefZone[Stmt];
615 if (Result)
616 return Result;
617
618 auto Domain = getDomainFor(Stmt);
619 Result = computeScalarReachingDefinition(Schedule, Domain, false, true);
620 simplify(Result);
621
622 return Result;
623}
624
625isl::map ZoneAlgorithm::getScalarReachingDefinition(isl::set DomainDef) {
Tobias Grosserdaf68ea2018-04-28 22:11:48 +0000626 auto DomId = DomainDef.get_tuple_id();
Tobias Grosserd3d3d6b2018-04-29 00:28:26 +0000627 auto *Stmt = static_cast<ScopStmt *>(isl_id_get_user(DomId.get()));
Michael Kruse138a3fb2017-08-04 22:51:23 +0000628
629 auto StmtResult = getScalarReachingDefinition(Stmt);
630
Tobias Grosserdaf68ea2018-04-28 22:11:48 +0000631 return StmtResult.intersect_range(DomainDef);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000632}
633
634isl::map ZoneAlgorithm::makeUnknownForDomain(ScopStmt *Stmt) const {
635 return ::makeUnknownForDomain(getDomainFor(Stmt));
636}
637
638isl::id ZoneAlgorithm::makeValueId(Value *V) {
639 if (!V)
640 return nullptr;
641
642 auto &Id = ValueIds[V];
643 if (Id.is_null()) {
644 auto Name = getIslCompatibleName("Val_", V, ValueIds.size() - 1,
645 std::string(), UseInstructionNames);
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000646 Id = isl::id::alloc(IslCtx.get(), Name.c_str(), V);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000647 }
648 return Id;
649}
650
651isl::space ZoneAlgorithm::makeValueSpace(Value *V) {
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000652 auto Result = ParamSpace.set_from_params();
653 return Result.set_tuple_id(isl::dim::set, makeValueId(V));
Michael Kruse138a3fb2017-08-04 22:51:23 +0000654}
655
656isl::set ZoneAlgorithm::makeValueSet(Value *V) {
657 auto Space = makeValueSpace(V);
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000658 return isl::set::universe(Space);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000659}
660
661isl::map ZoneAlgorithm::makeValInst(Value *Val, ScopStmt *UserStmt, Loop *Scope,
662 bool IsCertain) {
663 // If the definition/write is conditional, the value at the location could
664 // be either the written value or the old value. Since we cannot know which
665 // one, consider the value to be unknown.
666 if (!IsCertain)
667 return makeUnknownForDomain(UserStmt);
668
669 auto DomainUse = getDomainFor(UserStmt);
670 auto VUse = VirtualUse::create(S, UserStmt, Scope, Val, true);
671 switch (VUse.getKind()) {
672 case VirtualUse::Constant:
673 case VirtualUse::Block:
674 case VirtualUse::Hoisted:
675 case VirtualUse::ReadOnly: {
676 // The definition does not depend on the statement which uses it.
677 auto ValSet = makeValueSet(Val);
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000678 return isl::map::from_domain_and_range(DomainUse, ValSet);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000679 }
680
681 case VirtualUse::Synthesizable: {
682 auto *ScevExpr = VUse.getScevExpr();
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000683 auto UseDomainSpace = DomainUse.get_space();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000684
685 // Construct the SCEV space.
686 // TODO: Add only the induction variables referenced in SCEVAddRecExpr
687 // expressions, not just all of them.
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000688 auto ScevId = isl::manage(isl_id_alloc(
689 UseDomainSpace.get_ctx().get(), nullptr, const_cast<SCEV *>(ScevExpr)));
690
691 auto ScevSpace = UseDomainSpace.drop_dims(isl::dim::set, 0, 0);
692 ScevSpace = ScevSpace.set_tuple_id(isl::dim::set, ScevId);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000693
694 // { DomainUse[] -> ScevExpr[] }
Tobias Grosser2f549fd2018-04-28 21:22:17 +0000695 auto ValInst =
696 isl::map::identity(UseDomainSpace.map_from_domain_and_range(ScevSpace));
Michael Kruse138a3fb2017-08-04 22:51:23 +0000697 return ValInst;
698 }
699
700 case VirtualUse::Intra: {
701 // Definition and use is in the same statement. We do not need to compute
702 // a reaching definition.
703
704 // { llvm::Value }
705 auto ValSet = makeValueSet(Val);
706
707 // { UserDomain[] -> llvm::Value }
Tobias Grosserdaf68ea2018-04-28 22:11:48 +0000708 auto ValInstSet = isl::map::from_domain_and_range(DomainUse, ValSet);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000709
710 // { UserDomain[] -> [UserDomain[] - >llvm::Value] }
Tobias Grosserdaf68ea2018-04-28 22:11:48 +0000711 auto Result = ValInstSet.domain_map().reverse();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000712 simplify(Result);
713 return Result;
714 }
715
716 case VirtualUse::Inter: {
717 // The value is defined in a different statement.
718
719 auto *Inst = cast<Instruction>(Val);
720 auto *ValStmt = S->getStmtFor(Inst);
721
722 // If the llvm::Value is defined in a removed Stmt, we cannot derive its
723 // domain. We could use an arbitrary statement, but this could result in
724 // different ValInst[] for the same llvm::Value.
725 if (!ValStmt)
726 return ::makeUnknownForDomain(DomainUse);
727
728 // { DomainDef[] }
729 auto DomainDef = getDomainFor(ValStmt);
730
731 // { Scatter[] -> DomainDef[] }
732 auto ReachDef = getScalarReachingDefinition(DomainDef);
733
734 // { DomainUse[] -> Scatter[] }
735 auto UserSched = getScatterFor(DomainUse);
736
737 // { DomainUse[] -> DomainDef[] }
Tobias Grosserdaf68ea2018-04-28 22:11:48 +0000738 auto UsedInstance = UserSched.apply_range(ReachDef);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000739
740 // { llvm::Value }
741 auto ValSet = makeValueSet(Val);
742
743 // { DomainUse[] -> llvm::Value[] }
Tobias Grosserdaf68ea2018-04-28 22:11:48 +0000744 auto ValInstSet = isl::map::from_domain_and_range(DomainUse, ValSet);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000745
746 // { DomainUse[] -> [DomainDef[] -> llvm::Value] }
Tobias Grosserdaf68ea2018-04-28 22:11:48 +0000747 auto Result = UsedInstance.range_product(ValInstSet);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000748
749 simplify(Result);
750 return Result;
751 }
752 }
753 llvm_unreachable("Unhandled use type");
754}
755
Michael Kruse68821a82017-10-31 16:11:46 +0000756/// Remove all computed PHIs out of @p Input and replace by their incoming
757/// value.
758///
759/// @param Input { [] -> ValInst[] }
760/// @param ComputedPHIs Set of PHIs that are replaced. Its ValInst must appear
761/// on the LHS of @p NormalizeMap.
762/// @param NormalizeMap { ValInst[] -> ValInst[] }
763static isl::union_map normalizeValInst(isl::union_map Input,
764 const DenseSet<PHINode *> &ComputedPHIs,
765 isl::union_map NormalizeMap) {
766 isl::union_map Result = isl::union_map::empty(Input.get_space());
767 Input.foreach_map(
768 [&Result, &ComputedPHIs, &NormalizeMap](isl::map Map) -> isl::stat {
769 isl::space Space = Map.get_space();
770 isl::space RangeSpace = Space.range();
771
772 // Instructions within the SCoP are always wrapped. Non-wrapped tuples
773 // are therefore invariant in the SCoP and don't need normalization.
774 if (!RangeSpace.is_wrapping()) {
775 Result = Result.add_map(Map);
776 return isl::stat::ok;
777 }
778
779 auto *PHI = dyn_cast<PHINode>(static_cast<Value *>(
780 RangeSpace.unwrap().get_tuple_id(isl::dim::out).get_user()));
781
782 // If no normalization is necessary, then the ValInst stands for itself.
783 if (!ComputedPHIs.count(PHI)) {
784 Result = Result.add_map(Map);
785 return isl::stat::ok;
786 }
787
788 // Otherwise, apply the normalization.
789 isl::union_map Mapped = isl::union_map(Map).apply_range(NormalizeMap);
790 Result = Result.unite(Mapped);
791 NumPHINormialization++;
792 return isl::stat::ok;
793 });
794 return Result;
795}
796
797isl::union_map ZoneAlgorithm::makeNormalizedValInst(llvm::Value *Val,
798 ScopStmt *UserStmt,
799 llvm::Loop *Scope,
800 bool IsCertain) {
801 isl::map ValInst = makeValInst(Val, UserStmt, Scope, IsCertain);
802 isl::union_map Normalized =
803 normalizeValInst(ValInst, ComputedPHIs, NormalizeMap);
804 return Normalized;
805}
806
Michael Kruse47281842017-08-28 20:39:07 +0000807bool ZoneAlgorithm::isCompatibleAccess(MemoryAccess *MA) {
808 if (!MA)
809 return false;
810 if (!MA->isLatestArrayKind())
811 return false;
812 Instruction *AccInst = MA->getAccessInstruction();
813 return isa<StoreInst>(AccInst) || isa<LoadInst>(AccInst);
814}
815
Michael Kruse68821a82017-10-31 16:11:46 +0000816bool ZoneAlgorithm::isNormalizable(MemoryAccess *MA) {
817 assert(MA->isRead());
818
819 // Exclude ExitPHIs, we are assuming that a normalizable PHI has a READ
820 // MemoryAccess.
821 if (!MA->isOriginalPHIKind())
822 return false;
823
824 // Exclude recursive PHIs, normalizing them would require a transitive
825 // closure.
826 auto *PHI = cast<PHINode>(MA->getAccessInstruction());
827 if (RecursivePHIs.count(PHI))
828 return false;
829
830 // Ensure that each incoming value can be represented by a ValInst[].
831 // We do represent values from statements associated to multiple incoming
832 // value by the PHI itself, but we do not handle this case yet (especially
833 // isNormalized()) when normalizing.
834 const ScopArrayInfo *SAI = MA->getOriginalScopArrayInfo();
835 auto Incomings = S->getPHIIncomings(SAI);
836 for (MemoryAccess *Incoming : Incomings) {
837 if (Incoming->getIncoming().size() != 1)
838 return false;
839 }
840
841 return true;
842}
843
844bool ZoneAlgorithm::isNormalized(isl::map Map) {
845 isl::space Space = Map.get_space();
846 isl::space RangeSpace = Space.range();
847
848 if (!RangeSpace.is_wrapping())
849 return true;
850
851 auto *PHI = dyn_cast<PHINode>(static_cast<Value *>(
852 RangeSpace.unwrap().get_tuple_id(isl::dim::out).get_user()));
853 if (!PHI)
854 return true;
855
856 auto *IncomingStmt = static_cast<ScopStmt *>(
857 RangeSpace.unwrap().get_tuple_id(isl::dim::in).get_user());
858 MemoryAccess *PHIRead = IncomingStmt->lookupPHIReadOf(PHI);
859 if (!isNormalizable(PHIRead))
860 return true;
861
862 return false;
863}
864
865bool ZoneAlgorithm::isNormalized(isl::union_map UMap) {
866 auto Result = UMap.foreach_map([this](isl::map Map) -> isl::stat {
867 if (isNormalized(Map))
868 return isl::stat::ok;
869 return isl::stat::error;
870 });
871 return Result == isl::stat::ok;
872}
873
Michael Kruse138a3fb2017-08-04 22:51:23 +0000874void ZoneAlgorithm::computeCommon() {
875 AllReads = makeEmptyUnionMap();
876 AllMayWrites = makeEmptyUnionMap();
877 AllMustWrites = makeEmptyUnionMap();
878 AllWriteValInst = makeEmptyUnionMap();
Michael Kruse70af4f52017-08-07 18:40:29 +0000879 AllReadValInst = makeEmptyUnionMap();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000880
Michael Kruse68821a82017-10-31 16:11:46 +0000881 // Default to empty, i.e. no normalization/replacement is taking place. Call
882 // computeNormalizedPHIs() to initialize.
883 NormalizeMap = makeEmptyUnionMap();
884 ComputedPHIs.clear();
885
Michael Kruse138a3fb2017-08-04 22:51:23 +0000886 for (auto &Stmt : *S) {
887 for (auto *MA : Stmt) {
888 if (!MA->isLatestArrayKind())
889 continue;
890
891 if (MA->isRead())
892 addArrayReadAccess(MA);
893
894 if (MA->isWrite())
895 addArrayWriteAccess(MA);
896 }
897 }
898
899 // { DomainWrite[] -> Element[] }
Tobias Grosserdaf68ea2018-04-28 22:11:48 +0000900 AllWrites = AllMustWrites.unite(AllMayWrites);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000901
902 // { [Element[] -> Zone[]] -> DomainWrite[] }
903 WriteReachDefZone =
904 computeReachingDefinition(Schedule, AllWrites, false, true);
905 simplify(WriteReachDefZone);
906}
907
Michael Kruse68821a82017-10-31 16:11:46 +0000908void ZoneAlgorithm::computeNormalizedPHIs() {
909 // Determine which PHIs can reference themselves. They are excluded from
910 // normalization to avoid problems with transitive closures.
911 for (ScopStmt &Stmt : *S) {
912 for (MemoryAccess *MA : Stmt) {
913 if (!MA->isPHIKind())
914 continue;
915 if (!MA->isRead())
916 continue;
917
918 // TODO: Can be more efficient since isRecursivePHI can theoretically
919 // determine recursiveness for multiple values and/or cache results.
920 auto *PHI = cast<PHINode>(MA->getAccessInstruction());
921 if (isRecursivePHI(PHI)) {
922 NumRecursivePHIs++;
923 RecursivePHIs.insert(PHI);
924 }
925 }
926 }
927
928 // { PHIValInst[] -> IncomingValInst[] }
929 isl::union_map AllPHIMaps = makeEmptyUnionMap();
930
931 // Discover new PHIs and try to normalize them.
932 DenseSet<PHINode *> AllPHIs;
933 for (ScopStmt &Stmt : *S) {
934 for (MemoryAccess *MA : Stmt) {
935 if (!MA->isOriginalPHIKind())
936 continue;
937 if (!MA->isRead())
938 continue;
939 if (!isNormalizable(MA))
940 continue;
941
942 auto *PHI = cast<PHINode>(MA->getAccessInstruction());
943 const ScopArrayInfo *SAI = MA->getOriginalScopArrayInfo();
944
945 // { PHIDomain[] -> PHIValInst[] }
946 isl::map PHIValInst = makeValInst(PHI, &Stmt, Stmt.getSurroundingLoop());
947
948 // { IncomingDomain[] -> IncomingValInst[] }
949 isl::union_map IncomingValInsts = makeEmptyUnionMap();
950
951 // Get all incoming values.
952 for (MemoryAccess *MA : S->getPHIIncomings(SAI)) {
953 ScopStmt *IncomingStmt = MA->getStatement();
954
955 auto Incoming = MA->getIncoming();
956 assert(Incoming.size() == 1 && "The incoming value must be "
957 "representable by something else than "
958 "the PHI itself");
959 Value *IncomingVal = Incoming[0].second;
960
961 // { IncomingDomain[] -> IncomingValInst[] }
962 isl::map IncomingValInst = makeValInst(
963 IncomingVal, IncomingStmt, IncomingStmt->getSurroundingLoop());
964
965 IncomingValInsts = IncomingValInsts.add_map(IncomingValInst);
966 }
967
968 // Determine which instance of the PHI statement corresponds to which
969 // incoming value.
970 // { PHIDomain[] -> IncomingDomain[] }
971 isl::union_map PerPHI = computePerPHI(SAI);
972
973 // { PHIValInst[] -> IncomingValInst[] }
974 isl::union_map PHIMap =
975 PerPHI.apply_domain(PHIValInst).apply_range(IncomingValInsts);
976 assert(!PHIMap.is_single_valued().is_false());
977
978 // Resolve transitiveness: The incoming value of the newly discovered PHI
979 // may reference a previously normalized PHI. At the same time, already
980 // normalized PHIs might be normalized to the new PHI. At the end, none of
981 // the PHIs may appear on the right-hand-side of the normalization map.
982 PHIMap = normalizeValInst(PHIMap, AllPHIs, AllPHIMaps);
983 AllPHIs.insert(PHI);
984 AllPHIMaps = normalizeValInst(AllPHIMaps, AllPHIs, PHIMap);
985
986 AllPHIMaps = AllPHIMaps.unite(PHIMap);
987 NumNormalizablePHIs++;
988 }
989 }
990 simplify(AllPHIMaps);
991
992 // Apply the normalization.
993 ComputedPHIs = AllPHIs;
994 NormalizeMap = AllPHIMaps;
995
996 assert(!NormalizeMap || isNormalized(NormalizeMap));
997}
998
Michael Kruse138a3fb2017-08-04 22:51:23 +0000999void ZoneAlgorithm::printAccesses(llvm::raw_ostream &OS, int Indent) const {
1000 OS.indent(Indent) << "After accesses {\n";
1001 for (auto &Stmt : *S) {
1002 OS.indent(Indent + 4) << Stmt.getBaseName() << "\n";
1003 for (auto *MA : Stmt)
1004 MA->print(OS);
1005 }
1006 OS.indent(Indent) << "}\n";
1007}
Michael Kruse70af4f52017-08-07 18:40:29 +00001008
1009isl::union_map ZoneAlgorithm::computeKnownFromMustWrites() const {
1010 // { [Element[] -> Zone[]] -> [Element[] -> DomainWrite[]] }
1011 isl::union_map EltReachdDef = distributeDomain(WriteReachDefZone.curry());
1012
1013 // { [Element[] -> DomainWrite[]] -> ValInst[] }
1014 isl::union_map AllKnownWriteValInst = filterKnownValInst(AllWriteValInst);
1015
1016 // { [Element[] -> Zone[]] -> ValInst[] }
1017 return EltReachdDef.apply_range(AllKnownWriteValInst);
1018}
1019
1020isl::union_map ZoneAlgorithm::computeKnownFromLoad() const {
1021 // { Element[] }
1022 isl::union_set AllAccessedElts = AllReads.range().unite(AllWrites.range());
1023
1024 // { Element[] -> Scatter[] }
1025 isl::union_map EltZoneUniverse = isl::union_map::from_domain_and_range(
1026 AllAccessedElts, isl::set::universe(ScatterSpace));
1027
1028 // This assumes there are no "holes" in
1029 // isl_union_map_domain(WriteReachDefZone); alternatively, compute the zone
1030 // before the first write or that are not written at all.
1031 // { Element[] -> Scatter[] }
1032 isl::union_set NonReachDef =
1033 EltZoneUniverse.wrap().subtract(WriteReachDefZone.domain());
1034
1035 // { [Element[] -> Zone[]] -> ReachDefId[] }
1036 isl::union_map DefZone =
1037 WriteReachDefZone.unite(isl::union_map::from_domain(NonReachDef));
1038
1039 // { [Element[] -> Scatter[]] -> Element[] }
1040 isl::union_map EltZoneElt = EltZoneUniverse.domain_map();
1041
1042 // { [Element[] -> Zone[]] -> [Element[] -> ReachDefId[]] }
1043 isl::union_map DefZoneEltDefId = EltZoneElt.range_product(DefZone);
1044
1045 // { Element[] -> [Zone[] -> ReachDefId[]] }
1046 isl::union_map EltDefZone = DefZone.curry();
1047
1048 // { [Element[] -> Zone[] -> [Element[] -> ReachDefId[]] }
1049 isl::union_map EltZoneEltDefid = distributeDomain(EltDefZone);
1050
1051 // { [Element[] -> Scatter[]] -> DomainRead[] }
1052 isl::union_map Reads = AllReads.range_product(Schedule).reverse();
1053
1054 // { [Element[] -> Scatter[]] -> [Element[] -> DomainRead[]] }
1055 isl::union_map ReadsElt = EltZoneElt.range_product(Reads);
1056
1057 // { [Element[] -> Scatter[]] -> ValInst[] }
1058 isl::union_map ScatterKnown = ReadsElt.apply_range(AllReadValInst);
1059
1060 // { [Element[] -> ReachDefId[]] -> ValInst[] }
1061 isl::union_map DefidKnown =
1062 DefZoneEltDefId.apply_domain(ScatterKnown).reverse();
1063
1064 // { [Element[] -> Zone[]] -> ValInst[] }
1065 return DefZoneEltDefId.apply_range(DefidKnown);
1066}
1067
1068isl::union_map ZoneAlgorithm::computeKnown(bool FromWrite,
1069 bool FromRead) const {
1070 isl::union_map Result = makeEmptyUnionMap();
1071
1072 if (FromWrite)
1073 Result = Result.unite(computeKnownFromMustWrites());
1074
1075 if (FromRead)
1076 Result = Result.unite(computeKnownFromLoad());
1077
1078 simplify(Result);
1079 return Result;
1080}