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