Coverage Report

Created: 2017-03-28 09:59

/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/polly/lib/CodeGen/BlockGenerators.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- BlockGenerators.cpp - Generate code for statements -----*- 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
// This file implements the BlockGenerator and VectorBlockGenerator classes,
11
// which generate sequential code and vectorized code for a polyhedral
12
// statement, respectively.
13
//
14
//===----------------------------------------------------------------------===//
15
16
#include "polly/CodeGen/BlockGenerators.h"
17
#include "polly/CodeGen/CodeGeneration.h"
18
#include "polly/CodeGen/IslExprBuilder.h"
19
#include "polly/CodeGen/RuntimeDebugBuilder.h"
20
#include "polly/Options.h"
21
#include "polly/ScopInfo.h"
22
#include "polly/Support/GICHelper.h"
23
#include "polly/Support/SCEVValidator.h"
24
#include "polly/Support/ScopHelper.h"
25
#include "llvm/Analysis/LoopInfo.h"
26
#include "llvm/Analysis/RegionInfo.h"
27
#include "llvm/Analysis/ScalarEvolution.h"
28
#include "llvm/IR/IntrinsicInst.h"
29
#include "llvm/IR/Module.h"
30
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
31
#include "llvm/Transforms/Utils/Local.h"
32
#include "isl/aff.h"
33
#include "isl/ast.h"
34
#include "isl/ast_build.h"
35
#include "isl/set.h"
36
#include <deque>
37
38
using namespace llvm;
39
using namespace polly;
40
41
static cl::opt<bool> Aligned("enable-polly-aligned",
42
                             cl::desc("Assumed aligned memory accesses."),
43
                             cl::Hidden, cl::init(false), cl::ZeroOrMore,
44
                             cl::cat(PollyCategory));
45
46
bool PollyDebugPrinting;
47
static cl::opt<bool, true> DebugPrintingX(
48
    "polly-codegen-add-debug-printing",
49
    cl::desc("Add printf calls that show the values loaded/stored."),
50
    cl::location(PollyDebugPrinting), cl::Hidden, cl::init(false),
51
    cl::ZeroOrMore, cl::cat(PollyCategory));
52
53
BlockGenerator::BlockGenerator(
54
    PollyIRBuilder &B, LoopInfo &LI, ScalarEvolution &SE, DominatorTree &DT,
55
    AllocaMapTy &ScalarMap, EscapeUsersAllocaMapTy &EscapeMap,
56
    ValueMapT &GlobalMap, IslExprBuilder *ExprBuilder, BasicBlock *StartBlock)
57
    : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT),
58
      EntryBB(nullptr), ScalarMap(ScalarMap), EscapeMap(EscapeMap),
59
258
      GlobalMap(GlobalMap), StartBlock(StartBlock) {}
60
61
Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, Value *Old,
62
                                             ValueMapT &BBMap,
63
                                             LoopToScevMapT &LTS,
64
677
                                             Loop *L) const {
65
677
  if (!SE.isSCEVable(Old->getType()))
66
1
    return nullptr;
67
677
68
676
  const SCEV *Scev = SE.getSCEVAtScope(Old, L);
69
676
  if (!Scev)
70
0
    return nullptr;
71
676
72
676
  
if (676
isa<SCEVCouldNotCompute>(Scev)676
)
73
0
    return nullptr;
74
676
75
676
  const SCEV *NewScev = SCEVLoopAddRecRewriter::rewrite(Scev, LTS, SE);
76
676
  ValueMapT VTV;
77
676
  VTV.insert(BBMap.begin(), BBMap.end());
78
676
  VTV.insert(GlobalMap.begin(), GlobalMap.end());
79
676
80
676
  Scop &S = *Stmt.getParent();
81
676
  const DataLayout &DL = S.getFunction().getParent()->getDataLayout();
82
676
  auto IP = Builder.GetInsertPoint();
83
676
84
676
  assert(IP != Builder.GetInsertBlock()->end() &&
85
676
         "Only instructions can be insert points for SCEVExpander");
86
676
  Value *Expanded =
87
676
      expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), &*IP, &VTV,
88
676
                    StartBlock->getSinglePredecessor());
89
676
90
676
  BBMap[Old] = Expanded;
91
676
  return Expanded;
92
676
}
93
94
Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap,
95
1.94k
                                   LoopToScevMapT &LTS, Loop *L) const {
96
1.94k
  // Constants that do not reference any named value can always remain
97
1.94k
  // unchanged. Handle them early to avoid expensive map lookups. We do not take
98
1.94k
  // the fast-path for external constants which are referenced through globals
99
1.94k
  // as these may need to be rewritten when distributing code accross different
100
1.94k
  // LLVM modules.
101
1.94k
  if (
isa<Constant>(Old) && 1.94k
!isa<GlobalValue>(Old)410
)
102
385
    return Old;
103
1.94k
104
1.94k
  // Inline asm is like a constant to us.
105
1.55k
  
if (1.55k
isa<InlineAsm>(Old)1.55k
)
106
0
    return Old;
107
1.55k
108
1.55k
  
if (Value *1.55k
New1.55k
= GlobalMap.lookup(Old))
{101
109
101
    if (Value *NewRemapped = GlobalMap.lookup(New))
110
9
      New = NewRemapped;
111
101
    if (Old->getType()->getScalarSizeInBits() <
112
101
        New->getType()->getScalarSizeInBits())
113
0
      New = Builder.CreateTruncOrBitCast(New, Old->getType());
114
101
115
101
    return New;
116
101
  }
117
1.55k
118
1.45k
  
if (Value *1.45k
New1.45k
= BBMap.lookup(Old))
119
777
    return New;
120
1.45k
121
677
  
if (Value *677
New677
= trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L))
122
676
    return New;
123
677
124
677
  // A scop-constant value defined by a global or a function parameter.
125
1
  
if (1
isa<GlobalValue>(Old) || 1
isa<Argument>(Old)1
)
126
1
    return Old;
127
1
128
1
  // A scop-constant value defined by an instruction executed outside the scop.
129
0
  
if (const Instruction *0
Inst0
= dyn_cast<Instruction>(Old))
130
0
    
if (0
!Stmt.getParent()->contains(Inst->getParent())0
)
131
0
      return Old;
132
0
133
0
  // The scalar dependence is neither available nor SCEVCodegenable.
134
0
  
llvm_unreachable0
("Unexpected scalar dependence in region!");0
135
0
  return nullptr;
136
0
}
137
138
void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst,
139
542
                                    ValueMapT &BBMap, LoopToScevMapT &LTS) {
140
542
  // We do not generate debug intrinsics as we did not investigate how to
141
542
  // copy them correctly. At the current state, they just crash the code
142
542
  // generation as the meta-data operands are not correctly copied.
143
542
  if (isa<DbgInfoIntrinsic>(Inst))
144
0
    return;
145
542
146
542
  Instruction *NewInst = Inst->clone();
147
542
148
542
  // Replace old operands with the new ones.
149
1.03k
  for (Value *OldOperand : Inst->operands()) {
150
1.03k
    Value *NewOperand =
151
1.03k
        getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt));
152
1.03k
153
1.03k
    if (
!NewOperand1.03k
)
{0
154
0
      assert(!isa<StoreInst>(NewInst) &&
155
0
             "Store instructions are always needed!");
156
0
      delete NewInst;
157
0
      return;
158
0
    }
159
1.03k
160
1.03k
    NewInst->replaceUsesOfWith(OldOperand, NewOperand);
161
1.03k
  }
162
542
163
542
  Builder.Insert(NewInst);
164
542
  BBMap[Inst] = NewInst;
165
542
166
542
  if (!NewInst->getType()->isVoidTy())
167
450
    NewInst->setName("p_" + Inst->getName());
