Coverage Report

Created: 2018-08-20 19:24

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