Coverage Report

Created: 2018-04-24 22:41

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/polly/lib/Transform/Simplify.cpp
Line
Count
Source (jump to first uncovered line)
1
//===------ Simplify.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
// Simplify a SCoP by removing unnecessary statements and accesses.
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "polly/Simplify.h"
15
#include "polly/ScopInfo.h"
16
#include "polly/ScopPass.h"
17
#include "polly/Support/GICHelper.h"
18
#include "polly/Support/ISLOStream.h"
19
#include "polly/Support/ISLTools.h"
20
#include "polly/Support/VirtualInstruction.h"
21
#include "llvm/ADT/Statistic.h"
22
#include "llvm/Support/Debug.h"
23
#define DEBUG_TYPE "polly-simplify"
24
25
using namespace llvm;
26
using namespace polly;
27
28
namespace {
29
30
#define TWO_STATISTICS(VARNAME, DESC)                                          \
31
  static llvm::Statistic VARNAME[2] = {                                        \
32
      {DEBUG_TYPE, #VARNAME "0", DESC " (first)", {0}, {false}},               \
33
      {DEBUG_TYPE, #VARNAME "1", DESC " (second)", {0}, {false}}}
34
35
/// Number of max disjuncts we allow in removeOverwrites(). This is to avoid
36
/// that the analysis of accesses in a statement is becoming too complex. Chosen
37
/// to be relatively small because all the common cases should access only few
38
/// array elements per statement.
39
static int const SimplifyMaxDisjuncts = 4;
40
41
TWO_STATISTICS(ScopsProcessed, "Number of SCoPs processed");
42
TWO_STATISTICS(ScopsModified, "Number of SCoPs simplified");
43
44
TWO_STATISTICS(TotalOverwritesRemoved, "Number of removed overwritten writes");
45
TWO_STATISTICS(TotalWritesCoalesced, "Number of writes coalesced with another");
46
TWO_STATISTICS(TotalRedundantWritesRemoved,
47
               "Number of writes of same value removed in any SCoP");
48
TWO_STATISTICS(TotalEmptyPartialAccessesRemoved,
49
               "Number of empty partial accesses removed");
50
TWO_STATISTICS(TotalDeadAccessesRemoved, "Number of dead accesses removed");
51
TWO_STATISTICS(TotalDeadInstructionsRemoved,
52
               "Number of unused instructions removed");
53
TWO_STATISTICS(TotalStmtsRemoved, "Number of statements removed in any SCoP");
54
55
TWO_STATISTICS(NumValueWrites, "Number of scalar value writes after Simplify");
56
TWO_STATISTICS(
57
    NumValueWritesInLoops,
58
    "Number of scalar value writes nested in affine loops after Simplify");
59
TWO_STATISTICS(NumPHIWrites,
60
               "Number of scalar phi writes after the first simplification");
61
TWO_STATISTICS(
62
    NumPHIWritesInLoops,
63
    "Number of scalar phi writes nested in affine loops after Simplify");
64
TWO_STATISTICS(NumSingletonWrites, "Number of singleton writes after Simplify");
65
TWO_STATISTICS(
66
    NumSingletonWritesInLoops,
67
    "Number of singleton writes nested in affine loops after Simplify");
68
69
812
static bool isImplicitRead(MemoryAccess *MA) {
70
812
  return MA->isRead() && 
MA->isOriginalScalarKind()339
;
71
812
}
72
73
838
static bool isExplicitAccess(MemoryAccess *MA) {
74
838
  return MA->isOriginalArrayKind();
75
838
}
76
77
812
static bool isImplicitWrite(MemoryAccess *MA) {
78
812
  return MA->isWrite() && 
MA->isOriginalScalarKind()473
;
79
812
}
80
81
/// Like isl::union_map::add_map, but may also return an underapproximated
82
/// result if getting too complex.
83
///
84
/// This is implemented by adding disjuncts to the results until the limit is
85
/// reached.
86
static isl::union_map underapproximatedAddMap(isl::union_map UMap,
87
147
                                              isl::map Map) {
88
147
  if (UMap.is_null() || Map.is_null())
89
0
    return {};
90
147
91
147
  isl::map PrevMap = UMap.extract_map(Map.get_space());
92
147
93
147
  // Fast path: If known that we cannot exceed the disjunct limit, just add
94
147
  // them.
95
147
  if (isl_map_n_basic_map(PrevMap.get()) + isl_map_n_basic_map(Map.get()) <=
96
147
      SimplifyMaxDisjuncts)
97
141
    return UMap.add_map(Map);
98
6
99
6
  isl::map Result = isl::map::empty(PrevMap.get_space());
100
24
  PrevMap.foreach_basic_map([&Result](isl::basic_map BMap) -> isl::stat {
101
24
    if (isl_map_n_basic_map(Result.get()) > SimplifyMaxDisjuncts)
102
0
      return isl::stat::error;
103
24
    Result = Result.unite(BMap);
104
24
    return isl::stat::ok;
105
24
  });
106
6
  Map.foreach_basic_map([&Result](isl::basic_map BMap) -> isl::stat {
107
6
    if (isl_map_n_basic_map(Result.get()) > SimplifyMaxDisjuncts)
108
0
      return isl::stat::error;
109
6
    Result = Result.unite(BMap);
110
6
    return isl::stat::ok;
111
6
  });
112
6
113
6
  isl::union_map UResult =
114
6
      UMap.subtract(isl::map::universe(PrevMap.get_space()));
115
6
  UResult.add_map(Result);
116
6
117
6
  return UResult;
118
6
}
119
120
class Simplify : public ScopPass {
121
private:
122
  /// The invocation id (if there are multiple instances in the pass manager's
123
  /// pipeline) to determine which statistics to update.
124
  int CallNo;
125
126
  /// The last/current SCoP that is/has been processed.
127
  Scop *S;
128
129
  /// Number of writes that are overwritten anyway.
130
  int OverwritesRemoved = 0;
131
132
  /// Number of combined writes.
133
  int WritesCoalesced = 0;
134
135
  /// Number of redundant writes removed from this SCoP.
136
  int RedundantWritesRemoved = 0;
137
138
  /// Number of writes with empty access domain removed.
139
  int EmptyPartialAccessesRemoved = 0;
140
141
  /// Number of unused accesses removed from this SCoP.
142
  int DeadAccessesRemoved = 0;
143
144
  /// Number of unused instructions removed from this SCoP.
145
  int DeadInstructionsRemoved = 0;
146
147
  /// Number of unnecessary statements removed from the SCoP.
148
  int StmtsRemoved = 0;
149
150
  /// Return whether at least one simplification has been applied.
151
86
  bool isModified() const {
152
86
    return OverwritesRemoved > 0 || 
WritesCoalesced > 076
||
153
86
           
RedundantWritesRemoved > 066
||
EmptyPartialAccessesRemoved > 053
||
154
86
           
DeadAccessesRemoved > 051
||
DeadInstructionsRemoved > 036
||
155
86
           
StmtsRemoved > 032
;
156
86
  }
157
158
  /// Remove writes that are overwritten unconditionally later in the same
159
  /// statement.
160
  ///
161
  /// There must be no read of the same value between the write (that is to be
162
  /// removed) and the overwrite.
163
44
  void removeOverwrites() {
164
98
    for (auto &Stmt : *S) {
165
98
      isl::set Domain = Stmt.getDomain();
166
98
      isl::union_map WillBeOverwritten =
167
98
          isl::union_map::empty(S->getParamSpace());
168
98
169
98
      SmallVector<MemoryAccess *, 32> Accesses(getAccessesInOrder(Stmt));
170
98
171
98
      // Iterate in reverse order, so the overwrite comes before the write that
172
98
      // is to be removed.
173
225
      for (auto *MA : reverse(Accesses)) {
174
225
175
225
        // In region statements, the explicit accesses can be in blocks that are
176
225
        // can be executed in any order. We therefore process only the implicit
177
225
        // writes and stop after that.
178
225
        if (Stmt.isRegionStmt() && 
isExplicitAccess(MA)13
)
179
8
          break;
180
217
181
217
        auto AccRel = MA->getAccessRelation();
182
217
        AccRel = AccRel.intersect_domain(Domain);
183
217
        AccRel = AccRel.intersect_params(S->getContext());
184
217
185
217
        // If a value is read in-between, do not consider it as overwritten.
186
217
        if (MA->isRead()) {
187
70
          // Invalidate all overwrites for the array it accesses to avoid too
188
70
          // complex isl sets.
189
70
          isl::map AccRelUniv = isl::map::universe(AccRel.get_space());
190
70
          WillBeOverwritten = WillBeOverwritten.subtract(AccRelUniv);
191
70
          continue;
192
70
        }
193
147
194
147
        // If all of a write's elements are overwritten, remove it.
195
147
        isl::union_map AccRelUnion = AccRel;
196
147
        if (AccRelUnion.is_subset(WillBeOverwritten)) {
197
7
          DEBUG(dbgs() << "Removing " << MA
198
7
                       << " which will be overwritten anyway\n");
199
7
200
7
          Stmt.removeSingleMemoryAccess(MA);
201
7
          OverwritesRemoved++;
202
7
          TotalOverwritesRemoved[CallNo]++;
203
7
        }
204
147
205
147
        // Unconditional writes overwrite other values.
206
147
        if (MA->isMustWrite()) {
207
147
          // Avoid too complex isl sets. If necessary, throw away some of the
208
147
          // knowledge.
209
147
          WillBeOverwritten =
210
147
              underapproximatedAddMap(WillBeOverwritten, AccRel);
211
147
        }
212
147
      }
213
98
    }
214
44
  }
215
216
  /// Combine writes that write the same value if possible.
217
  ///
218
  /// This function is able to combine:
219
  /// - Partial writes with disjoint domain.
220
  /// - Writes that write to the same array element.
221
  ///
222
  /// In all cases, both writes must write the same values.
223
44
  void coalesceWrites() {
224
98
    for (auto &Stmt : *S) {
225
98
      isl::set Domain = Stmt.getDomain().intersect_params(S->getContext());
226
98
227
98
      // We let isl do the lookup for the same-value condition. For this, we
228
98
      // wrap llvm::Value into an isl::set such that isl can do the lookup in
229
98
      // its hashtable implementation. llvm::Values are only compared within a
230
98
      // ScopStmt, so the map can be local to this scope. TODO: Refactor with
231
98
      // ZoneAlgorithm::makeValueSet()
232
98
      SmallDenseMap<Value *, isl::set> ValueSets;
233
140
      auto makeValueSet = [&ValueSets, this](Value *V) -> isl::set {
234
140
        assert(V);
235
140
        isl::set &Result = ValueSets[V];
236
140
        if (Result.is_null()) {
237
96
          isl::ctx Ctx = S->getIslCtx();
238
96
          std::string Name =
239
96
              getIslCompatibleName("Val", V, ValueSets.size() - 1,
240
96
                                   std::string(), UseInstructionNames);
241
96
          isl::id Id = isl::id::alloc(Ctx, Name, V);
242
96
          Result = isl::set::universe(
243
96
              isl::space(Ctx, 0, 0).set_tuple_id(isl::dim::set, Id));
244
96
        }
245
140
        return Result;
246
140
      };
247
98
248
98
      // List of all eligible (for coalescing) writes of the future.
249
98
      // { [Domain[] -> Element[]] -> [Value[] -> MemoryAccess[]] }
250
98
      isl::union_map FutureWrites = isl::union_map::empty(S->getParamSpace());
251
98
252
98
      // Iterate over accesses from the last to the first.
253
98
      SmallVector<MemoryAccess *, 32> Accesses(getAccessesInOrder(Stmt));
254
218
      for (MemoryAccess *MA : reverse(Accesses)) {
255
218
        // In region statements, the explicit accesses can be in blocks that can
256
218
        // be executed in any order. We therefore process only the implicit
257
218
        // writes and stop after that.
258
218
        if (Stmt.isRegionStmt() && 
isExplicitAccess(MA)13
)
259
8
          break;
260
210
261
210
        // { Domain[] -> Element[] }
262
210
        isl::map AccRel =
263
210
            MA->getLatestAccessRelation().intersect_domain(Domain);
264
210
265
210
        // { [Domain[] -> Element[]] }
266
210
        isl::set AccRelWrapped = AccRel.wrap();
267
210
268
210
        // { Value[] }
269
210
        isl::set ValSet;
270
210
271
210
        if (MA->isMustWrite() && 
(140
MA->isOriginalScalarKind()140
||
272
140
                                  
isa<StoreInst>(MA->getAccessInstruction())112
)) {
273
140
          // Normally, tryGetValueStored() should be used to determine which
274
140
          // element is written, but it can return nullptr; For PHI accesses,
275
140
          // getAccessValue() returns the PHI instead of the PHI's incoming
276
140
          // value. In this case, where we only compare values of a single
277
140
          // statement, this is fine, because within a statement, a PHI in a
278
140
          // successor block has always the same value as the incoming write. We
279
140
          // still preferably use the incoming value directly so we also catch
280
140
          // direct uses of that.
281
140
          Value *StoredVal = MA->tryGetValueStored();
282
140
          if (!StoredVal)
283
1
            StoredVal = MA->getAccessValue();
284
140
          ValSet = makeValueSet(StoredVal);
285
140
286
140
          // { Domain[] }
287
140
          isl::set AccDomain = AccRel.domain();
288
140
289
140
          // Parts of the statement's domain that is not written by this access.
290
140
          isl::set UndefDomain = Domain.subtract(AccDomain);
291
140
292
140
          // { Element[] }
293
140
          isl::set ElementUniverse =
294
140
              isl::set::universe(AccRel.get_space().range());
295
140
296
140
          // { Domain[] -> Element[] }
297
140
          isl::map UndefAnything =
298
140
              isl::map::from_domain_and_range(UndefDomain, ElementUniverse);
299
140
300
140
          // We are looking a compatible write access. The other write can
301
140
          // access these elements...
302
140
          isl::map AllowedAccesses = AccRel.unite(UndefAnything);
303
140
304
140
          // ... and must write the same value.
305
140
          // { [Domain[] -> Element[]] -> Value[] }
306
140
          isl::map Filter =
307
140
              isl::map::from_domain_and_range(AllowedAccesses.wrap(), ValSet);
308
140
309
140
          // Lookup future write that fulfills these conditions.
310
140
          // { [[Domain[] -> Element[]] -> Value[]] -> MemoryAccess[] }
311
140
          isl::union_map Filtered =
312
140
              FutureWrites.uncurry().intersect_domain(Filter.wrap());
313
140
314
140
          // Iterate through the candidates.
315
140
          Filtered.foreach_map([&, this](isl::map Map) -> isl::stat {
316
39
            MemoryAccess *OtherMA = (MemoryAccess *)Map.get_space()
317
39
                                        .get_tuple_id(isl::dim::out)
318
39
                                        .get_user();
319
39
320
39
            isl::map OtherAccRel =
321
39
                OtherMA->getLatestAccessRelation().intersect_domain(Domain);
322
39
323
39
            // The filter only guaranteed that some of OtherMA's accessed
324
39
            // elements are allowed. Verify that it only accesses allowed
325
39
            // elements. Otherwise, continue with the next candidate.
326
39
            if (!OtherAccRel.is_subset(AllowedAccesses).is_true())
327
32
              return isl::stat::ok;
328
7
329
7
            // The combined access relation.
330
7
            // { Domain[] -> Element[] }
331
7
            isl::map NewAccRel = AccRel.unite(OtherAccRel);
332
7
            simplify(NewAccRel);
333
7
334
7
            // Carry out the coalescing.
335
7
            Stmt.removeSingleMemoryAccess(MA);
336
7
            OtherMA->setNewAccessRelation(NewAccRel);
337
7
338
7
            // We removed MA, OtherMA takes its role.
339
7
            MA = OtherMA;
340
7
341
7
            TotalWritesCoalesced[CallNo]++;
342
7
            WritesCoalesced++;
343
7
344
7
            // Don't look for more candidates.
345
7
            return isl::stat::error;
346
7
          });
347
140
        }
348
210
349
210
        // Two writes cannot be coalesced if there is another access (to some of
350
210
        // the written elements) between them. Remove all visited write accesses
351
210
        // from the list of eligible writes. Don't just remove the accessed
352
210
        // elements, but any MemoryAccess that touches any of the invalidated
353
210
        // elements.
354
210
        SmallPtrSet<MemoryAccess *, 2> TouchedAccesses;
355
210
        FutureWrites.intersect_domain(AccRelWrapped)
356
210
            .foreach_map([&TouchedAccesses](isl::map Map) -> isl::stat {
357
86
              MemoryAccess *MA = (MemoryAccess *)Map.get_space()
358
86
                                     .range()
359
86
                                     .unwrap()
360
86
                                     .get_tuple_id(isl::dim::out)
361
86
                                     .get_user();
362
86
              TouchedAccesses.insert(MA);
363
86
              return isl::stat::ok;
364
86
            });
365
210
        isl::union_map NewFutureWrites =
366
210
            isl::union_map::empty(FutureWrites.get_space());
367
210
        FutureWrites.foreach_map([&TouchedAccesses, &NewFutureWrites](
368
210
                                     isl::map FutureWrite) -> isl::stat {
369
123
          MemoryAccess *MA = (MemoryAccess *)FutureWrite.get_space()
370
123
                                 .range()
371
123
                                 .unwrap()
372
123
                                 .get_tuple_id(isl::dim::out)
373
123
                                 .get_user();
374
123
          if (!TouchedAccesses.count(MA))
375
37
            NewFutureWrites = NewFutureWrites.add_map(FutureWrite);
376
123
          return isl::stat::ok;
377
123
        });
378
210
        FutureWrites = NewFutureWrites;
379
210
380
210
        if (MA->isMustWrite() && 
!ValSet.is_null()140
) {
381
140
          // { MemoryAccess[] }
382
140
          auto AccSet =
383
140
              isl::set::universe(isl::space(S->getIslCtx(), 0, 0)
384
140
                                     .set_tuple_id(isl::dim::set, MA->getId()));
385
140
386
140
          // { Val[] -> MemoryAccess[] }
387
140
          isl::map ValAccSet = isl::map::from_domain_and_range(ValSet, AccSet);
388
140
389
140
          // { [Domain[] -> Element[]] -> [Value[] -> MemoryAccess[]] }
390
140
          isl::map AccRelValAcc =
391
140
              isl::map::from_domain_and_range(AccRelWrapped, ValAccSet.wrap());
392
140
          FutureWrites = FutureWrites.add_map(AccRelValAcc);
393
140
        }
394
210
      }
395
98
    }
396
44
  }
397
398
  /// Remove writes that just write the same value already stored in the
399
  /// element.
400
44
  void removeRedundantWrites() {
401
98
    for (auto &Stmt : *S) {
402
98
      SmallDenseMap<Value *, isl::set> ValueSets;
403
213
      auto makeValueSet = [&ValueSets, this](Value *V) -> isl::set {
404
213
        assert(V);
405
213
        isl::set &Result = ValueSets[V];
406
213
        if (Result.is_null()) {
407
121
          isl_ctx *Ctx = S->getIslCtx().get();
408
121
          std::string Name =
409
121
              getIslCompatibleName("Val", V, ValueSets.size() - 1,
410
121
                                   std::string(), UseInstructionNames);
411
121
          isl::id Id = give(isl_id_alloc(Ctx, Name.c_str(), V));
412
121
          Result = isl::set::universe(
413
121
              isl::space(Ctx, 0, 0).set_tuple_id(isl::dim::set, Id));
414
121
        }
415
213
        return Result;
416
213
      };
417
98
418
98
      isl::set Domain = Stmt.getDomain();
419
98
      Domain = Domain.intersect_params(S->getContext());
420
98
421
98
      // List of element reads that still have the same value while iterating
422
98
      // through the MemoryAccesses.
423
98
      // { [Domain[] -> Element[]] -> Val[] }
424
98
      isl::union_map Known = isl::union_map::empty(S->getParamSpace());
425
98
426
98
      SmallVector<MemoryAccess *, 32> Accesses(getAccessesInOrder(Stmt));
427
221
      for (MemoryAccess *MA : Accesses) {
428
221
        // Is the memory access in a defined order relative to the other
429
221
        // accesses? In region statements, only the first and the last accesses
430
221
        // have defined order. Execution of those in the middle may depend on
431
221
        // runtime conditions an therefore cannot be modified.
432
221
        bool IsOrdered =
433
221
            Stmt.isBlockStmt() || 
MA->isOriginalScalarKind()23
||
434
221
            
(14
!S->getBoxedLoops().size()14
&&
MA->getAccessInstruction()12
&&
435
14
             
Stmt.getEntryBlock() == MA->getAccessInstruction()->getParent()12
);
436
221
437
221
        isl::map AccRel = MA->getAccessRelation();
438
221
        AccRel = AccRel.intersect_domain(Domain);
439
221
        isl::set AccRelWrapped = AccRel.wrap();
440
221
441
221
        // Determine whether a write is redundant (stores only values that are
442
221
        // already present in the written array elements) and remove it if this
443
221
        // is the case.
444
221
        if (IsOrdered && 
MA->isMustWrite()213
&&
445
221
            
(133
isa<StoreInst>(MA->getAccessInstruction())133
||
446
133
             
MA->isOriginalScalarKind()27
)) {
447
133
          Value *StoredVal = MA->tryGetValueStored();
448
133
          if (!StoredVal)
449
1
            StoredVal = MA->getAccessValue();
450
133
451
133
          if (StoredVal) {
452
133
            // Lookup in the set of known values.
453
133
            isl::map AccRelStoredVal = isl::map::from_domain_and_range(
454
133
                AccRelWrapped, makeValueSet(StoredVal));
455
133
            if (isl::union_map(AccRelStoredVal).is_subset(Known)) {
456
15
              DEBUG(dbgs() << "Cleanup of " << MA << ":\n");
457
15
              DEBUG(dbgs() << "      Scalar: " << *StoredVal << "\n");
458
15
              DEBUG(dbgs() << "      AccRel: " << AccRel << "\n");
459
15
460
15
              Stmt.removeSingleMemoryAccess(MA);
461
15
462
15
              RedundantWritesRemoved++;
463
15
              TotalRedundantWritesRemoved[CallNo]++;
464
15
            }
465
133
          }
466
133
        }
467
221
468
221
        // Update the know values set.
469
221
        if (MA->isRead()) {
470
80
          // Loaded values are the currently known values of the array element
471
80
          // it was loaded from.
472
80
          Value *LoadedVal = MA->getAccessValue();
473
80
          if (LoadedVal && IsOrdered) {
474
80
            isl::map AccRelVal = isl::map::from_domain_and_range(
475
80
                AccRelWrapped, makeValueSet(LoadedVal));
476
80
477
80
            Known = Known.add_map(AccRelVal);
478
80
          }
479
141
        } else if (MA->isWrite()) {
480
141
          // Remove (possibly) overwritten values from the known elements set.
481
141
          // We remove all elements of the accessed array to avoid too complex
482
141
          // isl sets.
483
141
          isl::set AccRelUniv = isl::set::universe(AccRelWrapped.get_space());
484
141
          Known = Known.subtract_domain(AccRelUniv);
485
141
486
141
          // At this point, we could add the written value of must-writes.
487
141
          // However, writing same values is already handled by
488
141
          // coalesceWrites().
489
141
        }
490
221
      }
491
98
    }
492
44
  }
493
494
  /// Remove statements without side effects.
495
44
  void removeUnnecessaryStmts() {
496
44
    auto NumStmtsBefore = S->getSize();
497
44
    S->simplifySCoP(true);
498
44
    assert(NumStmtsBefore >= S->getSize());
499
44
    StmtsRemoved = NumStmtsBefore - S->getSize();
500
44
    DEBUG(dbgs() << "Removed " << StmtsRemoved << " (of " << NumStmtsBefore
501
44
                 << ") statements\n");
502
44
    TotalStmtsRemoved[CallNo] += StmtsRemoved;
503
44
  }
504
505
  /// Remove accesses that have an empty domain.
506
44
  void removeEmptyPartialAccesses() {
507
98
    for (ScopStmt &Stmt : *S) {
508
98
      // Defer the actual removal to not invalidate iterators.
509
98
      SmallVector<MemoryAccess *, 8> DeferredRemove;
510
98
511
236
      for (MemoryAccess *MA : Stmt) {
512
236
        if (!MA->isWrite())
513
80
          continue;
514
156
515
156
        isl::map AccRel = MA->getAccessRelation();
516
156
        if (!AccRel.is_empty().is_true())
517
155
          continue;
518
1
519
1
        DEBUG(dbgs() << "Removing " << MA
520
1
                     << " because it's a partial access that never occurs\n");
521
1
        DeferredRemove.push_back(MA);
522
1
      }
523
98
524
98
      for (MemoryAccess *MA : DeferredRemove) {
525
1
        Stmt.removeSingleMemoryAccess(MA);
526
1
        EmptyPartialAccessesRemoved++;
527
1
        TotalEmptyPartialAccessesRemoved[CallNo]++;
528
1
      }
529
98
    }
530
44
  }
531
532
  /// Mark all reachable instructions and access, and sweep those that are not
533
  /// reachable.
534
44
  void markAndSweep(LoopInfo *LI) {
535
44
    DenseSet<MemoryAccess *> UsedMA;
536
44
    DenseSet<VirtualInstruction> UsedInsts;
537
44
538
44
    // Get all reachable instructions and accesses.
539
44
    markReachable(S, LI, UsedInsts, UsedMA);
540
44
541
44
    // Remove all non-reachable accesses.
542
44
    // We need get all MemoryAccesses first, in order to not invalidate the
543
44
    // iterators when removing them.
544
44
    SmallVector<MemoryAccess *, 64> AllMAs;
545
44
    for (ScopStmt &Stmt : *S)
546
98
      AllMAs.append(Stmt.begin(), Stmt.end());
547
44
548
206
    for (MemoryAccess *MA : AllMAs) {
549
206
      if (UsedMA.count(MA))
550
182
        continue;
551
24
      DEBUG(dbgs() << "Removing " << MA << " because its value is not used\n");
552
24
      ScopStmt *Stmt = MA->getStatement();
553
24
      Stmt->removeSingleMemoryAccess(MA);
554
24
555
24
      DeadAccessesRemoved++;
556
24
      TotalDeadAccessesRemoved[CallNo]++;
557
24
    }
558
44
559
44
    // Remove all non-reachable instructions.
560
98
    for (ScopStmt &Stmt : *S) {
561
98
      // Note that for region statements, we can only remove the non-terminator
562
98
      // instructions of the entry block. All other instructions are not in the
563
98
      // instructions list, but implicitly always part of the statement.
564
98
565
98
      SmallVector<Instruction *, 32> AllInsts(Stmt.insts_begin(),
566
98
                                              Stmt.insts_end());
567
98
      SmallVector<Instruction *, 32> RemainInsts;
568
98
569
209
      for (Instruction *Inst : AllInsts) {
570
209
        auto It = UsedInsts.find({&Stmt, Inst});
571
209
        if (It == UsedInsts.end()) {
572
36
          DEBUG(dbgs() << "Removing "; Inst->print(dbgs());
573
36
                dbgs() << " because it is not used\n");
574
36
          DeadInstructionsRemoved++;
575
36
          TotalDeadInstructionsRemoved[CallNo]++;
576
36
          continue;
577
36
        }
578
173
579
173
        RemainInsts.push_back(Inst);
580
173
581
173
        // If instructions appear multiple times, keep only the first.
582
173
        UsedInsts.erase(It);
583
173
      }
584
98
585
98
      // Set the new instruction list to be only those we did not remove.
586
98
      Stmt.setInstructions(RemainInsts);
587
98
    }
588
44
  }
589
590
  /// Print simplification statistics to @p OS.
591
42
  void printStatistics(llvm::raw_ostream &OS, int Indent = 0) const {
592
42
    OS.indent(Indent) << "Statistics {\n";
593
42
    OS.indent(Indent + 4) << "Overwrites removed: " << OverwritesRemoved
594
42
                          << '\n';
595
42
    OS.indent(Indent + 4) << "Partial writes coalesced: " << WritesCoalesced
596
42
                          << "\n";
597
42
    OS.indent(Indent + 4) << "Redundant writes removed: "
598
42
                          << RedundantWritesRemoved << "\n";
599
42
    OS.indent(Indent + 4) << "Accesses with empty domains removed: "
600
42
                          << EmptyPartialAccessesRemoved << "\n";
601
42
    OS.indent(Indent + 4) << "Dead accesses removed: " << DeadAccessesRemoved
602
42
                          << '\n';
603
42
    OS.indent(Indent + 4) << "Dead instructions removed: "
604
42
                          << DeadInstructionsRemoved << '\n';
605
42
    OS.indent(Indent + 4) << "Stmts removed: " << StmtsRemoved << "\n";
606
42
    OS.indent(Indent) << "}\n";
607
42
  }
608
609
  /// Print the current state of all MemoryAccesses to @p OS.
610
26
  void printAccesses(llvm::raw_ostream &OS, int Indent = 0) const {
611
26
    OS.indent(Indent) << "After accesses {\n";
612
26
    for (auto &Stmt : *S) {
613
26
      OS.indent(Indent + 4) << Stmt.getBaseName() << "\n";
614
26
      for (auto *MA : Stmt)
615
40
        MA->print(OS);
616
26
    }
617
26
    OS.indent(Indent) << "}\n";
618
26
  }
619
620
public:
621
  static char ID;
622
44
  explicit Simplify(int CallNo = 0) : ScopPass(ID), CallNo(CallNo) {}
623
624
44
  virtual void getAnalysisUsage(AnalysisUsage &AU) const override {
625
44
    AU.addRequiredTransitive<ScopInfoRegionPass>();
626
44
    AU.addRequired<LoopInfoWrapperPass>();
627
44
    AU.setPreservesAll();
628
44
  }
629
630
44
  virtual bool runOnScop(Scop &S) override {
631
44
    // Reset statistics of last processed SCoP.
632
44
    releaseMemory();
633
44
    assert(!isModified());
634
44
635
44
    // Prepare processing of this SCoP.
636
44
    this->S = &S;
637
44
    ScopsProcessed[CallNo]++;
638
44
639
44
    DEBUG(dbgs() << "Removing partial writes that never happen...\n");
640
44
    removeEmptyPartialAccesses();
641
44
642
44
    DEBUG(dbgs() << "Removing overwrites...\n");
643
44
    removeOverwrites();
644
44
645
44
    DEBUG(dbgs() << "Coalesce partial writes...\n");
646
44
    coalesceWrites();
647
44
648
44
    DEBUG(dbgs() << "Removing redundant writes...\n");
649
44
    removeRedundantWrites();
650
44
651
44
    DEBUG(dbgs() << "Cleanup unused accesses...\n");
652
44
    LoopInfo *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
653
44
    markAndSweep(LI);
654
44
655
44
    DEBUG(dbgs() << "Removing statements without side effects...\n");
656
44
    removeUnnecessaryStmts();
657
44
658
44
    if (isModified())
659
28
      ScopsModified[CallNo]++;
660
44
    DEBUG(dbgs() << "\nFinal Scop:\n");
661
44
    DEBUG(dbgs() << S);
662
44
663
44
    auto ScopStats = S.getStatistics();
664
44
    NumValueWrites[CallNo] += ScopStats.NumValueWrites;
665
44
    NumValueWritesInLoops[CallNo] += ScopStats.NumValueWritesInLoops;
666
44
    NumPHIWrites[CallNo] += ScopStats.NumPHIWrites;
667
44
    NumPHIWritesInLoops[CallNo] += ScopStats.NumPHIWritesInLoops;
668
44
    NumSingletonWrites[CallNo] += ScopStats.NumSingletonWrites;
669
44
    NumSingletonWritesInLoops[CallNo] += ScopStats.NumSingletonWritesInLoops;
670
44
671
44
    return false;
672
44
  }
673
674
42
  virtual void printScop(raw_ostream &OS, Scop &S) const override {
675
42
    assert(&S == this->S &&
676
42
           "Can only print analysis for the last processed SCoP");
677
42
    printStatistics(OS);
678
42
679
42
    if (!isModified()) {
680
16
      OS << "SCoP could not be simplified\n";
681
16
      return;
682
16
    }
683
26
    printAccesses(OS);
684
26
  }
685
686
194
  virtual void releaseMemory() override {
687
194
    S = nullptr;
688
194
689
194
    OverwritesRemoved = 0;
690
194
    WritesCoalesced = 0;
691
194
    RedundantWritesRemoved = 0;
692
194
    EmptyPartialAccessesRemoved = 0;
693
194
    DeadAccessesRemoved = 0;
694
194
    DeadInstructionsRemoved = 0;
695
194
    StmtsRemoved = 0;
696
194
  }
697
};
698
699
char Simplify::ID;
700
} // anonymous namespace
701
702
namespace polly {
703
323
SmallVector<MemoryAccess *, 32> getAccessesInOrder(ScopStmt &Stmt) {
704
323
705
323
  SmallVector<MemoryAccess *, 32> Accesses;
706
323
707
323
  for (MemoryAccess *MemAcc : Stmt)
708
812
    if (isImplicitRead(MemAcc))
709
97
      Accesses.push_back(MemAcc);
710
323
711
323
  for (MemoryAccess *MemAcc : Stmt)
712
812
    if (isExplicitAccess(MemAcc))
713
629
      Accesses.push_back(MemAcc);
714
323
715
323
  for (MemoryAccess *MemAcc : Stmt)
716
812
    if (isImplicitWrite(MemAcc))
717
86
      Accesses.push_back(MemAcc);
718
323
719
323
  return Accesses;
720
323
}
721
} // namespace polly
722
723
0
Pass *polly::createSimplifyPass(int CallNo) { return new Simplify(CallNo); }
724
725
43.0k
INITIALIZE_PASS_BEGIN(Simplify, "polly-simplify", "Polly - Simplify", false,
726
43.0k
                      false)
727
43.0k
INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
728
43.0k
INITIALIZE_PASS_END(Simplify, "polly-simplify", "Polly - Simplify", false,
729
                    false)