168
542
}
169
170
Value *
171
BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst,
172
                                         ValueMapT &BBMap, LoopToScevMapT &LTS,
173
525
                                         isl_id_to_ast_expr *NewAccesses) {
174
525
  const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst);
175
525
  return generateLocationAccessed(
176
525
      Stmt, getLoopForStmt(Stmt),
177
525
      Inst.isNull() ? 
nullptr0
:
Inst.getPointerOperand()525
, BBMap, LTS,
178
525
      NewAccesses, MA.getId(), MA.getAccessValue()->getType());
179
525
}
180
181
Value *BlockGenerator::generateLocationAccessed(
182
    ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap,
183
    LoopToScevMapT &LTS, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id,
184
533
    Type *ExpectedType) {
185
533
  isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id);
186
533
187
533
  if (
AccessExpr533
)
{77
188
77
    AccessExpr = isl_ast_expr_address_of(AccessExpr);
189
77
    auto Address = ExprBuilder->create(AccessExpr);
190
77
191
77
    // Cast the address of this memory access to a pointer type that has the
192
77
    // same element type as the original access, but uses the address space of
193
77
    // the newly generated pointer.
194
77
    auto OldPtrTy = ExpectedType->getPointerTo();
195
77
    auto NewPtrTy = Address->getType();
196
77
    OldPtrTy = PointerType::get(OldPtrTy->getElementType(),
197
77
                                NewPtrTy->getPointerAddressSpace());
198
77
199
77
    if (OldPtrTy != NewPtrTy)
200
4
      Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy);
201
77
    return Address;
202
77
  }
203
456
  assert(
204
456
      Pointer &&
205
456
      "If expression was not generated, must use the original pointer value");
206
456
  return getNewValue(Stmt, Pointer, BBMap, LTS, L);
207
533
}
208
209
Value *
210
BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L,
211
                                   LoopToScevMapT &LTS, ValueMapT &BBMap,
212
218
                                   __isl_keep isl_id_to_ast_expr *NewAccesses) {
213
218
  if (Access.isLatestArrayKind())
214
8
    return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap,
215
8
                                    LTS, NewAccesses, Access.getId(),
216
8
                                    Access.getAccessValue()->getType());
217
218
218
210
  return getOrCreateAlloca(Access);
219
218
}
220
221
3.93k
Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const {
222
3.93k
  auto *StmtBB = Stmt.getEntryBlock();
223
3.93k
  return LI.getLoopFor(StmtBB);
224
3.93k
}
225
226
Value *BlockGenerator::generateArrayLoad(ScopStmt &Stmt, LoadInst *Load,
227
                                         ValueMapT &BBMap, LoopToScevMapT &LTS,
228
268
                                         isl_id_to_ast_expr *NewAccesses) {
229
268
  if (Value *PreloadLoad = GlobalMap.lookup(Load))
230
82
    return PreloadLoad;
231
268
232
186
  Value *NewPointer =
233
186
      generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses);
234
186
  Value *ScalarLoad = Builder.CreateAlignedLoad(
235
186
      NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_");
236
186
237
186
  if (PollyDebugPrinting)
238
5
    RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer,
239
5
                                          ": ", ScalarLoad, "\n");
240
186
241
186
  return ScalarLoad;
242
268
}
243
244
void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store,
245
                                        ValueMapT &BBMap, LoopToScevMapT &LTS,
246
285
                                        isl_id_to_ast_expr *NewAccesses) {
247
285
  Value *NewPointer =
248
285
      generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses);
249
285
  Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS,
250
285
                                    getLoopForStmt(Stmt));
251
285
252
285
  if (PollyDebugPrinting)
253
1
    RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to  ", NewPointer,
254
1
                                          ": ", ValueOperand, "\n");
255
285
256
285
  Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment());
257
285
}
258
259
1.84k
bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) {
260
1.84k
  Loop *L = getLoopForStmt(Stmt);
261
179
  return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) &&
262
1.84k
         canSynthesize(Inst, *Stmt.getParent(), &SE, L);
263
1.84k
}
264
265
void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst,
266
                                     ValueMapT &BBMap, LoopToScevMapT &LTS,
267
2.14k
                                     isl_id_to_ast_expr *NewAccesses) {
268
2.14k
  // Terminator instructions control the control flow. They are explicitly
269
2.14k
  // expressed in the clast and do not need to be copied.
270
2.14k
  if (Inst->isTerminator())
271
401
    return;
272
2.14k
273
2.14k
  // Synthesizable statements will be generated on-demand.
274
1.74k
  
if (1.74k
canSyntheziseInStmt(Stmt, Inst)1.74k
)
275
688
    return;
276
1.74k
277
1.05k
  
if (auto *1.05k
Load1.05k
= dyn_cast<LoadInst>(Inst))
{268
278
268
    Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses);
279
268
    // Compute NewLoad before its insertion in BBMap to make the insertion
280
268
    // deterministic.
281
268
    BBMap[Load] = NewLoad;
282
268
    return;
283
268
  }
284
1.05k
285
786
  
if (auto *786
Store786
= dyn_cast<StoreInst>(Inst))
{285
286
285
    // Identified as redundant by -polly-simplify.
287
285
    if (!Stmt.getArrayAccessOrNULLFor(Store))
288
0
      return;
289
285
290
285
    generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses);
291
285
    return;
292
285
  }
293
786
294
501
  
if (auto *501
PHI501
= dyn_cast<PHINode>(Inst))
{39
295
39
    copyPHIInstruction(Stmt, PHI, BBMap, LTS);
296
39
    return;
297
39
  }
298
501
299
501
  // Skip some special intrinsics for which we do not adjust the semantics to
300
501
  // the new schedule. All others are handled like every other instruction.
301
462
  
if (462
isIgnoredIntrinsic(Inst)462
)
302
7
    return;
303
462
304
455
  copyInstScalar(Stmt, Inst, BBMap, LTS);
305
455
}
306
307
314
void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) {
308
314
  auto NewBB = Builder.GetInsertBlock();
309
3.15k
  for (auto I = NewBB->rbegin(); 
I != NewBB->rend()3.15k
;
I++2.84k
)
{2.84k
310
2.84k
    Instruction *NewInst = &*I;
311
2.84k
312
2.84k
    if (!isInstructionTriviallyDead(NewInst))
313
2.62k
      continue;
314
2.84k
315
220
    for (auto Pair : BBMap)
316
1.24k
      
if (1.24k
Pair.second == NewInst1.24k
)
{208
317
208
        BBMap.erase(Pair.first);
318
208
      }
319
220
320
220
    NewInst->eraseFromParent();
321
220
    I = NewBB->rbegin();
322
220
  }
323
314
}
324
325
void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
326
314
                              isl_id_to_ast_expr *NewAccesses) {
327
314
  assert(Stmt.isBlockStmt() &&
328
314
         "Only block statements can be copied by the block generator");
329
314
330
314
  ValueMapT BBMap;
331
314
332
314
  BasicBlock *BB = Stmt.getBasicBlock();
333
314
  copyBB(Stmt, BB, BBMap, LTS, NewAccesses);
334
314
  removeDeadInstructions(BB, BBMap);
335
314
}
336
337
401
BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) {
338
401
  BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
339
401
                                  &*Builder.GetInsertPoint(), &DT, &LI);
340
401
  CopyBB->setName("polly.stmt." + BB->getName());
341
401
  return CopyBB;
342
401
}
343
344
BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB,
345
                                   ValueMapT &BBMap, LoopToScevMapT &LTS,
346
314
                                   isl_id_to_ast_expr *NewAccesses) {
347
314
  BasicBlock *CopyBB = splitBB(BB);
348
314
  Builder.SetInsertPoint(&CopyBB->front());
349
314
  generateScalarLoads(Stmt, LTS, BBMap, NewAccesses);
350
314
351
314
  copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses);
