Coverage Report

Created: 2017-10-03 07:32

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/polly/lib/Transform/MaximalStaticExpansion.cpp
Line
Count
Source (jump to first uncovered line)
1
//===- MaximalStaticExpansion.cpp -----------------------------------------===//
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
// This pass fully expand the memory accesses of a Scop to get rid of
11
// dependencies.
12
//
13
//===----------------------------------------------------------------------===//
14
15
#include "polly/DependenceInfo.h"
16
#include "polly/LinkAllPasses.h"
17
#include "polly/ScopInfo.h"
18
#include "polly/ScopPass.h"
19
#include "polly/Support/GICHelper.h"
20
#include "llvm/ADT/SmallPtrSet.h"
21
#include "llvm/ADT/StringRef.h"
22
#include "llvm/Analysis/OptimizationDiagnosticInfo.h"
23
#include "llvm/Pass.h"
24
#include "isl/isl-noexceptions.h"
25
#include "isl/union_map.h"
26
#include <cassert>
27
#include <limits>
28
#include <string>
29
#include <vector>
30
31
using namespace llvm;
32
using namespace polly;
33
34
14
#define DEBUG_TYPE "polly-mse"
35
36
namespace {
37
38
class MaximalStaticExpander : public ScopPass {
39
public:
40
  static char ID;
41
42
17
  explicit MaximalStaticExpander() : ScopPass(ID) {}
43
44
17
  ~MaximalStaticExpander() override = default;
45
46
  /// Expand the accesses of the SCoP.
47
  ///
48
  /// @param S The SCoP that must be expanded.
49
  bool runOnScop(Scop &S) override;
50
51
  /// Print the SCoP.
52
  ///
53
  /// @param OS The stream where to print.
54
  /// @param S The SCop that must be printed.
55
  void printScop(raw_ostream &OS, Scop &S) const override;
56
57
  /// Register all analyses and transformations required.
58
  void getAnalysisUsage(AnalysisUsage &AU) const override;
59
60
private:
61
  /// OptimizationRemarkEmitter object for displaying diagnostic remarks.
62
  OptimizationRemarkEmitter *ORE;
63
64
  /// Emit remark
65
  void emitRemark(StringRef Msg, Instruction *Inst);
66
67
  /// Return true if the SAI in parameter is expandable.
68
  ///
69
  /// @param SAI the SAI that need to be checked.
70
  /// @param Writes A set that will contains all the write accesses.
71
  /// @param Reads A set that will contains all the read accesses.
72
  /// @param S The SCop in which the SAI is in.
73
  /// @param Dependences The RAW dependences of the SCop.
74
  bool isExpandable(const ScopArrayInfo *SAI,
75
                    SmallPtrSetImpl<MemoryAccess *> &Writes,
76
                    SmallPtrSetImpl<MemoryAccess *> &Reads, Scop &S,
77
                    const isl::union_map &Dependences);
78
79
  /// Expand the MemoryAccess according to its domain.
80
  ///
81
  /// @param S The SCop in which the memory access appears in.
82
  /// @param MA The memory access that need to be expanded.
83
  ScopArrayInfo *expandAccess(Scop &S, MemoryAccess *MA);
84
85
  /// Filter the dependences to have only one related to current memory access.
86
  ///
87
  /// @param S The SCop in which the memory access appears in.
88
  /// @param MapDependences The dependences to filter.
89
  /// @param MA The memory access that need to be expanded.
90
  isl::union_map filterDependences(Scop &S,
91
                                   const isl::union_map &MapDependences,
92
                                   MemoryAccess *MA);
93
94
  /// Expand the MemoryAccess according to Dependences and already expanded
95
  /// MemoryAccesses.
96
  ///
97
  /// @param The SCop in which the memory access appears in.
98
  /// @param The memory access that need to be expanded.
99
  /// @param Dependences The RAW dependences of the SCop.
100
  /// @param ExpandedSAI The expanded SAI created during write expansion.
101
  /// @param Reverse if true, the Dependences union_map is reversed before
102
  /// intersection.
103
  void mapAccess(Scop &S, SmallPtrSetImpl<MemoryAccess *> &Accesses,
104
                 const isl::union_map &Dependences, ScopArrayInfo *ExpandedSAI,
105
                 bool Reverse);
106
107
  /// Expand PHI memory accesses.
108
  ///
109
  /// @param The SCop in which the memory access appears in.
110
  /// @param The ScopArrayInfo representing the PHI accesses to expand.
111
  /// @param Dependences The RAW dependences of the SCop.
112
  void expandPhi(Scop &S, const ScopArrayInfo *SAI,
113
                 const isl::union_map &Dependences);
114
};
115
116
} // namespace
117
118
#ifndef NDEBUG
119
/// Whether a dimension of a set is bounded (lower and upper) by a constant,
120
/// i.e. there are two constants Min and Max, such that every value x of the
121
/// chosen dimensions is Min <= x <= Max.
122
static bool isDimBoundedByConstant(isl::set Set, unsigned dim) {
123
  auto ParamDims = Set.dim(isl::dim::param);
124
  Set = Set.project_out(isl::dim::param, 0, ParamDims);
125
  Set = Set.project_out(isl::dim::set, 0, dim);
126
  auto SetDims = Set.dim(isl::dim::set);
127
  Set = Set.project_out(isl::dim::set, 1, SetDims - 1);
128
  return bool(Set.is_bounded());
129
}
130
#endif
131
132
/// If @p PwAff maps to a constant, return said constant. If @p Max/@p Min, it
133
/// can also be a piecewise constant and it would return the minimum/maximum
134
/// value. Otherwise, return NaN.
135
80
static isl::val getConstant(isl::pw_aff PwAff, bool Max, bool Min) {
136
80
  assert(!Max || !Min);
137
80
  isl::val Result;
138
80
  PwAff.foreach_piece([=, &Result](isl::set Set, isl::aff Aff) -> isl::stat {
139
80
    if (
Result && 80
Result.is_nan()0
)
140
0
      return isl::stat::ok;
141
80
142
80
    // TODO: If Min/Max, we can also determine a minimum/maximum value if
143
80
    // Set is constant-bounded.
144
80
    
if (80
!Aff.is_cst()80
) {
145
0
      Result = isl::val::nan(Aff.get_ctx());
146
0
      return isl::stat::error;
147
0
    }
148
80
149
80
    auto ThisVal = Aff.get_constant_val();
150
80
    if (
!Result80
) {
151
80
      Result = ThisVal;
152
80
      return isl::stat::ok;
153
80
    }
154
0
155
0
    
if (0
Result.eq(ThisVal)0
)
156
0
      return isl::stat::ok;
157
0
158
0
    
if (0
Max && 0
ThisVal.gt(Result)0
) {
159
0
      Result = ThisVal;
160
0
      return isl::stat::ok;
161
0
    }
162
0
163
0
    
if (0
Min && 0
ThisVal.lt(Result)0
) {
164
0
      Result = ThisVal;
165
0
      return isl::stat::ok;
166
0
    }
167
0
168
0
    // Not compatible
169
0
    Result = isl::val::nan(Aff.get_ctx());
170
0
    return isl::stat::error;
171
0
  });
172
80
  return Result;
173
80
}
174
175
char MaximalStaticExpander::ID = 0;
176
177
isl::union_map MaximalStaticExpander::filterDependences(
178
90
    Scop &S, const isl::union_map &Dependences, MemoryAccess *MA) {
179
90
  auto SAI = MA->getLatestScopArrayInfo();
180
90
181
90
  auto AccessDomainSet = MA->getAccessRelation().domain();
182
90
  auto AccessDomainId = AccessDomainSet.get_tuple_id();
183
90
184
90
  isl::union_map MapDependences = isl::union_map::empty(S.getParamSpace());
185
90
186
90
  Dependences.foreach_map([&MapDependences, &AccessDomainId,
187
1.07k
                           &SAI](isl::map Map) -> isl::stat {
188
1.07k
189
1.07k
    // Filter out Statement to Statement dependences.
190
1.07k
    if (!Map.can_curry())
191
478
      return isl::stat::ok;
192
594
193
594
    // Intersect with the relevant SAI.
194
594
    auto TmpMapDomainId =
195
594
        Map.get_space().domain().unwrap().range().get_tuple_id(isl::dim::set);
196
594
197
594
    ScopArrayInfo *UserSAI =
198
594
        static_cast<ScopArrayInfo *>(TmpMapDomainId.get_user());
199
594
200
594
    if (SAI != UserSAI)
201
462
      return isl::stat::ok;
202
132
203
132
    // Get the correct S1[] -> S2[] dependence.
204
132
    auto NewMap = Map.factor_domain();
205
132
    auto NewMapDomainId = NewMap.domain().get_tuple_id();
206
132
207
132
    if (AccessDomainId.keep() != NewMapDomainId.keep())
208
42
      return isl::stat::ok;
209
90
210
90
    // Add the corresponding map to MapDependences.
211
90
    MapDependences = MapDependences.add_map(NewMap);
212
90
213
90
    return isl::stat::ok;
214
90
  });
215
90
216
90
  return MapDependences;
217
90
}
218
219
bool MaximalStaticExpander::isExpandable(
220
    const ScopArrayInfo *SAI, SmallPtrSetImpl<MemoryAccess *> &Writes,
221
    SmallPtrSetImpl<MemoryAccess *> &Reads, Scop &S,
222
63
    const isl::union_map &Dependences) {
223
63
  if (
SAI->isValueKind()63
) {
224
3
    Writes.insert(S.getValueDef(SAI));
225
3
    for (auto MA : S.getValueUses(SAI))
226
4
      Reads.insert(MA);
227
3
    return true;
228
60
  } else 
if (60
SAI->isPHIKind()60
) {
229
28
    auto Read = S.getPHIRead(SAI);
230
28
231
28
    auto StmtDomain = isl::union_set(Read->getStatement()->getDomain());
232
28
233
28
    auto Writes = S.getPHIIncomings(SAI);
234
28
235
28
    // Get the domain where all the writes are writing to.
236
28
    auto WriteDomain = isl::union_set::empty(S.getParamSpace());
237
28
238
38
    for (auto Write : Writes) {
239
38
      auto MapDeps = filterDependences(S, Dependences, Write);
240
38
      MapDeps.foreach_map([&WriteDomain](isl::map Map) -> isl::stat {
241
38
        WriteDomain = WriteDomain.add_set(Map.range());
242
38
        return isl::stat::ok;
243
38
      });
244
38
    }
245
28
246
28
    // For now, read from original scalar is not possible.
247
28
    if (
!StmtDomain.is_equal(WriteDomain)28
) {
248
8
      emitRemark(SAI->getName() + " read from its original value.",
249
8
                 Read->getAccessInstruction());
250
8
      return false;
251
8
    }
252
20
253
20
    return true;
254
32
  } else 
if (32
SAI->isExitPHIKind()32
) {
255
0
    // For now, we are not able to expand ExitPhi.
256
0
    emitRemark(SAI->getName() + " is a ExitPhi node.",
257
0
               S.getEnteringBlock()->getFirstNonPHI());
258
0
    return false;
259
0
  }
260
32
261
32
  int NumberWrites = 0;
262
90
  for (ScopStmt &Stmt : S) {
263
90
    auto StmtReads = isl::union_map::empty(S.getParamSpace());
264
90
    auto StmtWrites = isl::union_map::empty(S.getParamSpace());
265
90
266
186
    for (MemoryAccess *MA : Stmt) {
267
186
      // Check if the current MemoryAccess involved the current SAI.
268
186
      if (SAI != MA->getLatestScopArrayInfo())
269
140
        continue;
270
46
271
46
      // For now, we are not able to expand array where read come after write
272
46
      // (to the same location) in a same statement.
273
46
      auto AccRel = isl::union_map(MA->getAccessRelation());
274
46
      if (
MA->isRead()46
) {
275
12
        // Reject load after store to same location.
276
12
        if (
!StmtWrites.is_disjoint(AccRel)12
) {
277
2
          emitRemark(SAI->getName() + " has read after write to the same "
278
2
                                      "element in same statement. The "
279
2
                                      "dependences found during analysis may "
280
2
                                      "be wrong because Polly is not able to "
281
2
                                      "handle such case for now.",
282
2
                     MA->getAccessInstruction());
283
2
          return false;
284
2
        }
285
10
286
10
        StmtReads = give(isl_union_map_union(StmtReads.take(), AccRel.take()));
287
46
      } else {
288
34
        StmtWrites =
289
34
            give(isl_union_map_union(StmtWrites.take(), AccRel.take()));
290
34
      }
291
46
292
46
      // For now, we are not able to expand MayWrite.
293
44
      
if (44
MA->isMayWrite()44
) {
294
0
        emitRemark(SAI->getName() + " has a maywrite access.",
295
0
                   MA->getAccessInstruction());
296
0
        return false;
297
0
      }
298
44
299
44
      // For now, we are not able to expand SAI with more than one write.
300
44
      
if (44
MA->isMustWrite()44
) {
301
34
        Writes.insert(MA);
302
34
        NumberWrites++;
303
34
        if (
NumberWrites > 134
) {
304
2
          emitRemark(SAI->getName() + " has more than 1 write access.",
305
2
                     MA->getAccessInstruction());
306
2
          return false;
307
2
        }
308
42
      }
309
42
310
42
      // Check if it is possible to expand this read.
311
42
      
if (42
MA->isRead()42
) {
312
10
        // Get the domain of the current ScopStmt.
313
10
        auto StmtDomain = Stmt.getDomain();
314
10
315
10
        // Get the domain of the future Read access.
316
10
        auto ReadDomainSet = MA->getAccessRelation().domain();
317
10
        auto ReadDomain = isl::union_set(ReadDomainSet);
318
10
319
10
        // Get the dependences relevant for this MA
320
10
        auto MapDependences = filterDependences(S, Dependences.reverse(), MA);
321
10
        unsigned NumberElementMap = isl_union_map_n_map(MapDependences.get());
322
10
323
10
        if (
NumberElementMap == 010
) {
324
0
          emitRemark("The expansion of " + SAI->getName() +
325
0
                         " would lead to a read from the original array.",
326
0
                     MA->getAccessInstruction());
327
0
          return false;
328
0
        }
329
10
330
10
        auto DepsDomain = MapDependences.domain();
331
10
332
10
        // If there are multiple maps in the Deps, we cannot handle this case
333
10
        // for now.
334
10
        if (
NumberElementMap != 110
) {
335
0
          emitRemark(SAI->getName() +
336
0
                         " has too many dependences to be handle for now.",
337
0
                     MA->getAccessInstruction());
338
0
          return false;
339
0
        }
340
10
341
10
        auto DepsDomainSet = isl::set(DepsDomain);
342
10
343
10
        // For now, read from the original array is not possible.
344
10
        if (
!StmtDomain.is_subset(DepsDomainSet)10
) {
345
2
          emitRemark("The expansion of " + SAI->getName() +
346
2
                         " would lead to a read from the original array.",
347
2
                     MA->getAccessInstruction());
348
2
          return false;
349
2
        }
350
8
351
8
        Reads.insert(MA);
352
8
      }
353
186
    }
354
90
  }
355
32
356
32
  // No need to expand SAI with no write.
357
26
  
if (26
NumberWrites == 026
) {
358
0
    emitRemark(SAI->getName() + " has 0 write access.",
359
0
               S.getEnteringBlock()->getFirstNonPHI());
360
0
    return false;
361
0
  }
362
26
363
26
  return true;
364
26
}
365
366
void MaximalStaticExpander::mapAccess(Scop &S,
367
                                      SmallPtrSetImpl<MemoryAccess *> &Accesses,
368
                                      const isl::union_map &Dependences,
369
                                      ScopArrayInfo *ExpandedSAI,
370
49
                                      bool Reverse) {
371
42
  for (auto MA : Accesses) {
372
42
    // Get the current AM.
373
42
    auto CurrentAccessMap = MA->getAccessRelation();
374
42
375
42
    // Get RAW dependences for the current WA.
376
42
    auto DomainSet = MA->getAccessRelation().domain();
377
42
    auto Domain = isl::union_set(DomainSet);
378
42
379
42
    // Get the dependences relevant for this MA.
380
42
    isl::union_map MapDependences;
381
42
    if (
Reverse42
) {
382
12
      MapDependences = filterDependences(S, Dependences.reverse(), MA);
383
42
    } else {
384
30
      MapDependences = filterDependences(S, Dependences, MA);
385
30
    }
386
42
387
42
    // If no dependences, no need to modify anything.
388
42
    if (MapDependences.is_empty())
389
0
      return;
390
42
391
42
    assert(isl_union_map_n_map(MapDependences.get()) == 1 &&
392
42
           "There are more than one RAW dependencies in the union map.");
393
42
    auto NewAccessMap = isl::map::from_union_map(MapDependences);
394
42
395
42
    auto Id = ExpandedSAI->getBasePtrId();
396
42
397
42
    // Replace the out tuple id with the one of the access array.
398
42
    NewAccessMap = NewAccessMap.set_tuple_id(isl::dim::out, Id);
399
42
400
42
    // Set the new access relation.
401
42
    MA->setNewAccessRelation(NewAccessMap);
402
42
  }
403
49
}
404
405
49
ScopArrayInfo *MaximalStaticExpander::expandAccess(Scop &S, MemoryAccess *MA) {
406
49
  // Get the current AM.
407
49
  auto CurrentAccessMap = MA->getAccessRelation();
408
49
409
49
  unsigned in_dimensions = CurrentAccessMap.dim(isl::dim::in);
410
49
411
49
  // Get domain from the current AM.
412
49
  auto Domain = CurrentAccessMap.domain();
413
49
414
49
  // Create a new AM from the domain.
415
49
  auto NewAccessMap = isl::map::from_domain(Domain);
416
49
417
49
  // Add dimensions to the new AM according to the current in_dim.
418
49
  NewAccessMap = NewAccessMap.add_dims(isl::dim::out, in_dimensions);
419
49
420
49
  // Create the string representing the name of the new SAI.
421
49
  // One new SAI for each statement so that each write go to a different memory
422
49
  // cell.
423
49
  auto CurrentStmtDomain = MA->getStatement()->getDomain();
424
49
  auto CurrentStmtName = CurrentStmtDomain.get_tuple_name();
425
49
  auto CurrentOutId = CurrentAccessMap.get_tuple_id(isl::dim::out);
426
49
  std::string CurrentOutIdString =
427
49
      MA->getScopArrayInfo()->getName() + "_" + CurrentStmtName + "_expanded";
428
49
429
49
  // Set the tuple id for the out dimension.
430
49
  NewAccessMap = NewAccessMap.set_tuple_id(isl::dim::out, CurrentOutId);
431
49
432
49
  // Create the size vector.
433
49
  std::vector<unsigned> Sizes;
434
129
  for (unsigned i = 0; 
i < in_dimensions129
;
i++80
) {
435
80
    assert(isDimBoundedByConstant(CurrentStmtDomain, i) &&
436
80
           "Domain boundary are not constant.");
437
80
    auto UpperBound = getConstant(CurrentStmtDomain.dim_max(i), true, false);
438
80
    assert(!UpperBound.is_null() && UpperBound.is_pos() &&
439
80
           !UpperBound.is_nan() &&
440
80
           "The upper bound is not a positive integer.");
441
80
    assert(UpperBound.le(isl::val(CurrentAccessMap.get_ctx(),
442
80
                                  std::numeric_limits<int>::max() - 1)) &&
443
80
           "The upper bound overflow a int.");
444
80
    Sizes.push_back(UpperBound.get_num_si() + 1);
445
80
  }
446
49
447
49
  // Get the ElementType of the current SAI.
448
49
  auto ElementType = MA->getLatestScopArrayInfo()->getElementType();
449
49
450
49
  // Create (or get if already existing) the new expanded SAI.
451
49
  auto ExpandedSAI =
452
49
      S.createScopArrayInfo(ElementType, CurrentOutIdString, Sizes);
453
49
  ExpandedSAI->setIsOnHeap(true);
454
49
455
49
  // Get the out Id of the expanded Array.
456
49
  auto NewOutId = ExpandedSAI->getBasePtrId();
457
49
458
49
  // Set the out id of the new AM to the new SAI id.
459
49
  NewAccessMap = NewAccessMap.set_tuple_id(isl::dim::out, NewOutId);
460
49
461
49
  // Add constraints to linked output with input id.
462
49
  auto SpaceMap = NewAccessMap.get_space();
463
49
  auto ConstraintBasicMap =
464
49
      isl::basic_map::equal(SpaceMap, SpaceMap.dim(isl::dim::in));
465
49
  NewAccessMap = isl::map(ConstraintBasicMap);
466
49
467
49
  // Set the new access relation map.
468
49
  MA->setNewAccessRelation(NewAccessMap);
469
49
470
49
  return ExpandedSAI;
471
49
}
472
473
void MaximalStaticExpander::expandPhi(Scop &S, const ScopArrayInfo *SAI,
474
20
                                      const isl::union_map &Dependences) {
475
20
  SmallPtrSet<MemoryAccess *, 4> Writes;
476
20
  for (auto MA : S.getPHIIncomings(SAI))
477
30
    Writes.insert(MA);
478
20
  auto Read = S.getPHIRead(SAI);
479
20
  auto ExpandedSAI = expandAccess(S, Read);
480
20
481
20
  mapAccess(S, Writes, Dependences, ExpandedSAI, false);
482
20
}
483
484
14
void MaximalStaticExpander::emitRemark(StringRef Msg, Instruction *Inst) {
485
14
  ORE->emit(OptimizationRemarkAnalysis(DEBUG_TYPE, "ExpansionRejection", Inst)
486
14
            << Msg);
487
14
}
488
489
17
bool MaximalStaticExpander::runOnScop(Scop &S) {
490
17
  // Get the ORE from OptimizationRemarkEmitterWrapperPass.
491
17
  ORE = &(getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE());
492
17
493
17
  // Get the RAW Dependences.
494
17
  auto &DI = getAnalysis<DependenceInfo>();
495
17
  auto &D = DI.getDependences(Dependences::AL_Reference);
496
17
  auto Dependences = isl::give(D.getDependences(Dependences::TYPE_RAW));
497
17
498
17
  SmallVector<ScopArrayInfo *, 4> CurrentSAI(S.arrays().begin(),
499
17
                                             S.arrays().end());
500
17
501
63
  for (auto SAI : CurrentSAI) {
502
63
    SmallPtrSet<MemoryAccess *, 4> AllWrites;
503
63
    SmallPtrSet<MemoryAccess *, 4> AllReads;
504
63
    if (!isExpandable(SAI, AllWrites, AllReads, S, Dependences))
505
14
      continue;
506
49
507
49
    
if (49
SAI->isValueKind() || 49
SAI->isArrayKind()46
) {
508
29
      assert(AllWrites.size() == 1 || SAI->isValueKind());
509
29
510
29
      auto TheWrite = *(AllWrites.begin());
511
29
      ScopArrayInfo *ExpandedArray = expandAccess(S, TheWrite);
512
29
513
29
      mapAccess(S, AllReads, Dependences, ExpandedArray, true);
514
49
    } else 
if (20
SAI->isPHIKind()20
) {
515
20
      expandPhi(S, SAI, Dependences);
516
20
    }
517
63
  }
518
17
519
17
  return false;
520
17
}
521
522
17
void MaximalStaticExpander::printScop(raw_ostream &OS, Scop &S) const {
523
17
  S.print(OS, false);
524
17
}
525
526
17
void MaximalStaticExpander::getAnalysisUsage(AnalysisUsage &AU) const {
527
17
  ScopPass::getAnalysisUsage(AU);
528
17
  AU.addRequired<DependenceInfo>();
529
17
  AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
530
17
}
531
532
0
Pass *polly::createMaximalStaticExpansionPass() {
533
0
  return new MaximalStaticExpander();
534
0
}
535
536
41.7k
INITIALIZE_PASS_BEGIN41.7k
(MaximalStaticExpander, "polly-mse",
537
41.7k
                      "Polly - Maximal static expansion of SCoP", false, false);
538
41.7k
INITIALIZE_PASS_DEPENDENCY(DependenceInfo);
539
41.7k
INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass);
540
41.7k
INITIALIZE_PASS_END(MaximalStaticExpander, "polly-mse",
541
                    "Polly - Maximal static expansion of SCoP", false, false)