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   if (Stmt.isBlockStmt())
454     for (Instruction *Inst : Stmt.getInstructions())
455       copyInstruction(Stmt, Inst, BBMap, LTS, NewAccesses);
456   else
457     for (Instruction &Inst : *BB)
458       copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses);
459 }
460 
461 Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) {
462   assert(!Access.isLatestArrayKind() && "Trying to get alloca for array kind");
463 
464   return getOrCreateAlloca(Access.getLatestScopArrayInfo());
465 }
466 
467 Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) {
468   assert(!Array->isArrayKind() && "Trying to get alloca for array kind");
469 
470   auto &Addr = ScalarMap[Array];
471 
472   if (Addr) {
473     // Allow allocas to be (temporarily) redirected once by adding a new
474     // old-alloca-addr to new-addr mapping to GlobalMap. This functionality
475     // is used for example by the OpenMP code generation where a first use
476     // of a scalar while still in the host code allocates a normal alloca with
477     // getOrCreateAlloca. When the values of this scalar are accessed during
478     // the generation of the parallel subfunction, these values are copied over
479     // to the parallel subfunction and each request for a scalar alloca slot
480     // must be forwarded to the temporary in-subfunction slot. This mapping is
481     // removed when the subfunction has been generated and again normal host
482     // code is generated. Due to the following reasons it is not possible to
483     // perform the GlobalMap lookup right after creating the alloca below, but
484     // instead we need to check GlobalMap at each call to getOrCreateAlloca:
485     //
486     //   1) GlobalMap may be changed multiple times (for each parallel loop),
487     //   2) The temporary mapping is commonly only known after the initial
488     //      alloca has already been generated, and
489     //   3) The original alloca value must be restored after leaving the
490     //      sub-function.
491     if (Value *NewAddr = GlobalMap.lookup(&*Addr))
492       return NewAddr;
493     return Addr;
494   }
495 
496   Type *Ty = Array->getElementType();
497   Value *ScalarBase = Array->getBasePtr();
498   std::string NameExt;
499   if (Array->isPHIKind())
500     NameExt = ".phiops";
501   else
502     NameExt = ".s2a";
503 
504   const DataLayout &DL = Builder.GetInsertBlock()->getModule()->getDataLayout();
505 
506   Addr = new AllocaInst(Ty, DL.getAllocaAddrSpace(),
507                         ScalarBase->getName() + NameExt);
508   EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock();
509   Addr->insertBefore(&*EntryBB->getFirstInsertionPt());
510 
511   return Addr;
512 }
513 
514 void BlockGenerator::handleOutsideUsers(const Scop &S, ScopArrayInfo *Array) {
515   Instruction *Inst = cast<Instruction>(Array->getBasePtr());
516 
517   // If there are escape users we get the alloca for this instruction and put it
518   // in the EscapeMap for later finalization. Lastly, if the instruction was
519   // copied multiple times we already did this and can exit.
520   if (EscapeMap.count(Inst))
521     return;
522 
523   EscapeUserVectorTy EscapeUsers;
524   for (User *U : Inst->users()) {
525 
526     // Non-instruction user will never escape.
527     Instruction *UI = dyn_cast<Instruction>(U);
528     if (!UI)
529       continue;
530 
531     if (S.contains(UI))
532       continue;
533 
534     EscapeUsers.push_back(UI);
535   }
536 
537   // Exit if no escape uses were found.
538   if (EscapeUsers.empty())
539     return;
540 
541   // Get or create an escape alloca for this instruction.
542   auto *ScalarAddr = getOrCreateAlloca(Array);
543 
544   // Remember that this instruction has escape uses and the escape alloca.
545   EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers));
546 }
547 
548 void BlockGenerator::generateScalarLoads(
549     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
550     __isl_keep isl_id_to_ast_expr *NewAccesses) {
551   for (MemoryAccess *MA : Stmt) {
552     if (MA->isOriginalArrayKind() || MA->isWrite())
553       continue;
554 
555 #ifndef NDEBUG
556     auto *StmtDom = Stmt.getDomain().release();
557     auto *AccDom = isl_map_domain(MA->getAccessRelation().release());
558     assert(isl_set_is_subset(StmtDom, AccDom) &&
559            "Scalar must be loaded in all statement instances");
560     isl_set_free(StmtDom);
561     isl_set_free(AccDom);
562 #endif
563 
564     auto *Address =
565         getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses);
566     assert((!isa<Instruction>(Address) ||
567             DT.dominates(cast<Instruction>(Address)->getParent(),
568                          Builder.GetInsertBlock())) &&
569            "Domination violation");
570     BBMap[MA->getAccessValue()] =
571         Builder.CreateLoad(Address, Address->getName() + ".reload");
572   }
573 }
574 
575 Value *BlockGenerator::buildContainsCondition(ScopStmt &Stmt,
576                                               const isl::set &Subdomain) {
577   isl::ast_build AstBuild = Stmt.getAstBuild();
578   isl::set Domain = Stmt.getDomain();
579 
580   isl::union_map USchedule = AstBuild.get_schedule();
581   USchedule = USchedule.intersect_domain(Domain);
582 
583   assert(!USchedule.is_empty());
584   isl::map Schedule = isl::map::from_union_map(USchedule);
585 
586   isl::set ScheduledDomain = Schedule.range();
587   isl::set ScheduledSet = Subdomain.apply(Schedule);
588 
589   isl::ast_build RestrictedBuild = AstBuild.restrict(ScheduledDomain);
590 
591   isl::ast_expr IsInSet = RestrictedBuild.expr_from(ScheduledSet);
592   Value *IsInSetExpr = ExprBuilder->create(IsInSet.copy());
593   IsInSetExpr = Builder.CreateICmpNE(
594       IsInSetExpr, ConstantInt::get(IsInSetExpr->getType(), 0));
595 
596   return IsInSetExpr;
597 }
598 
599 void BlockGenerator::generateConditionalExecution(
600     ScopStmt &Stmt, const isl::set &Subdomain, StringRef Subject,
601     const std::function<void()> &GenThenFunc) {
602   isl::set StmtDom = Stmt.getDomain();
603 
604   // Don't call GenThenFunc if it is never executed. An ast index expression
605   // might not be defined in this case.
606   if (Subdomain.is_empty())
607     return;
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   BasicBlock *HeadBlock = Builder.GetInsertBlock();
622   StringRef BlockName = HeadBlock->getName();
623 
624   // Generate the conditional block.
625   SplitBlockAndInsertIfThen(Cond, &*Builder.GetInsertPoint(), false, nullptr,
626                             &DT, &LI);
627   BranchInst *Branch = cast<BranchInst>(HeadBlock->getTerminator());
628   BasicBlock *ThenBlock = Branch->getSuccessor(0);
629   BasicBlock *TailBlock = Branch->getSuccessor(1);
630 
631   // Assign descriptive names.
632   if (auto *CondInst = dyn_cast<Instruction>(Cond))
633     CondInst->setName("polly." + Subject + ".cond");
634   ThenBlock->setName(BlockName + "." + Subject + ".partial");
635   TailBlock->setName(BlockName + ".cont");
636 
637   // Put the client code into the conditional block and continue in the merge
638   // block afterwards.
639   Builder.SetInsertPoint(ThenBlock, ThenBlock->getFirstInsertionPt());
640   GenThenFunc();
641   Builder.SetInsertPoint(TailBlock, TailBlock->getFirstInsertionPt());
642 }
643 
644 void BlockGenerator::generateScalarStores(
645     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
646     __isl_keep isl_id_to_ast_expr *NewAccesses) {
647   Loop *L = LI.getLoopFor(Stmt.getBasicBlock());
648 
649   assert(Stmt.isBlockStmt() &&
650          "Region statements need to use the generateScalarStores() function in "
651          "the RegionGenerator");
652 
653   for (MemoryAccess *MA : Stmt) {
654     if (MA->isOriginalArrayKind() || MA->isRead())
655       continue;
656 
657     isl::set AccDom = MA->getAccessRelation().domain();
658     std::string Subject = MA->getId().get_name();
659 
660     generateConditionalExecution(
661         Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
662           Value *Val = MA->getAccessValue();
663           if (MA->isAnyPHIKind()) {
664             assert(MA->getIncoming().size() >= 1 &&
665                    "Block statements have exactly one exiting block, or "
666                    "multiple but "
667                    "with same incoming block and value");
668             assert(std::all_of(MA->getIncoming().begin(),
669                                MA->getIncoming().end(),
670                                [&](std::pair<BasicBlock *, Value *> p) -> bool {
671                                  return p.first == Stmt.getBasicBlock();
672                                }) &&
673                    "Incoming block must be statement's block");
674             Val = MA->getIncoming()[0].second;
675           }
676           auto Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
677                                             BBMap, NewAccesses);
678 
679           Val = getNewValue(Stmt, Val, BBMap, LTS, L);
680           assert((!isa<Instruction>(Val) ||
681                   DT.dominates(cast<Instruction>(Val)->getParent(),
682                                Builder.GetInsertBlock())) &&
683                  "Domination violation");
684           assert((!isa<Instruction>(Address) ||
685                   DT.dominates(cast<Instruction>(Address)->getParent(),
686                                Builder.GetInsertBlock())) &&
687                  "Domination violation");
688           Builder.CreateStore(Val, Address);
689 
690         });
691   }
692 }
693 
694 void BlockGenerator::createScalarInitialization(Scop &S) {
695   BasicBlock *ExitBB = S.getExit();
696   BasicBlock *PreEntryBB = S.getEnteringBlock();
697 
698   Builder.SetInsertPoint(&*StartBlock->begin());
699 
700   for (auto &Array : S.arrays()) {
701     if (Array->getNumberOfDimensions() != 0)
702       continue;
703     if (Array->isPHIKind()) {
704       // For PHI nodes, the only values we need to store are the ones that
705       // reach the PHI node from outside the region. In general there should
706       // only be one such incoming edge and this edge should enter through
707       // 'PreEntryBB'.
708       auto PHI = cast<PHINode>(Array->getBasePtr());
709 
710       for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++)
711         if (!S.contains(*BI) && *BI != PreEntryBB)
712           llvm_unreachable("Incoming edges from outside the scop should always "
713                            "come from PreEntryBB");
714 
715       int Idx = PHI->getBasicBlockIndex(PreEntryBB);
716       if (Idx < 0)
717         continue;
718 
719       Value *ScalarValue = PHI->getIncomingValue(Idx);
720 
721       Builder.CreateStore(ScalarValue, getOrCreateAlloca(Array));
722       continue;
723     }
724 
725     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
726 
727     if (Inst && S.contains(Inst))
728       continue;
729 
730     // PHI nodes that are not marked as such in their SAI object are either exit
731     // PHI nodes we model as common scalars but without initialization, or
732     // incoming phi nodes that need to be initialized. Check if the first is the
733     // case for Inst and do not create and initialize memory if so.
734     if (auto *PHI = dyn_cast_or_null<PHINode>(Inst))
735       if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0)
736         continue;
737 
738     Builder.CreateStore(Array->getBasePtr(), getOrCreateAlloca(Array));
739   }
740 }
741 
742 void BlockGenerator::createScalarFinalization(Scop &S) {
743   // The exit block of the __unoptimized__ region.
744   BasicBlock *ExitBB = S.getExitingBlock();
745   // The merge block __just after__ the region and the optimized region.
746   BasicBlock *MergeBB = S.getExit();
747 
748   // The exit block of the __optimized__ region.
749   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
750   if (OptExitBB == ExitBB)
751     OptExitBB = *(++pred_begin(MergeBB));
752 
753   Builder.SetInsertPoint(OptExitBB->getTerminator());
754   for (const auto &EscapeMapping : EscapeMap) {
755     // Extract the escaping instruction and the escaping users as well as the
756     // alloca the instruction was demoted to.
757     Instruction *EscapeInst = EscapeMapping.first;
758     const auto &EscapeMappingValue = EscapeMapping.second;
759     const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second;
760     Value *ScalarAddr = EscapeMappingValue.first;
761 
762     // Reload the demoted instruction in the optimized version of the SCoP.
763     Value *EscapeInstReload =
764         Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload");
765     EscapeInstReload =
766         Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType());
767 
768     // Create the merge PHI that merges the optimized and unoptimized version.
769     PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2,
770                                         EscapeInst->getName() + ".merge");
771     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
772 
773     // Add the respective values to the merge PHI.
774     MergePHI->addIncoming(EscapeInstReload, OptExitBB);
775     MergePHI->addIncoming(EscapeInst, ExitBB);
776 
777     // The information of scalar evolution about the escaping instruction needs
778     // to be revoked so the new merged instruction will be used.
779     if (SE.isSCEVable(EscapeInst->getType()))
780       SE.forgetValue(EscapeInst);
781 
782     // Replace all uses of the demoted instruction with the merge PHI.
783     for (Instruction *EUser : EscapeUsers)
784       EUser->replaceUsesOfWith(EscapeInst, MergePHI);
785   }
786 }
787 
788 void BlockGenerator::findOutsideUsers(Scop &S) {
789   for (auto &Array : S.arrays()) {
790 
791     if (Array->getNumberOfDimensions() != 0)
792       continue;
793 
794     if (Array->isPHIKind())
795       continue;
796 
797     auto *Inst = dyn_cast<Instruction>(Array->getBasePtr());
798 
799     if (!Inst)
800       continue;
801 
802     // Scop invariant hoisting moves some of the base pointers out of the scop.
803     // We can ignore these, as the invariant load hoisting already registers the
804     // relevant outside users.
805     if (!S.contains(Inst))
806       continue;
807 
808     handleOutsideUsers(S, Array);
809   }
810 }
811 
812 void BlockGenerator::createExitPHINodeMerges(Scop &S) {
813   if (S.hasSingleExitEdge())
814     return;
815 
816   auto *ExitBB = S.getExitingBlock();
817   auto *MergeBB = S.getExit();
818   auto *AfterMergeBB = MergeBB->getSingleSuccessor();
819   BasicBlock *OptExitBB = *(pred_begin(MergeBB));
820   if (OptExitBB == ExitBB)
821     OptExitBB = *(++pred_begin(MergeBB));
822 
823   Builder.SetInsertPoint(OptExitBB->getTerminator());
824 
825   for (auto &SAI : S.arrays()) {
826     auto *Val = SAI->getBasePtr();
827 
828     // Only Value-like scalars need a merge PHI. Exit block PHIs receive either
829     // the original PHI's value or the reloaded incoming values from the
830     // generated code. An llvm::Value is merged between the original code's
831     // value or the generated one.
832     if (!SAI->isExitPHIKind())
833       continue;
834 
835     PHINode *PHI = dyn_cast<PHINode>(Val);
836     if (!PHI)
837       continue;
838 
839     if (PHI->getParent() != AfterMergeBB)
840       continue;
841 
842     std::string Name = PHI->getName();
843     Value *ScalarAddr = getOrCreateAlloca(SAI);
844     Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload");
845     Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType());
846     Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB);
847     assert((!isa<Instruction>(OriginalValue) ||
848             cast<Instruction>(OriginalValue)->getParent() != MergeBB) &&
849            "Original value must no be one we just generated.");
850     auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge");
851     MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt());
852     MergePHI->addIncoming(Reload, OptExitBB);
853     MergePHI->addIncoming(OriginalValue, ExitBB);
854     int Idx = PHI->getBasicBlockIndex(MergeBB);
855     PHI->setIncomingValue(Idx, MergePHI);
856   }
857 }
858 
859 void BlockGenerator::invalidateScalarEvolution(Scop &S) {
860   for (auto &Stmt : S)
861     if (Stmt.isCopyStmt())
862       continue;
863     else if (Stmt.isBlockStmt())
864       for (auto &Inst : *Stmt.getBasicBlock())
865         SE.forgetValue(&Inst);
866     else if (Stmt.isRegionStmt())
867       for (auto *BB : Stmt.getRegion()->blocks())
868         for (auto &Inst : *BB)
869           SE.forgetValue(&Inst);
870     else
871       llvm_unreachable("Unexpected statement type found");
872 
873   // Invalidate SCEV of loops surrounding the EscapeUsers.
874   for (const auto &EscapeMapping : EscapeMap) {
875     const EscapeUserVectorTy &EscapeUsers = EscapeMapping.second.second;
876     for (Instruction *EUser : EscapeUsers) {
877       if (Loop *L = LI.getLoopFor(EUser->getParent()))
878         while (L) {
879           SE.forgetLoop(L);
880           L = L->getParentLoop();
881         }
882     }
883   }
884 }
885 
886 void BlockGenerator::finalizeSCoP(Scop &S) {
887   findOutsideUsers(S);
888   createScalarInitialization(S);
889   createExitPHINodeMerges(S);
890   createScalarFinalization(S);
891   invalidateScalarEvolution(S);
892 }
893 
894 VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen,
895                                            std::vector<LoopToScevMapT> &VLTS,
896                                            isl_map *Schedule)
897     : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) {
898   assert(Schedule && "No statement domain provided");
899 }
900 
901 Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old,
902                                             ValueMapT &VectorMap,
903                                             VectorValueMapT &ScalarMaps,
904                                             Loop *L) {
905   if (Value *NewValue = VectorMap.lookup(Old))
906     return NewValue;
907 
908   int Width = getVectorWidth();
909 
910   Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width));
911 
912   for (int Lane = 0; Lane < Width; Lane++)
913     Vector = Builder.CreateInsertElement(
914         Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L),
915         Builder.getInt32(Lane));
916 
917   VectorMap[Old] = Vector;
918 
919   return Vector;
920 }
921 
922 Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) {
923   PointerType *PointerTy = dyn_cast<PointerType>(Val->getType());
924   assert(PointerTy && "PointerType expected");
925 
926   Type *ScalarType = PointerTy->getElementType();
927   VectorType *VectorType = VectorType::get(ScalarType, Width);
928 
929   return PointerType::getUnqual(VectorType);
930 }
931 
932 Value *VectorBlockGenerator::generateStrideOneLoad(
933     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
934     __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) {
935   unsigned VectorWidth = getVectorWidth();
936   auto *Pointer = Load->getPointerOperand();
937   Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth);
938   unsigned Offset = NegativeStride ? VectorWidth - 1 : 0;
939 
940   Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset],
941                                                VLTS[Offset], NewAccesses);
942   Value *VectorPtr =
943       Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
944   LoadInst *VecLoad =
945       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full");
946   if (!Aligned)
947     VecLoad->setAlignment(8);
948 
949   if (NegativeStride) {
950     SmallVector<Constant *, 16> Indices;
951     for (int i = VectorWidth - 1; i >= 0; i--)
952       Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i));
953     Constant *SV = llvm::ConstantVector::get(Indices);
954     Value *RevVecLoad = Builder.CreateShuffleVector(
955         VecLoad, VecLoad, SV, Load->getName() + "_reverse");
956     return RevVecLoad;
957   }
958 
959   return VecLoad;
960 }
961 
962 Value *VectorBlockGenerator::generateStrideZeroLoad(
963     ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap,
964     __isl_keep isl_id_to_ast_expr *NewAccesses) {
965   auto *Pointer = Load->getPointerOperand();
966   Type *VectorPtrType = getVectorPtrTy(Pointer, 1);
967   Value *NewPointer =
968       generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses);
969   Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType,
970                                            Load->getName() + "_p_vec_p");
971   LoadInst *ScalarLoad =
972       Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one");
973 
974   if (!Aligned)
975     ScalarLoad->setAlignment(8);
976 
977   Constant *SplatVector = Constant::getNullValue(
978       VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
979 
980   Value *VectorLoad = Builder.CreateShuffleVector(
981       ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat");
982   return VectorLoad;
983 }
984 
985 Value *VectorBlockGenerator::generateUnknownStrideLoad(
986     ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps,
987     __isl_keep isl_id_to_ast_expr *NewAccesses) {
988   int VectorWidth = getVectorWidth();
989   auto *Pointer = Load->getPointerOperand();
990   VectorType *VectorType = VectorType::get(
991       dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth);
992 
993   Value *Vector = UndefValue::get(VectorType);
994 
995   for (int i = 0; i < VectorWidth; i++) {
996     Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i],
997                                                  VLTS[i], NewAccesses);
998     Value *ScalarLoad =
999         Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_");
1000     Vector = Builder.CreateInsertElement(
1001         Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_");
1002   }
1003 
1004   return Vector;
1005 }
1006 
1007 void VectorBlockGenerator::generateLoad(
1008     ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap,
1009     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1010   if (Value *PreloadLoad = GlobalMap.lookup(Load)) {
1011     VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad,
1012                                                 Load->getName() + "_p");
1013     return;
1014   }
1015 
1016   if (!VectorType::isValidElementType(Load->getType())) {
1017     for (int i = 0; i < getVectorWidth(); i++)
1018       ScalarMaps[i][Load] =
1019           generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses);
1020     return;
1021   }
1022 
1023   const MemoryAccess &Access = Stmt.getArrayAccessFor(Load);
1024 
1025   // Make sure we have scalar values available to access the pointer to
1026   // the data location.
1027   extractScalarValues(Load, VectorMap, ScalarMaps);
1028 
1029   Value *NewLoad;
1030   if (Access.isStrideZero(isl::manage(isl_map_copy(Schedule))))
1031     NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses);
1032   else if (Access.isStrideOne(isl::manage(isl_map_copy(Schedule))))
1033     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses);
1034   else if (Access.isStrideX(isl::manage(isl_map_copy(Schedule)), -1))
1035     NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true);
1036   else
1037     NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses);
1038 
1039   VectorMap[Load] = NewLoad;
1040 }
1041 
1042 void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst,
1043                                          ValueMapT &VectorMap,
1044                                          VectorValueMapT &ScalarMaps) {
1045   int VectorWidth = getVectorWidth();
1046   Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap,
1047                                      ScalarMaps, getLoopForStmt(Stmt));
1048 
1049   assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction");
1050 
1051   const CastInst *Cast = dyn_cast<CastInst>(Inst);
1052   VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth);
1053   VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType);
1054 }
1055 
1056 void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst,
1057                                           ValueMapT &VectorMap,
1058                                           VectorValueMapT &ScalarMaps) {
1059   Loop *L = getLoopForStmt(Stmt);
1060   Value *OpZero = Inst->getOperand(0);
1061   Value *OpOne = Inst->getOperand(1);
1062 
1063   Value *NewOpZero, *NewOpOne;
1064   NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L);
1065   NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L);
1066 
1067   Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne,
1068                                        Inst->getName() + "p_vec");
1069   VectorMap[Inst] = NewInst;
1070 }
1071 
1072 void VectorBlockGenerator::copyStore(
1073     ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap,
1074     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1075   const MemoryAccess &Access = Stmt.getArrayAccessFor(Store);
1076 
1077   auto *Pointer = Store->getPointerOperand();
1078   Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap,
1079                                  ScalarMaps, getLoopForStmt(Stmt));
1080 
1081   // Make sure we have scalar values available to access the pointer to
1082   // the data location.
1083   extractScalarValues(Store, VectorMap, ScalarMaps);
1084 
1085   if (Access.isStrideOne(isl::manage(isl_map_copy(Schedule)))) {
1086     Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth());
1087     Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0],
1088                                                  VLTS[0], NewAccesses);
1089 
1090     Value *VectorPtr =
1091         Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr");
1092     StoreInst *Store = Builder.CreateStore(Vector, VectorPtr);
1093 
1094     if (!Aligned)
1095       Store->setAlignment(8);
1096   } else {
1097     for (unsigned i = 0; i < ScalarMaps.size(); i++) {
1098       Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i));
1099       Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i],
1100                                                    VLTS[i], NewAccesses);
1101       Builder.CreateStore(Scalar, NewPointer);
1102     }
1103   }
1104 }
1105 
1106 bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst,
1107                                              ValueMapT &VectorMap) {
1108   for (Value *Operand : Inst->operands())
1109     if (VectorMap.count(Operand))
1110       return true;
1111   return false;
1112 }
1113 
1114 bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst,
1115                                                ValueMapT &VectorMap,
1116                                                VectorValueMapT &ScalarMaps) {
1117   bool HasVectorOperand = false;
1118   int VectorWidth = getVectorWidth();
1119 
1120   for (Value *Operand : Inst->operands()) {
1121     ValueMapT::iterator VecOp = VectorMap.find(Operand);
1122 
1123     if (VecOp == VectorMap.end())
1124       continue;
1125 
1126     HasVectorOperand = true;
1127     Value *NewVector = VecOp->second;
1128 
1129     for (int i = 0; i < VectorWidth; ++i) {
1130       ValueMapT &SM = ScalarMaps[i];
1131 
1132       // If there is one scalar extracted, all scalar elements should have
1133       // already been extracted by the code here. So no need to check for the
1134       // existence of all of them.
1135       if (SM.count(Operand))
1136         break;
1137 
1138       SM[Operand] =
1139           Builder.CreateExtractElement(NewVector, Builder.getInt32(i));
1140     }
1141   }
1142 
1143   return HasVectorOperand;
1144 }
1145 
1146 void VectorBlockGenerator::copyInstScalarized(
1147     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
1148     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1149   bool HasVectorOperand;
1150   int VectorWidth = getVectorWidth();
1151 
1152   HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps);
1153 
1154   for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++)
1155     BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane],
1156                                     VLTS[VectorLane], NewAccesses);
1157 
1158   if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand)
1159     return;
1160 
1161   // Make the result available as vector value.
1162   VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth);
1163   Value *Vector = UndefValue::get(VectorType);
1164 
1165   for (int i = 0; i < VectorWidth; i++)
1166     Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst],
1167                                          Builder.getInt32(i));
1168 
1169   VectorMap[Inst] = Vector;
1170 }
1171 
1172 int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); }
1173 
1174 void VectorBlockGenerator::copyInstruction(
1175     ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap,
1176     VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1177   // Terminator instructions control the control flow. They are explicitly
1178   // expressed in the clast and do not need to be copied.
1179   if (Inst->isTerminator())
1180     return;
1181 
1182   if (canSyntheziseInStmt(Stmt, Inst))
1183     return;
1184 
1185   if (auto *Load = dyn_cast<LoadInst>(Inst)) {
1186     generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses);
1187     return;
1188   }
1189 
1190   if (hasVectorOperands(Inst, VectorMap)) {
1191     if (auto *Store = dyn_cast<StoreInst>(Inst)) {
1192       // Identified as redundant by -polly-simplify.
1193       if (!Stmt.getArrayAccessOrNULLFor(Store))
1194         return;
1195 
1196       copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses);
1197       return;
1198     }
1199 
1200     if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) {
1201       copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps);
1202       return;
1203     }
1204 
1205     if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) {
1206       copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps);
1207       return;
1208     }
1209 
1210     // Fallthrough: We generate scalar instructions, if we don't know how to
1211     // generate vector code.
1212   }
1213 
1214   copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses);
1215 }
1216 
1217 void VectorBlockGenerator::generateScalarVectorLoads(
1218     ScopStmt &Stmt, ValueMapT &VectorBlockMap) {
1219   for (MemoryAccess *MA : Stmt) {
1220     if (MA->isArrayKind() || MA->isWrite())
1221       continue;
1222 
1223     auto *Address = getOrCreateAlloca(*MA);
1224     Type *VectorPtrType = getVectorPtrTy(Address, 1);
1225     Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType,
1226                                              Address->getName() + "_p_vec_p");
1227     auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload");
1228     Constant *SplatVector = Constant::getNullValue(
1229         VectorType::get(Builder.getInt32Ty(), getVectorWidth()));
1230 
1231     Value *VectorVal = Builder.CreateShuffleVector(
1232         Val, Val, SplatVector, Address->getName() + "_p_splat");
1233     VectorBlockMap[MA->getAccessValue()] = VectorVal;
1234   }
1235 }
1236 
1237 void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) {
1238   for (MemoryAccess *MA : Stmt) {
1239     if (MA->isArrayKind() || MA->isRead())
1240       continue;
1241 
1242     llvm_unreachable("Scalar stores not expected in vector loop");
1243   }
1244 }
1245 
1246 void VectorBlockGenerator::copyStmt(
1247     ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) {
1248   assert(Stmt.isBlockStmt() &&
1249          "TODO: Only block statements can be copied by the vector block "
1250          "generator");
1251 
1252   BasicBlock *BB = Stmt.getBasicBlock();
1253   BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(),
1254                                   &*Builder.GetInsertPoint(), &DT, &LI);
1255   CopyBB->setName("polly.stmt." + BB->getName());
1256   Builder.SetInsertPoint(&CopyBB->front());
1257 
1258   // Create two maps that store the mapping from the original instructions of
1259   // the old basic block to their copies in the new basic block. Those maps
1260   // are basic block local.
1261   //
1262   // As vector code generation is supported there is one map for scalar values
1263   // and one for vector values.
1264   //
1265   // In case we just do scalar code generation, the vectorMap is not used and
1266   // the scalarMap has just one dimension, which contains the mapping.
1267   //
1268   // In case vector code generation is done, an instruction may either appear
1269   // in the vector map once (as it is calculating >vectorwidth< values at a
1270   // time. Or (if the values are calculated using scalar operations), it
1271   // appears once in every dimension of the scalarMap.
1272   VectorValueMapT ScalarBlockMap(getVectorWidth());
1273   ValueMapT VectorBlockMap;
1274 
1275   generateScalarVectorLoads(Stmt, VectorBlockMap);
1276 
1277   for (Instruction &Inst : *BB)
1278     copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses);
1279 
1280   verifyNoScalarStores(Stmt);
1281 }
1282 
1283 BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB,
1284                                              BasicBlock *BBCopy) {
1285 
1286   BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock();
1287   BasicBlock *BBCopyIDom = EndBlockMap.lookup(BBIDom);
1288 
1289   if (BBCopyIDom)
1290     DT.changeImmediateDominator(BBCopy, BBCopyIDom);
1291 
1292   return StartBlockMap.lookup(BBIDom);
1293 }
1294 
1295 // This is to determine whether an llvm::Value (defined in @p BB) is usable when
1296 // leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock())
1297 // does not work in cases where the exit block has edges from outside the
1298 // region. In that case the llvm::Value would never be usable in in the exit
1299 // block. The RegionGenerator however creates an new exit block ('ExitBBCopy')
1300 // for the subregion's exiting edges only. We need to determine whether an
1301 // llvm::Value is usable in there. We do this by checking whether it dominates
1302 // all exiting blocks individually.
1303 static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R,
1304                                       BasicBlock *BB) {
1305   for (auto ExitingBB : predecessors(R->getExit())) {
1306     // Check for non-subregion incoming edges.
1307     if (!R->contains(ExitingBB))
1308       continue;
1309 
1310     if (!DT.dominates(BB, ExitingBB))
1311       return false;
1312   }
1313 
1314   return true;
1315 }
1316 
1317 // Find the direct dominator of the subregion's exit block if the subregion was
1318 // simplified.
1319 static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) {
1320   BasicBlock *Common = nullptr;
1321   for (auto ExitingBB : predecessors(R->getExit())) {
1322     // Check for non-subregion incoming edges.
1323     if (!R->contains(ExitingBB))
1324       continue;
1325 
1326     // First exiting edge.
1327     if (!Common) {
1328       Common = ExitingBB;
1329       continue;
1330     }
1331 
1332     Common = DT.findNearestCommonDominator(Common, ExitingBB);
1333   }
1334 
1335   assert(Common && R->contains(Common));
1336   return Common;
1337 }
1338 
1339 void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT &LTS,
1340                                isl_id_to_ast_expr *IdToAstExp) {
1341   assert(Stmt.isRegionStmt() &&
1342          "Only region statements can be copied by the region generator");
1343 
1344   // Forget all old mappings.
1345   StartBlockMap.clear();
1346   EndBlockMap.clear();
1347   RegionMaps.clear();
1348   IncompletePHINodeMap.clear();
1349 
1350   // Collection of all values related to this subregion.
1351   ValueMapT ValueMap;
1352 
1353   // The region represented by the statement.
1354   Region *R = Stmt.getRegion();
1355 
1356   // Create a dedicated entry for the region where we can reload all demoted
1357   // inputs.
1358   BasicBlock *EntryBB = R->getEntry();
1359   BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(),
1360                                        &*Builder.GetInsertPoint(), &DT, &LI);
1361   EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry");
1362   Builder.SetInsertPoint(&EntryBBCopy->front());
1363 
1364   ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy];
1365   generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp);
1366 
1367   for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI)
1368     if (!R->contains(*PI)) {
1369       StartBlockMap[*PI] = EntryBBCopy;
1370       EndBlockMap[*PI] = EntryBBCopy;
1371     }
1372 
1373   // Iterate over all blocks in the region in a breadth-first search.
1374   std::deque<BasicBlock *> Blocks;
1375   SmallSetVector<BasicBlock *, 8> SeenBlocks;
1376   Blocks.push_back(EntryBB);
1377   SeenBlocks.insert(EntryBB);
1378 
1379   while (!Blocks.empty()) {
1380     BasicBlock *BB = Blocks.front();
1381     Blocks.pop_front();
1382 
1383     // First split the block and update dominance information.
1384     BasicBlock *BBCopy = splitBB(BB);
1385     BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy);
1386 
1387     // Get the mapping for this block and initialize it with either the scalar
1388     // loads from the generated entering block (which dominates all blocks of
1389     // this subregion) or the maps of the immediate dominator, if part of the
1390     // subregion. The latter necessarily includes the former.
1391     ValueMapT *InitBBMap;
1392     if (BBCopyIDom) {
1393       assert(RegionMaps.count(BBCopyIDom));
1394       InitBBMap = &RegionMaps[BBCopyIDom];
1395     } else
1396       InitBBMap = &EntryBBMap;
1397     auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap));
1398     ValueMapT &RegionMap = Inserted.first->second;
1399 
1400     // Copy the block with the BlockGenerator.
1401     Builder.SetInsertPoint(&BBCopy->front());
1402     copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp);
1403 
1404     // In order to remap PHI nodes we store also basic block mappings.
1405     StartBlockMap[BB] = BBCopy;
1406     EndBlockMap[BB] = Builder.GetInsertBlock();
1407 
1408     // Add values to incomplete PHI nodes waiting for this block to be copied.
1409     for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB])
1410       addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS);
1411     IncompletePHINodeMap[BB].clear();
1412 
1413     // And continue with new successors inside the region.
1414     for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++)
1415       if (R->contains(*SI) && SeenBlocks.insert(*SI))
1416         Blocks.push_back(*SI);
1417 
1418     // Remember value in case it is visible after this subregion.
1419     if (isDominatingSubregionExit(DT, R, BB))
1420       ValueMap.insert(RegionMap.begin(), RegionMap.end());
1421   }
1422 
1423   // Now create a new dedicated region exit block and add it to the region map.
1424   BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(),
1425                                       &*Builder.GetInsertPoint(), &DT, &LI);
1426   ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit");
1427   StartBlockMap[R->getExit()] = ExitBBCopy;
1428   EndBlockMap[R->getExit()] = ExitBBCopy;
1429 
1430   BasicBlock *ExitDomBBCopy = EndBlockMap.lookup(findExitDominator(DT, R));
1431   assert(ExitDomBBCopy &&
1432          "Common exit dominator must be within region; at least the entry node "
1433          "must match");
1434   DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy);
1435 
1436   // As the block generator doesn't handle control flow we need to add the
1437   // region control flow by hand after all blocks have been copied.
1438   for (BasicBlock *BB : SeenBlocks) {
1439 
1440     BasicBlock *BBCopyStart = StartBlockMap[BB];
1441     BasicBlock *BBCopyEnd = EndBlockMap[BB];
1442     TerminatorInst *TI = BB->getTerminator();
1443     if (isa<UnreachableInst>(TI)) {
1444       while (!BBCopyEnd->empty())
1445         BBCopyEnd->begin()->eraseFromParent();
1446       new UnreachableInst(BBCopyEnd->getContext(), BBCopyEnd);
1447       continue;
1448     }
1449 
1450     Instruction *BICopy = BBCopyEnd->getTerminator();
1451 
1452     ValueMapT &RegionMap = RegionMaps[BBCopyStart];
1453     RegionMap.insert(StartBlockMap.begin(), StartBlockMap.end());
1454 
1455     Builder.SetInsertPoint(BICopy);
1456     copyInstScalar(Stmt, TI, RegionMap, LTS);
1457     BICopy->eraseFromParent();
1458   }
1459 
1460   // Add counting PHI nodes to all loops in the region that can be used as
1461   // replacement for SCEVs referring to the old loop.
1462   for (BasicBlock *BB : SeenBlocks) {
1463     Loop *L = LI.getLoopFor(BB);
1464     if (L == nullptr || L->getHeader() != BB || !R->contains(L))
1465       continue;
1466 
1467     BasicBlock *BBCopy = StartBlockMap[BB];
1468     Value *NullVal = Builder.getInt32(0);
1469     PHINode *LoopPHI =
1470         PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv");
1471     Instruction *LoopPHIInc = BinaryOperator::CreateAdd(
1472         LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc");
1473     LoopPHI->insertBefore(&BBCopy->front());
1474     LoopPHIInc->insertBefore(BBCopy->getTerminator());
1475 
1476     for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) {
1477       if (!R->contains(PredBB))
1478         continue;
1479       if (L->contains(PredBB))
1480         LoopPHI->addIncoming(LoopPHIInc, EndBlockMap[PredBB]);
1481       else
1482         LoopPHI->addIncoming(NullVal, EndBlockMap[PredBB]);
1483     }
1484 
1485     for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy)))
1486       if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0)
1487         LoopPHI->addIncoming(NullVal, PredBBCopy);
1488 
1489     LTS[L] = SE.getUnknown(LoopPHI);
1490   }
1491 
1492   // Continue generating code in the exit block.
1493   Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt());
1494 
1495   // Write values visible to other statements.
1496   generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp);
1497   StartBlockMap.clear();
1498   EndBlockMap.clear();
1499   RegionMaps.clear();
1500   IncompletePHINodeMap.clear();
1501 }
1502 
1503 PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT &LTS,
1504                                        ValueMapT &BBMap, Loop *L) {
1505   ScopStmt *Stmt = MA->getStatement();
1506   Region *SubR = Stmt->getRegion();
1507   auto Incoming = MA->getIncoming();
1508 
1509   PollyIRBuilder::InsertPointGuard IPGuard(Builder);
1510   PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction());
1511   BasicBlock *NewSubregionExit = Builder.GetInsertBlock();
1512 
1513   // This can happen if the subregion is simplified after the ScopStmts
1514   // have been created; simplification happens as part of CodeGeneration.
1515   if (OrigPHI->getParent() != SubR->getExit()) {
1516     BasicBlock *FormerExit = SubR->getExitingBlock();
1517     if (FormerExit)
1518       NewSubregionExit = StartBlockMap.lookup(FormerExit);
1519   }
1520 
1521   PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(),
1522                                     "polly." + OrigPHI->getName(),
1523                                     NewSubregionExit->getFirstNonPHI());
1524 
1525   // Add the incoming values to the PHI.
1526   for (auto &Pair : Incoming) {
1527     BasicBlock *OrigIncomingBlock = Pair.first;
1528     BasicBlock *NewIncomingBlockStart = StartBlockMap.lookup(OrigIncomingBlock);
1529     BasicBlock *NewIncomingBlockEnd = EndBlockMap.lookup(OrigIncomingBlock);
1530     Builder.SetInsertPoint(NewIncomingBlockEnd->getTerminator());
1531     assert(RegionMaps.count(NewIncomingBlockStart));
1532     assert(RegionMaps.count(NewIncomingBlockEnd));
1533     ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlockStart];
1534 
1535     Value *OrigIncomingValue = Pair.second;
1536     Value *NewIncomingValue =
1537         getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L);
1538     NewPHI->addIncoming(NewIncomingValue, NewIncomingBlockEnd);
1539   }
1540 
1541   return NewPHI;
1542 }
1543 
1544 Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT &LTS,
1545                                       ValueMapT &BBMap) {
1546   ScopStmt *Stmt = MA->getStatement();
1547 
1548   // TODO: Add some test cases that ensure this is really the right choice.
1549   Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit());
1550 
1551   if (MA->isAnyPHIKind()) {
1552     auto Incoming = MA->getIncoming();
1553     assert(!Incoming.empty() &&
1554            "PHI WRITEs must have originate from at least one incoming block");
1555 
1556     // If there is only one incoming value, we do not need to create a PHI.
1557     if (Incoming.size() == 1) {
1558       Value *OldVal = Incoming[0].second;
1559       return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1560     }
1561 
1562     return buildExitPHI(MA, LTS, BBMap, L);
1563   }
1564 
1565   // MemoryKind::Value accesses leaving the subregion must dominate the exit
1566   // block; just pass the copied value.
1567   Value *OldVal = MA->getAccessValue();
1568   return getNewValue(*Stmt, OldVal, BBMap, LTS, L);
1569 }
1570 
1571 void RegionGenerator::generateScalarStores(
1572     ScopStmt &Stmt, LoopToScevMapT &LTS, ValueMapT &BBMap,
1573     __isl_keep isl_id_to_ast_expr *NewAccesses) {
1574   assert(Stmt.getRegion() &&
1575          "Block statements need to use the generateScalarStores() "
1576          "function in the BlockGenerator");
1577 
1578   for (MemoryAccess *MA : Stmt) {
1579     if (MA->isOriginalArrayKind() || MA->isRead())
1580       continue;
1581 
1582     isl::set AccDom = MA->getAccessRelation().domain();
1583     std::string Subject = MA->getId().get_name();
1584     generateConditionalExecution(
1585         Stmt, AccDom, Subject.c_str(), [&, this, MA]() {
1586 
1587           Value *NewVal = getExitScalar(MA, LTS, BBMap);
1588           Value *Address = getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS,
1589                                               BBMap, NewAccesses);
1590           assert((!isa<Instruction>(NewVal) ||
1591                   DT.dominates(cast<Instruction>(NewVal)->getParent(),
1592                                Builder.GetInsertBlock())) &&
1593                  "Domination violation");
1594           assert((!isa<Instruction>(Address) ||
1595                   DT.dominates(cast<Instruction>(Address)->getParent(),
1596                                Builder.GetInsertBlock())) &&
1597                  "Domination violation");
1598           Builder.CreateStore(NewVal, Address);
1599         });
1600   }
1601 }
1602 
1603 void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI,
1604                                       PHINode *PHICopy, BasicBlock *IncomingBB,
1605                                       LoopToScevMapT &LTS) {
1606   // If the incoming block was not yet copied mark this PHI as incomplete.
1607   // Once the block will be copied the incoming value will be added.
1608   BasicBlock *BBCopyStart = StartBlockMap[IncomingBB];
1609   BasicBlock *BBCopyEnd = EndBlockMap[IncomingBB];
1610   if (!BBCopyStart) {
1611     assert(!BBCopyEnd);
1612     assert(Stmt.represents(IncomingBB) &&
1613            "Bad incoming block for PHI in non-affine region");
1614     IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy));
1615     return;
1616   }
1617 
1618   assert(RegionMaps.count(BBCopyStart) &&
1619          "Incoming PHI block did not have a BBMap");
1620   ValueMapT &BBCopyMap = RegionMaps[BBCopyStart];
1621 
1622   Value *OpCopy = nullptr;
1623 
1624   if (Stmt.represents(IncomingBB)) {
1625     Value *Op = PHI->getIncomingValueForBlock(IncomingBB);
1626 
1627     // If the current insert block is different from the PHIs incoming block
1628     // change it, otherwise do not.
1629     auto IP = Builder.GetInsertPoint();
1630     if (IP->getParent() != BBCopyEnd)
1631       Builder.SetInsertPoint(BBCopyEnd->getTerminator());
1632     OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt));
1633     if (IP->getParent() != BBCopyEnd)
1634       Builder.SetInsertPoint(&*IP);
1635   } else {
1636     // All edges from outside the non-affine region become a single edge
1637     // in the new copy of the non-affine region. Make sure to only add the
1638     // corresponding edge the first time we encounter a basic block from
1639     // outside the non-affine region.
1640     if (PHICopy->getBasicBlockIndex(BBCopyEnd) >= 0)
1641       return;
1642 
1643     // Get the reloaded value.
1644     OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt));
1645   }
1646 
1647   assert(OpCopy && "Incoming PHI value was not copied properly");
1648   PHICopy->addIncoming(OpCopy, BBCopyEnd);
1649 }
1650 
1651 void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI,
1652                                          ValueMapT &BBMap,
1653                                          LoopToScevMapT &LTS) {
1654   unsigned NumIncoming = PHI->getNumIncomingValues();
1655   PHINode *PHICopy =
1656       Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName());
1657   PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI());
1658   BBMap[PHI] = PHICopy;
1659 
1660   for (BasicBlock *IncomingBB : PHI->blocks())
1661     addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS);
1662 }
1663