352
314
353
314
  // After a basic block was copied store all scalars that escape this block in
354
314
  // their alloca.
355
314
  generateScalarStores(Stmt, LTS, BBMap, NewAccesses);
356
314
  return CopyBB;
357
314
}
358
359
void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB,
360
                            ValueMapT &BBMap, LoopToScevMapT &LTS,
361
401
                            isl_id_to_ast_expr *NewAccesses) {
362
401
  EntryBB = &CopyBB->getParent()->getEntryBlock();
363
401
364
401
  for (Instruction &Inst : *BB)
365
2.06k
    copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
366
401
}
367
368
213
Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) {
369
213
  assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind");
370
213
371
213
  return getOrCreateAlloca(Access.getLatestScopArrayInfo());
372
213
}
373
374
288
Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
375
288
  assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
376
288
377
288
  auto &Addr = ScalarMap[Array];
378
288
379
288
  if (
Addr288
)
{164
380
164
    // Allow allocas to be (temporarily) redirected once by adding a new
381
164
    // old-alloca-addr to new-addr mapping to GlobalMap. This funcitionality
382
164
    // is used for example by the OpenMP code generation where a first use
383
164
    // of a scalar while still in the host code allocates a normal alloca with
384
164
    // getOrCreateAlloca. When the values of this scalar are accessed during
385
164
    // the generation of the parallel subfunction, these values are copied over
386
164
    // to the parallel subfunction and each request for a scalar alloca slot
387
164
    // must be forwared to the temporary in-subfunction slot. This mapping is
388
164
    // removed when the subfunction has been generated and again normal host
389
164
    // code is generated. Due to the following reasons it is not possible to
390
164
    // perform the GlobalMap lookup right after creating the alloca below, but
391
164
    // instead we need to check GlobalMap at each call to getOrCreateAlloca:
392
164
    //
393
164
    //   1) GlobalMap may be changed multiple times (for each parallel loop),
394
164
    //   2) The temporary mapping is commonly only known after the initial
395
164
    //      alloca has already been generated, and
396
164
    //   3) The original alloca value must be restored after leaving the
397
164
    //      sub-function.
398
164
    if (Value *NewAddr = GlobalMap.lookup(&*Addr))
399
2
      return NewAddr;
400
162
    return Addr;
401
164
  }
402
288
403
124
  Type *Ty = Array->getElementType();
404
124
  Value *ScalarBase = Array->getBasePtr();
405
124
  std::string NameExt;
406
124
  if (Array->isPHIKind())
407
32
    NameExt = ".phiops";
408
124
  else
409
92
    NameExt = ".s2a";
410
124
411
124
  Addr = new AllocaInst(Ty, ScalarBase->getName() + NameExt);
412
124
  EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
413
124
  Addr->insertBefore(&*EntryBB->getFirstInsertionPt());
414
124
415
124
  return Addr;
416
288
}
417
418
69
void BlockGenerator::handleOutsideUsers(const Scop &S, ScopArrayInfo *Array) {
419
69
  Instruction *Inst = cast<Instruction>(Array->getBasePtr());
420
69
421
69
  // If there are escape users we get the alloca for this instruction and put it
422
69
  // in the EscapeMap for later finalization. Lastly, if the instruction was
423
69
  // copied multiple times we already did this and can exit.
424
69
  if (EscapeMap.count(Inst))
425
6
    return;
426
69
427
63
  EscapeUserVectorTy EscapeUsers;
428
96
  for (User *U : Inst->users()) {
429
96
430
96
    // Non-instruction user will never escape.
431
96
    Instruction *UI = dyn_cast<Instruction>(U);
432
96
    if (!UI)
433
0
      continue;
434
96
435
96
    
if (96
S.contains(UI)96
)
436
59
      continue;
437
96
438
37
    EscapeUsers.push_back(UI);
439
37
  }
440
63
441
63
  // Exit if no escape uses were found.
442
63
  if (EscapeUsers.empty())
443
32
    return;
444
63
445
63
  // Get or create an escape alloca for this instruction.
446
31
  auto *ScalarAddr = getOrCreateAlloca(Array);
447
31
448
31
  // Remember that this instruction has escape uses and the escape alloca.
449
31
  EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
450
31
}
451
452
void BlockGenerator::generateScalarLoads(
453
    ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
454
343
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
455
671
  for (MemoryAccess *MA : Stmt) {
456
671
    if (
MA->isOriginalArrayKind() || 671
MA->isWrite()218
)
457
585
      continue;
458
671
459
671
#ifndef NDEBUG
460
    auto *StmtDom = Stmt.getDomain();
461
    auto *AccDom = isl_map_domain(MA->getAccessRelation());
462
    assert(isl_set_is_subset(StmtDom, AccDom) &&
463
           "Scalar must be loaded in all statement instances");
464
    isl_set_free(StmtDom);
465
    isl_set_free(AccDom);
466
#endif
467
671
468
86
    auto *Address =
469
86
        getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
470
86
    assert((!isa<Instruction>(Address) ||
471
86
            DT.dominates(cast<Instruction>(Address)->getParent(),
472
86
                         Builder.GetInsertBlock())) &&
473
86
           "Domination violation");
474
86
    BBMap[MA->getAccessValue()] =
475
86
        Builder.CreateLoad(Address, Address->getName() + ".reload");
476
86
  }
477
343
}
478
479
void BlockGenerator::generateScalarStores(
480
    ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
481
314
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
482
314
  Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
483
314
484
314
  assert(Stmt.isBlockStmt() &&
485
314
         "Region statements need to use the generateScalarStores() function in "
486
314
         "the RegionGenerator");
487
314
488
587
  for (MemoryAccess *MA : Stmt) {
489
587
    if (
MA->isOriginalArrayKind() || 587
MA->isRead()190
)
490
474
      continue;
491
587
492
587
#ifndef NDEBUG
493
    auto *StmtDom = Stmt.getDomain();
494
    auto *AccDom = isl_map_domain(MA->getAccessRelation());
495
    assert(isl_set_is_subset(StmtDom, AccDom) &&
496
           "Scalar must be stored in all statement instances");
497
    isl_set_free(StmtDom);
498
    isl_set_free(AccDom);
499
#endif
500
587
501
113
    Value *Val = MA->getAccessValue();
502
113
    if (
MA->isAnyPHIKind()113
)
{55
503
55
      assert(MA->getIncoming().size() >= 1 &&
504
55
             "Block statements have exactly one exiting block, or multiple but "
505
55
             "with same incoming block and value");
506
55
      assert(std::all_of(MA->getIncoming().begin(), MA->getIncoming().end(),
507
55
                         [&](std::pair<BasicBlock *, Value *> p) -> bool {
508
55
                           return p.first == Stmt.getBasicBlock();
509
55
                         }) &&
510
55
             "Incoming block must be statement's block");
511
55
      Val = MA->getIncoming()[0].second;
512
55
    }
513
113
    auto Address =
514
113
        getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
515
113
516
113
    Val = getNewValue(Stmt, Val, BBMap, LTS, L);
517
113
    assert((!isa<Instruction>(Val) ||
518
113
            DT.dominates(cast<Instruction>(Val)->getParent(),
519
113
                         Builder.GetInsertBlock())) &&
520
113
           "Domination violation");
521
113
    assert((!isa<Instruction>(Address) ||
522
113
            DT.dominates(cast<Instruction>(Address)->getParent(),
523
113
                         Builder.GetInsertBlock())) &&
524
113
           "Domination violation");
525
113
    Builder.CreateStore(Val, Address);
526
113
  }
527
314
}
528
529
253
void BlockGenerator::createScalarInitialization(Scop &S) {
530
253
  BasicBlock *ExitBB = S.getExit();
531
253
  BasicBlock *PreEntryBB = S.getEnteringBlock();
532
253
533
253
  Builder.SetInsertPoint(&*StartBlock->begin());
534
253
535
524
  for (auto &Array : S.arrays()) {
536
524
    if (Array->getNumberOfDimensions() != 0)
537
390
      continue;
538
134
    
if (134
Array->isPHIKind()134
)
{33
539
33
      // For PHI nodes, the only values we need to store are the ones that
540
33
      // reach the PHI node from outside the region. In general there should
541
33
      // only be one such incoming edge and this edge should enter through
542
33
      // 'PreEntryBB'.
543
33
      auto PHI = cast<PHINode>(Array->getBasePtr());
544
33
545
96
      for (auto BI = PHI->block_begin(), BE = PHI->block_end(); 
BI != BE96
;
BI++63
)
546
63
        
if (63
!S.contains(*BI) && 63
*BI != PreEntryBB13
)
547
0
          llvm_unreachable("Incoming edges from outside the scop should always "
548
33
                           "come from PreEntryBB");
549
33
550
33
      int Idx = PHI->getBasicBlockIndex(PreEntryBB);
551
33
      if (Idx < 0)
552
20
        continue;
553
33
554
13
      Value *ScalarValue = PHI->getIncomingValue(Idx);
555
13
556
13
      Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
557
13
      continue;
558
33
    }
559
134
560
101
    auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
561
101
562
101
    if (
Inst && 101
S.contains(Inst)91
)
563
69
      continue;
564
101
565
101
    // PHI nodes that are not marked as such in their SAI object are either exit
566
101
    // PHI nodes we model as common scalars but without initialization, or
567
101
    // incoming phi nodes that need to be initialized. Check if the first is the
568
101
    // case for Inst and do not create and initialize memory if so.
569
32
    
if (auto *32
PHI32
= dyn_cast_or_null<PHINode>(Inst))
570
21
      
if (21
!S.hasSingleExitEdge() && 21
PHI->getBasicBlockIndex(ExitBB) >= 020
)
571
20
        continue;
572
32
573
12
    Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
574
12
  }
575
253
}
576
577
253
void BlockGenerator::createScalarFinalization(Scop &S) {
578
253
  // The exit block of the __unoptimized__ region.
579
253
  BasicBlock *ExitBB = S.getExitingBlock();
580
253
  // The merge block __just after__ the region and the optimized region.
581
253
  BasicBlock *MergeBB = S.getExit();
582
253
583
253
  // The exit block of the __optimized__ region.
584
253
  BasicBlock *OptExitBB = *(pred_begin(MergeBB));
585
253
  if (OptExitBB == ExitBB)
586
0
    OptExitBB = *(++pred_begin(MergeBB));
587
253
588
253
  Builder.SetInsertPoint(OptExitBB->getTerminator());
589
37
  for (const auto &EscapeMapping : EscapeMap) {
590
37
    // Extract the escaping instruction and the escaping users as well as the
591
37
    // alloca the instruction was demoted to.
592
37
    Instruction *EscapeInst = EscapeMapping.first;
593
37
    const auto &EscapeMappingValue = EscapeMapping.second;
594
37
    const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
595
37
    Value *ScalarAddr = EscapeMappingValue.first;
596
37
597
37
    // Reload the demoted instruction in the optimized version of the SCoP.
598
37
    Value *EscapeInstReload =
599
37
        Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
600
37
    EscapeInstReload =
601
37
        Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
602
37
603
37
    // Create the merge PHI that merges the optimized and unoptimized version.
604
37
    PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
605
37
                                        EscapeInst->getName() + ".merge");
606
37
    MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
607
37
608
37
    // Add the respective values to the merge PHI.
609
37
    MergePHI->addIncoming(EscapeInstReload, OptExitBB);
610
37
    MergePHI->addIncoming(EscapeInst, ExitBB);
611
37
612
37
    // The information of scalar evolution about the escaping instruction needs
613
37
    // to be revoked so the new merged instruction will be used.
614
37
    if (SE.isSCEVable(EscapeInst->getType()))
615
30
      SE.forgetValue(EscapeInst);
616
37
617
37
    // Replace all uses of the demoted instruction with the merge PHI.
618
37
    for (Instruction *EUser : EscapeUsers)
619
44
      EUser->replaceUsesOfWith(EscapeInst, MergePHI);
620
37
  }
