Coverage Report

Created: 2017-11-21 16:49

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/Transform/DeLICM.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------ DeLICM.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
// Undo the effect of Loop Invariant Code Motion (LICM) and
11
// GVN Partial Redundancy Elimination (PRE) on SCoP-level.
12
//
13
// Namely, remove register/scalar dependencies by mapping them back to array
14
// elements.
15
//
16
//===----------------------------------------------------------------------===//
17
18
#include "polly/DeLICM.h"
19
#include "polly/Options.h"
20
#include "polly/ScopInfo.h"
21
#include "polly/ScopPass.h"
22
#include "polly/Support/ISLOStream.h"
23
#include "polly/Support/ISLTools.h"
24
#include "polly/ZoneAlgo.h"
25
#include "llvm/ADT/Statistic.h"
26
7
#define DEBUG_TYPE "polly-delicm"
27
28
using namespace polly;
29
using namespace llvm;
30
31
namespace {
32
33
cl::opt<int>
34
    DelicmMaxOps("polly-delicm-max-ops",
35
                 cl::desc("Maximum number of isl operations to invest for "
36
                          "lifetime analysis; 0=no limit"),
37
                 cl::init(1000000), cl::cat(PollyCategory));
38
39
cl::opt<bool> DelicmOverapproximateWrites(
40
    "polly-delicm-overapproximate-writes",
41
    cl::desc(
42
        "Do more PHI writes than necessary in order to avoid partial accesses"),
43
    cl::init(false), cl::Hidden, cl::cat(PollyCategory));
44
45
cl::opt<bool> DelicmPartialWrites("polly-delicm-partial-writes",
46
                                  cl::desc("Allow partial writes"),
47
                                  cl::init(true), cl::Hidden,
48
                                  cl::cat(PollyCategory));
49
50
cl::opt<bool>
51
    DelicmComputeKnown("polly-delicm-compute-known",
52
                       cl::desc("Compute known content of array elements"),
53
                       cl::init(true), cl::Hidden, cl::cat(PollyCategory));
54
55
STATISTIC(DeLICMAnalyzed, "Number of successfully analyzed SCoPs");
56
STATISTIC(DeLICMOutOfQuota,
57
          "Analyses aborted because max_operations was reached");
58
STATISTIC(MappedValueScalars, "Number of mapped Value scalars");
59
STATISTIC(MappedPHIScalars, "Number of mapped PHI scalars");
60
STATISTIC(TargetsMapped, "Number of stores used for at least one mapping");
61
STATISTIC(DeLICMScopsModified, "Number of SCoPs optimized");
62
63
STATISTIC(NumValueWrites, "Number of scalar value writes after DeLICM");
64
STATISTIC(NumValueWritesInLoops,
65
          "Number of scalar value writes nested in affine loops after DeLICM");
66
STATISTIC(NumPHIWrites, "Number of scalar phi writes after DeLICM");
67
STATISTIC(NumPHIWritesInLoops,
68
          "Number of scalar phi writes nested in affine loops after DeLICM");
69
STATISTIC(NumSingletonWrites, "Number of singleton writes after DeLICM");
70
STATISTIC(NumSingletonWritesInLoops,
71
          "Number of singleton writes nested in affine loops after DeLICM");
72
73
isl::union_map computeReachingOverwrite(isl::union_map Schedule,
74
                                        isl::union_map Writes,
75
                                        bool InclPrevWrite,
76
16
                                        bool InclOverwrite) {
77
16
  return computeReachingWrite(Schedule, Writes, true, InclPrevWrite,
78
16
                              InclOverwrite);
79
16
}
80
81
/// Compute the next overwrite for a scalar.
82
///
83
/// @param Schedule      { DomainWrite[] -> Scatter[] }
84
///                      Schedule of (at least) all writes. Instances not in @p
85
///                      Writes are ignored.
86
/// @param Writes        { DomainWrite[] }
87
///                      The element instances that write to the scalar.
88
/// @param InclPrevWrite Whether to extend the timepoints to include
89
///                      the timepoint where the previous write happens.
90
/// @param InclOverwrite Whether the reaching overwrite includes the timepoint
91
///                      of the overwrite itself.
92
///
93
/// @return { Scatter[] -> DomainDef[] }
94
isl::union_map computeScalarReachingOverwrite(isl::union_map Schedule,
95
                                              isl::union_set Writes,
96
                                              bool InclPrevWrite,
97
16
                                              bool InclOverwrite) {
98
16
99
16
  // { DomainWrite[] }
100
16
  auto WritesMap = give(isl_union_map_from_domain(Writes.take()));
101
16
102
16
  // { [Element[] -> Scatter[]] -> DomainWrite[] }
103
16
  auto Result = computeReachingOverwrite(
104
16
      std::move(Schedule), std::move(WritesMap), InclPrevWrite, InclOverwrite);
105
16
106
16
  return give(isl_union_map_domain_factor_range(Result.take()));
107
16
}
108
109
/// Overload of computeScalarReachingOverwrite, with only one writing statement.
110
/// Consequently, the result consists of only one map space.
111
///
112
/// @param Schedule      { DomainWrite[] -> Scatter[] }
113
/// @param Writes        { DomainWrite[] }
114
/// @param InclPrevWrite Include the previous write to result.
115
/// @param InclOverwrite Include the overwrite to the result.
116
///
117
/// @return { Scatter[] -> DomainWrite[] }
118
isl::map computeScalarReachingOverwrite(isl::union_map Schedule,
119
                                        isl::set Writes, bool InclPrevWrite,
120
16
                                        bool InclOverwrite) {
121
16
  isl::space ScatterSpace = getScatterSpace(Schedule);
122
16
  isl::space DomSpace = Writes.get_space();
123
16
124
16
  isl::union_map ReachOverwrite = computeScalarReachingOverwrite(
125
16
      Schedule, isl::union_set(Writes), InclPrevWrite, InclOverwrite);
126
16
127
16
  isl::space ResultSpace = ScatterSpace.map_from_domain_and_range(DomSpace);
128
16
  return singleton(std::move(ReachOverwrite), ResultSpace);
129
16
}
130
131
/// Try to find a 'natural' extension of a mapped to elements outside its
132
/// domain.
133
///
134
/// @param Relevant The map with mapping that may not be modified.
135
/// @param Universe The domain to which @p Relevant needs to be extended.
136
///
137
/// @return A map with that associates the domain elements of @p Relevant to the
138
///         same elements and in addition the elements of @p Universe to some
139
///         undefined elements. The function prefers to return simple maps.
140
6
isl::union_map expandMapping(isl::union_map Relevant, isl::union_set Universe) {
141
6
  Relevant = Relevant.coalesce();
142
6
  isl::union_set RelevantDomain = Relevant.domain();
143
6
  isl::union_map Simplified = Relevant.gist_domain(RelevantDomain);
144
6
  Simplified = Simplified.coalesce();
145
6
  return Simplified.intersect_domain(Universe);
146
6
}
147
148
/// Represent the knowledge of the contents of any array elements in any zone or
149
/// the knowledge we would add when mapping a scalar to an array element.
150
///
151
/// Every array element at every zone unit has one of two states:
152
///
153
/// - Unused: Not occupied by any value so a transformation can change it to
154
///   other values.
155
///
156
/// - Occupied: The element contains a value that is still needed.
157
///
158
/// The union of Unused and Unknown zones forms the universe, the set of all
159
/// elements at every timepoint. The universe can easily be derived from the
160
/// array elements that are accessed someway. Arrays that are never accessed
161
/// also never play a role in any computation and can hence be ignored. With a
162
/// given universe, only one of the sets needs to stored implicitly. Computing
163
/// the complement is also an expensive operation, hence this class has been
164
/// designed that only one of sets is needed while the other is assumed to be
165
/// implicit. It can still be given, but is mostly ignored.
166
///
167
/// There are two use cases for the Knowledge class:
168
///
169
/// 1) To represent the knowledge of the current state of ScopInfo. The unused
170
///    state means that an element is currently unused: there is no read of it
171
///    before the next overwrite. Also called 'Existing'.
172
///
173
/// 2) To represent the requirements for mapping a scalar to array elements. The
174
///    unused state means that there is no change/requirement. Also called
175
///    'Proposed'.
176
///
177
/// In addition to these states at unit zones, Knowledge needs to know when
178
/// values are written. This is because written values may have no lifetime (one
179
/// reason is that the value is never read). Such writes would therefore never
180
/// conflict, but overwrite values that might still be required. Another source
181
/// of problems are multiple writes to the same element at the same timepoint,
182
/// because their order is undefined.
183
class Knowledge {
184
private:
185
  /// { [Element[] -> Zone[]] }
186
  /// Set of array elements and when they are alive.
187
  /// Can contain a nullptr; in this case the set is implicitly defined as the
188
  /// complement of #Unused.
189
  ///
190
  /// The set of alive array elements is represented as zone, as the set of live
191
  /// values can differ depending on how the elements are interpreted.
192
  /// Assuming a value X is written at timestep [0] and read at timestep [1]
193
  /// without being used at any later point, then the value is alive in the
194
  /// interval ]0,1[. This interval cannot be represented by an integer set, as
195
  /// it does not contain any integer point. Zones allow us to represent this
196
  /// interval and can be converted to sets of timepoints when needed (e.g., in
197
  /// isConflicting when comparing to the write sets).
198
  /// @see convertZoneToTimepoints and this file's comment for more details.
199
  isl::union_set Occupied;
200
201
  /// { [Element[] -> Zone[]] }
202
  /// Set of array elements when they are not alive, i.e. their memory can be
203
  /// used for other purposed. Can contain a nullptr; in this case the set is
204
  /// implicitly defined as the complement of #Occupied.
205
  isl::union_set Unused;
206
207
  /// { [Element[] -> Zone[]] -> ValInst[] }
208
  /// Maps to the known content for each array element at any interval.
209
  ///
210
  /// Any element/interval can map to multiple known elements. This is due to
211
  /// multiple llvm::Value referring to the same content. Examples are
212
  ///
213
  /// - A value stored and loaded again. The LoadInst represents the same value
214
  /// as the StoreInst's value operand.
215
  ///
216
  /// - A PHINode is equal to any one of the incoming values. In case of
217
  /// LCSSA-form, it is always equal to its single incoming value.
218
  ///
219
  /// Two Knowledges are considered not conflicting if at least one of the known
220
  /// values match. Not known values are not stored as an unnamed tuple (as
221
  /// #Written does), but maps to nothing.
222
  ///
223
  ///  Known values are usually just defined for #Occupied elements. Knowing
224
  ///  #Unused contents has no advantage as it can be overwritten.
225
  isl::union_map Known;
226
227
  /// { [Element[] -> Scatter[]] -> ValInst[] }
228
  /// The write actions currently in the scop or that would be added when
229
  /// mapping a scalar. Maps to the value that is written.
230
  ///
231
  /// Written values that cannot be identified are represented by an unknown
232
  /// ValInst[] (an unnamed tuple of 0 dimension). It conflicts with itself.
233
  isl::union_map Written;
234
235
  /// Check whether this Knowledge object is well-formed.
236
562
  void checkConsistency() const {
237
#ifndef NDEBUG
238
    // Default-initialized object
239
    if (!Occupied && !Unused && !Known && !Written)
240
      return;
241
242
    assert(Occupied || Unused);
243
    assert(Known);
244
    assert(Written);
245
246
    // If not all fields are defined, we cannot derived the universe.
247
    if (!Occupied || !Unused)
248
      return;
249
250
    assert(isl_union_set_is_disjoint(Occupied.keep(), Unused.keep()) ==
251
           isl_bool_true);
252
    auto Universe = give(isl_union_set_union(Occupied.copy(), Unused.copy()));
253
254
    assert(!Known.domain().is_subset(Universe).is_false());
255
    assert(!Written.domain().is_subset(Universe).is_false());
256
#endif
257
  }
258
259
public:
260
  /// Initialize a nullptr-Knowledge. This is only provided for convenience; do
261
  /// not use such an object.
262
36
  Knowledge() {}
263
264
  /// Create a new object with the given members.
265
  Knowledge(isl::union_set Occupied, isl::union_set Unused,
266
            isl::union_map Known, isl::union_map Written)
267
      : Occupied(std::move(Occupied)), Unused(std::move(Unused)),
268
523
        Known(std::move(Known)), Written(std::move(Written)) {
269
523
    checkConsistency();
270
523
  }
271
272
  /// Return whether this object was not default-constructed.
273
17
  bool isUsable() const { return (Occupied || Unused) && Known && Written; }
274
275
  /// Print the content of this object to @p OS.
276
0
  void print(llvm::raw_ostream &OS, unsigned Indent = 0) const {
277
0
    if (isUsable()) {
278
0
      if (Occupied)
279
0
        OS.indent(Indent) << "Occupied: " << Occupied << "\n";
280
0
      else
281
0
        OS.indent(Indent) << "Occupied: <Everything else not in Unused>\n";
282
0
      if (Unused)
283
0
        OS.indent(Indent) << "Unused:   " << Unused << "\n";
284
0
      else
285
0
        OS.indent(Indent) << "Unused:   <Everything else not in Occupied>\n";
286
0
      OS.indent(Indent) << "Known:    " << Known << "\n";
287
0
      OS.indent(Indent) << "Written : " << Written << '\n';
288
0
    } else {
289
0
      OS.indent(Indent) << "Invalid knowledge\n";
290
0
    }
291
0
  }
292
293
  /// Combine two knowledges, this and @p That.
294
39
  void learnFrom(Knowledge That) {
295
39
    assert(!isConflicting(*this, That));
296
39
    assert(Unused && That.Occupied);
297
39
    assert(
298
39
        !That.Unused &&
299
39
        "This function is only prepared to learn occupied elements from That");
300
39
    assert(!Occupied && "This function does not implement "
301
39
                        "`this->Occupied = "
302
39
                        "give(isl_union_set_union(this->Occupied.take(), "
303
39
                        "That.Occupied.copy()));`");
304
39
305
39
    Unused = give(isl_union_set_subtract(Unused.take(), That.Occupied.copy()));
306
39
    Known = give(isl_union_map_union(Known.take(), That.Known.copy()));
307
39
    Written = give(isl_union_map_union(Written.take(), That.Written.take()));
308
39
309
39
    checkConsistency();
310
39
  }
311
312
  /// Determine whether two Knowledges conflict with each other.
313
  ///
314
  /// In theory @p Existing and @p Proposed are symmetric, but the
315
  /// implementation is constrained by the implicit interpretation. That is, @p
316
  /// Existing must have #Unused defined (use case 1) and @p Proposed must have
317
  /// #Occupied defined (use case 1).
318
  ///
319
  /// A conflict is defined as non-preserved semantics when they are merged. For
320
  /// instance, when for the same array and zone they assume different
321
  /// llvm::Values.
322
  ///
323
  /// @param Existing One of the knowledges with #Unused defined.
324
  /// @param Proposed One of the knowledges with #Occupied defined.
325
  /// @param OS       Dump the conflict reason to this output stream; use
326
  ///                 nullptr to not output anything.
327
  /// @param Indent   Indention for the conflict reason.
328
  ///
329
  /// @return True, iff the two knowledges are conflicting.
330
  static bool isConflicting(const Knowledge &Existing,
331
                            const Knowledge &Proposed,
332
                            llvm::raw_ostream *OS = nullptr,
333
273
                            unsigned Indent = 0) {
334
273
    assert(Existing.Unused);
335
273
    assert(Proposed.Occupied);
336
273
337
#ifndef NDEBUG
338
    if (Existing.Occupied && Proposed.Unused) {
339
      auto ExistingUniverse = give(isl_union_set_union(Existing.Occupied.copy(),
340
                                                       Existing.Unused.copy()));
341
      auto ProposedUniverse = give(isl_union_set_union(Proposed.Occupied.copy(),
342
                                                       Proposed.Unused.copy()));
343
      assert(isl_union_set_is_equal(ExistingUniverse.keep(),
344
                                    ProposedUniverse.keep()) == isl_bool_true &&
345
             "Both inputs' Knowledges must be over the same universe");
346
    }
347
#endif
348
349
273
    // Do the Existing and Proposed lifetimes conflict?
350
273
    //
351
273
    // Lifetimes are described as the cross-product of array elements and zone
352
273
    // intervals in which they are alive (the space { [Element[] -> Zone[]] }).
353
273
    // In the following we call this "element/lifetime interval".
354
273
    //
355
273
    // In order to not conflict, one of the following conditions must apply for
356
273
    // each element/lifetime interval:
357
273
    //
358
273
    // 1. If occupied in one of the knowledges, it is unused in the other.
359
273
    //
360
273
    //   - or -
361
273
    //
362
273
    // 2. Both contain the same value.
363
273
    //
364
273
    // Instead of partitioning the element/lifetime intervals into a part that
365
273
    // both Knowledges occupy (which requires an expensive subtraction) and for
366
273
    // these to check whether they are known to be the same value, we check only
367
273
    // the second condition and ensure that it also applies when then first
368
273
    // condition is true. This is done by adding a wildcard value to
369
273
    // Proposed.Known and Existing.Unused such that they match as a common known
370
273
    // value. We use the "unknown ValInst" for this purpose. Every
371
273
    // Existing.Unused may match with an unknown Proposed.Occupied because these
372
273
    // never are in conflict with each other.
373
273
    auto ProposedOccupiedAnyVal = makeUnknownForDomain(Proposed.Occupied);
374
273
    auto ProposedValues = Proposed.Known.unite(ProposedOccupiedAnyVal);
375
273
376
273
    auto ExistingUnusedAnyVal = makeUnknownForDomain(Existing.Unused);
377
273
    auto ExistingValues = Existing.Known.unite(ExistingUnusedAnyVal);
378
273
379
273
    auto MatchingVals = ExistingValues.intersect(ProposedValues);
380
273
    auto Matches = MatchingVals.domain();
381
273
382
273
    // Any Proposed.Occupied must either have a match between the known values
383
273
    // of Existing and Occupied, or be in Existing.Unused. In the latter case,
384
273
    // the previously added "AnyVal" will match each other.
385
273
    if (!Proposed.Occupied.is_subset(Matches)) {
386
42
      if (OS) {
387
0
        auto Conflicting = Proposed.Occupied.subtract(Matches);
388
0
        auto ExistingConflictingKnown =
389
0
            Existing.Known.intersect_domain(Conflicting);
390
0
        auto ProposedConflictingKnown =
391
0
            Proposed.Known.intersect_domain(Conflicting);
392
0
393
0
        OS->indent(Indent) << "Proposed lifetime conflicting with Existing's\n";
394
0
        OS->indent(Indent) << "Conflicting occupied: " << Conflicting << "\n";
395
0
        if (!ExistingConflictingKnown.is_empty())
396
0
          OS->indent(Indent)
397
0
              << "Existing Known:       " << ExistingConflictingKnown << "\n";
398
0
        if (!ProposedConflictingKnown.is_empty())
399
0
          OS->indent(Indent)
400
0
              << "Proposed Known:       " << ProposedConflictingKnown << "\n";
401
0
      }
402
42
      return true;
403
42
    }
404
231
405
231
    // Do the writes in Existing conflict with occupied values in Proposed?
406
231
    //
407
231
    // In order to not conflict, it must either write to unused lifetime or
408
231
    // write the same value. To check, we remove the writes that write into
409
231
    // Proposed.Unused (they never conflict) and then see whether the written
410
231
    // value is already in Proposed.Known. If there are multiple known values
411
231
    // and a written value is known under different names, it is enough when one
412
231
    // of the written values (assuming that they are the same value under
413
231
    // different names, e.g. a PHINode and one of the incoming values) matches
414
231
    // one of the known names.
415
231
    //
416
231
    // We convert here the set of lifetimes to actual timepoints. A lifetime is
417
231
    // in conflict with a set of write timepoints, if either a live timepoint is
418
231
    // clearly within the lifetime or if a write happens at the beginning of the
419
231
    // lifetime (where it would conflict with the value that actually writes the
420
231
    // value alive). There is no conflict at the end of a lifetime, as the alive
421
231
    // value will always be read, before it is overwritten again. The last
422
231
    // property holds in Polly for all scalar values and we expect all users of
423
231
    // Knowledge to check this property also for accesses to MemoryKind::Array.
424
231
    auto ProposedFixedDefs =
425
231
        convertZoneToTimepoints(Proposed.Occupied, true, false);
426
231
    auto ProposedFixedKnown =
427
231
        convertZoneToTimepoints(Proposed.Known, isl::dim::in, true, false);
428
231
429
231
    auto ExistingConflictingWrites =
430
231
        Existing.Written.intersect_domain(ProposedFixedDefs);
431
231
    auto ExistingConflictingWritesDomain = ExistingConflictingWrites.domain();
432
231
433
231
    auto CommonWrittenVal =
434
231
        ProposedFixedKnown.intersect(ExistingConflictingWrites);
435
231
    auto CommonWrittenValDomain = CommonWrittenVal.domain();
436
231
437
231
    if (!ExistingConflictingWritesDomain.is_subset(CommonWrittenValDomain)) {
438
24
      if (OS) {
439
0
        auto ExistingConflictingWritten =
440
0
            ExistingConflictingWrites.subtract_domain(CommonWrittenValDomain);
441
0
        auto ProposedConflictingKnown = ProposedFixedKnown.subtract_domain(
442
0
            ExistingConflictingWritten.domain());
443
0
444
0
        OS->indent(Indent)
445
0
            << "Proposed a lifetime where there is an Existing write into it\n";
446
0
        OS->indent(Indent) << "Existing conflicting writes: "
447
0
                           << ExistingConflictingWritten << "\n";
448
0
        if (!ProposedConflictingKnown.is_empty())
449
0
          OS->indent(Indent)
450
0
              << "Proposed conflicting known:  " << ProposedConflictingKnown
451
0
              << "\n";
452
0
      }
453
24
      return true;
454
24
    }
455
207
456
207
    // Do the writes in Proposed conflict with occupied values in Existing?
457
207
    auto ExistingAvailableDefs =
458
207
        convertZoneToTimepoints(Existing.Unused, true, false);
459
207
    auto ExistingKnownDefs =
460
207
        convertZoneToTimepoints(Existing.Known, isl::dim::in, true, false);
461
207
462
207
    auto ProposedWrittenDomain = Proposed.Written.domain();
463
207
    auto KnownIdentical = ExistingKnownDefs.intersect(Proposed.Written);
464
207
    auto IdenticalOrUnused =
465
207
        ExistingAvailableDefs.unite(KnownIdentical.domain());
466
207
    if (!ProposedWrittenDomain.is_subset(IdenticalOrUnused)) {
467
24
      if (OS) {
468
0
        auto Conflicting = ProposedWrittenDomain.subtract(IdenticalOrUnused);
469
0
        auto ExistingConflictingKnown =
470
0
            ExistingKnownDefs.intersect_domain(Conflicting);
471
0
        auto ProposedConflictingWritten =
472
0
            Proposed.Written.intersect_domain(Conflicting);
473
0
474
0
        OS->indent(Indent) << "Proposed writes into range used by Existing\n";
475
0
        OS->indent(Indent) << "Proposed conflicting writes: "
476
0
                           << ProposedConflictingWritten << "\n";
477
0
        if (!ExistingConflictingKnown.is_empty())
478
0
          OS->indent(Indent)
479
0
              << "Existing conflicting known: " << ExistingConflictingKnown
480
0
              << "\n";
481
0
      }
482
24
      return true;
483
24
    }
484
183
485
183
    // Does Proposed write at the same time as Existing already does (order of
486
183
    // writes is undefined)? Writing the same value is permitted.
487
183
    auto ExistingWrittenDomain =
488
183
        isl::manage(isl_union_map_domain(Existing.Written.copy()));
489
183
    auto BothWritten =
490
183
        Existing.Written.domain().intersect(Proposed.Written.domain());
491
183
    auto ExistingKnownWritten = filterKnownValInst(Existing.Written);
492
183
    auto ProposedKnownWritten = filterKnownValInst(Proposed.Written);
493
183
    auto CommonWritten =
494
183
        ExistingKnownWritten.intersect(ProposedKnownWritten).domain();
495
183
496
183
    if (!BothWritten.is_subset(CommonWritten)) {
497
24
      if (OS) {
498
0
        auto Conflicting = BothWritten.subtract(CommonWritten);
499
0
        auto ExistingConflictingWritten =
500
0
            Existing.Written.intersect_domain(Conflicting);
501
0
        auto ProposedConflictingWritten =
502
0
            Proposed.Written.intersect_domain(Conflicting);
503
0
504
0
        OS->indent(Indent) << "Proposed writes at the same time as an already "
505
0
                              "Existing write\n";
506
0
        OS->indent(Indent) << "Conflicting writes: " << Conflicting << "\n";
507
0
        if (!ExistingConflictingWritten.is_empty())
508
0
          OS->indent(Indent)
509
0
              << "Exiting write:      " << ExistingConflictingWritten << "\n";
510
0
        if (!ProposedConflictingWritten.is_empty())
511
0
          OS->indent(Indent)
512
0
              << "Proposed write:     " << ProposedConflictingWritten << "\n";
513
0
      }
514
24
      return true;
515
24
    }
516
159
517
159
    return false;
518
159
  }
519
};
520
521
/// Implementation of the DeLICM/DePRE transformation.
522
class DeLICMImpl : public ZoneAlgorithm {
523
private:
524
  /// Knowledge before any transformation took place.
525
  Knowledge OriginalZone;
526
527
  /// Current knowledge of the SCoP including all already applied
528
  /// transformations.
529
  Knowledge Zone;
530
531
  /// Number of StoreInsts something can be mapped to.
532
  int NumberOfCompatibleTargets = 0;
533
534
  /// The number of StoreInsts to which at least one value or PHI has been
535
  /// mapped to.
536
  int NumberOfTargetsMapped = 0;
537
538
  /// The number of llvm::Value mapped to some array element.
539
  int NumberOfMappedValueScalars = 0;
540
541
  /// The number of PHIs mapped to some array element.
542
  int NumberOfMappedPHIScalars = 0;
543
544
  /// Determine whether two knowledges are conflicting with each other.
545
  ///
546
  /// @see Knowledge::isConflicting
547
41
  bool isConflicting(const Knowledge &Proposed) {
548
41
    raw_ostream *OS = nullptr;
549
41
    DEBUG(OS = &llvm::dbgs());
550
41
    return Knowledge::isConflicting(Zone, Proposed, OS, 4);
551
41
  }
552
553
  /// Determine whether @p SAI is a scalar that can be mapped to an array
554
  /// element.
555
44
  bool isMappable(const ScopArrayInfo *SAI) {
556
44
    assert(SAI);
557
44
558
44
    if (SAI->isValueKind()) {
559
28
      auto *MA = S->getValueDef(SAI);
560
28
      if (!MA) {
561
1
        DEBUG(dbgs()
562
1
              << "    Reject because value is read-only within the scop\n");
563
1
        return false;
564
1
      }
565
27
566
27
      // Mapping if value is used after scop is not supported. The code
567
27
      // generator would need to reload the scalar after the scop, but it
568
27
      // does not have the information to where it is mapped to. Only the
569
27
      // MemoryAccesses have that information, not the ScopArrayInfo.
570
27
      auto Inst = MA->getAccessInstruction();
571
41
      for (auto User : Inst->users()) {
572
41
        if (!isa<Instruction>(User))
573
0
          return false;
574
41
        auto UserInst = cast<Instruction>(User);
575
41
576
41
        if (!S->contains(UserInst)) {
577
0
          DEBUG(dbgs() << "    Reject because value is escaping\n");
578
0
          return false;
579
0
        }
580
27
      }
581
27
582
27
      return true;
583
27
    }
584
16
585
16
    if (SAI->isPHIKind()) {
586
16
      auto *MA = S->getPHIRead(SAI);
587
16
      assert(MA);
588
16
589
16
      // Mapping of an incoming block from before the SCoP is not supported by
590
16
      // the code generator.
591
16
      auto PHI = cast<PHINode>(MA->getAccessInstruction());
592
32
      for (auto Incoming : PHI->blocks()) {
593
32
        if (!S->contains(Incoming)) {
594
0
          DEBUG(dbgs() << "    Reject because at least one incoming block is "
595
0
                          "not in the scop region\n");
596
0
          return false;
597
0
        }
598
16
      }
599
16
600
16
      return true;
601
16
    }
602
0
603
0
    DEBUG(dbgs() << "    Reject ExitPHI or other non-value\n");
604
0
    return false;
605
0
  }
606
607
  /// Compute the uses of a MemoryKind::Value and its lifetime (from its
608
  /// definition to the last use).
609
  ///
610
  /// @param SAI The ScopArrayInfo representing the value's storage.
611
  ///
612
  /// @return { DomainDef[] -> DomainUse[] }, { DomainDef[] -> Zone[] }
613
  ///         First element is the set of uses for each definition.
614
  ///         The second is the lifetime of each definition.
615
  std::tuple<isl::union_map, isl::map>
616
25
  computeValueUses(const ScopArrayInfo *SAI) {
617
25
    assert(SAI->isValueKind());
618
25
619
25
    // { DomainRead[] }
620
25
    auto Reads = makeEmptyUnionSet();
621
25
622
25
    // Find all uses.
623
25
    for (auto *MA : S->getValueUses(SAI))
624
33
      Reads =
625
33
          give(isl_union_set_add_set(Reads.take(), getDomainFor(MA).take()));
626
25
627
25
    // { DomainRead[] -> Scatter[] }
628
25
    auto ReadSchedule = getScatterFor(Reads);
629
25
630
25
    auto *DefMA = S->getValueDef(SAI);
631
25
    assert(DefMA);
632
25
633
25
    // { DomainDef[] }
634
25
    auto Writes = getDomainFor(DefMA);
635
25
636
25
    // { DomainDef[] -> Scatter[] }
637
25
    auto WriteScatter = getScatterFor(Writes);
638
25
639
25
    // { Scatter[] -> DomainDef[] }
640
25
    auto ReachDef = getScalarReachingDefinition(DefMA->getStatement());
641
25
642
25
    // { [DomainDef[] -> Scatter[]] -> DomainUse[] }
643
25
    auto Uses = give(
644
25
        isl_union_map_apply_range(isl_union_map_from_map(isl_map_range_map(
645
25
                                      isl_map_reverse(ReachDef.take()))),
646
25
                                  isl_union_map_reverse(ReadSchedule.take())));
647
25
648
25
    // { DomainDef[] -> Scatter[] }
649
25
    auto UseScatter =
650
25
        singleton(give(isl_union_set_unwrap(isl_union_map_domain(Uses.copy()))),
651
25
                  give(isl_space_map_from_domain_and_range(
652
25
                      isl_set_get_space(Writes.keep()), ScatterSpace.copy())));
653
25
654
25
    // { DomainDef[] -> Zone[] }
655
25
    auto Lifetime = betweenScatter(WriteScatter, UseScatter, false, true);
656
25
657
25
    // { DomainDef[] -> DomainRead[] }
658
25
    auto DefUses = give(isl_union_map_domain_factor_domain(Uses.take()));
659
25
660
25
    return std::make_pair(DefUses, Lifetime);
661
25
  }
662
663
  /// Try to map a MemoryKind::Value to a given array element.
664
  ///
665
  /// @param SAI       Representation of the scalar's memory to map.
666
  /// @param TargetElt { Scatter[] -> Element[] }
667
  ///                  Suggestion where to map a scalar to when at a timepoint.
668
  ///
669
  /// @return true if the scalar was successfully mapped.
670
26
  bool tryMapValue(const ScopArrayInfo *SAI, isl::map TargetElt) {
671
26
    assert(SAI->isValueKind());
672
26
673
26
    auto *DefMA = S->getValueDef(SAI);
674
26
    assert(DefMA->isValueKind());
675
26
    assert(DefMA->isMustWrite());
676
26
    auto *V = DefMA->getAccessValue();
677
26
    auto *DefInst = DefMA->getAccessInstruction();
678
26
679
26
    // Stop if the scalar has already been mapped.
680
26
    if (!DefMA->getLatestScopArrayInfo()->isValueKind())
681
0
      return false;
682
26
683
26
    // { DomainDef[] -> Scatter[] }
684
26
    auto DefSched = getScatterFor(DefMA);
685
26
686
26
    // Where each write is mapped to, according to the suggestion.
687
26
    // { DomainDef[] -> Element[] }
688
26
    auto DefTarget = give(isl_map_apply_domain(
689
26
        TargetElt.copy(), isl_map_reverse(DefSched.copy())));
690
26
    simplify(DefTarget);
691
26
    DEBUG(dbgs() << "    Def Mapping: " << DefTarget << '\n');
692
26
693
26
    auto OrigDomain = getDomainFor(DefMA);
694
26
    auto MappedDomain = give(isl_map_domain(DefTarget.copy()));
695
26
    if (!isl_set_is_subset(OrigDomain.keep(), MappedDomain.keep())) {
696
1
      DEBUG(dbgs()
697
1
            << "    Reject because mapping does not encompass all instances\n");
698
1
      return false;
699
1
    }
700
25
701
25
    // { DomainDef[] -> Zone[] }
702
25
    isl::map Lifetime;
703
25
704
25
    // { DomainDef[] -> DomainUse[] }
705
25
    isl::union_map DefUses;
706
25
707
25
    std::tie(DefUses, Lifetime) = computeValueUses(SAI);
708
25
    DEBUG(dbgs() << "    Lifetime: " << Lifetime << '\n');
709
25
710
25
    /// { [Element[] -> Zone[]] }
711
25
    auto EltZone = give(
712
25
        isl_map_wrap(isl_map_apply_domain(Lifetime.copy(), DefTarget.copy())));
713
25
    simplify(EltZone);
714
25
715
25
    // When known knowledge is disabled, just return the unknown value. It will
716
25
    // either get filtered out or conflict with itself.
717
25
    // { DomainDef[] -> ValInst[] }
718
25
    isl::map ValInst;
719
25
    if (DelicmComputeKnown)
720
25
      ValInst = makeValInst(V, DefMA->getStatement(),
721
25
                            LI->getLoopFor(DefInst->getParent()));
722
0
    else
723
0
      ValInst = makeUnknownForDomain(DefMA->getStatement());
724
25
725
25
    // { DomainDef[] -> [Element[] -> Zone[]] }
726
25
    auto EltKnownTranslator =
727
25
        give(isl_map_range_product(DefTarget.copy(), Lifetime.copy()));
728
25
729
25
    // { [Element[] -> Zone[]] -> ValInst[] }
730
25
    auto EltKnown =
731
25
        give(isl_map_apply_domain(ValInst.copy(), EltKnownTranslator.take()));
732
25
    simplify(EltKnown);
733
25
734
25
    // { DomainDef[] -> [Element[] -> Scatter[]] }
735
25
    auto WrittenTranslator =
736
25
        give(isl_map_range_product(DefTarget.copy(), DefSched.take()));
737
25
738
25
    // { [Element[] -> Scatter[]] -> ValInst[] }
739
25
    auto DefEltSched =
740
25
        give(isl_map_apply_domain(ValInst.copy(), WrittenTranslator.take()));
741
25
    simplify(DefEltSched);
742
25
743
25
    Knowledge Proposed(EltZone, nullptr, filterKnownValInst(EltKnown),
744
25
                       DefEltSched);
745
25
    if (isConflicting(Proposed))
746
2
      return false;
747
23
748
23
    // { DomainUse[] -> Element[] }
749
23
    auto UseTarget = give(
750
23
        isl_union_map_apply_range(isl_union_map_reverse(DefUses.take()),
751
23
                                  isl_union_map_from_map(DefTarget.copy())));
752
23
753
23
    mapValue(SAI, std::move(DefTarget), std::move(UseTarget),
754
23
             std::move(Lifetime), std::move(Proposed));
755
23
    return true;
756
23
  }
757
758
  /// After a scalar has been mapped, update the global knowledge.
759
39
  void applyLifetime(Knowledge Proposed) {
760
39
    Zone.learnFrom(std::move(Proposed));
761
39
  }
762
763
  /// Map a MemoryKind::Value scalar to an array element.
764
  ///
765
  /// Callers must have ensured that the mapping is valid and not conflicting.
766
  ///
767
  /// @param SAI       The ScopArrayInfo representing the scalar's memory to
768
  ///                  map.
769
  /// @param DefTarget { DomainDef[] -> Element[] }
770
  ///                  The array element to map the scalar to.
771
  /// @param UseTarget { DomainUse[] -> Element[] }
772
  ///                  The array elements the uses are mapped to.
773
  /// @param Lifetime  { DomainDef[] -> Zone[] }
774
  ///                  The lifetime of each llvm::Value definition for
775
  ///                  reporting.
776
  /// @param Proposed  Mapping constraints for reporting.
777
  void mapValue(const ScopArrayInfo *SAI, isl::map DefTarget,
778
                isl::union_map UseTarget, isl::map Lifetime,
779
23
                Knowledge Proposed) {
780
23
    // Redirect the read accesses.
781
30
    for (auto *MA : S->getValueUses(SAI)) {
782
30
      // { DomainUse[] }
783
30
      auto Domain = getDomainFor(MA);
784
30
785
30
      // { DomainUse[] -> Element[] }
786
30
      auto NewAccRel = give(isl_union_map_intersect_domain(
787
30
          UseTarget.copy(), isl_union_set_from_set(Domain.take())));
788
30
      simplify(NewAccRel);
789
30
790
30
      assert(isl_union_map_n_map(NewAccRel.keep()) == 1);
791
30
      MA->setNewAccessRelation(isl::map::from_union_map(NewAccRel));
792
30
    }
793
23
794
23
    auto *WA = S->getValueDef(SAI);
795
23
    WA->setNewAccessRelation(DefTarget);
796
23
    applyLifetime(Proposed);
797
23
798
23
    MappedValueScalars++;
799
23
    NumberOfMappedValueScalars += 1;
800
23
  }
801
802
  isl::map makeValInst(Value *Val, ScopStmt *UserStmt, Loop *Scope,
803
57
                       bool IsCertain = true) {
804
57
    // When known knowledge is disabled, just return the unknown value. It will
805
57
    // either get filtered out or conflict with itself.
806
57
    if (!DelicmComputeKnown)
807
0
      return makeUnknownForDomain(UserStmt);
808
57
    return ZoneAlgorithm::makeValInst(Val, UserStmt, Scope, IsCertain);
809
57
  }
810
811
  /// Express the incoming values of a PHI for each incoming statement in an
812
  /// isl::union_map.
813
  ///
814
  /// @param SAI The PHI scalar represented by a ScopArrayInfo.
815
  ///
816
  /// @return { PHIWriteDomain[] -> ValInst[] }
817
16
  isl::union_map determinePHIWrittenValues(const ScopArrayInfo *SAI) {
818
16
    auto Result = makeEmptyUnionMap();
819
16
820
16
    // Collect the incoming values.
821
32
    for (auto *MA : S->getPHIIncomings(SAI)) {
822
32
      // { DomainWrite[] -> ValInst[] }
823
32
      isl::union_map ValInst;
824
32
      auto *WriteStmt = MA->getStatement();
825
32
826
32
      auto Incoming = MA->getIncoming();
827
32
      assert(!Incoming.empty());
828
32
      if (Incoming.size() == 1) {
829
32
        ValInst = makeValInst(Incoming[0].second, WriteStmt,
830
32
                              LI->getLoopFor(Incoming[0].first));
831
32
      } else {
832
0
        // If the PHI is in a subregion's exit node it can have multiple
833
0
        // incoming values (+ maybe another incoming edge from an unrelated
834
0
        // block). We cannot directly represent it as a single llvm::Value.
835
0
        // We currently model it as unknown value, but modeling as the PHIInst
836
0
        // itself could be OK, too.
837
0
        ValInst = makeUnknownForDomain(WriteStmt);
838
0
      }
839
32
840
32
      Result = give(isl_union_map_union(Result.take(), ValInst.take()));
841
32
    }
842
16
843
16
    assert(isl_union_map_is_single_valued(Result.keep()) == isl_bool_true &&
844
16
           "Cannot have multiple incoming values for same incoming statement");
845
16
    return Result;
846
16
  }
847
848
  /// Try to map a MemoryKind::PHI scalar to a given array element.
849
  ///
850
  /// @param SAI       Representation of the scalar's memory to map.
851
  /// @param TargetElt { Scatter[] -> Element[] }
852
  ///                  Suggestion where to map the scalar to when at a
853
  ///                  timepoint.
854
  ///
855
  /// @return true if the PHI scalar has been mapped.
856
16
  bool tryMapPHI(const ScopArrayInfo *SAI, isl::map TargetElt) {
857
16
    auto *PHIRead = S->getPHIRead(SAI);
858
16
    assert(PHIRead->isPHIKind());
859
16
    assert(PHIRead->isRead());
860
16
861
16
    // Skip if already been mapped.
862
16
    if (!PHIRead->getLatestScopArrayInfo()->isPHIKind())
863
0
      return false;
864
16
865
16
    // { DomainRead[] -> Scatter[] }
866
16
    auto PHISched = getScatterFor(PHIRead);
867
16
868
16
    // { DomainRead[] -> Element[] }
869
16
    auto PHITarget =
870
16
        give(isl_map_apply_range(PHISched.copy(), TargetElt.copy()));
871
16
    simplify(PHITarget);
872
16
    DEBUG(dbgs() << "    Mapping: " << PHITarget << '\n');
873
16
874
16
    auto OrigDomain = getDomainFor(PHIRead);
875
16
    auto MappedDomain = give(isl_map_domain(PHITarget.copy()));
876
16
    if (!isl_set_is_subset(OrigDomain.keep(), MappedDomain.keep())) {
877
0
      DEBUG(dbgs()
878
0
            << "    Reject because mapping does not encompass all instances\n");
879
0
      return false;
880
0
    }
881
16
882
16
    // { DomainRead[] -> DomainWrite[] }
883
16
    auto PerPHIWrites = computePerPHI(SAI);
884
16
885
16
    // { DomainWrite[] -> Element[] }
886
16
    auto WritesTarget = give(isl_union_map_reverse(isl_union_map_apply_domain(
887
16
        PerPHIWrites.copy(), isl_union_map_from_map(PHITarget.copy()))));
888
16
    simplify(WritesTarget);
889
16
890
16
    // { DomainWrite[] }
891
16
    auto UniverseWritesDom = give(isl_union_set_empty(ParamSpace.copy()));
892
16
893
16
    for (auto *MA : S->getPHIIncomings(SAI))
894
32
      UniverseWritesDom = give(isl_union_set_add_set(UniverseWritesDom.take(),
895
32
                                                     getDomainFor(MA).take()));
896
16
897
16
    auto RelevantWritesTarget = WritesTarget;
898
16
    if (DelicmOverapproximateWrites)
899
6
      WritesTarget = expandMapping(WritesTarget, UniverseWritesDom);
900
16
901
16
    auto ExpandedWritesDom = give(isl_union_map_domain(WritesTarget.copy()));
902
16
    if (!DelicmPartialWrites &&
903
16
        !isl_union_set_is_subset(UniverseWritesDom.keep(),
904
2
                                 ExpandedWritesDom.keep())) {
905
0
      DEBUG(dbgs() << "    Reject because did not find PHI write mapping for "
906
0
                      "all instances\n");
907
0
      if (DelicmOverapproximateWrites)
908
0
        DEBUG(dbgs() << "      Relevant Mapping:    " << RelevantWritesTarget
909
0
                     << '\n');
910
0
      DEBUG(dbgs() << "      Deduced Mapping:     " << WritesTarget << '\n');
911
0
      DEBUG(dbgs() << "      Missing instances:    "
912
0
                   << give(isl_union_set_subtract(UniverseWritesDom.copy(),
913
0
                                                  ExpandedWritesDom.copy()))
914
0
                   << '\n');
915
0
      return false;
916
0
    }
917
16
918
16
    //  { DomainRead[] -> Scatter[] }
919
16
    auto PerPHIWriteScatter = give(isl_map_from_union_map(
920
16
        isl_union_map_apply_range(PerPHIWrites.copy(), Schedule.copy())));
921
16
922
16
    // { DomainRead[] -> Zone[] }
923
16
    auto Lifetime = betweenScatter(PerPHIWriteScatter, PHISched, false, true);
924
16
    simplify(Lifetime);
925
16
    DEBUG(dbgs() << "    Lifetime: " << Lifetime << "\n");
926
16
927
16
    // { DomainWrite[] -> Zone[] }
928
16
    auto WriteLifetime = give(isl_union_map_apply_domain(
929
16
        isl_union_map_from_map(Lifetime.copy()), PerPHIWrites.copy()));
930
16
931
16
    // { DomainWrite[] -> ValInst[] }
932
16
    auto WrittenValue = determinePHIWrittenValues(SAI);
933
16
934
16
    // { DomainWrite[] -> [Element[] -> Scatter[]] }
935
16
    auto WrittenTranslator =
936
16
        give(isl_union_map_range_product(WritesTarget.copy(), Schedule.copy()));
937
16
938
16
    // { [Element[] -> Scatter[]] -> ValInst[] }
939
16
    auto Written = give(isl_union_map_apply_domain(WrittenValue.copy(),
940
16
                                                   WrittenTranslator.copy()));
941
16
    simplify(Written);
942
16
943
16
    // { DomainWrite[] -> [Element[] -> Zone[]] }
944
16
    auto LifetimeTranslator = give(
945
16
        isl_union_map_range_product(WritesTarget.copy(), WriteLifetime.copy()));
946
16
947
16
    // { DomainWrite[] -> ValInst[] }
948
16
    auto WrittenKnownValue = filterKnownValInst(WrittenValue);
949
16
950
16
    // { [Element[] -> Zone[]] -> ValInst[] }
951
16
    auto EltLifetimeInst = give(isl_union_map_apply_domain(
952
16
        WrittenKnownValue.copy(), LifetimeTranslator.copy()));
953
16
    simplify(EltLifetimeInst);
954
16
955
16
    // { [Element[] -> Zone[] }
956
16
    auto Occupied = give(isl_union_map_range(LifetimeTranslator.copy()));
957
16
    simplify(Occupied);
958
16
959
16
    Knowledge Proposed(Occupied, nullptr, EltLifetimeInst, Written);
960
16
    if (isConflicting(Proposed))
961
0
      return false;
962
16
963
16
    mapPHI(SAI, std::move(PHITarget), std::move(WritesTarget),
964
16
           std::move(Lifetime), std::move(Proposed));
965
16
    return true;
966
16
  }
967
968
  /// Map a MemoryKind::PHI scalar to an array element.
969
  ///
970
  /// Callers must have ensured that the mapping is valid and not conflicting
971
  /// with the common knowledge.
972
  ///
973
  /// @param SAI         The ScopArrayInfo representing the scalar's memory to
974
  ///                    map.
975
  /// @param ReadTarget  { DomainRead[] -> Element[] }
976
  ///                    The array element to map the scalar to.
977
  /// @param WriteTarget { DomainWrite[] -> Element[] }
978
  ///                    New access target for each PHI incoming write.
979
  /// @param Lifetime    { DomainRead[] -> Zone[] }
980
  ///                    The lifetime of each PHI for reporting.
981
  /// @param Proposed    Mapping constraints for reporting.
982
  void mapPHI(const ScopArrayInfo *SAI, isl::map ReadTarget,
983
              isl::union_map WriteTarget, isl::map Lifetime,
984
16
              Knowledge Proposed) {
985
16
    // { Element[] }
986
16
    isl::space ElementSpace = ReadTarget.get_space().range();
987
16
988
16
    // Redirect the PHI incoming writes.
989
32
    for (auto *MA : S->getPHIIncomings(SAI)) {
990
32
      // { DomainWrite[] }
991
32
      auto Domain = getDomainFor(MA);
992
32
993
32
      // { DomainWrite[] -> Element[] }
994
32
      auto NewAccRel = give(isl_union_map_intersect_domain(
995
32
          WriteTarget.copy(), isl_union_set_from_set(Domain.copy())));
996
32
      simplify(NewAccRel);
997
32
998
32
      isl::space NewAccRelSpace =
999
32
          Domain.get_space().map_from_domain_and_range(ElementSpace);
1000
32
      isl::map NewAccRelMap = singleton(NewAccRel, NewAccRelSpace);
1001
32
      MA->setNewAccessRelation(NewAccRelMap);
1002
32
    }
1003
16
1004
16
    // Redirect the PHI read.
1005
16
    auto *PHIRead = S->getPHIRead(SAI);
1006
16
    PHIRead->setNewAccessRelation(ReadTarget);
1007
16
    applyLifetime(Proposed);
1008
16
1009
16
    MappedPHIScalars++;
1010
16
    NumberOfMappedPHIScalars++;
1011
16
  }
1012
1013
  /// Search and map scalars to memory overwritten by @p TargetStoreMA.
1014
  ///
1015
  /// Start trying to map scalars that are used in the same statement as the
1016
  /// store. For every successful mapping, try to also map scalars of the
1017
  /// statements where those are written. Repeat, until no more mapping
1018
  /// opportunity is found.
1019
  ///
1020
  /// There is currently no preference in which order scalars are tried.
1021
  /// Ideally, we would direct it towards a load instruction of the same array
1022
  /// element.
1023
16
  bool collapseScalarsToStore(MemoryAccess *TargetStoreMA) {
1024
16
    assert(TargetStoreMA->isLatestArrayKind());
1025
16
    assert(TargetStoreMA->isMustWrite());
1026
16
1027
16
    auto TargetStmt = TargetStoreMA->getStatement();
1028
16
1029
16
    // { DomTarget[] }
1030
16
    auto TargetDom = getDomainFor(TargetStmt);
1031
16
1032
16
    // { DomTarget[] -> Element[] }
1033
16
    auto TargetAccRel = getAccessRelationFor(TargetStoreMA);
1034
16
1035
16
    // { Zone[] -> DomTarget[] }
1036
16
    // For each point in time, find the next target store instance.
1037
16
    auto Target =
1038
16
        computeScalarReachingOverwrite(Schedule, TargetDom, false, true);
1039
16
1040
16
    // { Zone[] -> Element[] }
1041
16
    // Use the target store's write location as a suggestion to map scalars to.
1042
16
    auto EltTarget =
1043
16
        give(isl_map_apply_range(Target.take(), TargetAccRel.take()));
1044
16
    simplify(EltTarget);
1045
16
    DEBUG(dbgs() << "    Target mapping is " << EltTarget << '\n');
1046
16
1047
16
    // Stack of elements not yet processed.
1048
16
    SmallVector<MemoryAccess *, 16> Worklist;
1049
16
1050
16
    // Set of scalars already tested.
1051
16
    SmallPtrSet<const ScopArrayInfo *, 16> Closed;
1052
16
1053
16
    // Lambda to add all scalar reads to the work list.
1054
44
    auto ProcessAllIncoming = [&](ScopStmt *Stmt) {
1055
85
      for (auto *MA : *Stmt) {
1056
85
        if (!MA->isLatestScalarKind())
1057
57
          continue;
1058
28
        if (!MA->isRead())
1059
4
          continue;
1060
24
1061
24
        Worklist.push_back(MA);
1062
24
      }
1063
44
    };
1064
16
1065
16
    auto *WrittenVal = TargetStoreMA->getAccessInstruction()->getOperand(0);
1066
16
    if (auto *WrittenValInputMA = TargetStmt->lookupInputAccessOf(WrittenVal))
1067
12
      Worklist.push_back(WrittenValInputMA);
1068
4
    else
1069
4
      ProcessAllIncoming(TargetStmt);
1070
16
1071
16
    auto AnyMapped = false;
1072
16
    auto &DL = S->getRegion().getEntry()->getModule()->getDataLayout();
1073
16
    auto StoreSize =
1074
16
        DL.getTypeAllocSize(TargetStoreMA->getAccessValue()->getType());
1075
16
1076
67
    while (!Worklist.empty()) {
1077
51
      auto *MA = Worklist.pop_back_val();
1078
51
1079
51
      auto *SAI = MA->getScopArrayInfo();
1080
51
      if (Closed.count(SAI))
1081
7
        continue;
1082
44
      Closed.insert(SAI);
1083
44
      DEBUG(dbgs() << "\n    Trying to map " << MA << " (SAI: " << SAI
1084
44
                   << ")\n");
1085
44
1086
44
      // Skip non-mappable scalars.
1087
44
      if (!isMappable(SAI))
1088
1
        continue;
1089
43
1090
43
      auto MASize = DL.getTypeAllocSize(MA->getAccessValue()->getType());
1091
43
      if (MASize > StoreSize) {
1092
1
        DEBUG(dbgs() << "    Reject because storage size is insufficient\n");
1093
1
        continue;
1094
1
      }
1095
42
1096
42
      // Try to map MemoryKind::Value scalars.
1097
42
      if (SAI->isValueKind()) {
1098
26
        if (!tryMapValue(SAI, EltTarget))
1099
3
          continue;
1100
23
1101
23
        auto *DefAcc = S->getValueDef(SAI);
1102
23
        ProcessAllIncoming(DefAcc->getStatement());
1103
23
1104
23
        AnyMapped = true;
1105
23
        continue;
1106
23
      }
1107
16
1108
16
      // Try to map MemoryKind::PHI scalars.
1109
16
      if (SAI->isPHIKind()) {
1110
16
        if (!tryMapPHI(SAI, EltTarget))
1111
0
          continue;
1112
16
        // Add inputs of all incoming statements to the worklist. Prefer the
1113
16
        // input accesses of the incoming blocks.
1114
32
        
for (auto *PHIWrite : S->getPHIIncomings(SAI)) 16
{
1115
32
          auto *PHIWriteStmt = PHIWrite->getStatement();
1116
32
          bool FoundAny = false;
1117
32
          for (auto Incoming : PHIWrite->getIncoming()) {
1118
32
            auto *IncomingInputMA =
1119
32
                PHIWriteStmt->lookupInputAccessOf(Incoming.second);
1120
32
            if (!IncomingInputMA)
1121
17
              continue;
1122
15
1123
15
            Worklist.push_back(IncomingInputMA);
1124
15
            FoundAny = true;
1125
15
          }
1126
32
1127
32
          if (!FoundAny)
1128
17
            ProcessAllIncoming(PHIWrite->getStatement());
1129
32
        }
1130
16
1131
16
        AnyMapped = true;
1132
16
        continue;
1133
16
      }
1134
51
    }
1135
16
1136
16
    if (AnyMapped) {
1137
13
      TargetsMapped++;
1138
13
      NumberOfTargetsMapped++;
1139
13
    }
1140
16
    return AnyMapped;
1141
16
  }
1142
1143
  /// Compute when an array element is unused.
1144
  ///
1145
  /// @return { [Element[] -> Zone[]] }
1146
18
  isl::union_set computeLifetime() const {
1147
18
    // { Element[] -> Zone[] }
1148
18
    auto ArrayUnused = computeArrayUnused(Schedule, AllMustWrites, AllReads,
1149
18
                                          false, false, true);
1150
18
1151
18
    auto Result = give(isl_union_map_wrap(ArrayUnused.copy()));
1152
18
1153
18
    simplify(Result);
1154
18
    return Result;
1155
18
  }
1156
1157
  /// Determine when an array element is written to, and which value instance is
1158
  /// written.
1159
  ///
1160
  /// @return { [Element[] -> Scatter[]] -> ValInst[] }
1161
18
  isl::union_map computeWritten() const {
1162
18
    // { [Element[] -> Scatter[]] -> ValInst[] }
1163
18
    auto EltWritten = applyDomainRange(AllWriteValInst, Schedule);
1164
18
1165
18
    simplify(EltWritten);
1166
18
    return EltWritten;
1167
18
  }
1168
1169
  /// Determine whether an access touches at most one element.
1170
  ///
1171
  /// The accessed element could be a scalar or accessing an array with constant
1172
  /// subscript, such that all instances access only that element.
1173
  ///
1174
  /// @param MA The access to test.
1175
  ///
1176
  /// @return True, if zero or one elements are accessed; False if at least two
1177
  ///         different elements are accessed.
1178
20
  bool isScalarAccess(MemoryAccess *MA) {
1179
20
    auto Map = getAccessRelationFor(MA);
1180
20
    auto Set = give(isl_map_range(Map.take()));
1181
20
    return isl_set_is_singleton(Set.keep()) == isl_bool_true;
1182
20
  }
1183
1184
  /// Print mapping statistics to @p OS.
1185
17
  void printStatistics(llvm::raw_ostream &OS, int Indent = 0) const {
1186
17
    OS.indent(Indent) << "Statistics {\n";
1187
17
    OS.indent(Indent + 4) << "Compatible overwrites: "
1188
17
                          << NumberOfCompatibleTargets << "\n";
1189
17
    OS.indent(Indent + 4) << "Overwrites mapped to:  " << NumberOfTargetsMapped
1190
17
                          << '\n';
1191
17
    OS.indent(Indent + 4) << "Value scalars mapped:  "
1192
17
                          << NumberOfMappedValueScalars << '\n';
1193
17
    OS.indent(Indent + 4) << "PHI scalars mapped:    "
1194
17
                          << NumberOfMappedPHIScalars << '\n';
1195
17
    OS.indent(Indent) << "}\n";
1196
17
  }
1197
1198
  /// Return whether at least one transformation been applied.
1199
17
  bool isModified() const { return NumberOfTargetsMapped > 0; }
1200
1201
public:
1202
18
  DeLICMImpl(Scop *S, LoopInfo *LI) : ZoneAlgorithm("polly-delicm", S, LI) {}
1203
1204
  /// Calculate the lifetime (definition to last use) of every array element.
1205
  ///
1206
  /// @return True if the computed lifetimes (#Zone) is usable.
1207
18
  bool computeZone() {
1208
18
    // Check that nothing strange occurs.
1209
18
    collectCompatibleElts();
1210
18
1211
18
    isl::union_set EltUnused;
1212
18
    isl::union_map EltKnown, EltWritten;
1213
18
1214
18
    {
1215
18
      IslMaxOperationsGuard MaxOpGuard(IslCtx.get(), DelicmMaxOps);
1216
18
1217
18
      computeCommon();
1218
18
1219
18
      EltUnused = computeLifetime();
1220
18
      EltKnown = computeKnown(true, false);
1221
18
      EltWritten = computeWritten();
1222
18
    }
1223
18
    DeLICMAnalyzed++;
1224
18
1225
18
    if (!EltUnused || !EltKnown || !EltWritten) {
1226
0
      assert(isl_ctx_last_error(IslCtx.get()) == isl_error_quota &&
1227
0
             "The only reason that these things have not been computed should "
1228
0
             "be if the max-operations limit hit");
1229
0
      DeLICMOutOfQuota++;
1230
0
      DEBUG(dbgs() << "DeLICM analysis exceeded max_operations\n");
1231
0
      DebugLoc Begin, End;
1232
0
      getDebugLocations(getBBPairForRegion(&S->getRegion()), Begin, End);
1233
0
      OptimizationRemarkAnalysis R(DEBUG_TYPE, "OutOfQuota", Begin,
1234
0
                                   S->getEntry());
1235
0
      R << "maximal number of operations exceeded during zone analysis";
1236
0
      S->getFunction().getContext().diagnose(R);
1237
0
      return false;
1238
0
    }
1239
18
1240
18
    Zone = OriginalZone = Knowledge(nullptr, EltUnused, EltKnown, EltWritten);
1241
18
    DEBUG(dbgs() << "Computed Zone:\n"; OriginalZone.print(dbgs(), 4));
1242
18
1243
18
    assert(Zone.isUsable() && OriginalZone.isUsable());
1244
18
    return true;
1245
18
  }
1246
1247
  /// Try to map as many scalars to unused array elements as possible.
1248
  ///
1249
  /// Multiple scalars might be mappable to intersecting unused array element
1250
  /// zones, but we can only chose one. This is a greedy algorithm, therefore
1251
  /// the first processed element claims it.
1252
18
  void greedyCollapse() {
1253
18
    bool Modified = false;
1254
18
1255
86
    for (auto &Stmt : *S) {
1256
168
      for (auto *MA : Stmt) {
1257
168
        if (!MA->isLatestArrayKind())
1258
129
          continue;
1259
39
        if (!MA->isWrite())
1260
16
          continue;
1261
23
1262
23
        if (MA->isMayWrite()) {
1263
0
          DEBUG(dbgs() << "Access " << MA
1264
0
                       << " pruned because it is a MAY_WRITE\n");
1265
0
          OptimizationRemarkMissed R(DEBUG_TYPE, "TargetMayWrite",
1266
0
                                     MA->getAccessInstruction());
1267
0
          R << "Skipped possible mapping target because it is not an "
1268
0
               "unconditional overwrite";
1269
0
          S->getFunction().getContext().diagnose(R);
1270
0
          continue;
1271
0
        }
1272
23
1273
23
        if (Stmt.getNumIterators() == 0) {
1274
3
          DEBUG(dbgs() << "Access " << MA
1275
3
                       << " pruned because it is not in a loop\n");
1276
3
          OptimizationRemarkMissed R(DEBUG_TYPE, "WriteNotInLoop",
1277
3
                                     MA->getAccessInstruction());
1278
3
          R << "skipped possible mapping target because it is not in a loop";
1279
3
          S->getFunction().getContext().diagnose(R);
1280
3
          continue;
1281
3
        }
1282
20
1283
20
        if (isScalarAccess(MA)) {
1284
1
          DEBUG(dbgs() << "Access " << MA
1285
1
                       << " pruned because it writes only a single element\n");
1286
1
          OptimizationRemarkMissed R(DEBUG_TYPE, "ScalarWrite",
1287
1
                                     MA->getAccessInstruction());
1288
1
          R << "skipped possible mapping target because the memory location "
1289
1
               "written to does not depend on its outer loop";
1290
1
          S->getFunction().getContext().diagnose(R);
1291
1
          continue;
1292
1
        }
1293
19
1294
19
        if (!isa<StoreInst>(MA->getAccessInstruction())) {
1295
3
          DEBUG(dbgs() << "Access " << MA
1296
3
                       << " pruned because it is not a StoreInst\n");
1297
3
          OptimizationRemarkMissed R(DEBUG_TYPE, "NotAStore",
1298
3
                                     MA->getAccessInstruction());
1299
3
          R << "skipped possible mapping target because non-store instructions "
1300
3
               "are not supported";
1301
3
          S->getFunction().getContext().diagnose(R);
1302
3
          continue;
1303
3
        }
1304
16
1305
16
        // Check for more than one element acces per statement instance.
1306
16
        // Currently we expect write accesses to be functional, eg. disallow
1307
16
        //
1308
16
        //   { Stmt[0] -> [i] : 0 <= i < 2 }
1309
16
        //
1310
16
        // This may occur when some accesses to the element write/read only
1311
16
        // parts of the element, eg. a single byte. Polly then divides each
1312
16
        // element into subelements of the smallest access length, normal access
1313
16
        // then touch multiple of such subelements. It is very common when the
1314
16
        // array is accesses with memset, memcpy or memmove which take i8*
1315
16
        // arguments.
1316
16
        isl::union_map AccRel = MA->getLatestAccessRelation();
1317
16
        if (!AccRel.is_single_valued().is_true()) {
1318
0
          DEBUG(dbgs() << "Access " << MA
1319
0
                       << " is incompatible because it writes multiple "
1320
0
                          "elements per instance\n");
1321
0
          OptimizationRemarkMissed R(DEBUG_TYPE, "NonFunctionalAccRel",
1322
0
                                     MA->getAccessInstruction());
1323
0
          R << "skipped possible mapping target because it writes more than "
1324
0
               "one element";
1325
0
          S->getFunction().getContext().diagnose(R);
1326
0
          continue;
1327
0
        }
1328
16
1329
16
        isl::union_set TouchedElts = AccRel.range();
1330
16
        if (!TouchedElts.is_subset(CompatibleElts)) {
1331
0
          DEBUG(
1332
0
              dbgs()
1333
0
              << "Access " << MA
1334
0
              << " is incompatible because it touches incompatible elements\n");
1335
0
          OptimizationRemarkMissed R(DEBUG_TYPE, "IncompatibleElts",
1336
0
                                     MA->getAccessInstruction());
1337
0
          R << "skipped possible mapping target because a target location "
1338
0
               "cannot be reliably analyzed";
1339
0
          S->getFunction().getContext().diagnose(R);
1340
0
          continue;
1341
0
        }
1342
16
1343
16
        assert(isCompatibleAccess(MA));
1344
16
        NumberOfCompatibleTargets++;
1345
16
        DEBUG(dbgs() << "Analyzing target access " << MA << "\n");
1346
16
        if (collapseScalarsToStore(MA))
1347
13
          Modified = true;
1348
168
      }
1349
86
    }
1350
18
1351
18
    if (Modified)
1352
13
      DeLICMScopsModified++;
1353
18
  }
1354
1355
  /// Dump the internal information about a performed DeLICM to @p OS.
1356
17
  void print(llvm::raw_ostream &OS, int Indent = 0) {
1357
17
    if (!Zone.isUsable()) {
1358
0
      OS.indent(Indent) << "Zone not computed\n";
1359
0
      return;
1360
0
    }
1361
17
1362
17
    printStatistics(OS, Indent);
1363
17
    if (!isModified()) {
1364
4
      OS.indent(Indent) << "No modification has been made\n";
1365
4
      return;
1366
4
    }
1367
13
    printAccesses(OS, Indent);
1368
13
  }
1369
};
1370
1371
class DeLICM : public ScopPass {
1372
private:
1373
  DeLICM(const DeLICM &) = delete;
1374
  const DeLICM &operator=(const DeLICM &) = delete;
1375
1376
  /// The pass implementation, also holding per-scop data.
1377
  std::unique_ptr<DeLICMImpl> Impl;
1378
1379
18
  void collapseToUnused(Scop &S) {
1380
18
    auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1381
18
    Impl = make_unique<DeLICMImpl>(&S, &LI);
1382
18
1383
18
    if (!Impl->computeZone()) {
1384
0
      DEBUG(dbgs() << "Abort because cannot reliably compute lifetimes\n");
1385
0
      return;
1386
0
    }
1387
18
1388
18
    DEBUG(dbgs() << "Collapsing scalars to unused array elements...\n");
1389
18
    Impl->greedyCollapse();
1390
18
1391
18
    DEBUG(dbgs() << "\nFinal Scop:\n");
1392
18
    DEBUG(dbgs() << S);
1393
18
  }
1394
1395
public:
1396
  static char ID;
1397
18
  explicit DeLICM() : ScopPass(ID) {}
1398
1399
18
  virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
1400
18
    AU.addRequiredTransitive<ScopInfoRegionPass>();
1401
18
    AU.addRequired<LoopInfoWrapperPass>();
1402
18
    AU.setPreservesAll();
1403
18
  }
1404
1405
18
  virtual bool runOnScop(Scop &S) override {
1406
18
    // Free resources for previous scop's computation, if not yet done.
1407
18
    releaseMemory();
1408
18
1409
18
    collapseToUnused(S);
1410
18
1411
18
    auto ScopStats = S.getStatistics();
1412
18
    NumValueWrites += ScopStats.NumValueWrites;
1413
18
    NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
1414
18
    NumPHIWrites += ScopStats.NumPHIWrites;
1415
18
    NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
1416
18
    NumSingletonWrites += ScopStats.NumSingletonWrites;
1417
18
    NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
1418
18
1419
18
    return false;
1420
18
  }
1421
1422
17
  virtual void printScop(raw_ostream &OS, Scop &S) const override {
1423
17
    if (!Impl)
1424
0
      return;
1425
17
    assert(Impl->getScop() == &S);
1426
17
1427
17
    OS << "DeLICM result:\n";
1428
17
    Impl->print(OS);
1429
17
  }
1430
1431
95
  virtual void releaseMemory() override { Impl.reset(); }
1432
};
1433
1434
char DeLICM::ID;
1435
} // anonymous namespace
1436
1437
0
Pass *polly::createDeLICMPass() { return new DeLICM(); }
1438
1439
17.2k
INITIALIZE_PASS_BEGIN(DeLICM, "polly-delicm", "Polly - DeLICM/DePRE", false,
1440
17.2k
                      false)
1441
17.2k
INITIALIZE_PASS_DEPENDENCY(ScopInfoWrapperPass)
1442
17.2k
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1443
17.2k
INITIALIZE_PASS_END(DeLICM, "polly-delicm", "Polly - DeLICM/DePRE", false,
1444
                    false)
1445
1446
bool polly::isConflicting(
1447
    isl::union_set ExistingOccupied, isl::union_set ExistingUnused,
1448
    isl::union_map ExistingKnown, isl::union_map ExistingWrites,
1449
    isl::union_set ProposedOccupied, isl::union_set ProposedUnused,
1450
    isl::union_map ProposedKnown, isl::union_map ProposedWrites,
1451
232
    llvm::raw_ostream *OS, unsigned Indent) {
1452
232
  Knowledge Existing(std::move(ExistingOccupied), std::move(ExistingUnused),
1453
232
                     std::move(ExistingKnown), std::move(ExistingWrites));
1454
232
  Knowledge Proposed(std::move(ProposedOccupied), std::move(ProposedUnused),
1455
232
                     std::move(ProposedKnown), std::move(ProposedWrites));
1456
232
1457
232
  return Knowledge::isConflicting(Existing, Proposed, OS, Indent);
1458
232
}