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