621
253
}
622
623
253
void BlockGenerator::findOutsideUsers(Scop &S) {
624
524
  for (auto &Array : S.arrays()) {
625
524
626
524
    if (Array->getNumberOfDimensions() != 0)
627
390
      continue;
628
524
629
134
    
if (134
Array->isPHIKind()134
)
630
33
      continue;
631
134
632
101
    auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
633
101
634
101
    if (!Inst)
635
10
      continue;
636
101
637
101
    // Scop invariant hoisting moves some of the base pointers out of the scop.
638
101
    // We can ignore these, as the invariant load hoisting already registers the
639
101
    // relevant outside users.
640
91
    
if (91
!S.contains(Inst)91
)
641
22
      continue;
642
91
643
69
    handleOutsideUsers(S, Array);
644
69
  }
645
253
}
646
647
253
void BlockGenerator::createExitPHINodeMerges(Scop &S) {
648
253
  if (S.hasSingleExitEdge())
649
201
    return;
650
253
651
52
  auto *ExitBB = S.getExitingBlock();
652
52
  auto *MergeBB = S.getExit();
653
52
  auto *AfterMergeBB = MergeBB->getSingleSuccessor();
654
52
  BasicBlock *OptExitBB = *(pred_begin(MergeBB));
655
52
  if (OptExitBB == ExitBB)
656
0
    OptExitBB = *(++pred_begin(MergeBB));
657
52
658
52
  Builder.SetInsertPoint(OptExitBB->getTerminator());
659
52
660
116
  for (auto &SAI : S.arrays()) {
661
116
    auto *Val = SAI->getBasePtr();
662
116
663
116
    // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
664
116
    // the original PHI's value or the reloaded incoming values from the
665
116
    // generated code. An llvm::Value is merged between the original code's
666
116
    // value or the generated one.
667
116
    if (!SAI->isExitPHIKind())
668
97
      continue;
669
116
670
19
    PHINode *PHI = dyn_cast<PHINode>(Val);
671
19
    if (!PHI)
672
0
      continue;
673
19
674
19
    
if (19
PHI->getParent() != AfterMergeBB19
)
675
0
      continue;
676
19
677
19
    std::string Name = PHI->getName();
678
19
    Value *ScalarAddr = getOrCreateAlloca(SAI);
679
19
    Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
680
19
    Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
681
19
    Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
682
19
    assert((!isa<Instruction>(OriginalValue) ||
683
19
            cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
684
19
           "Original value must no be one we just generated.");
685
19
    auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
686
19
    MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
687
19
    MergePHI->addIncoming(Reload, OptExitBB);
688
19
    MergePHI->addIncoming(OriginalValue, ExitBB);
689
19
    int Idx = PHI->getBasicBlockIndex(MergeBB);
690
19
    PHI->setIncomingValue(Idx, MergePHI);
691
19
  }
692
52
}
693
694
253
void BlockGenerator::invalidateScalarEvolution(Scop &S) {
695
253
  for (auto &Stmt : S)
696
344
    
if (344
Stmt.isCopyStmt()344
)
697
2
      continue;
698
342
    else 
if (342
Stmt.isBlockStmt()342
)
699
314
      for (auto &Inst : *Stmt.getBasicBlock())
700
1.75k
        SE.forgetValue(&Inst);
701
28
    else 
if (28
Stmt.isRegionStmt()28
)
702
28
      for (auto *BB : Stmt.getRegion()->blocks())
703
84
        for (auto &Inst : *BB)
704
252
          SE.forgetValue(&Inst);
705
28
    else
706
0
      llvm_unreachable("Unexpected statement type found");
707
253
}
708
709
253
void BlockGenerator::finalizeSCoP(Scop &S) {
710
253
  findOutsideUsers(S);
711
253
  createScalarInitialization(S);
712
253
  createExitPHINodeMerges(S);
713
253
  createScalarFinalization(S);
714
253
  invalidateScalarEvolution(S);
715
253
}
716
717
VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
718
                                           std::vector<LoopToScevMapT> &VLTS,
719
                                           isl_map *Schedule)
