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