Coverage Report

Created: 2018-02-20 23:11

/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
29
#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
39
                                        bool InclOverwrite) {
77
39
  return computeReachingWrite(Schedule, Writes, true, InclPrevWrite,
78
39
                              InclOverwrite);
79
39
}
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
39
                                              bool InclOverwrite) {
98
39
99
39
  // { DomainWrite[] }
100
39
  auto WritesMap = give(isl_union_map_from_domain(Writes.take()));
101
39
102
39
  // { [Element[] -> Scatter[]] -> DomainWrite[] }
103
39
  auto Result = computeReachingOverwrite(
104
39
      std::move(Schedule), std::move(WritesMap), InclPrevWrite, InclOverwrite);
105
39
106
39
  return give(isl_union_map_domain_factor_range(Result.take()));
107
39
}
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
39
                                        bool InclOverwrite) {
121
39
  isl::space ScatterSpace = getScatterSpace(Schedule);
122
39
  isl::space DomSpace = Writes.get_space();
123
39
124
39
  isl::union_map ReachOverwrite = computeScalarReachingOverwrite(
125
39
      Schedule, isl::union_set(Writes), InclPrevWrite, InclOverwrite);
126
39
127
39
  isl::space ResultSpace = ScatterSpace.map_from_domain_and_range(DomSpace);
128
39
  return singleton(std::move(ReachOverwrite), ResultSpace);
129
39
}
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
11
isl::union_map expandMapping(isl::union_map Relevant, isl::union_set Universe) {
141
11
  Relevant = Relevant.coalesce();
142
11
  isl::union_set RelevantDomain = Relevant.domain();
143
11
  isl::union_map Simplified = Relevant.gist_domain(RelevantDomain);
144
11
  Simplified = Simplified.coalesce();
145
11
  return Simplified.intersect_domain(Universe);
146
11
}
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
680
  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
98
  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
598
        Known(std::move(Known)), Written(std::move(Written)) {
269
598
    checkConsistency();
270
598
  }
271
272
  /// Return whether this object was not default-constructed.
273
45
  bool isUsable() const { return (Occupied || Unused) && 
Known43
&&
Written43
; }
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
82
  void learnFrom(Knowledge That) {
295
82
    assert(!isConflicting(*this, That));
296
82
    assert(Unused && That.Occupied);
297
82
    assert(
298
82
        !That.Unused &&
299
82
        "This function is only prepared to learn occupied elements from That");
300
82
    assert(!Occupied && "This function does not implement "
301
82
                        "`this->Occupied = "
302
82
                        "give(isl_union_set_union(this->Occupied.take(), "
303
82
                        "That.Occupied.copy()));`");
304
82
305
82
    Unused = give(isl_union_set_subtract(Unused.take(), That.Occupied.copy()));
306
82
    Known = give(isl_union_map_union(Known.take(), That.Known.copy()));
307
82
    Written = give(isl_union_map_union(Written.take(), That.Written.take()));
308
82
309
82
    checkConsistency();
310
82
  }
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
319
                            unsigned Indent = 0) {
334
319
    assert(Existing.Unused);
335
319
    assert(Proposed.Occupied);
336
319
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
319
    // Do the Existing and Proposed lifetimes conflict?
350
319
    //
351
319
    // Lifetimes are described as the cross-product of array elements and zone
352
319
    // intervals in which they are alive (the space { [Element[] -> Zone[]] }).
353
319
    // In the following we call this "element/lifetime interval".
354
319
    //
355
319
    // In order to not conflict, one of the following conditions must apply for
356
319
    // each element/lifetime interval:
357
319
    //
358
319
    // 1. If occupied in one of the knowledges, it is unused in the other.
359
319
    //
360
319
    //   - or -
361
319
    //
362
319
    // 2. Both contain the same value.
363
319
    //
364
319
    // Instead of partitioning the element/lifetime intervals into a part that
365
319
    // both Knowledges occupy (which requires an expensive subtraction) and for
366
319
    // these to check whether they are known to be the same value, we check only
367
319
    // the second condition and ensure that it also applies when then first
368
319
    // condition is true. This is done by adding a wildcard value to
369
319
    // Proposed.Known and Existing.Unused such that they match as a common known
370
319
    // value. We use the "unknown ValInst" for this purpose. Every
371
319
    // Existing.Unused may match with an unknown Proposed.Occupied because these
372
319
    // never are in conflict with each other.
373
319
    auto ProposedOccupiedAnyVal = makeUnknownForDomain(Proposed.Occupied);
374
319
    auto ProposedValues = Proposed.Known.unite(ProposedOccupiedAnyVal);
375
319
376
319
    auto ExistingUnusedAnyVal = makeUnknownForDomain(Existing.Unused);
377
319
    auto ExistingValues = Existing.Known.unite(ExistingUnusedAnyVal);
378
319
379
319
    auto MatchingVals = ExistingValues.intersect(ProposedValues);
380
319
    auto Matches = MatchingVals.domain();
381
319
382
319
    // Any Proposed.Occupied must either have a match between the known values
383
319
    // of Existing and Occupied, or be in Existing.Unused. In the latter case,
384
319
    // the previously added "AnyVal" will match each other.
385
319
    if (!Proposed.Occupied.is_subset(Matches)) {
386
43
      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
43
      return true;
403
43
    }
404
276
405
276
    // Do the writes in Existing conflict with occupied values in Proposed?
406
276
    //
407
276
    // In order to not conflict, it must either write to unused lifetime or
408
276
    // write the same value. To check, we remove the writes that write into
409
276
    // Proposed.Unused (they never conflict) and then see whether the written
410
276
    // value is already in Proposed.Known. If there are multiple known values
411
276
    // and a written value is known under different names, it is enough when one
412
276
    // of the written values (assuming that they are the same value under
413
276
    // different names, e.g. a PHINode and one of the incoming values) matches
414
276
    // one of the known names.
415
276
    //
416
276
    // We convert here the set of lifetimes to actual timepoints. A lifetime is
417
276
    // in conflict with a set of write timepoints, if either a live timepoint is
418
276
    // clearly within the lifetime or if a write happens at the beginning of the
419
276
    // lifetime (where it would conflict with the value that actually writes the
420
276
    // value alive). There is no conflict at the end of a lifetime, as the alive
421
276
    // value will always be read, before it is overwritten again. The last
422
276
    // property holds in Polly for all scalar values and we expect all users of
423
276
    // Knowledge to check this property also for accesses to MemoryKind::Array.
424
276
    auto ProposedFixedDefs =
425
276
        convertZoneToTimepoints(Proposed.Occupied, true, false);
426
276
    auto ProposedFixedKnown =
427
276
        convertZoneToTimepoints(Proposed.Known, isl::dim::in, true, false);
428
276
429
276
    auto ExistingConflictingWrites =
430
276
        Existing.Written.intersect_domain(ProposedFixedDefs);
431
276
    auto ExistingConflictingWritesDomain = ExistingConflictingWrites.domain();
432
276
433
276
    auto CommonWrittenVal =
434
276
        ProposedFixedKnown.intersect(ExistingConflictingWrites);
435
276
    auto CommonWrittenValDomain = CommonWrittenVal.domain();
436
276
437
276
    if (!ExistingConflictingWritesDomain.is_subset(CommonWrittenValDomain)) {
438
26
      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
26
      return true;
454
26
    }
455
250
456
250
    // Do the writes in Proposed conflict with occupied values in Existing?
457
250
    auto ExistingAvailableDefs =
458
250
        convertZoneToTimepoints(Existing.Unused, true, false);
459
250
    auto ExistingKnownDefs =
460
250
        convertZoneToTimepoints(Existing.Known, isl::dim::in, true, false);
461
250
462
250
    auto ProposedWrittenDomain = Proposed.Written.domain();
463
250
    auto KnownIdentical = ExistingKnownDefs.intersect(Proposed.Written);
464
250
    auto IdenticalOrUnused =
465
250
        ExistingAvailableDefs.unite(KnownIdentical.domain());
466
250
    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
226
485
226
    // Does Proposed write at the same time as Existing already does (order of
486
226
    // writes is undefined)? Writing the same value is permitted.
487
226
    auto ExistingWrittenDomain = Existing.Written.domain();
488
226
    auto BothWritten =
489
226
        Existing.Written.domain().intersect(Proposed.Written.domain());
490
226
    auto ExistingKnownWritten = filterKnownValInst(Existing.Written);
491
226
    auto ProposedKnownWritten = filterKnownValInst(Proposed.Written);
492
226
    auto CommonWritten =
493
226
        ExistingKnownWritten.intersect(ProposedKnownWritten).domain();
494
226
495
226
    if (!BothWritten.is_subset(CommonWritten)) {
496
24
      if (OS) {
497
0
        auto Conflicting = BothWritten.subtract(CommonWritten);
498
0
        auto ExistingConflictingWritten =
499
0
            Existing.Written.intersect_domain(Conflicting);
500
0
        auto ProposedConflictingWritten =
501
0
            Proposed.Written.intersect_domain(Conflicting);
502
0
503
0
        OS->indent(Indent) << "Proposed writes at the same time as an already "
504
0
                              "Existing write\n";
505
0
        OS->indent(Indent) << "Conflicting writes: " << Conflicting << "\n";
506
0
        if (!ExistingConflictingWritten.is_empty())
507
0
          OS->indent(Indent)
508
0
              << "Exiting write:      " << ExistingConflictingWritten << "\n";
509
0
        if (!ProposedConflictingWritten.is_empty())
510
0
          OS->indent(Indent)
511
0
              << "Proposed write:     " << ProposedConflictingWritten << "\n";
512
0
      }
513
24
      return true;
514
24
    }
515
202
516
202
    return false;
517
202
  }