720
20
    : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
721
20
  assert(Schedule && "No statement domain provided");
722
20
}
723
724
Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
725
                                            ValueMapT &VectorMap,
726
                                            VectorValueMapT &ScalarMaps,
727
32
                                            Loop *L) {
728
32
  if (Value *NewValue = VectorMap.lookup(Old))
729
29
    return NewValue;
730
32
731
3
  int Width = getVectorWidth();
732
3
733
3
  Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
734
3
735
15
  for (int Lane = 0; 
Lane < Width15
;
Lane++12
)
736
12
    Vector = Builder.CreateInsertElement(
737
12
        Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
738
12
        Builder.getInt32(Lane));
739
3
740
3
  VectorMap[Old] = Vector;
741
3
742
3
  return Vector;
743
32
}
744
745
27
Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
746
27
  PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
747
27
  assert(PointerTy && "PointerType expected");
748
27
749
27
  Type *ScalarType = PointerTy->getElementType();
750
27
  VectorType *VectorType = VectorType::get(ScalarType, Width);
751
27
752
27
  return PointerType::getUnqual(VectorType);
753
27
}
754
755
Value *VectorBlockGenerator::generateStrideOneLoad(
756
    ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
757
8
    __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
758
8
  unsigned VectorWidth = getVectorWidth();
759
8
  auto *Pointer = Load->getPointerOperand();
760
8
  Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
761
7
  unsigned Offset = NegativeStride ? 
VectorWidth - 11
:
07
;
762
8
763
8
  Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
764
8
                                               VLTS[Offset], NewAccesses);
765
8
  Value *VectorPtr =
766
8
      Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
767
8
  LoadInst *VecLoad =
768
8
      Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
769
8
  if (!Aligned)
770
8
    VecLoad->setAlignment(8);
771
8
772
8
  if (
NegativeStride8
)
{1
773
1
    SmallVector<Constant *, 16> Indices;
774
5
    for (int i = VectorWidth - 1; 
i >= 05
;
i--4
)
775
4
      Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
776
1
    Constant *SV = llvm::ConstantVector::get(Indices);
777
1
    Value *RevVecLoad = Builder.CreateShuffleVector(
778
1
        VecLoad, VecLoad, SV, Load->getName() + "_reverse");
779
1
    return RevVecLoad;
780
1
  }
781
8
782
7
  return VecLoad;
783
8
}
784
785
Value *VectorBlockGenerator::generateStrideZeroLoad(
786
    ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
787
3
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
788
3
  auto *Pointer = Load->getPointerOperand();
789
3
  Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
790
3
  Value *NewPointer =
791
3
      generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
792
3
  Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
793
3
                                           Load->getName() + "_p_vec_p");
794
3
  LoadInst *ScalarLoad =
795
3
      Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
796
3
797
3
  if (!Aligned)
798
3
    ScalarLoad->setAlignment(8);
799
3
800
3
  Constant *SplatVector = Constant::getNullValue(
801
3
      VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
802
3
803
3
  Value *VectorLoad = Builder.CreateShuffleVector(
804
3
      ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
805
3
  return VectorLoad;
806
3
}
807
808
Value *VectorBlockGenerator::generateUnknownStrideLoad(
809
    ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
810
3
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
811
3
  int VectorWidth = getVectorWidth();
812
3
  auto *Pointer = Load->getPointerOperand();
813
3
  VectorType *VectorType = VectorType::get(
814
3
      dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
815
3
816
3
  Value *Vector = UndefValue::get(VectorType);
817
3
818
23
  for (int i = 0; 
i < VectorWidth23
;
i++20
)
{20
819
20
    Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
820
20
                                                 VLTS[i], NewAccesses);
821
20
    Value *ScalarLoad =
822
20
        Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
823
20
    Vector = Builder.CreateInsertElement(
824
20
        Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
825
20
  }
826
3
827
3
  return Vector;
828
3
}
829
830
void VectorBlockGenerator::generateLoad(
831
    ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
832
20
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
833
20
  if (Value *
PreloadLoad20
= GlobalMap.lookup(Load))
{6
834
6
    VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
835
6
                                                Load->getName() + "_p");
836
6
    return;
837
6
  }
838
20
839
14
  
if (14
!VectorType::isValidElementType(Load->getType())14
)
{0
840
0
    for (int i = 0; 
i < getVectorWidth()0
;
i++0
)
841
0
      ScalarMaps[i][Load] =
842
0
          generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
843
0
    return;
844
0
  }
845
14
846
14
  const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
847
14
848
14
  // Make sure we have scalar values available to access the pointer to
849
14
  // the data location.
850
14
  extractScalarValues(Load, VectorMap, ScalarMaps);
851
14
852
14
  Value *NewLoad;
853
14
  if (Access.isStrideZero(isl_map_copy(Schedule)))
854
3
    NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
855
11
  else 
if (11
Access.isStrideOne(isl_map_copy(Schedule))11
)
856
7
    NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
857
4
  else 
if (4
Access.isStrideX(isl_map_copy(Schedule), -1)4
)
858
1
    NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
859
4
  else
860
3
    NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
861
14
862
14
  VectorMap[Load] = NewLoad;
863
14
}
864
865
void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
866
                                         ValueMapT &VectorMap,
867
1
                                         VectorValueMapT &ScalarMaps) {
868
1
  int VectorWidth = getVectorWidth();
869
1
  Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
870
1
                                     ScalarMaps, getLoopForStmt(Stmt));
871
1
872
1
  assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
873
1
874
1
  const CastInst *Cast = dyn_cast<CastInst>(Inst);
875
1
  VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
876
1
  VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
877
1
}
878
879
void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
880
                                          ValueMapT &VectorMap,
881
7
                                          VectorValueMapT &ScalarMaps) {
882
7
  Loop *L = getLoopForStmt(Stmt);
883
7
  Value *OpZero = Inst->getOperand(0);
884
7
  Value *OpOne = Inst->getOperand(1);
885
7
886
7
  Value *NewOpZero, *NewOpOne;
887
7
  NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
888
7
  NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
889
7
890
7
  Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
891
7
                                       Inst->getName() + "p_vec");
892
7
  VectorMap[Inst] = NewInst;
893
7
}
894
895
void VectorBlockGenerator::copyStore(
896
    ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
897
17
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
898
17
  const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
899
17
900
17
  auto *Pointer = Store->getPointerOperand();
901
17
  Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
902
17
                                 ScalarMaps, getLoopForStmt(Stmt));
903
17
904
17
  // Make sure we have scalar values available to access the pointer to
905
17
  // the data location.
906
17
  extractScalarValues(Store, VectorMap, ScalarMaps);
907
17
908
17
  if (
Access.isStrideOne(isl_map_copy(Schedule))17
)
{15
909
15
    Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
910
15
    Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
911
15
                                                 VLTS[0], NewAccesses);
912
15
913
15
    Value *VectorPtr =
914
15
        Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
915
15
    StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
916
15
917
15
    if (!Aligned)
918
15
      Store->setAlignment(8);
919
2
  } else {
920
10
    for (unsigned i = 0; 
i < ScalarMaps.size()10
;
i++8
)
{8
921
8
      Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
922
8
      Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
923
8
                                                   VLTS[i], NewAccesses);
924
8
      Builder.CreateStore(Scalar, NewPointer);
925
8
    }
