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