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