926
2
  }
927
17
}
928
929
bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
930
40
                                             ValueMapT &VectorMap) {
931
40
  for (Value *Operand : Inst->operands())
932
51
    
if (51
VectorMap.count(Operand)51
)
933
28
      return true;
934
12
  return false;
935
40
}
936
937
bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
938
                                               ValueMapT &VectorMap,
939
46
                                               VectorValueMapT &ScalarMaps) {
940
46
  bool HasVectorOperand = false;
941
46
  int VectorWidth = getVectorWidth();
942
46
943
77
  for (Value *Operand : Inst->operands()) {
944
77
    ValueMapT::iterator VecOp = VectorMap.find(Operand);
945
77
946
77
    if (VecOp == VectorMap.end())
947
57
      continue;
948
77
949
20
    HasVectorOperand = true;
950
20
    Value *NewVector = VecOp->second;
951
20
952
115
    for (int i = 0; 
i < VectorWidth115
;
++i95
)
{98
953
98
      ValueMapT &SM = ScalarMaps[i];
954
98
955
98
      // If there is one scalar extracted, all scalar elements should have
956
98
      // already been extracted by the code here. So no need to check for the
957
98
      // existence of all of them.
958
98
      if (SM.count(Operand))
959
3
        break;
960
98
961
95
      SM[Operand] =
962
95
          Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
963
95
    }
964
20
  }
965
46
966
46
  return HasVectorOperand;
967
46
}
968
969
void VectorBlockGenerator::copyInstScalarized(
970
    ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
971
15
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
972
15
  bool HasVectorOperand;
973
15
  int VectorWidth = getVectorWidth();
974
15
975
15
  HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
976
15
977
91
  for (int VectorLane = 0; 
VectorLane < getVectorWidth()91
;
VectorLane++76
)
978
76
    BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
979
76
                                    VLTS[VectorLane], NewAccesses);
980
15
981
15
  if (
!VectorType::isValidElementType(Inst->getType()) || 15
!HasVectorOperand12
)
982
12
    return;
983
15
984
15
  // Make the result available as vector value.
985
3
  VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
986
3
  Value *Vector = UndefValue::get(VectorType);
987
3
988
15
  for (int i = 0; 
i < VectorWidth15
;
i++12
)
989
12
    Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
990
12
                                         Builder.getInt32(i));
991
3
992
3
  VectorMap[Inst] = Vector;
993
3
}
994
995
212
int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
996
997
void VectorBlockGenerator::copyInstruction(
998
    ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
999
122
    VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1000
122
  // Terminator instructions control the control flow. They are explicitly
1001
122
  // expressed in the clast and do not need to be copied.
1002
122
  if (Inst->isTerminator())
1003
20
    return;
1004
122
1005
102
  
if (102
canSyntheziseInStmt(Stmt, Inst)102
)
1006
42
    return;
1007
102
1008
60
  
if (auto *60
Load60
= dyn_cast<LoadInst>(Inst))
{20
1009
20
    generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
1010
20
    return;
1011
20
  }
1012
60
1013
40
  
if (40
hasVectorOperands(Inst, VectorMap)40
)
{28
1014
28
    if (auto *
Store28
= dyn_cast<StoreInst>(Inst))
{17
1015
17
      // Identified as redundant by -polly-simplify.
1016
17
      if (!Stmt.getArrayAccessOrNULLFor(Store))
1017
0
        return;
1018
17
1019
17
      copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
1020
17
      return;
1021
17
    }
1022
28
1023
11
    
if (auto *11
Unary11
= dyn_cast<UnaryInstruction>(Inst))
{1
1024
1
      copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
1025
1
      return;
1026
1
    }
1027
11
1028
10
    
if (auto *10
Binary10
= dyn_cast<BinaryOperator>(Inst))
{7
1029
7
      copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
1030
7
      return;
1031
7
    }
1032
10
1033
10
    // Falltrough: We generate scalar instructions, if we don't know how to
1034
10
    // generate vector code.
1035
10
  }
1036
40
1037
15
  copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
1038
15
}
1039
1040
void VectorBlockGenerator::generateScalarVectorLoads(
1041
20
    ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1042
35
  for (MemoryAccess *MA : Stmt) {
1043
35
    if (
MA->isArrayKind() || 35
MA->isWrite()1
)
1044
34
      continue;
1045
35
1046
1
    auto *Address = getOrCreateAlloca(*MA);
1047
1
    Type *VectorPtrType = getVectorPtrTy(Address, 1);
1048
1
    Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1049
1
                                             Address->getName() + "_p_vec_p");
1050
1
    auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1051
1
    Constant *SplatVector = Constant::getNullValue(
1052
1
        VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1053
1
1054
1
    Value *VectorVal = Builder.CreateShuffleVector(
1055
1
        Val, Val, SplatVector, Address->getName() + "_p_splat");
1056
1
    VectorBlockMap[MA->getAccessValue()] = VectorVal;
1057
1
  }
1058
20
}
1059
1060
20
void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1061
35
  for (MemoryAccess *MA : Stmt) {
1062
35
    if (
MA->isArrayKind() || 35
MA->isRead()1
)
1063
35
      continue;
1064
35
1065
0
    
llvm_unreachable0
("Scalar stores not expected in vector loop");0
1066
0
  }
1067
20
}
1068
1069
void VectorBlockGenerator::copyStmt(
1070
20
    ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1071
20
  assert(Stmt.isBlockStmt() &&
1072
20
         "TODO: Only block statements can be copied by the vector block "
1073
20
         "generator");
1074
20
1075
20
  BasicBlock *BB = Stmt.getBasicBlock();
1076
20
  BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1077
20
                                  &*Builder.GetInsertPoint(), &DT, &LI);
1078
20
  CopyBB->setName("polly.stmt." + BB->getName());
1079
20
  Builder.SetInsertPoint(&CopyBB->front());
1080
20
1081
20
  // Create two maps that store the mapping from the original instructions of
1082
20
  // the old basic block to their copies in the new basic block. Those maps
1083
20
  // are basic block local.
1084
20
  //
1085
20
  // As vector code generation is supported there is one map for scalar values
1086
20
  // and one for vector values.
1087
20
  //
1088
20
  // In case we just do scalar code generation, the vectorMap is not used and
1089
20
  // the scalarMap has just one dimension, which contains the mapping.
1090
20
  //
1091
20
  // In case vector code generation is done, an instruction may either appear
1092
20
  // in the vector map once (as it is calculating >vectorwidth< values at a
1093
20
  // time. Or (if the values are calculated using scalar operations), it
1094
20
  // appears once in every dimension of the scalarMap.
1095
20
  VectorValueMapT ScalarBlockMap(getVectorWidth());
1096
20
  ValueMapT VectorBlockMap;
1097
20
1098
20
  generateScalarVectorLoads(Stmt, VectorBlockMap);
1099
20
1100
20
  for (Instruction &Inst : *BB)
1101
122
    copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
1102
20
1103
20
  verifyNoScalarStores(Stmt);
1104
20
}
1105
1106
BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1107
87
                                             BasicBlock *BBCopy) {
1108
87
1109
87
  BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1110
87
  BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom);
1111
87
1112
87
  if (BBCopyIDom)
1113
86
    DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1114
87
1115
87
  return BBCopyIDom;
