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