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