1116
87
}
1117
1118
// This is to determine whether an llvm::Value (defined in @p BB) is usable when
1119
// leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1120
// does not work in cases where the exit block has edges from outside the
1121
// region. In that case the llvm::Value would never be usable in in the exit
1122
// block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1123
// for the subregion's exiting edges only. We need to determine whether an
1124
// llvm::Value is usable in there. We do this by checking whether it dominates
1125
// all exiting blocks individually.
1126
static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1127
87
                                      BasicBlock *BB) {
1128
165
  for (auto ExitingBB : predecessors(R->getExit())) {
1129
165
    // Check for non-subregion incoming edges.
1130
165
    if (!R->contains(ExitingBB))
1131
29
      continue;
1132
165
1133
136
    
if (136
!DT.dominates(BB, ExitingBB)136
)
1134
50
      return false;
1135
136
  }
1136
87
1137
37
  return true;
1138
87
}
1139
1140
// Find the direct dominator of the subregion's exit block if the subregion was
1141
// simplified.
1142
29
static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1143
29
  BasicBlock *Common = nullptr;
1144
62
  for (auto ExitingBB : predecessors(R->getExit())) {
1145
62
    // Check for non-subregion incoming edges.
1146
62
    if (!R->contains(ExitingBB))
1147
10
      continue;
1148
62
1149
62
    // First exiting edge.
1150
52
    
if (52
!Common52
)
{29
1151
29
      Common = ExitingBB;
1152
29
      continue;
1153
29
    }
1154
52
1155
23
    Common = DT.findNearestCommonDominator(Common, ExitingBB);
1156
23
  }
1157
29
1158
29
  assert(Common && R->contains(Common));
1159
29
  return Common;
1160
29
}
1161
1162
void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
1163
29
                               isl_id_to_ast_expr *IdToAstExp) {
1164
29
  assert(Stmt.isRegionStmt() &&
1165
29
         "Only region statements can be copied by the region generator");
1166
29
1167
29
  // Forget all old mappings.
1168
29
  BlockMap.clear();
1169
29
  RegionMaps.clear();
1170
29
  IncompletePHINodeMap.clear();
1171
29
1172
29
  // Collection of all values related to this subregion.
1173
29
  ValueMapT ValueMap;
1174
29
1175
29
  // The region represented by the statement.
1176
29
  Region *R = Stmt.getRegion();
1177
29
1178
29
  // Create a dedicated entry for the region where we can reload all demoted
1179
29
  // inputs.
1180
29
  BasicBlock *EntryBB = R->getEntry();
1181
29
  BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1182
29
                                       &*Builder.GetInsertPoint(), &DT, &LI);
1183
29
  EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1184
29
  Builder.SetInsertPoint(&EntryBBCopy->front());
1185
29
1186
29
  ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1187
29
  generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1188
29
1189
71
  for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); 
PI != PE71
;
++PI42
)
1190
42
    
if (42
!R->contains(*PI)42
)
1191
41
      BlockMap[*PI] = EntryBBCopy;
1192
29
1193
29
  // Iterate over all blocks in the region in a breadth-first search.
1194
29
  std::deque<BasicBlock *> Blocks;
1195
29
  SmallSetVector<BasicBlock *, 8> SeenBlocks;
1196
29
  Blocks.push_back(EntryBB);
1197
29
  SeenBlocks.insert(EntryBB);
1198
29
1199
116
  while (
!Blocks.empty()116
)
{87
1200
87
    BasicBlock *BB = Blocks.front();
1201
87
    Blocks.pop_front();
1202
87
1203
87
    // First split the block and update dominance information.
1204
87
    BasicBlock *BBCopy = splitBB(BB);
1205
87
    BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1206
87
1207
87
    // Get the mapping for this block and initialize it with either the scalar
1208
87
    // loads from the generated entering block (which dominates all blocks of
1209
87
    // this subregion) or the maps of the immediate dominator, if part of the
1210
87
    // subregion. The latter necessarily includes the former.
1211
87
    ValueMapT *InitBBMap;
1212
87
    if (
BBCopyIDom87
)
{86
1213
86
      assert(RegionMaps.count(BBCopyIDom));
1214
86
      InitBBMap = &RegionMaps[BBCopyIDom];
1215
86
    } else
1216
1
      InitBBMap = &EntryBBMap;
1217
87
    auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1218
87
    ValueMapT &RegionMap = Inserted.first->second;
1219
87
1220
87
    // Copy the block with the BlockGenerator.
1221
87
    Builder.SetInsertPoint(&BBCopy->front());
1222
87
    copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1223
87
1224
87
    // In order to remap PHI nodes we store also basic block mappings.
1225
87
    BlockMap[BB] = BBCopy;
1226
87
1227
87
    // Add values to incomplete PHI nodes waiting for this block to be copied.
1228
87
    for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1229
2
      addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1230
87
    IncompletePHINodeMap[BB].clear();
1231
87
1232
87
    // And continue with new successors inside the region.
1233
210
    for (auto SI = succ_begin(BB), SE = succ_end(BB); 
SI != SE210
;
SI++123
)
1234
123
      
if (123
R->contains(*SI) && 123
SeenBlocks.insert(*SI)71
)
1235
58
        Blocks.push_back(*SI);
1236
87
1237
87
    // Remember value in case it is visible after this subregion.
1238
87
    if (isDominatingSubregionExit(DT, R, BB))
1239
37
      ValueMap.insert(RegionMap.begin(), RegionMap.end());
1240
87
  }
1241
29
1242
29
  // Now create a new dedicated region exit block and add it to the region map.
1243
29
  BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1244
29
                                      &*Builder.GetInsertPoint(), &DT, &LI);
1245
29
  ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1246
29
  BlockMap[R->getExit()] = ExitBBCopy;
1247
29
1248
29
  BasicBlock *ExitDomBBCopy = BlockMap.lookup(findExitDominator(DT, R));
1249
29
  assert(ExitDomBBCopy &&
1250
29
         "Common exit dominator must be within region; at least the entry node "
1251
29
         "must match");
1252
29
  DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1253
29
1254
29
  // As the block generator doesn't handle control flow we need to add the
1255
29
  // region control flow by hand after all blocks have been copied.
1256
87
  for (BasicBlock *BB : SeenBlocks) {
1257
87
1258
87
    BasicBlock *BBCopy = BlockMap[BB];
1259
87
    TerminatorInst *TI = BB->getTerminator();
1260
87
    if (
isa<UnreachableInst>(TI)87
)
{0
1261
0
      while (!BBCopy->empty())
1262
0
        BBCopy->begin()->eraseFromParent();
1263
0
      new UnreachableInst(BBCopy->getContext(), BBCopy);
1264
0
      continue;
1265
0
    }
1266
87
1267
87
    Instruction *BICopy = BBCopy->getTerminator();
1268
87
1269
87
    ValueMapT &RegionMap = RegionMaps[BBCopy];
1270
87
    RegionMap.insert(BlockMap.begin(), BlockMap.end());
1271
87
1272
87
    Builder.SetInsertPoint(BICopy);
1273
87
    copyInstScalar(Stmt, TI, RegionMap, LTS);
1274
87
    BICopy->eraseFromParent();
1275
87
  }
1276
29
1277
29
  // Add counting PHI nodes to all loops in the region that can be used as
1278
29
  // replacement for SCEVs refering to the old loop.
1279
87
  for (BasicBlock *BB : SeenBlocks) {
1280
87
    Loop *L = LI.getLoopFor(BB);
1281
87
    if (
L == nullptr || 87
L->getHeader() != BB60
||
!R->contains(L)9
)
1282
87
      continue;
1283
87
1284
0
    BasicBlock *BBCopy = BlockMap[BB];
1285
0
    Value *NullVal = Builder.getInt32(0);
1286
0
    PHINode *LoopPHI =
1287
0
        PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1288
0
    Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1289
0
        LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1290
0
    LoopPHI->insertBefore(&BBCopy->front());
1291
0
    LoopPHIInc->insertBefore(BBCopy->getTerminator());
1292
0
1293
0
    for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1294
0
      if (!R->contains(PredBB))
1295
0
        continue;
1296
0
      
if (0
L->contains(PredBB)0
)
1297
0
        LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]);
