blob: e08d5a9f59a33382df7a8a38caf033865c9766ae [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"
157
158#define DEBUG_TYPE "polly-zone"
159
160using namespace polly;
161using namespace llvm;
162
163static isl::union_map computeReachingDefinition(isl::union_map Schedule,
164 isl::union_map Writes,
165 bool InclDef, bool InclRedef) {
166 return computeReachingWrite(Schedule, Writes, false, InclDef, InclRedef);
167}
168
169/// Compute the reaching definition of a scalar.
170///
171/// Compared to computeReachingDefinition, there is just one element which is
172/// accessed and therefore only a set if instances that accesses that element is
173/// required.
174///
175/// @param Schedule { DomainWrite[] -> Scatter[] }
176/// @param Writes { DomainWrite[] }
177/// @param InclDef Include the timepoint of the definition to the result.
178/// @param InclRedef Include the timepoint of the overwrite into the result.
179///
180/// @return { Scatter[] -> DomainWrite[] }
181static isl::union_map computeScalarReachingDefinition(isl::union_map Schedule,
182 isl::union_set Writes,
183 bool InclDef,
184 bool InclRedef) {
Michael Kruse138a3fb2017-08-04 22:51:23 +0000185 // { DomainWrite[] -> Element[] }
Tobias Grosser0dd42512017-08-21 14:19:40 +0000186 isl::union_map Defs = isl::union_map::from_domain(Writes);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000187
188 // { [Element[] -> Scatter[]] -> DomainWrite[] }
189 auto ReachDefs =
190 computeReachingDefinition(Schedule, Defs, InclDef, InclRedef);
191
192 // { Scatter[] -> DomainWrite[] }
Tobias Grosser0dd42512017-08-21 14:19:40 +0000193 return ReachDefs.curry().range().unwrap();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000194}
195
196/// Compute the reaching definition of a scalar.
197///
198/// This overload accepts only a single writing statement as an isl_map,
199/// consequently the result also is only a single isl_map.
200///
201/// @param Schedule { DomainWrite[] -> Scatter[] }
202/// @param Writes { DomainWrite[] }
203/// @param InclDef Include the timepoint of the definition to the result.
204/// @param InclRedef Include the timepoint of the overwrite into the result.
205///
206/// @return { Scatter[] -> DomainWrite[] }
207static isl::map computeScalarReachingDefinition(isl::union_map Schedule,
208 isl::set Writes, bool InclDef,
209 bool InclRedef) {
Tobias Grosser0dd42512017-08-21 14:19:40 +0000210 isl::space DomainSpace = Writes.get_space();
211 isl::space ScatterSpace = getScatterSpace(Schedule);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000212
213 // { Scatter[] -> DomainWrite[] }
Tobias Grosser0dd42512017-08-21 14:19:40 +0000214 isl::union_map UMap = computeScalarReachingDefinition(
215 Schedule, isl::union_set(Writes), InclDef, InclRedef);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000216
Tobias Grosser0dd42512017-08-21 14:19:40 +0000217 isl::space ResultSpace = ScatterSpace.map_from_domain_and_range(DomainSpace);
Michael Kruse138a3fb2017-08-04 22:51:23 +0000218 return singleton(UMap, ResultSpace);
219}
220
221isl::union_map polly::makeUnknownForDomain(isl::union_set Domain) {
222 return give(isl_union_map_from_domain(Domain.take()));
223}
224
225/// Create a domain-to-unknown value mapping.
226///
227/// @see makeUnknownForDomain(isl::union_set)
228///
229/// @param Domain { Domain[] }
230///
231/// @return { Domain[] -> ValInst[] }
232static isl::map makeUnknownForDomain(isl::set Domain) {
233 return give(isl_map_from_domain(Domain.take()));
234}
235
Michael Kruse70af4f52017-08-07 18:40:29 +0000236/// Return whether @p Map maps to an unknown value.
237///
238/// @param { [] -> ValInst[] }
239static bool isMapToUnknown(const isl::map &Map) {
240 isl::space Space = Map.get_space().range();
241 return Space.has_tuple_id(isl::dim::set).is_false() &&
242 Space.is_wrapping().is_false() && Space.dim(isl::dim::set) == 0;
243}
244
Michael Krusece673582017-08-08 17:00:27 +0000245isl::union_map polly::filterKnownValInst(const isl::union_map &UMap) {
Michael Kruse70af4f52017-08-07 18:40:29 +0000246 isl::union_map Result = isl::union_map::empty(UMap.get_space());
Michael Kruse630fc7b2017-08-09 11:21:40 +0000247 isl::stat Success = UMap.foreach_map([=, &Result](isl::map Map) -> isl::stat {
Michael Kruse70af4f52017-08-07 18:40:29 +0000248 if (!isMapToUnknown(Map))
249 Result = Result.add_map(Map);
250 return isl::stat::ok;
251 });
Michael Kruse630fc7b2017-08-09 11:21:40 +0000252 if (Success != isl::stat::ok)
253 return {};
Michael Kruse70af4f52017-08-07 18:40:29 +0000254 return Result;
255}
256
Michael Kruse138a3fb2017-08-04 22:51:23 +0000257static std::string printInstruction(Instruction *Instr,
258 bool IsForDebug = false) {
259 std::string Result;
260 raw_string_ostream OS(Result);
261 Instr->print(OS, IsForDebug);
262 OS.flush();
263 size_t i = 0;
264 while (i < Result.size() && Result[i] == ' ')
265 i += 1;
266 return Result.substr(i);
267}
268
269ZoneAlgorithm::ZoneAlgorithm(const char *PassName, Scop *S, LoopInfo *LI)
270 : PassName(PassName), IslCtx(S->getSharedIslCtx()), S(S), LI(LI),
Tobias Grosser61bd3a42017-08-06 21:42:38 +0000271 Schedule(S->getSchedule()) {
Tobias Grosser31df6f32017-08-06 21:42:25 +0000272 auto Domains = S->getDomains();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000273
274 Schedule =
275 give(isl_union_map_intersect_domain(Schedule.take(), Domains.take()));
276 ParamSpace = give(isl_union_map_get_space(Schedule.keep()));
277 ScatterSpace = getScatterSpace(Schedule);
278}
279
Tobias Grosser2ef37812017-08-07 22:01:29 +0000280/// Check if all stores in @p Stmt store the very same value.
281///
Michael Kruse8756b3f2017-08-09 09:29:15 +0000282/// This covers a special situation occurring in Polybench's
283/// covariance/correlation (which is typical for algorithms that cover symmetric
284/// matrices):
285///
286/// for (int i = 0; i < n; i += 1)
287/// for (int j = 0; j <= i; j += 1) {
288/// double x = ...;
289/// C[i][j] = x;
290/// C[j][i] = x;
291/// }
292///
293/// For i == j, the same value is written twice to the same element.Double
294/// writes to the same element are not allowed in DeLICM because its algorithm
295/// does not see which of the writes is effective.But if its the same value
296/// anyway, it doesn't matter.
297///
298/// LLVM passes, however, cannot simplify this because the write is necessary
299/// for i != j (unless it would add a condition for one of the writes to occur
300/// only if i != j).
301///
Tobias Grosser2ef37812017-08-07 22:01:29 +0000302/// TODO: In the future we may want to extent this to make the checks
303/// specific to different memory locations.
304static bool onlySameValueWrites(ScopStmt *Stmt) {
305 Value *V = nullptr;
306
307 for (auto *MA : *Stmt) {
308 if (!MA->isLatestArrayKind() || !MA->isMustWrite() ||
309 !MA->isOriginalArrayKind())
310 continue;
311
312 if (!V) {
313 V = MA->getAccessValue();
314 continue;
315 }
316
317 if (V != MA->getAccessValue())
318 return false;
319 }
320 return true;
321}
322
Michael Kruse138a3fb2017-08-04 22:51:23 +0000323bool ZoneAlgorithm::isCompatibleStmt(ScopStmt *Stmt) {
324 auto Stores = makeEmptyUnionMap();
325 auto Loads = makeEmptyUnionMap();
326
327 // This assumes that the MemoryKind::Array MemoryAccesses are iterated in
328 // order.
329 for (auto *MA : *Stmt) {
330 if (!MA->isLatestArrayKind())
331 continue;
332
333 auto AccRel = give(isl_union_map_from_map(getAccessRelationFor(MA).take()));
334
335 if (MA->isRead()) {
336 // Reject load after store to same location.
337 if (!isl_union_map_is_disjoint(Stores.keep(), AccRel.keep())) {
Michael Krusee983e6b2017-08-28 11:22:23 +0000338 DEBUG(dbgs() << "Load after store of same element in same statement\n");
Michael Kruse138a3fb2017-08-04 22:51:23 +0000339 OptimizationRemarkMissed R(PassName, "LoadAfterStore",
340 MA->getAccessInstruction());
341 R << "load after store of same element in same statement";
342 R << " (previous stores: " << Stores;
343 R << ", loading: " << AccRel << ")";
344 S->getFunction().getContext().diagnose(R);
345 return false;
346 }
347
348 Loads = give(isl_union_map_union(Loads.take(), AccRel.take()));
349
350 continue;
351 }
352
353 if (!isa<StoreInst>(MA->getAccessInstruction())) {
354 DEBUG(dbgs() << "WRITE that is not a StoreInst not supported\n");
355 OptimizationRemarkMissed R(PassName, "UnusualStore",
356 MA->getAccessInstruction());
357 R << "encountered write that is not a StoreInst: "
358 << printInstruction(MA->getAccessInstruction());
359 S->getFunction().getContext().diagnose(R);
360 return false;
361 }
362
363 // In region statements the order is less clear, eg. the load and store
364 // might be in a boxed loop.
365 if (Stmt->isRegionStmt() &&
366 !isl_union_map_is_disjoint(Loads.keep(), AccRel.keep())) {
Michael Krusee983e6b2017-08-28 11:22:23 +0000367 DEBUG(dbgs() << "WRITE in non-affine subregion not supported\n");
Michael Kruse138a3fb2017-08-04 22:51:23 +0000368 OptimizationRemarkMissed R(PassName, "StoreInSubregion",
369 MA->getAccessInstruction());
370 R << "store is in a non-affine subregion";
371 S->getFunction().getContext().diagnose(R);
372 return false;
373 }
374
375 // Do not allow more than one store to the same location.
Michael Krusea9033aa2017-08-09 09:29:09 +0000376 if (!isl_union_map_is_disjoint(Stores.keep(), AccRel.keep()) &&
377 !onlySameValueWrites(Stmt)) {
Michael Krusee983e6b2017-08-28 11:22:23 +0000378 DEBUG(dbgs() << "WRITE after WRITE to same element\n");
Michael Kruse138a3fb2017-08-04 22:51:23 +0000379 OptimizationRemarkMissed R(PassName, "StoreAfterStore",
380 MA->getAccessInstruction());
Michael Krusea9033aa2017-08-09 09:29:09 +0000381 R << "store after store of same element in same statement";
382 R << " (previous stores: " << Stores;
383 R << ", storing: " << AccRel << ")";
384 S->getFunction().getContext().diagnose(R);
385 return false;
Michael Kruse138a3fb2017-08-04 22:51:23 +0000386 }
387
388 Stores = give(isl_union_map_union(Stores.take(), AccRel.take()));
389 }
390
391 return true;
392}
393
394void ZoneAlgorithm::addArrayReadAccess(MemoryAccess *MA) {
395 assert(MA->isLatestArrayKind());
396 assert(MA->isRead());
Michael Kruse70af4f52017-08-07 18:40:29 +0000397 ScopStmt *Stmt = MA->getStatement();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000398
399 // { DomainRead[] -> Element[] }
400 auto AccRel = getAccessRelationFor(MA);
401 AllReads = give(isl_union_map_add_map(AllReads.take(), AccRel.copy()));
Michael Kruse70af4f52017-08-07 18:40:29 +0000402
403 if (LoadInst *Load = dyn_cast_or_null<LoadInst>(MA->getAccessInstruction())) {
404 // { DomainRead[] -> ValInst[] }
405 isl::map LoadValInst = makeValInst(
406 Load, Stmt, LI->getLoopFor(Load->getParent()), Stmt->isBlockStmt());
407
408 // { DomainRead[] -> [Element[] -> DomainRead[]] }
409 isl::map IncludeElement =
410 give(isl_map_curry(isl_map_domain_map(AccRel.take())));
411
412 // { [Element[] -> DomainRead[]] -> ValInst[] }
413 isl::map EltLoadValInst =
414 give(isl_map_apply_domain(LoadValInst.take(), IncludeElement.take()));
415
416 AllReadValInst = give(
417 isl_union_map_add_map(AllReadValInst.take(), EltLoadValInst.take()));
418 }
Michael Kruse138a3fb2017-08-04 22:51:23 +0000419}
420
421void ZoneAlgorithm::addArrayWriteAccess(MemoryAccess *MA) {
422 assert(MA->isLatestArrayKind());
423 assert(MA->isWrite());
424 auto *Stmt = MA->getStatement();
425
426 // { Domain[] -> Element[] }
427 auto AccRel = getAccessRelationFor(MA);
428
429 if (MA->isMustWrite())
430 AllMustWrites =
431 give(isl_union_map_add_map(AllMustWrites.take(), AccRel.copy()));
432
433 if (MA->isMayWrite())
434 AllMayWrites =
435 give(isl_union_map_add_map(AllMayWrites.take(), AccRel.copy()));
436
437 // { Domain[] -> ValInst[] }
438 auto WriteValInstance =
439 makeValInst(MA->getAccessValue(), Stmt,
440 LI->getLoopFor(MA->getAccessInstruction()->getParent()),
441 MA->isMustWrite());
442
443 // { Domain[] -> [Element[] -> Domain[]] }
444 auto IncludeElement = give(isl_map_curry(isl_map_domain_map(AccRel.copy())));
445
446 // { [Element[] -> DomainWrite[]] -> ValInst[] }
447 auto EltWriteValInst = give(
448 isl_map_apply_domain(WriteValInstance.take(), IncludeElement.take()));
449
450 AllWriteValInst = give(
451 isl_union_map_add_map(AllWriteValInst.take(), EltWriteValInst.take()));
452}
453
454isl::union_set ZoneAlgorithm::makeEmptyUnionSet() const {
455 return give(isl_union_set_empty(ParamSpace.copy()));
456}
457
458isl::union_map ZoneAlgorithm::makeEmptyUnionMap() const {
459 return give(isl_union_map_empty(ParamSpace.copy()));
460}
461
462bool ZoneAlgorithm::isCompatibleScop() {
463 for (auto &Stmt : *S) {
464 if (!isCompatibleStmt(&Stmt))
465 return false;
466 }
467 return true;
468}
469
470isl::map ZoneAlgorithm::getScatterFor(ScopStmt *Stmt) const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000471 isl::space ResultSpace = give(isl_space_map_from_domain_and_range(
472 Stmt->getDomainSpace().release(), ScatterSpace.copy()));
Michael Kruse138a3fb2017-08-04 22:51:23 +0000473 return give(isl_union_map_extract_map(Schedule.keep(), ResultSpace.take()));
474}
475
476isl::map ZoneAlgorithm::getScatterFor(MemoryAccess *MA) const {
477 return getScatterFor(MA->getStatement());
478}
479
480isl::union_map ZoneAlgorithm::getScatterFor(isl::union_set Domain) const {
481 return give(isl_union_map_intersect_domain(Schedule.copy(), Domain.take()));
482}
483
484isl::map ZoneAlgorithm::getScatterFor(isl::set Domain) const {
485 auto ResultSpace = give(isl_space_map_from_domain_and_range(
486 isl_set_get_space(Domain.keep()), ScatterSpace.copy()));
487 auto UDomain = give(isl_union_set_from_set(Domain.copy()));
488 auto UResult = getScatterFor(std::move(UDomain));
489 auto Result = singleton(std::move(UResult), std::move(ResultSpace));
490 assert(!Result || isl_set_is_equal(give(isl_map_domain(Result.copy())).keep(),
491 Domain.keep()) == isl_bool_true);
492 return Result;
493}
494
495isl::set ZoneAlgorithm::getDomainFor(ScopStmt *Stmt) const {
Tobias Grosserdcf8d692017-08-06 16:39:52 +0000496 return Stmt->getDomain().remove_redundancies();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000497}
498
499isl::set ZoneAlgorithm::getDomainFor(MemoryAccess *MA) const {
500 return getDomainFor(MA->getStatement());
501}
502
503isl::map ZoneAlgorithm::getAccessRelationFor(MemoryAccess *MA) const {
504 auto Domain = getDomainFor(MA);
505 auto AccRel = MA->getLatestAccessRelation();
506 return give(isl_map_intersect_domain(AccRel.take(), Domain.take()));
507}
508
509isl::map ZoneAlgorithm::getScalarReachingDefinition(ScopStmt *Stmt) {
510 auto &Result = ScalarReachDefZone[Stmt];
511 if (Result)
512 return Result;
513
514 auto Domain = getDomainFor(Stmt);
515 Result = computeScalarReachingDefinition(Schedule, Domain, false, true);
516 simplify(Result);
517
518 return Result;
519}
520
521isl::map ZoneAlgorithm::getScalarReachingDefinition(isl::set DomainDef) {
522 auto DomId = give(isl_set_get_tuple_id(DomainDef.keep()));
523 auto *Stmt = static_cast<ScopStmt *>(isl_id_get_user(DomId.keep()));
524
525 auto StmtResult = getScalarReachingDefinition(Stmt);
526
527 return give(isl_map_intersect_range(StmtResult.take(), DomainDef.take()));
528}
529
530isl::map ZoneAlgorithm::makeUnknownForDomain(ScopStmt *Stmt) const {
531 return ::makeUnknownForDomain(getDomainFor(Stmt));
532}
533
534isl::id ZoneAlgorithm::makeValueId(Value *V) {
535 if (!V)
536 return nullptr;
537
538 auto &Id = ValueIds[V];
539 if (Id.is_null()) {
540 auto Name = getIslCompatibleName("Val_", V, ValueIds.size() - 1,
541 std::string(), UseInstructionNames);
542 Id = give(isl_id_alloc(IslCtx.get(), Name.c_str(), V));
543 }
544 return Id;
545}
546
547isl::space ZoneAlgorithm::makeValueSpace(Value *V) {
548 auto Result = give(isl_space_set_from_params(ParamSpace.copy()));
549 return give(isl_space_set_tuple_id(Result.take(), isl_dim_set,
550 makeValueId(V).take()));
551}
552
553isl::set ZoneAlgorithm::makeValueSet(Value *V) {
554 auto Space = makeValueSpace(V);
555 return give(isl_set_universe(Space.take()));
556}
557
558isl::map ZoneAlgorithm::makeValInst(Value *Val, ScopStmt *UserStmt, Loop *Scope,
559 bool IsCertain) {
560 // If the definition/write is conditional, the value at the location could
561 // be either the written value or the old value. Since we cannot know which
562 // one, consider the value to be unknown.
563 if (!IsCertain)
564 return makeUnknownForDomain(UserStmt);
565
566 auto DomainUse = getDomainFor(UserStmt);
567 auto VUse = VirtualUse::create(S, UserStmt, Scope, Val, true);
568 switch (VUse.getKind()) {
569 case VirtualUse::Constant:
570 case VirtualUse::Block:
571 case VirtualUse::Hoisted:
572 case VirtualUse::ReadOnly: {
573 // The definition does not depend on the statement which uses it.
574 auto ValSet = makeValueSet(Val);
575 return give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
576 }
577
578 case VirtualUse::Synthesizable: {
579 auto *ScevExpr = VUse.getScevExpr();
580 auto UseDomainSpace = give(isl_set_get_space(DomainUse.keep()));
581
582 // Construct the SCEV space.
583 // TODO: Add only the induction variables referenced in SCEVAddRecExpr
584 // expressions, not just all of them.
585 auto ScevId = give(isl_id_alloc(UseDomainSpace.get_ctx().get(), nullptr,
586 const_cast<SCEV *>(ScevExpr)));
587 auto ScevSpace =
588 give(isl_space_drop_dims(UseDomainSpace.copy(), isl_dim_set, 0, 0));
589 ScevSpace = give(
590 isl_space_set_tuple_id(ScevSpace.take(), isl_dim_set, ScevId.copy()));
591
592 // { DomainUse[] -> ScevExpr[] }
593 auto ValInst = give(isl_map_identity(isl_space_map_from_domain_and_range(
594 UseDomainSpace.copy(), ScevSpace.copy())));
595 return ValInst;
596 }
597
598 case VirtualUse::Intra: {
599 // Definition and use is in the same statement. We do not need to compute
600 // a reaching definition.
601
602 // { llvm::Value }
603 auto ValSet = makeValueSet(Val);
604
605 // { UserDomain[] -> llvm::Value }
606 auto ValInstSet =
607 give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
608
609 // { UserDomain[] -> [UserDomain[] - >llvm::Value] }
610 auto Result = give(isl_map_reverse(isl_map_domain_map(ValInstSet.take())));
611 simplify(Result);
612 return Result;
613 }
614
615 case VirtualUse::Inter: {
616 // The value is defined in a different statement.
617
618 auto *Inst = cast<Instruction>(Val);
619 auto *ValStmt = S->getStmtFor(Inst);
620
621 // If the llvm::Value is defined in a removed Stmt, we cannot derive its
622 // domain. We could use an arbitrary statement, but this could result in
623 // different ValInst[] for the same llvm::Value.
624 if (!ValStmt)
625 return ::makeUnknownForDomain(DomainUse);
626
627 // { DomainDef[] }
628 auto DomainDef = getDomainFor(ValStmt);
629
630 // { Scatter[] -> DomainDef[] }
631 auto ReachDef = getScalarReachingDefinition(DomainDef);
632
633 // { DomainUse[] -> Scatter[] }
634 auto UserSched = getScatterFor(DomainUse);
635
636 // { DomainUse[] -> DomainDef[] }
637 auto UsedInstance =
638 give(isl_map_apply_range(UserSched.take(), ReachDef.take()));
639
640 // { llvm::Value }
641 auto ValSet = makeValueSet(Val);
642
643 // { DomainUse[] -> llvm::Value[] }
644 auto ValInstSet =
645 give(isl_map_from_domain_and_range(DomainUse.take(), ValSet.take()));
646
647 // { DomainUse[] -> [DomainDef[] -> llvm::Value] }
648 auto Result =
649 give(isl_map_range_product(UsedInstance.take(), ValInstSet.take()));
650
651 simplify(Result);
652 return Result;
653 }
654 }
655 llvm_unreachable("Unhandled use type");
656}
657
658void ZoneAlgorithm::computeCommon() {
659 AllReads = makeEmptyUnionMap();
660 AllMayWrites = makeEmptyUnionMap();
661 AllMustWrites = makeEmptyUnionMap();
662 AllWriteValInst = makeEmptyUnionMap();
Michael Kruse70af4f52017-08-07 18:40:29 +0000663 AllReadValInst = makeEmptyUnionMap();
Michael Kruse138a3fb2017-08-04 22:51:23 +0000664
665 for (auto &Stmt : *S) {
666 for (auto *MA : Stmt) {
667 if (!MA->isLatestArrayKind())
668 continue;
669
670 if (MA->isRead())
671 addArrayReadAccess(MA);
672
673 if (MA->isWrite())
674 addArrayWriteAccess(MA);
675 }
676 }
677
678 // { DomainWrite[] -> Element[] }
Michael Kruse70af4f52017-08-07 18:40:29 +0000679 AllWrites =
Michael Kruse138a3fb2017-08-04 22:51:23 +0000680 give(isl_union_map_union(AllMustWrites.copy(), AllMayWrites.copy()));
681
682 // { [Element[] -> Zone[]] -> DomainWrite[] }
683 WriteReachDefZone =
684 computeReachingDefinition(Schedule, AllWrites, false, true);
685 simplify(WriteReachDefZone);
686}
687
688void ZoneAlgorithm::printAccesses(llvm::raw_ostream &OS, int Indent) const {
689 OS.indent(Indent) << "After accesses {\n";
690 for (auto &Stmt : *S) {
691 OS.indent(Indent + 4) << Stmt.getBaseName() << "\n";
692 for (auto *MA : Stmt)
693 MA->print(OS);
694 }
695 OS.indent(Indent) << "}\n";
696}
Michael Kruse70af4f52017-08-07 18:40:29 +0000697
698isl::union_map ZoneAlgorithm::computeKnownFromMustWrites() const {
699 // { [Element[] -> Zone[]] -> [Element[] -> DomainWrite[]] }
700 isl::union_map EltReachdDef = distributeDomain(WriteReachDefZone.curry());
701
702 // { [Element[] -> DomainWrite[]] -> ValInst[] }
703 isl::union_map AllKnownWriteValInst = filterKnownValInst(AllWriteValInst);
704
705 // { [Element[] -> Zone[]] -> ValInst[] }
706 return EltReachdDef.apply_range(AllKnownWriteValInst);
707}
708
709isl::union_map ZoneAlgorithm::computeKnownFromLoad() const {
710 // { Element[] }
711 isl::union_set AllAccessedElts = AllReads.range().unite(AllWrites.range());
712
713 // { Element[] -> Scatter[] }
714 isl::union_map EltZoneUniverse = isl::union_map::from_domain_and_range(
715 AllAccessedElts, isl::set::universe(ScatterSpace));
716
717 // This assumes there are no "holes" in
718 // isl_union_map_domain(WriteReachDefZone); alternatively, compute the zone
719 // before the first write or that are not written at all.
720 // { Element[] -> Scatter[] }
721 isl::union_set NonReachDef =
722 EltZoneUniverse.wrap().subtract(WriteReachDefZone.domain());
723
724 // { [Element[] -> Zone[]] -> ReachDefId[] }
725 isl::union_map DefZone =
726 WriteReachDefZone.unite(isl::union_map::from_domain(NonReachDef));
727
728 // { [Element[] -> Scatter[]] -> Element[] }
729 isl::union_map EltZoneElt = EltZoneUniverse.domain_map();
730
731 // { [Element[] -> Zone[]] -> [Element[] -> ReachDefId[]] }
732 isl::union_map DefZoneEltDefId = EltZoneElt.range_product(DefZone);
733
734 // { Element[] -> [Zone[] -> ReachDefId[]] }
735 isl::union_map EltDefZone = DefZone.curry();
736
737 // { [Element[] -> Zone[] -> [Element[] -> ReachDefId[]] }
738 isl::union_map EltZoneEltDefid = distributeDomain(EltDefZone);
739
740 // { [Element[] -> Scatter[]] -> DomainRead[] }
741 isl::union_map Reads = AllReads.range_product(Schedule).reverse();
742
743 // { [Element[] -> Scatter[]] -> [Element[] -> DomainRead[]] }
744 isl::union_map ReadsElt = EltZoneElt.range_product(Reads);
745
746 // { [Element[] -> Scatter[]] -> ValInst[] }
747 isl::union_map ScatterKnown = ReadsElt.apply_range(AllReadValInst);
748
749 // { [Element[] -> ReachDefId[]] -> ValInst[] }
750 isl::union_map DefidKnown =
751 DefZoneEltDefId.apply_domain(ScatterKnown).reverse();
752
753 // { [Element[] -> Zone[]] -> ValInst[] }
754 return DefZoneEltDefId.apply_range(DefidKnown);
755}
756
757isl::union_map ZoneAlgorithm::computeKnown(bool FromWrite,
758 bool FromRead) const {
759 isl::union_map Result = makeEmptyUnionMap();
760
761 if (FromWrite)
762 Result = Result.unite(computeKnownFromMustWrites());
763
764 if (FromRead)
765 Result = Result.unite(computeKnownFromLoad());
766
767 simplify(Result);
768 return Result;
769}