518
};
519
520
/// Implementation of the DeLICM/DePRE transformation.
521
class DeLICMImpl : public ZoneAlgorithm {
522
private:
523
  /// Knowledge before any transformation took place.
524
  Knowledge OriginalZone;
525
526
  /// Current knowledge of the SCoP including all already applied
527
  /// transformations.
528
  Knowledge Zone;
529
530
  /// Number of StoreInsts something can be mapped to.
531
  int NumberOfCompatibleTargets = 0;
532
533
  /// The number of StoreInsts to which at least one value or PHI has been
534
  /// mapped to.
535
  int NumberOfTargetsMapped = 0;
536
537
  /// The number of llvm::Value mapped to some array element.
538
  int NumberOfMappedValueScalars = 0;
539
540
  /// The number of PHIs mapped to some array element.
541
  int NumberOfMappedPHIScalars = 0;
542
543
  /// Determine whether two knowledges are conflicting with each other.
544
  ///
545
  /// @see Knowledge::isConflicting
546
87
  bool isConflicting(const Knowledge &Proposed) {
547
87
    raw_ostream *OS = nullptr;
548
87
    DEBUG(OS = &llvm::dbgs());
549
87
    return Knowledge::isConflicting(Zone, Proposed, OS, 4);
550
87
  }
551
552
  /// Determine whether @p SAI is a scalar that can be mapped to an array
553
  /// element.
554
95
  bool isMappable(const ScopArrayInfo *SAI) {
555
95
    assert(SAI);
556
95
557
95
    if (SAI->isValueKind()) {
558
62
      auto *MA = S->getValueDef(SAI);
559
62
      if (!MA) {
560
2
        DEBUG(dbgs()
561
2
              << "    Reject because value is read-only within the scop\n");
562
2
        return false;
563
2
      }
564
60
565
60
      // Mapping if value is used after scop is not supported. The code
566
60
      // generator would need to reload the scalar after the scop, but it
567
60
      // does not have the information to where it is mapped to. Only the
568
60
      // MemoryAccesses have that information, not the ScopArrayInfo.
569
60
      auto Inst = MA->getAccessInstruction();
570
98
      for (auto User : Inst->users()) {
571
98
        if (!isa<Instruction>(User))
572
0
          return false;
573
98
        auto UserInst = cast<Instruction>(User);
574
98
575
98
        if (!S->contains(UserInst)) {
576
1
          DEBUG(dbgs() << "    Reject because value is escaping\n");
577
1
          return false;
578
1
        }
579
98
      }
580
60
581
60
      
return true59
;
582
33
    }
583
33
584
33
    if (SAI->isPHIKind()) {
585
33
      auto *MA = S->getPHIRead(SAI);
586
33
      assert(MA);
587
33
588
33
      // Mapping of an incoming block from before the SCoP is not supported by
589
33
      // the code generator.
590
33
      auto PHI = cast<PHINode>(MA->getAccessInstruction());
591
66
      for (auto Incoming : PHI->blocks()) {
592
66
        if (!S->contains(Incoming)) {
593
0
          DEBUG(dbgs() << "    Reject because at least one incoming block is "
594
0
                          "not in the scop region\n");
595
0
          return false;
596
0
        }
597
66
      }
598
33
599
33
      return true;
600
0
    }
601
0
602
0
    DEBUG(dbgs() << "    Reject ExitPHI or other non-value\n");
603
0
    return false;
604
0
  }
605
606
  /// Compute the uses of a MemoryKind::Value and its lifetime (from its
607
  /// definition to the last use).
608
  ///
609
  /// @param SAI The ScopArrayInfo representing the value's storage.
610
  ///
611
  /// @return { DomainDef[] -> DomainUse[] }, { DomainDef[] -> Zone[] }
612
  ///         First element is the set of uses for each definition.
613
  ///         The second is the lifetime of each definition.
614
  std::tuple<isl::union_map, isl::map>
615
55
  computeValueUses(const ScopArrayInfo *SAI) {
616
55
    assert(SAI->isValueKind());
617
55
618
55
    // { DomainRead[] }
619
55
    auto Reads = makeEmptyUnionSet();
620
55
621
55
    // Find all uses.
622
55
    for (auto *MA : S->getValueUses(SAI))
623
78
      Reads =
624
78
          give(isl_union_set_add_set(Reads.take(), getDomainFor(MA).take()));
625
55
626
55
    // { DomainRead[] -> Scatter[] }
627
55
    auto ReadSchedule = getScatterFor(Reads);
628
55
629
55
    auto *DefMA = S->getValueDef(SAI);
630
55
    assert(DefMA);
631
55
632
55
    // { DomainDef[] }
633
55
    auto Writes = getDomainFor(DefMA);
634
55
635
55
    // { DomainDef[] -> Scatter[] }
636
55
    auto WriteScatter = getScatterFor(Writes);
637
55
638
55
    // { Scatter[] -> DomainDef[] }
639
55
    auto ReachDef = getScalarReachingDefinition(DefMA->getStatement());
640
55
641
55
    // { [DomainDef[] -> Scatter[]] -> DomainUse[] }
642
55
    auto Uses = give(
643
55
        isl_union_map_apply_range(isl_union_map_from_map(isl_map_range_map(
644
55
                                      isl_map_reverse(ReachDef.take()))),
645
55
                                  isl_union_map_reverse(ReadSchedule.take())));
646
55
647
55
    // { DomainDef[] -> Scatter[] }
648
55
    auto UseScatter =
649
55
        singleton(give(isl_union_set_unwrap(isl_union_map_domain(Uses.copy()))),
650
55
                  give(isl_space_map_from_domain_and_range(
651
55
                      isl_set_get_space(Writes.keep()), ScatterSpace.copy())));
652
55
653
55
    // { DomainDef[] -> Zone[] }
654
55
    auto Lifetime = betweenScatter(WriteScatter, UseScatter, false, true);
655
55
656
55
    // { DomainDef[] -> DomainRead[] }
657
55
    auto DefUses = give(isl_union_map_domain_factor_domain(Uses.take()));
658
55
659
55
    return std::make_pair(DefUses, Lifetime);
660
55
  }
661
662
  /// Try to map a MemoryKind::Value to a given array element.
663
  ///
664
  /// @param SAI       Representation of the scalar's memory to map.
665
  /// @param TargetElt { Scatter[] -> Element[] }
666
  ///                  Suggestion where to map a scalar to when at a timepoint.
667
  ///
668
  /// @return true if the scalar was successfully mapped.
669
58
  bool tryMapValue(const ScopArrayInfo *SAI, isl::map TargetElt) {
670
58
    assert(SAI->isValueKind());
671
58
672
58
    auto *DefMA = S->getValueDef(SAI);
673
58
    assert(DefMA->isValueKind());
674
58
    assert(DefMA->isMustWrite());
675
58
    auto *V = DefMA->getAccessValue();
676
58
    auto *DefInst = DefMA->getAccessInstruction();
677
58
678
58
    // Stop if the scalar has already been mapped.
679
58
    if (!DefMA->getLatestScopArrayInfo()->isValueKind())
680
1
      return false;
681
57
682
57
    // { DomainDef[] -> Scatter[] }
683
57
    auto DefSched = getScatterFor(DefMA);
684
57
685
57
    // Where each write is mapped to, according to the suggestion.
686
57
    // { DomainDef[] -> Element[] }
687
57
    auto DefTarget = give(isl_map_apply_domain(
688
57
        TargetElt.copy(), isl_map_reverse(DefSched.copy())));
689
57
    simplify(DefTarget);
690
57
    DEBUG(dbgs() << "    Def Mapping: " << DefTarget << '\n');
691
57
692
57
    auto OrigDomain = getDomainFor(DefMA);
693
57
    auto MappedDomain = give(isl_map_domain(DefTarget.copy()));
694
57
    if (!isl_set_is_subset(OrigDomain.keep(), MappedDomain.keep())) {
695
2
      DEBUG(dbgs()
696
2
            << "    Reject because mapping does not encompass all instances\n");
697
2
      return false;
698
2
    }
699
55
700
55
    // { DomainDef[] -> Zone[] }
701
55
    isl::map Lifetime;
702
55
703
55
    // { DomainDef[] -> DomainUse[] }
704
55
    isl::union_map DefUses;
705
55
706
55
    std::tie(DefUses, Lifetime) = computeValueUses(SAI);
707
55
    DEBUG(dbgs() << "    Lifetime: " << Lifetime << '\n');
708
55
709
55
    /// { [Element[] -> Zone[]] }
710
55
    auto EltZone = give(
711
55
        isl_map_wrap(isl_map_apply_domain(Lifetime.copy(), DefTarget.copy())));
712
55
    simplify(EltZone);
713
55
714
55
    // When known knowledge is disabled, just return the unknown value. It will
715
55
    // either get filtered out or conflict with itself.
716
55
    // { DomainDef[] -> ValInst[] }
717
55
    isl::map ValInst;
718
55
    if (DelicmComputeKnown)
719
55
      ValInst = makeValInst(V, DefMA->getStatement(),
720
55
                            LI->getLoopFor(DefInst->getParent()));
721
0
    else
722
0
      ValInst = makeUnknownForDomain(DefMA->getStatement());
723
55
724
55
    // { DomainDef[] -> [Element[] -> Zone[]] }
725
55
    auto EltKnownTranslator =
726
55
        give(isl_map_range_product(DefTarget.copy(), Lifetime.copy()));
727
55
728
55
    // { [Element[] -> Zone[]] -> ValInst[] }
729
55
    auto EltKnown =
730
55
        give(isl_map_apply_domain(ValInst.copy(), EltKnownTranslator.take()));
731
55
    simplify(EltKnown);
732
55
733
55
    // { DomainDef[] -> [Element[] -> Scatter[]] }
734
55
    auto WrittenTranslator =
735
55
        give(isl_map_range_product(DefTarget.copy(), DefSched.take()));
736
55
737
55
    // { [Element[] -> Scatter[]] -> ValInst[] }
738
55
    auto DefEltSched =
739
55
        give(isl_map_apply_domain(ValInst.copy(), WrittenTranslator.take()));
740
55
    simplify(DefEltSched);
741
55
742
55
    Knowledge Proposed(EltZone, nullptr, filterKnownValInst(EltKnown),
743
55
                       DefEltSched);
744
55
    if (isConflicting(Proposed))
745
5
      return false;
746
50
747
50
    // { DomainUse[] -> Element[] }
748
50
    auto UseTarget = give(
749
50
        isl_union_map_apply_range(isl_union_map_reverse(DefUses.take()),
750
50
                                  isl_union_map_from_map(DefTarget.copy())));
751
50
752
50
    mapValue(SAI, std::move(DefTarget), std::move(UseTarget),
753
50
             std::move(Lifetime), std::move(Proposed));
754
50
    return true;
755
50
  }
756
757
  /// After a scalar has been mapped, update the global knowledge.
758
82
  void applyLifetime(Knowledge Proposed) {
759
82
    Zone.learnFrom(std::move(Proposed));
760
82
  }
761
762
  /// Map a MemoryKind::Value scalar to an array element.
763
  ///
764
  /// Callers must have ensured that the mapping is valid and not conflicting.
765
  ///
766
  /// @param SAI       The ScopArrayInfo representing the scalar's memory to
767
  ///                  map.
768
  /// @param DefTarget { DomainDef[] -> Element[] }
769
  ///                  The array element to map the scalar to.
770
  /// @param UseTarget { DomainUse[] -> Element[] }
771
  ///                  The array elements the uses are mapped to.
772
  /// @param Lifetime  { DomainDef[] -> Zone[] }
773
  ///                  The lifetime of each llvm::Value definition for
774
  ///                  reporting.
775
  /// @param Proposed  Mapping constraints for reporting.
776
  void mapValue(const ScopArrayInfo *SAI, isl::map DefTarget,
777
                isl::union_map UseTarget, isl::map Lifetime,
778
50
                Knowledge Proposed) {
779
50
    // Redirect the read accesses.
780
68
    for (auto *MA : S->getValueUses(SAI)) {
781
68
      // { DomainUse[] }
782
68
      auto Domain = getDomainFor(MA);
783
68
784
68
      // { DomainUse[] -> Element[] }
785
68
      auto NewAccRel = give(isl_union_map_intersect_domain(
786
68
          UseTarget.copy(), isl_union_set_from_set(Domain.take())));
787
68
      simplify(NewAccRel);
788
68
789
68
      assert(isl_union_map_n_map(NewAccRel.keep()) == 1);
790
68
      MA->setNewAccessRelation(isl::map::from_union_map(NewAccRel));
791
68
    }
792
50
793
50
    auto *WA = S->getValueDef(SAI);
794
50
    WA->setNewAccessRelation(DefTarget);
795
50
    applyLifetime(Proposed);
796
50
797
50
    MappedValueScalars++;
798
50
    NumberOfMappedValueScalars += 1;
799
50
  }
800
801
  isl::map makeValInst(Value *Val, ScopStmt *UserStmt, Loop *Scope,
802
119
                       bool IsCertain = true) {
803
119
    // When known knowledge is disabled, just return the unknown value. It will
804
119
    // either get filtered out or conflict with itself.
805
119
    if (!DelicmComputeKnown)
806
0
      return makeUnknownForDomain(UserStmt);
807
119
    return ZoneAlgorithm::makeValInst(Val, UserStmt, Scope, IsCertain);
808
119
  }
809
810
  /// Express the incoming values of a PHI for each incoming statement in an
811
  /// isl::union_map.
812
  ///
813
  /// @param SAI The PHI scalar represented by a ScopArrayInfo.
814
  ///
815
  /// @return { PHIWriteDomain[] -> ValInst[] }
816
32
  isl::union_map determinePHIWrittenValues(const ScopArrayInfo *SAI) {
817
32
    auto Result = makeEmptyUnionMap();
818
32
819
32
    // Collect the incoming values.
820
64
    for (auto *MA : S->getPHIIncomings(SAI)) {
821
64
      // { DomainWrite[] -> ValInst[] }
822
64
      isl::union_map ValInst;
823
64
      auto *WriteStmt = MA->getStatement();
824
64
825
64
      auto Incoming = MA->getIncoming();
826
64
      assert(!Incoming.empty());
827
64
      if (Incoming.size() == 1) {
828
64
        ValInst = makeValInst(Incoming[0].second, WriteStmt,
829
64
                              LI->getLoopFor(Incoming[0].first));
830
64
      } else {
831
0
        // If the PHI is in a subregion's exit node it can have multiple
832
0
        // incoming values (+ maybe another incoming edge from an unrelated
833
0
        // block). We cannot directly represent it as a single llvm::Value.
834
0
        // We currently model it as unknown value, but modeling as the PHIInst
835
0
        // itself could be OK, too.
836
0
        ValInst = makeUnknownForDomain(WriteStmt);
837
0
      }
838
64
839
64
      Result = give(isl_union_map_union(Result.take(), ValInst.take()));
840
64
    }
841
32
842
32
    assert(isl_union_map_is_single_valued(Result.keep()) == isl_bool_true &&
843
32
           "Cannot have multiple incoming values for same incoming statement");
844
32
    return Result;
845
32
  }
846
847
  /// Try to map a MemoryKind::PHI scalar to a given array element.
848
  ///
849
  /// @param SAI       Representation of the scalar's memory to map.
850
  /// @param TargetElt { Scatter[] -> Element[] }
851
  ///                  Suggestion where to map the scalar to when at a
852
  ///                  timepoint.
853
  ///
854
  /// @return true if the PHI scalar has been mapped.
855
33
  bool tryMapPHI(const ScopArrayInfo *SAI, isl::map TargetElt) {
856
33
    auto *PHIRead = S->getPHIRead(SAI);
857
33
    assert(PHIRead->isPHIKind());
858
33
    assert(PHIRead->isRead());
859
33
860
33
    // Skip if already been mapped.
861
33
    if (!PHIRead->getLatestScopArrayInfo()->isPHIKind())
862
0
      return false;
863
33
864
33
    // { DomainRead[] -> Scatter[] }
865
33
    auto PHISched = getScatterFor(PHIRead);
866
33
867
33
    // { DomainRead[] -> Element[] }
868
33
    auto PHITarget =
869
33
        give(isl_map_apply_range(PHISched.copy(), TargetElt.copy()));
870
33
    simplify(PHITarget);
871
33
    DEBUG(dbgs() << "    Mapping: " << PHITarget << '\n');
872
33
873
33
    auto OrigDomain = getDomainFor(PHIRead);
874
33
    auto MappedDomain = give(isl_map_domain(PHITarget.copy()));
875
33
    if (!isl_set_is_subset(OrigDomain.keep(), MappedDomain.keep())) {
876
0
      DEBUG(dbgs()
877
0
            << "    Reject because mapping does not encompass all instances\n");
878
0
      return false;
879
0
    }
880
33
881
33
    // { DomainRead[] -> DomainWrite[] }
882
33
    auto PerPHIWrites = computePerPHI(SAI);
883
33
884
33
    // { DomainWrite[] -> Element[] }
885
33
    auto WritesTarget = give(isl_union_map_reverse(isl_union_map_apply_domain(
886
33
        PerPHIWrites.copy(), isl_union_map_from_map(PHITarget.copy()))));
887
33
    simplify(WritesTarget);
888
33
889
33
    // { DomainWrite[] }
890
33
    auto UniverseWritesDom = give(isl_union_set_empty(ParamSpace.copy()));
891
33
892
33
    for (auto *MA : S->getPHIIncomings(SAI))
893
66
      UniverseWritesDom = give(isl_union_set_add_set(UniverseWritesDom.take(),
894
66
                                                     getDomainFor(MA).take()));
895
33
896
33
    auto RelevantWritesTarget = WritesTarget;
897
33
    if (DelicmOverapproximateWrites)
898
11
      WritesTarget = expandMapping(WritesTarget, UniverseWritesDom);
899
33
900
33
    auto ExpandedWritesDom = give(isl_union_map_domain(WritesTarget.copy()));
901
33
    if (!DelicmPartialWrites &&
902
33
        !isl_union_set_is_subset(UniverseWritesDom.keep(),
903
3
                                 ExpandedWritesDom.keep())) {
904
1
      DEBUG(dbgs() << "    Reject because did not find PHI write mapping for "
905
1
                      "all instances\n");
906
1
      if (DelicmOverapproximateWrites)
907
1
        DEBUG(dbgs() << "      Relevant Mapping:    " << RelevantWritesTarget
908
1
                     << '\n');
909
1
      DEBUG(dbgs() << "      Deduced Mapping:     " << WritesTarget << '\n');
910
1
      DEBUG(dbgs() << "      Missing instances:    "
911
1
                   << give(isl_union_set_subtract(UniverseWritesDom.copy(),
912
1
                                                  ExpandedWritesDom.copy()))
913
1
                   << '\n');
914
1
      return false;
915
1
    }
916
32
917
32
    //  { DomainRead[] -> Scatter[] }
918
32
    auto PerPHIWriteScatter = give(isl_map_from_union_map(
919
32
        isl_union_map_apply_range(PerPHIWrites.copy(), Schedule.copy())));
920
32
921
32
    // { DomainRead[] -> Zone[] }
922
32
    auto Lifetime = betweenScatter(PerPHIWriteScatter, PHISched, false, true);
923
32
    simplify(Lifetime);
924
32
    DEBUG(dbgs() << "    Lifetime: " << Lifetime << "\n");
925
32
926
32
    // { DomainWrite[] -> Zone[] }
927
32
    auto WriteLifetime = give(isl_union_map_apply_domain(
928
32
        isl_union_map_from_map(Lifetime.copy()), PerPHIWrites.copy()));
929
32
930
32
    // { DomainWrite[] -> ValInst[] }
931
32
    auto WrittenValue = determinePHIWrittenValues(SAI);
932
32
933
32
    // { DomainWrite[] -> [Element[] -> Scatter[]] }
934
32
    auto WrittenTranslator =
935
32
        give(isl_union_map_range_product(WritesTarget.copy(), Schedule.copy()));
936
32
937
32
    // { [Element[] -> Scatter[]] -> ValInst[] }
938
32
    auto Written = give(isl_union_map_apply_domain(WrittenValue.copy(),
939
32
                                                   WrittenTranslator.copy()));
940
32
    simplify(Written);
941
32
942
32
    // { DomainWrite[] -> [Element[] -> Zone[]] }
943
32
    auto LifetimeTranslator = give(
944
32
        isl_union_map_range_product(WritesTarget.copy(), WriteLifetime.copy()));
945
32
946
32
    // { DomainWrite[] -> ValInst[] }
947
32
    auto WrittenKnownValue = filterKnownValInst(WrittenValue);
948
32
949
32
    // { [Element[] -> Zone[]] -> ValInst[] }
950
32
    auto EltLifetimeInst = give(isl_union_map_apply_domain(
951
32
        WrittenKnownValue.copy(), LifetimeTranslator.copy()));
952
32
    simplify(EltLifetimeInst);
953
32
954
32
    // { [Element[] -> Zone[] }
955
32
    auto Occupied = give(isl_union_map_range(LifetimeTranslator.copy()));
956
32
    simplify(Occupied);
957
32
958
32
    Knowledge Proposed(Occupied, nullptr, EltLifetimeInst, Written);
959
32
    if (isConflicting(Proposed))
960
0
      return false;
961
32
962
32
    mapPHI(SAI, std::move(PHITarget), std::move(WritesTarget),
963
32
           std::move(Lifetime), std::move(Proposed));
964
32
    return true;
965
32
  }
966
967
  /// Map a MemoryKind::PHI scalar to an array element.
968
  ///
969
  /// Callers must have ensured that the mapping is valid and not conflicting
970
  /// with the common knowledge.
971
  ///
972
  /// @param SAI         The ScopArrayInfo representing the scalar's memory to
973
  ///                    map.
974
  /// @param ReadTarget  { DomainRead[] -> Element[] }
975
  ///                    The array element to map the scalar to.
976
  /// @param WriteTarget { DomainWrite[] -> Element[] }
977
  ///                    New access target for each PHI incoming write.
978
  /// @param Lifetime    { DomainRead[] -> Zone[] }
979
  ///                    The lifetime of each PHI for reporting.
980
  /// @param Proposed    Mapping constraints for reporting.
981
  void mapPHI(const ScopArrayInfo *SAI, isl::map ReadTarget,
982
              isl::union_map WriteTarget, isl::map Lifetime,
983
32
              Knowledge Proposed) {
984
32
    // { Element[] }
985
32
    isl::space ElementSpace = ReadTarget.get_space().range();
986
32
987
32
    // Redirect the PHI incoming writes.
988
64
    for (auto *MA : S->getPHIIncomings(SAI)) {
989
64
      // { DomainWrite[] }
990
64
      auto Domain = getDomainFor(MA);
991
64
992
64
      // { DomainWrite[] -> Element[] }
993
64
      auto NewAccRel = give(isl_union_map_intersect_domain(
994
64
          WriteTarget.copy(), isl_union_set_from_set(Domain.copy())));
995
64
      simplify(NewAccRel);
996
64
997
64
      isl::space NewAccRelSpace =
998
64
          Domain.get_space().map_from_domain_and_range(ElementSpace);
999
64
      isl::map NewAccRelMap = singleton(NewAccRel, NewAccRelSpace);
1000
64
      MA->setNewAccessRelation(NewAccRelMap);
1001
64
    }
1002
32
1003
32
    // Redirect the PHI read.
1004
32
    auto *PHIRead = S->getPHIRead(SAI);
1005
32
    PHIRead->setNewAccessRelation(ReadTarget);
1006
32
    applyLifetime(Proposed);
1007
32
1008
32
    MappedPHIScalars++;
1009
32
    NumberOfMappedPHIScalars++;
1010
32
  }
1011
1012
  /// Search and map scalars to memory overwritten by @p TargetStoreMA.
1013
  ///
1014
  /// Start trying to map scalars that are used in the same statement as the
1015
  /// store. For every successful mapping, try to also map scalars of the
1016
  /// statements where those are written. Repeat, until no more mapping
1017
  /// opportunity is found.
1018
  ///
1019
  /// There is currently no preference in which order scalars are tried.
1020
  /// Ideally, we would direct it towards a load instruction of the same array
1021
  /// element.
1022
39
  bool collapseScalarsToStore(MemoryAccess *TargetStoreMA) {
1023
39
    assert(TargetStoreMA->isLatestArrayKind());
1024
39
    assert(TargetStoreMA->isMustWrite());
1025
39
1026
39
    auto TargetStmt = TargetStoreMA->getStatement();
1027
39
1028
39
    // { DomTarget[] }
1029
39
    auto TargetDom = getDomainFor(TargetStmt);
1030
39
1031
39
    // { DomTarget[] -> Element[] }
1032
39
    auto TargetAccRel = getAccessRelationFor(TargetStoreMA);
1033
39
1034
39
    // { Zone[] -> DomTarget[] }
1035
39
    // For each point in time, find the next target store instance.
1036
39
    auto Target =
1037
39
        computeScalarReachingOverwrite(Schedule, TargetDom, false, true);
1038
39
1039
39
    // { Zone[] -> Element[] }
1040
39
    // Use the target store's write location as a suggestion to map scalars to.
1041
39
    auto EltTarget =
1042
39
        give(isl_map_apply_range(Target.take(), TargetAccRel.take()));
1043
39
    simplify(EltTarget);
1044
39
    DEBUG(dbgs() << "    Target mapping is " << EltTarget << '\n');
1045
39
1046
39
    // Stack of elements not yet processed.
1047
39
    SmallVector<MemoryAccess *, 16> Worklist;
1048
39
1049
39
    // Set of scalars already tested.
1050
39
    SmallPtrSet<const ScopArrayInfo *, 16> Closed;
1051
39
1052
39
    // Lambda to add all scalar reads to the work list.
1053
94
    auto ProcessAllIncoming = [&](ScopStmt *Stmt) {
1054
188
      for (auto *MA : *Stmt) {
1055
188
        if (!MA->isLatestScalarKind())
1056
129
          continue;
1057
59
        if (!MA->isRead())
1058
9
          continue;
1059
50
1060
50
        Worklist.push_back(MA);
1061
50
      }
1062
94
    };
1063
39
1064
39
    auto *WrittenVal = TargetStoreMA->getAccessInstruction()->getOperand(0);
1065
39
    if (auto *WrittenValInputMA = TargetStmt->lookupInputAccessOf(WrittenVal))
1066
29
      Worklist.push_back(WrittenValInputMA);
1067
10
    else
1068
10
      ProcessAllIncoming(TargetStmt);
1069
39
1070
39
    auto AnyMapped = false;
1071
39
    auto &DL = S->getRegion().getEntry()->getModule()->getDataLayout();
1072
39
    auto StoreSize =
1073
39
        DL.getTypeAllocSize(TargetStoreMA->getAccessValue()->getType());
1074
39
1075
148
    while (!Worklist.empty()) {
1076
109
      auto *MA = Worklist.pop_back_val();
1077
109
1078
109
      auto *SAI = MA->getScopArrayInfo();
1079
109
      if (Closed.count(SAI))
1080
14
        continue;
1081
95
      Closed.insert(SAI);
1082
95
      DEBUG(dbgs() << "\n    Trying to map " << MA << " (SAI: " << SAI
1083
95
                   << ")\n");
1084
95
1085
95
      // Skip non-mappable scalars.
1086
95
      if (!isMappable(SAI))
1087
3
        continue;
1088
92
1089
92
      auto MASize = DL.getTypeAllocSize(MA->getAccessValue()->getType());
1090
92
      if (MASize > StoreSize) {
1091
1
        DEBUG(dbgs() << "    Reject because storage size is insufficient\n");
1092
1
        continue;
1093
1
      }
1094
91
1095
91
      // Try to map MemoryKind::Value scalars.
1096
91
      if (SAI->isValueKind()) {
1097
58
        if (!tryMapValue(SAI, EltTarget))
1098
8
          continue;
1099
50
1100
50
        auto *DefAcc = S->getValueDef(SAI);
1101
50
        ProcessAllIncoming(DefAcc->getStatement());
1102
50
1103
50
        AnyMapped = true;
1104
50
        continue;
1105
50
      }
1106
33
1107
33
      // Try to map MemoryKind::PHI scalars.
1108
33
      if (SAI->isPHIKind()) {
1109
33
        if (!tryMapPHI(SAI, EltTarget))
1110
1
          continue;
1111
32
        // Add inputs of all incoming statements to the worklist. Prefer the
1112
32
        // input accesses of the incoming blocks.
1113
64
        
for (auto *PHIWrite : S->getPHIIncomings(SAI))32
{
1114
64
          auto *PHIWriteStmt = PHIWrite->getStatement();
1115
64
          bool FoundAny = false;
1116
64
          for (auto Incoming : PHIWrite->getIncoming()) {
1117
64
            auto *IncomingInputMA =
1118
64
                PHIWriteStmt->lookupInputAccessOf(Incoming.second);
1119
64
            if (!IncomingInputMA)
1120
34
              continue;
1121
30
1122
30
            Worklist.push_back(IncomingInputMA);
1123
30
            FoundAny = true;
1124
30
          }
1125
64
1126
64
          if (!FoundAny)
1127
34
            ProcessAllIncoming(PHIWrite->getStatement());
1128
64
        }
1129
32
1130
32
        AnyMapped = true;
1131
32
        continue;
1132
32
      }
1133
33
    }
1134
39
1135
39
    if (AnyMapped) {
1136
29
      TargetsMapped++;
1137
29
      NumberOfTargetsMapped++;
1138
29
    }
1139
39
    return AnyMapped;
1140
39
  }
1141
1142
  /// Compute when an array element is unused.
1143
  ///
1144
  /// @return { [Element[] -> Zone[]] }
1145
49
  isl::union_set computeLifetime() const {
1146
49
    // { Element[] -> Zone[] }
1147
49
    auto ArrayUnused = computeArrayUnused(Schedule, AllMustWrites, AllReads,
1148
49
                                          false, false, true);
1149
49
1150
49
    auto Result = give(isl_union_map_wrap(ArrayUnused.copy()));
1151
49
1152
49
    simplify(Result);
1153
49
    return Result;
1154
49
  }
1155
1156
  /// Determine when an array element is written to, and which value instance is
1157
  /// written.
1158
  ///
1159
  /// @return { [Element[] -> Scatter[]] -> ValInst[] }
1160
49
  isl::union_map computeWritten() const {
1161
49
    // { [Element[] -> Scatter[]] -> ValInst[] }
1162
49
    auto EltWritten = applyDomainRange(AllWriteValInst, Schedule);
1163
49
1164
49
    simplify(EltWritten);
1165
49
    return EltWritten;
1166
49
  }
1167
1168
  /// Determine whether an access touches at most one element.
1169
  ///
1170
  /// The accessed element could be a scalar or accessing an array with constant
1171
  /// subscript, such that all instances access only that element.
1172
  ///
1173
  /// @param MA The access to test.
1174
  ///
1175
  /// @return True, if zero or one elements are accessed; False if at least two
1176
  ///         different elements are accessed.
1177
57
  bool isScalarAccess(MemoryAccess *MA) {
1178
57
    auto Map = getAccessRelationFor(MA);
1179
57
    auto Set = give(isl_map_range(Map.take()));
1180
57
    return isl_set_is_singleton(Set.keep()) == isl_bool_true;
1181
57
  }
1182
1183
  /// Print mapping statistics to @p OS.
1184
43
  void printStatistics(llvm::raw_ostream &OS, int Indent = 0) const {
1185
43
    OS.indent(Indent) << "Statistics {\n";
1186
43
    OS.indent(Indent + 4) << "Compatible overwrites: "
1187
43
                          << NumberOfCompatibleTargets << "\n";
1188
43
    OS.indent(Indent + 4) << "Overwrites mapped to:  " << NumberOfTargetsMapped
1189
43
                          << '\n';
1190
43
    OS.indent(Indent + 4) << "Value scalars mapped:  "
1191
43
                          << NumberOfMappedValueScalars << '\n';
1192
43
    OS.indent(Indent + 4) << "PHI scalars mapped:    "
1193
43
                          << NumberOfMappedPHIScalars << '\n';
1194
43
    OS.indent(Indent) << "}\n";
1195
43
  }
1196
1197
  /// Return whether at least one transformation been applied.
1198
43
  bool isModified() const { return NumberOfTargetsMapped > 0; }
1199
1200
public:
1201
49
  DeLICMImpl(Scop *S, LoopInfo *LI) : ZoneAlgorithm("polly-delicm", S, LI) {}
1202
1203
  /// Calculate the lifetime (definition to last use) of every array element.
1204
  ///
1205
  /// @return True if the computed lifetimes (#Zone) is usable.
1206
49
  bool computeZone() {
1207
49
    // Check that nothing strange occurs.
1208
49
    collectCompatibleElts();
1209
49
1210
49
    isl::union_set EltUnused;
1211
49
    isl::union_map EltKnown, EltWritten;
1212
49
1213
49
    {
1214
49
      IslMaxOperationsGuard MaxOpGuard(IslCtx.get(), DelicmMaxOps);
1215
49
1216
49
      computeCommon();
1217
49
1218
49
      EltUnused = computeLifetime();
1219
49
      EltKnown = computeKnown(true, false);
1220
49
      EltWritten = computeWritten();
1221
49
    }
1222
49
    DeLICMAnalyzed++;
1223
49
1224
49
    if (!EltUnused || 
!EltKnown47
||
!EltWritten47
) {
1225
2
      assert(isl_ctx_last_error(IslCtx.get()) == isl_error_quota &&
1226
2
             "The only reason that these things have not been computed should "
1227
2
             "be if the max-operations limit hit");
1228
2
      DeLICMOutOfQuota++;
1229
2
      DEBUG(dbgs() << "DeLICM analysis exceeded max_operations\n");
1230
2
      DebugLoc Begin, End;
1231
2
      getDebugLocations(getBBPairForRegion(&S->getRegion()), Begin, End);
1232
2
      OptimizationRemarkAnalysis R(DEBUG_TYPE, "OutOfQuota", Begin,
1233
2
                                   S->getEntry());
1234
2
      R << "maximal number of operations exceeded during zone analysis";
1235
2
      S->getFunction().getContext().diagnose(R);
1236
2
      return false;
1237
2
    }
1238
47
1239
47
    Zone = OriginalZone = Knowledge(nullptr, EltUnused, EltKnown, EltWritten);
1240
47
    DEBUG(dbgs() << "Computed Zone:\n"; OriginalZone.print(dbgs(), 4));
1241
47
1242
47
    assert(Zone.isUsable() && OriginalZone.isUsable());
1243
47
    return true;
1244
47
  }
1245
1246
  /// Try to map as many scalars to unused array elements as possible.
1247
  ///
1248
  /// Multiple scalars might be mappable to intersecting unused array element
1249
  /// zones, but we can only chose one. This is a greedy algorithm, therefore
1250
  /// the first processed element claims it.
1251
47
  void greedyCollapse() {
1252
47
    bool Modified = false;
1253
47
1254
218
    for (auto &Stmt : *S) {
1255
426
      for (auto *MA : Stmt) {
1256
426
        if (!MA->isLatestArrayKind())
1257
321
          continue;
1258
105
        if (!MA->isWrite())
1259
39
          continue;
1260
66
1261
66
        if (MA->isMayWrite()) {
1262
4
          DEBUG(dbgs() << "Access " << MA
1263
4
                       << " pruned because it is a MAY_WRITE\n");
1264
4
          OptimizationRemarkMissed R(DEBUG_TYPE, "TargetMayWrite",
1265
4
                                     MA->getAccessInstruction());
1266
4
          R << "Skipped possible mapping target because it is not an "
1267
4
               "unconditional overwrite";
1268
4
          S->getFunction().getContext().diagnose(R);
1269
4
          continue;
1270
4
        }
1271
62
1272
62
        if (Stmt.getNumIterators() == 0) {
1273
5
          DEBUG(dbgs() << "Access " << MA
1274
5
                       << " pruned because it is not in a loop\n");
1275
5
          OptimizationRemarkMissed R(DEBUG_TYPE, "WriteNotInLoop",
1276
5
                                     MA->getAccessInstruction());
1277
5
          R << "skipped possible mapping target because it is not in a loop";
1278
5
          S->getFunction().getContext().diagnose(R);
1279
5
          continue;
1280
5
        }
1281
57
1282
57
        if (isScalarAccess(MA)) {
1283
5
          DEBUG(dbgs() << "Access " << MA
1284
5
                       << " pruned because it writes only a single element\n");
1285
5
          OptimizationRemarkMissed R(DEBUG_TYPE, "ScalarWrite",
1286
5
                                     MA->getAccessInstruction());
1287
5
          R << "skipped possible mapping target because the memory location "
1288
5
               "written to does not depend on its outer loop";
1289
5
          S->getFunction().getContext().diagnose(R);
1290
5
          continue;
1291
5
        }
1292
52
1293
52
        if (!isa<StoreInst>(MA->getAccessInstruction())) {
1294
8
          DEBUG(dbgs() << "Access " << MA
1295
8
                       << " pruned because it is not a StoreInst\n");
1296
8
          OptimizationRemarkMissed R(DEBUG_TYPE, "NotAStore",
1297
8
                                     MA->getAccessInstruction());
1298
8
          R << "skipped possible mapping target because non-store instructions "
1299
8
               "are not supported";
1300
8
          S->getFunction().getContext().diagnose(R);
1301
8
          continue;
1302
8
        }
1303
44
1304
44
        // Check for more than one element acces per statement instance.
1305
44
        // Currently we expect write accesses to be functional, eg. disallow
1306
44
        //
1307
44
        //   { Stmt[0] -> [i] : 0 <= i < 2 }
1308
44
        //
1309
44
        // This may occur when some accesses to the element write/read only
1310
44
        // parts of the element, eg. a single byte. Polly then divides each
1311
44
        // element into subelements of the smallest access length, normal access
1312
44
        // then touch multiple of such subelements. It is very common when the
1313
44
        // array is accesses with memset, memcpy or memmove which take i8*
1314
44
        // arguments.
1315
44
        isl::union_map AccRel = MA->getLatestAccessRelation();
1316
44
        if (!AccRel.is_single_valued().is_true()) {
1317
1
          DEBUG(dbgs() << "Access " << MA
1318
1
                       << " is incompatible because it writes multiple "
1319
1
                          "elements per instance\n");
1320
1
          OptimizationRemarkMissed R(DEBUG_TYPE, "NonFunctionalAccRel",
1321
1
                                     MA->getAccessInstruction());
1322
1
          R << "skipped possible mapping target because it writes more than "
1323
1
               "one element";
1324
1
          S->getFunction().getContext().diagnose(R);
1325
1
          continue;
1326
1
        }
1327
43
1328
43
        isl::union_set TouchedElts = AccRel.range();
1329
43
        if (!TouchedElts.is_subset(CompatibleElts)) {
1330
4
          DEBUG(
1331
4
              dbgs()
1332
4
              << "Access " << MA
1333
4
              << " is incompatible because it touches incompatible elements\n");
1334
4
          OptimizationRemarkMissed R(DEBUG_TYPE, "IncompatibleElts",
1335
4
                                     MA->getAccessInstruction());
1336
4
          R << "skipped possible mapping target because a target location "
1337
4
               "cannot be reliably analyzed";
1338
4
          S->getFunction().getContext().diagnose(R);
1339
4
          continue;
1340
4
        }
1341
39
1342
39
        assert(isCompatibleAccess(MA));
1343
39
        NumberOfCompatibleTargets++;
1344
39
        DEBUG(dbgs() << "Analyzing target access " << MA << "\n");
1345
39
        if (collapseScalarsToStore(MA))
1346
29
          Modified = true;
1347
39
      }
1348
218
    }
1349
47
1350
47
    if (Modified)
1351
29
      DeLICMScopsModified++;
1352
47
  }
1353
1354
  /// Dump the internal information about a performed DeLICM to @p OS.
1355
45
  void print(llvm::raw_ostream &OS, int Indent = 0) {
1356
45
    if (!Zone.isUsable()) {
1357
2
      OS.indent(Indent) << "Zone not computed\n";
1358
2
      return;
1359
2
    }
1360
43
1361
43
    printStatistics(OS, Indent);
1362
43
    if (!isModified()) {
1363
16
      OS.indent(Indent) << "No modification has been made\n";
1364
16
      return;
1365
16
    }
1366
27
    printAccesses(OS, Indent);
1367
27
  }
1368
};
1369
1370
class DeLICM : public ScopPass {
1371
private:
1372
  DeLICM(const DeLICM &) = delete;
1373
  const DeLICM &operator=(const DeLICM &) = delete;
1374
1375
  /// The pass implementation, also holding per-scop data.
1376
  std::unique_ptr<DeLICMImpl> Impl;
1377
1378
49
  void collapseToUnused(Scop &S) {
1379
49
    auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1380
49
    Impl = make_unique<DeLICMImpl>(&S, &LI);
1381
49
1382
49
    if (!Impl->computeZone()) {
1383
2
      DEBUG(dbgs() << "Abort because cannot reliably compute lifetimes\n");
1384
2
      return;
1385
2
    }
1386
47
1387
47
    DEBUG(dbgs() << "Collapsing scalars to unused array elements...\n");
1388
47
    Impl->greedyCollapse();
1389
47
1390
47
    DEBUG(dbgs() << "\nFinal Scop:\n");
1391
47
    DEBUG(dbgs() << S);
1392
47
  }
1393
1394
public:
1395
  static char ID;
1396
49
  explicit DeLICM() : ScopPass(ID) {}
1397
1398
49
  virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
1399
49
    AU.addRequiredTransitive<ScopInfoRegionPass>();
1400
49
    AU.addRequired<LoopInfoWrapperPass>();
1401
49
    AU.setPreservesAll();
1402
49
  }