1298
0
      else
1299
0
        LoopPHI->addIncoming(NullVal, BlockMap[PredBB]);
1300
0
    }
1301
0
1302
0
    for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1303
0
      
if (0
LoopPHI->getBasicBlockIndex(PredBBCopy) < 00
)
1304
0
        LoopPHI->addIncoming(NullVal, PredBBCopy);
1305
0
1306
0
    LTS[L] = SE.getUnknown(LoopPHI);
1307
0
  }
1308
29
1309
29
  // Continue generating code in the exit block.
1310
29
  Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
1311
29
1312
29
  // Write values visible to other statements.
1313
29
  generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1314
29
  BlockMap.clear();
1315
29
  RegionMaps.clear();
1316
29
  IncompletePHINodeMap.clear();
1317
29
}
1318
1319
PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1320
11
                                       ValueMapT &BBMap, Loop *L) {
1321
11
  ScopStmt *Stmt = MA->getStatement();
1322
11
  Region *SubR = Stmt->getRegion();
1323
11
  auto Incoming = MA->getIncoming();
1324
11
1325
11
  PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1326
11
  PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1327
11
  BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1328
11
1329
11
  // This can happen if the subregion is simplified after the ScopStmts
1330
11
  // have been created; simplification happens as part of CodeGeneration.
1331
11
  if (
OrigPHI->getParent() != SubR->getExit()11
)
{5
1332
5
    BasicBlock *FormerExit = SubR->getExitingBlock();
1333
5
    if (FormerExit)
1334
3
      NewSubregionExit = BlockMap.lookup(FormerExit);
1335
5
  }
1336
11
1337
11
  PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1338
11
                                    "polly." + OrigPHI->getName(),
1339
11
                                    NewSubregionExit->getFirstNonPHI());
1340
11
1341
11
  // Add the incoming values to the PHI.
1342
24
  for (auto &Pair : Incoming) {
1343
24
    BasicBlock *OrigIncomingBlock = Pair.first;
1344
24
    BasicBlock *NewIncomingBlock = BlockMap.lookup(OrigIncomingBlock);
1345
24
    Builder.SetInsertPoint(NewIncomingBlock->getTerminator());
1346
24
    assert(RegionMaps.count(NewIncomingBlock));
1347
24
    ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlock];
1348
24
1349
24
    Value *OrigIncomingValue = Pair.second;
1350
24
    Value *NewIncomingValue =
1351
24
        getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1352
24
    NewPHI->addIncoming(NewIncomingValue, NewIncomingBlock);
1353
24
  }
1354
11
1355
11
  return NewPHI;
1356
11
}
1357
1358
Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1359
19
                                      ValueMapT &BBMap) {
1360
19
  ScopStmt *Stmt = MA->getStatement();
1361
19
1362
19
  // TODO: Add some test cases that ensure this is really the right choice.
1363
19
  Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1364
19
1365
19
  if (
MA->isAnyPHIKind()19
)
{11
1366
11
    auto Incoming = MA->getIncoming();
1367
11
    assert(!Incoming.empty() &&
1368
11
           "PHI WRITEs must have originate from at least one incoming block");
1369
11
1370
11
    // If there is only one incoming value, we do not need to create a PHI.
1371
11
    if (
Incoming.size() == 111
)
{0
1372
0
      Value *OldVal = Incoming[0].second;
1373
0
      return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1374
0
    }
1375
11
1376
11
    return buildExitPHI(MA, LTS, BBMap, L);
1377
11
  }
1378
19
1379
19
  // MemoryKind::Value accesses leaving the subregion must dominate the exit
1380
19
  // block; just pass the copied value.
1381
8
  Value *OldVal = MA->getAccessValue();
1382
8
  return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1383
19
}
1384
1385
void RegionGenerator::generateScalarStores(
1386
    ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1387
29
    __isl_keep isl_id_to_ast_expr *NewAccesses) {
1388
29
  assert(Stmt.getRegion() &&
1389
29
         "Block statements need to use the generateScalarStores() "
1390
29
         "function in the BlockGenerator");
1391
29
1392
84
  for (MemoryAccess *MA : Stmt) {
1393
84
    if (
MA->isOriginalArrayKind() || 84
MA->isRead()28
)
1394
65
      continue;
1395
84
1396
19
    Value *NewVal = getExitScalar(MA, LTS, BBMap);
1397
19
    Value *Address =
1398
19
        getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
1399
19
    assert((!isa<Instruction>(NewVal) ||
1400
19
            DT.dominates(cast<Instruction>(NewVal)->getParent(),
1401
19
                         Builder.GetInsertBlock())) &&
1402
19
           "Domination violation");
1403
19
    assert((!isa<Instruction>(Address) ||
1404
19
            DT.dominates(cast<Instruction>(Address)->getParent(),
1405
19
                         Builder.GetInsertBlock())) &&
1406
19
           "Domination violation");
1407
19
    Builder.CreateStore(NewVal, Address);
1408
19
  }
1409
29
}
1410
1411
void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI,
1412
                                      PHINode *PHICopy, BasicBlock *IncomingBB,
1413
14
                                      LoopToScevMapT &LTS) {
1414
14
  // If the incoming block was not yet copied mark this PHI as incomplete.
1415
14
  // Once the block will be copied the incoming value will be added.
1416
14
  BasicBlock *BBCopy = BlockMap[IncomingBB];
1417
14
  if (
!BBCopy14
)
{2
1418
2
    assert(Stmt.contains(IncomingBB) &&
1419
2
           "Bad incoming block for PHI in non-affine region");
1420
2
    IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1421
2
    return;
1422
2
  }
1423
14
1424
12
  assert(RegionMaps.count(BBCopy) && "Incoming PHI block did not have a BBMap");
1425
12
  ValueMapT &BBCopyMap = RegionMaps[BBCopy];
1426
12
1427
12
  Value *OpCopy = nullptr;
1428
12
1429
12
  if (
Stmt.contains(IncomingBB)12
)
{5
1430
5
    Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1431
5
1432
5
    // If the current insert block is different from the PHIs incoming block
1433
5
    // change it, otherwise do not.
1434
5
    auto IP = Builder.GetInsertPoint();
1435
5
    if (IP->getParent() != BBCopy)
1436
3
      Builder.SetInsertPoint(BBCopy->getTerminator());
1437
5
    OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1438
5
    if (IP->getParent() != BBCopy)
1439
3
      Builder.SetInsertPoint(&*IP);
1440
7
  } else {
1441
7
    // All edges from outside the non-affine region become a single edge
1442
7
    // in the new copy of the non-affine region. Make sure to only add the
1443
7
    // corresponding edge the first time we encounter a basic block from
1444
7
    // outside the non-affine region.
1445
7
    if (PHICopy->getBasicBlockIndex(BBCopy) >= 0)
1446
2
      return;
1447
7
1448
7
    // Get the reloaded value.
1449
5
    OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
1450
5
  }
1451
12
1452
10
  assert(OpCopy && "Incoming PHI value was not copied properly");
1453
10
  assert(BBCopy && "Incoming PHI block was not copied properly");
1454
10
  PHICopy->addIncoming(OpCopy, BBCopy);
1455
10
}
1456
1457
void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1458
                                         ValueMapT &BBMap,
1459
7
                                         LoopToScevMapT &LTS) {
1460
7
  unsigned NumIncoming = PHI->getNumIncomingValues();
1461
7
  PHINode *PHICopy =
1462
7
      Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1463
7
  PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1464
7
  BBMap[PHI] = PHICopy;
1465
7
1466
7
  for (BasicBlock *IncomingBB : PHI->blocks())
1467
12
    addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
1468
7
}