1403
1404
49
  virtual bool runOnScop(Scop &S) override {
1405
49
    // Free resources for previous scop's computation, if not yet done.
1406
49
    releaseMemory();
1407
49
1408
49
    collapseToUnused(S);
1409
49
1410
49
    auto ScopStats = S.getStatistics();
1411
49
    NumValueWrites += ScopStats.NumValueWrites;
1412
49
    NumValueWritesInLoops += ScopStats.NumValueWritesInLoops;
1413
49
    NumPHIWrites += ScopStats.NumPHIWrites;
1414
49
    NumPHIWritesInLoops += ScopStats.NumPHIWritesInLoops;
1415
49
    NumSingletonWrites += ScopStats.NumSingletonWrites;
1416
49
    NumSingletonWritesInLoops += ScopStats.NumSingletonWritesInLoops;
1417
49
1418
49
    return false;
1419
49
  }
1420
1421
45
  virtual void printScop(raw_ostream &OS, Scop &S) const override {
1422
45
    if (!Impl)
1423
0
      return;
1424
45
    assert(Impl->getScop() == &S);
1425
45
1426
45
    OS << "DeLICM result:\n";
1427
45
    Impl->print(OS);
1428
45
  }
1429
1430
263
  virtual void releaseMemory() override { Impl.reset(); }
1431
};
1432
1433
char DeLICM::ID;
1434
} // anonymous namespace
1435
1436
0
Pass *polly::createDeLICMPass() { return new DeLICM(); }
1437
1438
42.1k
INITIALIZE_PASS_BEGIN(DeLICM, "polly-delicm", "Polly - DeLICM/DePRE", false,
1439
42.1k
                      false)
1440
42.1k
INITIALIZE_PASS_DEPENDENCY(ScopInfoWrapperPass)
1441
42.1k
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
1442
42.1k
INITIALIZE_PASS_END(DeLICM, "polly-delicm", "Polly - DeLICM/DePRE", false,
1443
                    false)
1444
1445
bool polly::isConflicting(
1446
    isl::union_set ExistingOccupied, isl::union_set ExistingUnused,
1447
    isl::union_map ExistingKnown, isl::union_map ExistingWrites,
1448
    isl::union_set ProposedOccupied, isl::union_set ProposedUnused,
1449
    isl::union_map ProposedKnown, isl::union_map ProposedWrites,
1450
232
    llvm::raw_ostream *OS, unsigned Indent) {
1451
232
  Knowledge Existing(std::move(ExistingOccupied), std::move(ExistingUnused),
1452
232
                     std::move(ExistingKnown), std::move(ExistingWrites));
1453
232
  Knowledge Proposed(std::move(ProposedOccupied), std::move(ProposedUnused),
1454
232
                     std::move(ProposedKnown), std::move(ProposedWrites));
1455
232
1456
232
  return Knowledge::isConflicting(Existing, Proposed, OS, Indent);
1457
232
}