13b11a16aSHongbin Zheng //===--- BlockGenerators.cpp - Generate code for statements -----*- C++ -*-===// 23b11a16aSHongbin Zheng // 33b11a16aSHongbin Zheng // The LLVM Compiler Infrastructure 43b11a16aSHongbin Zheng // 53b11a16aSHongbin Zheng // This file is distributed under the University of Illinois Open Source 63b11a16aSHongbin Zheng // License. See LICENSE.TXT for details. 73b11a16aSHongbin Zheng // 83b11a16aSHongbin Zheng //===----------------------------------------------------------------------===// 93b11a16aSHongbin Zheng // 103b11a16aSHongbin Zheng // This file implements the BlockGenerator and VectorBlockGenerator classes, 113b11a16aSHongbin Zheng // which generate sequential code and vectorized code for a polyhedral 123b11a16aSHongbin Zheng // statement, respectively. 133b11a16aSHongbin Zheng // 143b11a16aSHongbin Zheng //===----------------------------------------------------------------------===// 153b11a16aSHongbin Zheng 168a846610SHongbin Zheng #include "polly/CodeGen/BlockGenerators.h" 1783628182STobias Grosser #include "polly/CodeGen/CodeGeneration.h" 18a63b2579SJohannes Doerfert #include "polly/CodeGen/IslExprBuilder.h" 1986bc93a9STobias Grosser #include "polly/CodeGen/RuntimeDebugBuilder.h" 20637bd631STobias Grosser #include "polly/Options.h" 215624d3c9STobias Grosser #include "polly/ScopInfo.h" 223b11a16aSHongbin Zheng #include "polly/Support/GICHelper.h" 2397cb813cSSebastian Pop #include "polly/Support/SCEVValidator.h" 24ecfe21b7STobias Grosser #include "polly/Support/ScopHelper.h" 25e71c6ab5STobias Grosser #include "llvm/Analysis/LoopInfo.h" 26f32d651dSJohannes Doerfert #include "llvm/Analysis/RegionInfo.h" 27e71c6ab5STobias Grosser #include "llvm/Analysis/ScalarEvolution.h" 28030237d0STobias Grosser #include "llvm/IR/IntrinsicInst.h" 29c9895067STobias Grosser #include "llvm/IR/Module.h" 303b11a16aSHongbin Zheng #include "llvm/Transforms/Utils/BasicBlockUtils.h" 311b9d25a4STobias Grosser #include "llvm/Transforms/Utils/Local.h" 32f32d651dSJohannes Doerfert #include "isl/aff.h" 33f32d651dSJohannes Doerfert #include "isl/ast.h" 34f32d651dSJohannes Doerfert #include "isl/ast_build.h" 35ba0d0922STobias Grosser #include "isl/set.h" 36f32d651dSJohannes Doerfert #include <deque> 37f32d651dSJohannes Doerfert 383b11a16aSHongbin Zheng using namespace llvm; 393b11a16aSHongbin Zheng using namespace polly; 403b11a16aSHongbin Zheng 41878aba49STobias Grosser static cl::opt<bool> Aligned("enable-polly-aligned", 42878aba49STobias Grosser cl::desc("Assumed aligned memory accesses."), 43878aba49STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, 44878aba49STobias Grosser cl::cat(PollyCategory)); 453b11a16aSHongbin Zheng 4686bc93a9STobias Grosser static cl::opt<bool> DebugPrinting( 4786bc93a9STobias Grosser "polly-codegen-add-debug-printing", 4886bc93a9STobias Grosser cl::desc("Add printf calls that show the values loaded/stored."), 4986bc93a9STobias Grosser cl::Hidden, cl::init(false), cl::ZeroOrMore, cl::cat(PollyCategory)); 5086bc93a9STobias Grosser 51acf80064SEli Friedman BlockGenerator::BlockGenerator( 52acf80064SEli Friedman PollyIRBuilder &B, LoopInfo &LI, ScalarEvolution &SE, DominatorTree &DT, 53acf80064SEli Friedman ScalarAllocaMapTy &ScalarMap, ScalarAllocaMapTy &PHIOpMap, 54acf80064SEli Friedman EscapeUsersAllocaMapTy &EscapeMap, ValueMapT &GlobalMap, 55acf80064SEli Friedman IslExprBuilder *ExprBuilder, BasicBlock *StartBlock) 56ecff11dcSJohannes Doerfert : Builder(B), LI(LI), SE(SE), ExprBuilder(ExprBuilder), DT(DT), 57ecff11dcSJohannes Doerfert EntryBB(nullptr), PHIOpMap(PHIOpMap), ScalarMap(ScalarMap), 58acf80064SEli Friedman EscapeMap(EscapeMap), GlobalMap(GlobalMap), StartBlock(StartBlock) {} 59e71c6ab5STobias Grosser 602f1acac6STobias Grosser Value *BlockGenerator::trySynthesizeNewValue(ScopStmt &Stmt, Value *Old, 6133cb9f94STobias Grosser ValueMapT &BBMap, 6233cb9f94STobias Grosser LoopToScevMapT <S, 63bc132607STobias Grosser Loop *L) const { 6442df8d1dSJohannes Doerfert if (!SE.isSCEVable(Old->getType())) 6542df8d1dSJohannes Doerfert return nullptr; 6642df8d1dSJohannes Doerfert 6742df8d1dSJohannes Doerfert const SCEV *Scev = SE.getSCEVAtScope(Old, L); 6842df8d1dSJohannes Doerfert if (!Scev) 6942df8d1dSJohannes Doerfert return nullptr; 7042df8d1dSJohannes Doerfert 7142df8d1dSJohannes Doerfert if (isa<SCEVCouldNotCompute>(Scev)) 7242df8d1dSJohannes Doerfert return nullptr; 7342df8d1dSJohannes Doerfert 7403bcb910SSanjoy Das const SCEV *NewScev = SCEVLoopAddRecRewriter::rewrite(Scev, LTS, SE); 7509e3697fSJohannes Doerfert ValueMapT VTV; 76637b23dcSSebastian Pop VTV.insert(BBMap.begin(), BBMap.end()); 77637b23dcSSebastian Pop VTV.insert(GlobalMap.begin(), GlobalMap.end()); 78e69e1141SJohannes Doerfert 79e69e1141SJohannes Doerfert Scop &S = *Stmt.getParent(); 803f52e354SJohannes Doerfert const DataLayout &DL = S.getFunction().getParent()->getDataLayout(); 81e69e1141SJohannes Doerfert auto IP = Builder.GetInsertPoint(); 82e69e1141SJohannes Doerfert 83e69e1141SJohannes Doerfert assert(IP != Builder.GetInsertBlock()->end() && 8445e7944bSTobias Grosser "Only instructions can be insert points for SCEVExpander"); 8542df8d1dSJohannes Doerfert Value *Expanded = 86acf80064SEli Friedman expandCodeFor(S, SE, DL, "polly", NewScev, Old->getType(), &*IP, &VTV, 87acf80064SEli Friedman StartBlock->getSinglePredecessor()); 88e71c6ab5STobias Grosser 89e71c6ab5STobias Grosser BBMap[Old] = Expanded; 90e71c6ab5STobias Grosser return Expanded; 91e71c6ab5STobias Grosser } 9233cb9f94STobias Grosser 932f1acac6STobias Grosser Value *BlockGenerator::getNewValue(ScopStmt &Stmt, Value *Old, ValueMapT &BBMap, 942f1acac6STobias Grosser LoopToScevMapT <S, Loop *L) const { 959bd0dad9STobias Grosser // Constants that do not reference any named value can always remain 965bbc0e18SMichael Kruse // unchanged. Handle them early to avoid expensive map lookups. We do not take 979bd0dad9STobias Grosser // the fast-path for external constants which are referenced through globals 989bd0dad9STobias Grosser // as these may need to be rewritten when distributing code accross different 999bd0dad9STobias Grosser // LLVM modules. 1009bd0dad9STobias Grosser if (isa<Constant>(Old) && !isa<GlobalValue>(Old)) 1016f764bbdSTobias Grosser return Old; 10233cb9f94STobias Grosser 10328f8ac1dSJohannes Doerfert // Inline asm is like a constant to us. 10428f8ac1dSJohannes Doerfert if (isa<InlineAsm>(Old)) 10528f8ac1dSJohannes Doerfert return Old; 10628f8ac1dSJohannes Doerfert 10733cb9f94STobias Grosser if (Value *New = GlobalMap.lookup(Old)) { 10833cb9f94STobias Grosser if (Value *NewRemapped = GlobalMap.lookup(New)) 10933cb9f94STobias Grosser New = NewRemapped; 11033cb9f94STobias Grosser if (Old->getType()->getScalarSizeInBits() < 11133cb9f94STobias Grosser New->getType()->getScalarSizeInBits()) 11233cb9f94STobias Grosser New = Builder.CreateTruncOrBitCast(New, Old->getType()); 11333cb9f94STobias Grosser 11433cb9f94STobias Grosser return New; 11533cb9f94STobias Grosser } 11633cb9f94STobias Grosser 11733cb9f94STobias Grosser if (Value *New = BBMap.lookup(Old)) 11833cb9f94STobias Grosser return New; 11933cb9f94STobias Grosser 12033cb9f94STobias Grosser if (Value *New = trySynthesizeNewValue(Stmt, Old, BBMap, LTS, L)) 12133cb9f94STobias Grosser return New; 12233cb9f94STobias Grosser 12316371acdSTobias Grosser // A scop-constant value defined by a global or a function parameter. 12416371acdSTobias Grosser if (isa<GlobalValue>(Old) || isa<Argument>(Old)) 1256f764bbdSTobias Grosser return Old; 12616371acdSTobias Grosser 12716371acdSTobias Grosser // A scop-constant value defined by an instruction executed outside the scop. 12816371acdSTobias Grosser if (const Instruction *Inst = dyn_cast<Instruction>(Old)) 129952b5304SJohannes Doerfert if (!Stmt.getParent()->contains(Inst->getParent())) 1306f764bbdSTobias Grosser return Old; 13116371acdSTobias Grosser 13216371acdSTobias Grosser // The scalar dependence is neither available nor SCEVCodegenable. 1335b463ceaSHongbin Zheng llvm_unreachable("Unexpected scalar dependence in region!"); 1345a56cbf4STobias Grosser return nullptr; 1353b11a16aSHongbin Zheng } 1363b11a16aSHongbin Zheng 1372f1acac6STobias Grosser void BlockGenerator::copyInstScalar(ScopStmt &Stmt, Instruction *Inst, 138bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S) { 139030237d0STobias Grosser // We do not generate debug intrinsics as we did not investigate how to 140030237d0STobias Grosser // copy them correctly. At the current state, they just crash the code 141030237d0STobias Grosser // generation as the meta-data operands are not correctly copied. 142030237d0STobias Grosser if (isa<DbgInfoIntrinsic>(Inst)) 143030237d0STobias Grosser return; 144030237d0STobias Grosser 1453b11a16aSHongbin Zheng Instruction *NewInst = Inst->clone(); 1463b11a16aSHongbin Zheng 1473b11a16aSHongbin Zheng // Replace old operands with the new ones. 14891f5b262STobias Grosser for (Value *OldOperand : Inst->operands()) { 149bc132607STobias Grosser Value *NewOperand = 1502c3ffc04SJohannes Doerfert getNewValue(Stmt, OldOperand, BBMap, LTS, getLoopForStmt(Stmt)); 1513b11a16aSHongbin Zheng 1523b11a16aSHongbin Zheng if (!NewOperand) { 153c14582f2STobias Grosser assert(!isa<StoreInst>(NewInst) && 154c14582f2STobias Grosser "Store instructions are always needed!"); 1553b11a16aSHongbin Zheng delete NewInst; 1563b11a16aSHongbin Zheng return; 1573b11a16aSHongbin Zheng } 1583b11a16aSHongbin Zheng 1593b11a16aSHongbin Zheng NewInst->replaceUsesOfWith(OldOperand, NewOperand); 1603b11a16aSHongbin Zheng } 1613b11a16aSHongbin Zheng 1623b11a16aSHongbin Zheng Builder.Insert(NewInst); 1633b11a16aSHongbin Zheng BBMap[Inst] = NewInst; 1643b11a16aSHongbin Zheng 1653b11a16aSHongbin Zheng if (!NewInst->getType()->isVoidTy()) 1663b11a16aSHongbin Zheng NewInst->setName("p_" + Inst->getName()); 1673b11a16aSHongbin Zheng } 1683b11a16aSHongbin Zheng 16970131d34SMichael Kruse Value * 17070131d34SMichael Kruse BlockGenerator::generateLocationAccessed(ScopStmt &Stmt, MemAccInst Inst, 17170131d34SMichael Kruse ValueMapT &BBMap, LoopToScevMapT <S, 17270131d34SMichael Kruse isl_id_to_ast_expr *NewAccesses) { 17309214772STobias Grosser const MemoryAccess &MA = Stmt.getArrayAccessFor(Inst); 1742fa35194SMichael Kruse return generateLocationAccessed( 1752fa35194SMichael Kruse Stmt, getLoopForStmt(Stmt), 1762fa35194SMichael Kruse Inst.isNull() ? nullptr : Inst.getPointerOperand(), BBMap, LTS, 1772fa35194SMichael Kruse NewAccesses, MA.getId(), MA.getAccessValue()->getType()); 1782fa35194SMichael Kruse } 1793b11a16aSHongbin Zheng 1802fa35194SMichael Kruse Value *BlockGenerator::generateLocationAccessed( 1812fa35194SMichael Kruse ScopStmt &Stmt, Loop *L, Value *Pointer, ValueMapT &BBMap, 1822fa35194SMichael Kruse LoopToScevMapT <S, isl_id_to_ast_expr *NewAccesses, __isl_take isl_id *Id, 1832fa35194SMichael Kruse Type *ExpectedType) { 1842fa35194SMichael Kruse isl_ast_expr *AccessExpr = isl_id_to_ast_expr_get(NewAccesses, Id); 1853b11a16aSHongbin Zheng 1862d1ed0bfSTobias Grosser if (AccessExpr) { 1872d1ed0bfSTobias Grosser AccessExpr = isl_ast_expr_address_of(AccessExpr); 18898b3ee50STobias Grosser auto Address = ExprBuilder->create(AccessExpr); 18998b3ee50STobias Grosser 19098b3ee50STobias Grosser // Cast the address of this memory access to a pointer type that has the 19198b3ee50STobias Grosser // same element type as the original access, but uses the address space of 19298b3ee50STobias Grosser // the newly generated pointer. 1932fa35194SMichael Kruse auto OldPtrTy = ExpectedType->getPointerTo(); 19498b3ee50STobias Grosser auto NewPtrTy = Address->getType(); 19598b3ee50STobias Grosser OldPtrTy = PointerType::get(OldPtrTy->getElementType(), 19698b3ee50STobias Grosser NewPtrTy->getPointerAddressSpace()); 19798b3ee50STobias Grosser 198d840fc72STobias Grosser if (OldPtrTy != NewPtrTy) 19998b3ee50STobias Grosser Address = Builder.CreateBitOrPointerCast(Address, OldPtrTy); 20098b3ee50STobias Grosser return Address; 2012d1ed0bfSTobias Grosser } 2022fa35194SMichael Kruse assert( 2032fa35194SMichael Kruse Pointer && 2042fa35194SMichael Kruse "If expression was not generated, must use the original pointer value"); 2052fa35194SMichael Kruse return getNewValue(Stmt, Pointer, BBMap, LTS, L); 2062fa35194SMichael Kruse } 2072d1ed0bfSTobias Grosser 2082fa35194SMichael Kruse Value * 2092fa35194SMichael Kruse BlockGenerator::getImplicitAddress(MemoryAccess &Access, Loop *L, 2102fa35194SMichael Kruse LoopToScevMapT <S, ValueMapT &BBMap, 2112fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 2122fa35194SMichael Kruse if (Access.isLatestArrayKind()) 2132fa35194SMichael Kruse return generateLocationAccessed(*Access.getStatement(), L, nullptr, BBMap, 2142fa35194SMichael Kruse LTS, NewAccesses, Access.getId(), 2152fa35194SMichael Kruse Access.getAccessValue()->getType()); 2162fa35194SMichael Kruse 2172fa35194SMichael Kruse if (Access.isLatestValueKind() || Access.isLatestExitPHIKind()) 2182fa35194SMichael Kruse return getOrCreateScalarAlloca(Access.getBaseAddr()); 2192fa35194SMichael Kruse 2202fa35194SMichael Kruse if (Access.isLatestPHIKind()) 2212fa35194SMichael Kruse return getOrCreatePHIAlloca(Access.getBaseAddr()); 2222fa35194SMichael Kruse 2232fa35194SMichael Kruse llvm_unreachable("Unknown access type"); 2243b11a16aSHongbin Zheng } 2253b11a16aSHongbin Zheng 2262c3ffc04SJohannes Doerfert Loop *BlockGenerator::getLoopForStmt(const ScopStmt &Stmt) const { 227375cb5feSMichael Kruse auto *StmtBB = Stmt.getEntryBlock(); 2282c3ffc04SJohannes Doerfert return LI.getLoopFor(StmtBB); 229369430ffSTobias Grosser } 230369430ffSTobias Grosser 231888ab551SMichael Kruse Value *BlockGenerator::generateArrayLoad(ScopStmt &Stmt, LoadInst *Load, 232bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 2332d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 234c1db67e2SJohannes Doerfert if (Value *PreloadLoad = GlobalMap.lookup(Load)) 235c1db67e2SJohannes Doerfert return PreloadLoad; 236c1db67e2SJohannes Doerfert 237bc132607STobias Grosser Value *NewPointer = 23870131d34SMichael Kruse generateLocationAccessed(Stmt, Load, BBMap, LTS, NewAccesses); 23987901453SJohannes Doerfert Value *ScalarLoad = Builder.CreateAlignedLoad( 24087901453SJohannes Doerfert NewPointer, Load->getAlignment(), Load->getName() + "_p_scalar_"); 24186bc93a9STobias Grosser 24286bc93a9STobias Grosser if (DebugPrinting) 24386bc93a9STobias Grosser RuntimeDebugBuilder::createCPUPrinter(Builder, "Load from ", NewPointer, 24486bc93a9STobias Grosser ": ", ScalarLoad, "\n"); 24586bc93a9STobias Grosser 2463b11a16aSHongbin Zheng return ScalarLoad; 2473b11a16aSHongbin Zheng } 2483b11a16aSHongbin Zheng 249888ab551SMichael Kruse void BlockGenerator::generateArrayStore(ScopStmt &Stmt, StoreInst *Store, 250bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 2512d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 252bc132607STobias Grosser Value *NewPointer = 25370131d34SMichael Kruse generateLocationAccessed(Stmt, Store, BBMap, LTS, NewAccesses); 254bc132607STobias Grosser Value *ValueOperand = getNewValue(Stmt, Store->getValueOperand(), BBMap, LTS, 2552c3ffc04SJohannes Doerfert getLoopForStmt(Stmt)); 2563b11a16aSHongbin Zheng 25786bc93a9STobias Grosser if (DebugPrinting) 25886bc93a9STobias Grosser RuntimeDebugBuilder::createCPUPrinter(Builder, "Store to ", NewPointer, 25986bc93a9STobias Grosser ": ", ValueOperand, "\n"); 26086bc93a9STobias Grosser 261c186ac7aSTobias Grosser Builder.CreateAlignedStore(ValueOperand, NewPointer, Store->getAlignment()); 2623b11a16aSHongbin Zheng } 2633b11a16aSHongbin Zheng 2645dced269SJohannes Doerfert bool BlockGenerator::canSyntheziseInStmt(ScopStmt &Stmt, Instruction *Inst) { 2652c3ffc04SJohannes Doerfert Loop *L = getLoopForStmt(Stmt); 2665dced269SJohannes Doerfert return (Stmt.isBlockStmt() || !Stmt.getRegion()->contains(L)) && 26711c5e079SMichael Kruse canSynthesize(Inst, *Stmt.getParent(), &SE, L); 2685dced269SJohannes Doerfert } 2695dced269SJohannes Doerfert 2702f1acac6STobias Grosser void BlockGenerator::copyInstruction(ScopStmt &Stmt, Instruction *Inst, 271bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 2722d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 2733b11a16aSHongbin Zheng // Terminator instructions control the control flow. They are explicitly 2743b11a16aSHongbin Zheng // expressed in the clast and do not need to be copied. 2753b11a16aSHongbin Zheng if (Inst->isTerminator()) 2763b11a16aSHongbin Zheng return; 2773b11a16aSHongbin Zheng 278aff56c8aSTobias Grosser // Synthesizable statements will be generated on-demand. 2795dced269SJohannes Doerfert if (canSyntheziseInStmt(Stmt, Inst)) 280e71c6ab5STobias Grosser return; 281e71c6ab5STobias Grosser 2829646e3feSTobias Grosser if (auto *Load = dyn_cast<LoadInst>(Inst)) { 283888ab551SMichael Kruse Value *NewLoad = generateArrayLoad(Stmt, Load, BBMap, LTS, NewAccesses); 2843d94fedfSSebastian Pop // Compute NewLoad before its insertion in BBMap to make the insertion 2853d94fedfSSebastian Pop // deterministic. 286753d43f9SSebastian Pop BBMap[Load] = NewLoad; 2873b11a16aSHongbin Zheng return; 2883b11a16aSHongbin Zheng } 2893b11a16aSHongbin Zheng 2909646e3feSTobias Grosser if (auto *Store = dyn_cast<StoreInst>(Inst)) { 291888ab551SMichael Kruse generateArrayStore(Stmt, Store, BBMap, LTS, NewAccesses); 2923b11a16aSHongbin Zheng return; 2933b11a16aSHongbin Zheng } 2943b11a16aSHongbin Zheng 2959646e3feSTobias Grosser if (auto *PHI = dyn_cast<PHINode>(Inst)) { 296bc132607STobias Grosser copyPHIInstruction(Stmt, PHI, BBMap, LTS); 297ecff11dcSJohannes Doerfert return; 298ecff11dcSJohannes Doerfert } 299ecff11dcSJohannes Doerfert 3003f500fa2SJohannes Doerfert // Skip some special intrinsics for which we do not adjust the semantics to 3013f500fa2SJohannes Doerfert // the new schedule. All others are handled like every other instruction. 3029c0ffe3aSTobias Grosser if (isIgnoredIntrinsic(Inst)) 3033f500fa2SJohannes Doerfert return; 3043f500fa2SJohannes Doerfert 305bc132607STobias Grosser copyInstScalar(Stmt, Inst, BBMap, LTS); 3063b11a16aSHongbin Zheng } 3073b11a16aSHongbin Zheng 3089d12d8adSTobias Grosser void BlockGenerator::removeDeadInstructions(BasicBlock *BB, ValueMapT &BBMap) { 309c59b3ce0STobias Grosser auto NewBB = Builder.GetInsertBlock(); 310c59b3ce0STobias Grosser for (auto I = NewBB->rbegin(); I != NewBB->rend(); I++) { 311c59b3ce0STobias Grosser Instruction *NewInst = &*I; 3129d12d8adSTobias Grosser 3139d12d8adSTobias Grosser if (!isInstructionTriviallyDead(NewInst)) 3149d12d8adSTobias Grosser continue; 3159d12d8adSTobias Grosser 316c59b3ce0STobias Grosser for (auto Pair : BBMap) 317c59b3ce0STobias Grosser if (Pair.second == NewInst) { 318c59b3ce0STobias Grosser BBMap.erase(Pair.first); 319c59b3ce0STobias Grosser } 320c59b3ce0STobias Grosser 3219d12d8adSTobias Grosser NewInst->eraseFromParent(); 322c59b3ce0STobias Grosser I = NewBB->rbegin(); 3239d12d8adSTobias Grosser } 3249d12d8adSTobias Grosser } 3259d12d8adSTobias Grosser 326bc132607STobias Grosser void BlockGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT <S, 3272d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 328275a1756SJohannes Doerfert assert(Stmt.isBlockStmt() && 329275a1756SJohannes Doerfert "Only block statements can be copied by the block generator"); 330275a1756SJohannes Doerfert 331275a1756SJohannes Doerfert ValueMapT BBMap; 332275a1756SJohannes Doerfert 333be9c9117SJohannes Doerfert BasicBlock *BB = Stmt.getBasicBlock(); 334bc132607STobias Grosser copyBB(Stmt, BB, BBMap, LTS, NewAccesses); 3359d12d8adSTobias Grosser removeDeadInstructions(BB, BBMap); 336275a1756SJohannes Doerfert } 337275a1756SJohannes Doerfert 338514f6efaSJohannes Doerfert BasicBlock *BlockGenerator::splitBB(BasicBlock *BB) { 339b8f58b53SDuncan P. N. Exon Smith BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(), 340b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 3413b11a16aSHongbin Zheng CopyBB->setName("polly.stmt." + BB->getName()); 342514f6efaSJohannes Doerfert return CopyBB; 343514f6efaSJohannes Doerfert } 3443b11a16aSHongbin Zheng 345514f6efaSJohannes Doerfert BasicBlock *BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, 346bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 3472d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 348514f6efaSJohannes Doerfert BasicBlock *CopyBB = splitBB(BB); 349b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&CopyBB->front()); 3502fa35194SMichael Kruse generateScalarLoads(Stmt, LTS, BBMap, NewAccesses); 351225f0d1eSMichael Kruse 352bc132607STobias Grosser copyBB(Stmt, BB, CopyBB, BBMap, LTS, NewAccesses); 353225f0d1eSMichael Kruse 354225f0d1eSMichael Kruse // After a basic block was copied store all scalars that escape this block in 355225f0d1eSMichael Kruse // their alloca. 3562fa35194SMichael Kruse generateScalarStores(Stmt, LTS, BBMap, NewAccesses); 357514f6efaSJohannes Doerfert return CopyBB; 358514f6efaSJohannes Doerfert } 359514f6efaSJohannes Doerfert 360514f6efaSJohannes Doerfert void BlockGenerator::copyBB(ScopStmt &Stmt, BasicBlock *BB, BasicBlock *CopyBB, 361bc132607STobias Grosser ValueMapT &BBMap, LoopToScevMapT <S, 3622d1ed0bfSTobias Grosser isl_id_to_ast_expr *NewAccesses) { 363ecff11dcSJohannes Doerfert EntryBB = &CopyBB->getParent()->getEntryBlock(); 364ecff11dcSJohannes Doerfert 36591f5b262STobias Grosser for (Instruction &Inst : *BB) 366bc132607STobias Grosser copyInstruction(Stmt, &Inst, BBMap, LTS, NewAccesses); 367ecff11dcSJohannes Doerfert } 368ecff11dcSJohannes Doerfert 36964c0ff41STobias Grosser Value *BlockGenerator::getOrCreateAlloca(Value *ScalarBase, 370ecff11dcSJohannes Doerfert ScalarAllocaMapTy &Map, 3712985400aSTobias Grosser const char *NameExt) { 372ecff11dcSJohannes Doerfert // If no alloca was found create one and insert it in the entry block. 373e9cb5a09STobias Grosser if (!Map.count(ScalarBase)) { 374ecff11dcSJohannes Doerfert auto *Ty = ScalarBase->getType(); 375b09455deSTobias Grosser auto NewAddr = new AllocaInst(Ty, ScalarBase->getName() + NameExt); 37664c0ff41STobias Grosser EntryBB = &Builder.GetInsertBlock()->getParent()->getEntryBlock(); 377b8f58b53SDuncan P. N. Exon Smith NewAddr->insertBefore(&*EntryBB->getFirstInsertionPt()); 378e9cb5a09STobias Grosser Map[ScalarBase] = NewAddr; 379ecff11dcSJohannes Doerfert } 380ecff11dcSJohannes Doerfert 381e9cb5a09STobias Grosser auto Addr = Map[ScalarBase]; 382e9cb5a09STobias Grosser 3835c7f16beSTobias Grosser if (auto NewAddr = GlobalMap.lookup(Addr)) 3845c7f16beSTobias Grosser return NewAddr; 38564c0ff41STobias Grosser 386ecff11dcSJohannes Doerfert return Addr; 387ecff11dcSJohannes Doerfert } 388ecff11dcSJohannes Doerfert 389800e17a7SJohannes Doerfert Value *BlockGenerator::getOrCreateAlloca(const MemoryAccess &Access) { 3903216f854STobias Grosser assert(!Access.isArrayKind() && "Trying to get alloca for array kind"); 3913216f854STobias Grosser 392a535dff4STobias Grosser if (Access.isPHIKind()) 393b8d27aabSTobias Grosser return getOrCreatePHIAlloca(Access.getBaseAddr()); 394b8d27aabSTobias Grosser else 395b8d27aabSTobias Grosser return getOrCreateScalarAlloca(Access.getBaseAddr()); 396a4f0988dSTobias Grosser } 397a4f0988dSTobias Grosser 398a4f0988dSTobias Grosser Value *BlockGenerator::getOrCreateAlloca(const ScopArrayInfo *Array) { 3993216f854STobias Grosser assert(!Array->isArrayKind() && "Trying to get alloca for array kind"); 4003216f854STobias Grosser 401a535dff4STobias Grosser if (Array->isPHIKind()) 402a4f0988dSTobias Grosser return getOrCreatePHIAlloca(Array->getBasePtr()); 403f8d55f7eSTobias Grosser else 404a4f0988dSTobias Grosser return getOrCreateScalarAlloca(Array->getBasePtr()); 405f8d55f7eSTobias Grosser } 406f8d55f7eSTobias Grosser 407bc132607STobias Grosser Value *BlockGenerator::getOrCreateScalarAlloca(Value *ScalarBase) { 408bc132607STobias Grosser return getOrCreateAlloca(ScalarBase, ScalarMap, ".s2a"); 409b79a67dfSTobias Grosser } 410b79a67dfSTobias Grosser 411bc132607STobias Grosser Value *BlockGenerator::getOrCreatePHIAlloca(Value *ScalarBase) { 412bc132607STobias Grosser return getOrCreateAlloca(ScalarBase, PHIOpMap, ".phiops"); 413b79a67dfSTobias Grosser } 414b79a67dfSTobias Grosser 41538a012c4SJohannes Doerfert void BlockGenerator::handleOutsideUsers(const Scop &S, Instruction *Inst) { 4162985400aSTobias Grosser // If there are escape users we get the alloca for this instruction and put it 4172985400aSTobias Grosser // in the EscapeMap for later finalization. Lastly, if the instruction was 4182985400aSTobias Grosser // copied multiple times we already did this and can exit. 419acb6ade7SMichael Kruse if (EscapeMap.count(Inst)) 420acb6ade7SMichael Kruse return; 421e69e1141SJohannes Doerfert 422ecff11dcSJohannes Doerfert EscapeUserVectorTy EscapeUsers; 423ecff11dcSJohannes Doerfert for (User *U : Inst->users()) { 424ecff11dcSJohannes Doerfert 425ecff11dcSJohannes Doerfert // Non-instruction user will never escape. 426ecff11dcSJohannes Doerfert Instruction *UI = dyn_cast<Instruction>(U); 427ecff11dcSJohannes Doerfert if (!UI) 428ecff11dcSJohannes Doerfert continue; 429ecff11dcSJohannes Doerfert 430952b5304SJohannes Doerfert if (S.contains(UI)) 431ecff11dcSJohannes Doerfert continue; 432ecff11dcSJohannes Doerfert 433ecff11dcSJohannes Doerfert EscapeUsers.push_back(UI); 434ecff11dcSJohannes Doerfert } 435ecff11dcSJohannes Doerfert 436ecff11dcSJohannes Doerfert // Exit if no escape uses were found. 437ecff11dcSJohannes Doerfert if (EscapeUsers.empty()) 438ecff11dcSJohannes Doerfert return; 439ecff11dcSJohannes Doerfert 440ecff11dcSJohannes Doerfert // Get or create an escape alloca for this instruction. 44138a012c4SJohannes Doerfert auto *ScalarAddr = getOrCreateScalarAlloca(Inst); 442ecff11dcSJohannes Doerfert 443ecff11dcSJohannes Doerfert // Remember that this instruction has escape uses and the escape alloca. 444ecff11dcSJohannes Doerfert EscapeMap[Inst] = std::make_pair(ScalarAddr, std::move(EscapeUsers)); 445ecff11dcSJohannes Doerfert } 446ecff11dcSJohannes Doerfert 4472fa35194SMichael Kruse void BlockGenerator::generateScalarLoads( 4482fa35194SMichael Kruse ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 4492fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 450225f0d1eSMichael Kruse for (MemoryAccess *MA : Stmt) { 4512fa35194SMichael Kruse if (MA->isOriginalArrayKind() || MA->isWrite()) 452ecff11dcSJohannes Doerfert continue; 453ecff11dcSJohannes Doerfert 45477394f13SMichael Kruse #ifndef NDEBUG 45577394f13SMichael Kruse auto *StmtDom = Stmt.getDomain(); 45677394f13SMichael Kruse auto *AccDom = isl_map_domain(MA->getAccessRelation()); 45777394f13SMichael Kruse assert(isl_set_is_subset(StmtDom, AccDom) && 45877394f13SMichael Kruse "Scalar must be loaded in all statement instances"); 45977394f13SMichael Kruse isl_set_free(StmtDom); 46077394f13SMichael Kruse isl_set_free(AccDom); 46177394f13SMichael Kruse #endif 46277394f13SMichael Kruse 4632fa35194SMichael Kruse auto *Address = 4642fa35194SMichael Kruse getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses); 465eac9726eSMichael Kruse assert((!isa<Instruction>(Address) || 466eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Address)->getParent(), 467eac9726eSMichael Kruse Builder.GetInsertBlock())) && 468eac9726eSMichael Kruse "Domination violation"); 469e2bccbbfSMichael Kruse BBMap[MA->getBaseAddr()] = 4702fc50df9STobias Grosser Builder.CreateLoad(Address, Address->getName() + ".reload"); 471ecff11dcSJohannes Doerfert } 472ecff11dcSJohannes Doerfert } 473ecff11dcSJohannes Doerfert 4742fa35194SMichael Kruse void BlockGenerator::generateScalarStores( 4752fa35194SMichael Kruse ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 4762fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 477f2cdd144STobias Grosser Loop *L = LI.getLoopFor(Stmt.getBasicBlock()); 478ecff11dcSJohannes Doerfert 47921a059afSTobias Grosser assert(Stmt.isBlockStmt() && 48021a059afSTobias Grosser "Region statements need to use the generateScalarStores() function in " 48121a059afSTobias Grosser "the RegionGenerator"); 482ecff11dcSJohannes Doerfert 483ecff11dcSJohannes Doerfert for (MemoryAccess *MA : Stmt) { 4842fa35194SMichael Kruse if (MA->isOriginalArrayKind() || MA->isRead()) 485ecff11dcSJohannes Doerfert continue; 486ecff11dcSJohannes Doerfert 48777394f13SMichael Kruse #ifndef NDEBUG 48877394f13SMichael Kruse auto *StmtDom = Stmt.getDomain(); 48977394f13SMichael Kruse auto *AccDom = isl_map_domain(MA->getAccessRelation()); 49077394f13SMichael Kruse assert(isl_set_is_subset(StmtDom, AccDom) && 49177394f13SMichael Kruse "Scalar must be stored in all statement instances"); 49277394f13SMichael Kruse isl_set_free(StmtDom); 49377394f13SMichael Kruse isl_set_free(AccDom); 49477394f13SMichael Kruse #endif 49577394f13SMichael Kruse 496d86f2157SJohannes Doerfert Value *Val = MA->getAccessValue(); 497ee6a4fc6SMichael Kruse if (MA->isAnyPHIKind()) { 498ee6a4fc6SMichael Kruse assert(MA->getIncoming().size() >= 1 && 499ee6a4fc6SMichael Kruse "Block statements have exactly one exiting block, or multiple but " 500ee6a4fc6SMichael Kruse "with same incoming block and value"); 501ee6a4fc6SMichael Kruse assert(std::all_of(MA->getIncoming().begin(), MA->getIncoming().end(), 502ee6a4fc6SMichael Kruse [&](std::pair<BasicBlock *, Value *> p) -> bool { 503ee6a4fc6SMichael Kruse return p.first == Stmt.getBasicBlock(); 504ee6a4fc6SMichael Kruse }) && 505ee6a4fc6SMichael Kruse "Incoming block must be statement's block"); 506ee6a4fc6SMichael Kruse Val = MA->getIncoming()[0].second; 507ee6a4fc6SMichael Kruse } 5082fa35194SMichael Kruse auto Address = 5092fa35194SMichael Kruse getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses); 510d86f2157SJohannes Doerfert 511f2cdd144STobias Grosser Val = getNewValue(Stmt, Val, BBMap, LTS, L); 512eac9726eSMichael Kruse assert((!isa<Instruction>(Val) || 513eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Val)->getParent(), 514eac9726eSMichael Kruse Builder.GetInsertBlock())) && 515eac9726eSMichael Kruse "Domination violation"); 516eac9726eSMichael Kruse assert((!isa<Instruction>(Address) || 517eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Address)->getParent(), 518eac9726eSMichael Kruse Builder.GetInsertBlock())) && 519eac9726eSMichael Kruse "Domination violation"); 52092245228STobias Grosser Builder.CreateStore(Val, Address); 521ecff11dcSJohannes Doerfert } 522ecff11dcSJohannes Doerfert } 523ecff11dcSJohannes Doerfert 524c0091a77STobias Grosser void BlockGenerator::createScalarInitialization(Scop &S) { 525ef74443cSJohannes Doerfert BasicBlock *ExitBB = S.getExit(); 526acf80064SEli Friedman BasicBlock *PreEntryBB = S.getEnteringBlock(); 527188542fdSJohannes Doerfert 528acf80064SEli Friedman Builder.SetInsertPoint(&*StartBlock->begin()); 529ecff11dcSJohannes Doerfert 530d7754a12SRoman Gareev for (auto &Array : S.arrays()) { 531c0091a77STobias Grosser if (Array->getNumberOfDimensions() != 0) 532c0091a77STobias Grosser continue; 533a535dff4STobias Grosser if (Array->isPHIKind()) { 534c0091a77STobias Grosser // For PHI nodes, the only values we need to store are the ones that 535c0091a77STobias Grosser // reach the PHI node from outside the region. In general there should 536c0091a77STobias Grosser // only be one such incoming edge and this edge should enter through 537acf80064SEli Friedman // 'PreEntryBB'. 538c0091a77STobias Grosser auto PHI = cast<PHINode>(Array->getBasePtr()); 539ecff11dcSJohannes Doerfert 540c0091a77STobias Grosser for (auto BI = PHI->block_begin(), BE = PHI->block_end(); BI != BE; BI++) 541acf80064SEli Friedman if (!S.contains(*BI) && *BI != PreEntryBB) 542c0091a77STobias Grosser llvm_unreachable("Incoming edges from outside the scop should always " 543acf80064SEli Friedman "come from PreEntryBB"); 544c0091a77STobias Grosser 545acf80064SEli Friedman int Idx = PHI->getBasicBlockIndex(PreEntryBB); 546c0091a77STobias Grosser if (Idx < 0) 547ecff11dcSJohannes Doerfert continue; 548ecff11dcSJohannes Doerfert 549c0091a77STobias Grosser Value *ScalarValue = PHI->getIncomingValue(Idx); 550ecff11dcSJohannes Doerfert 551bc132607STobias Grosser Builder.CreateStore(ScalarValue, getOrCreatePHIAlloca(PHI)); 552c0091a77STobias Grosser continue; 553c0091a77STobias Grosser } 554c0091a77STobias Grosser 555c0091a77STobias Grosser auto *Inst = dyn_cast<Instruction>(Array->getBasePtr()); 556c0091a77STobias Grosser 557952b5304SJohannes Doerfert if (Inst && S.contains(Inst)) 558c0091a77STobias Grosser continue; 559c0091a77STobias Grosser 560188542fdSJohannes Doerfert // PHI nodes that are not marked as such in their SAI object are either exit 561188542fdSJohannes Doerfert // PHI nodes we model as common scalars but without initialization, or 562188542fdSJohannes Doerfert // incoming phi nodes that need to be initialized. Check if the first is the 563188542fdSJohannes Doerfert // case for Inst and do not create and initialize memory if so. 564188542fdSJohannes Doerfert if (auto *PHI = dyn_cast_or_null<PHINode>(Inst)) 565188542fdSJohannes Doerfert if (!S.hasSingleExitEdge() && PHI->getBasicBlockIndex(ExitBB) >= 0) 566717b8667SJohannes Doerfert continue; 567717b8667SJohannes Doerfert 568c0091a77STobias Grosser Builder.CreateStore(Array->getBasePtr(), 569bc132607STobias Grosser getOrCreateScalarAlloca(Array->getBasePtr())); 570ecff11dcSJohannes Doerfert } 571ecff11dcSJohannes Doerfert } 572ecff11dcSJohannes Doerfert 573ef74443cSJohannes Doerfert void BlockGenerator::createScalarFinalization(Scop &S) { 574ecff11dcSJohannes Doerfert // The exit block of the __unoptimized__ region. 575ef74443cSJohannes Doerfert BasicBlock *ExitBB = S.getExitingBlock(); 576ecff11dcSJohannes Doerfert // The merge block __just after__ the region and the optimized region. 577ef74443cSJohannes Doerfert BasicBlock *MergeBB = S.getExit(); 578ecff11dcSJohannes Doerfert 579ecff11dcSJohannes Doerfert // The exit block of the __optimized__ region. 580ecff11dcSJohannes Doerfert BasicBlock *OptExitBB = *(pred_begin(MergeBB)); 581ecff11dcSJohannes Doerfert if (OptExitBB == ExitBB) 582ecff11dcSJohannes Doerfert OptExitBB = *(++pred_begin(MergeBB)); 583ecff11dcSJohannes Doerfert 584ecff11dcSJohannes Doerfert Builder.SetInsertPoint(OptExitBB->getTerminator()); 585ecff11dcSJohannes Doerfert for (const auto &EscapeMapping : EscapeMap) { 586ecff11dcSJohannes Doerfert // Extract the escaping instruction and the escaping users as well as the 587ecff11dcSJohannes Doerfert // alloca the instruction was demoted to. 588fbde4355SMichael Kruse Instruction *EscapeInst = EscapeMapping.first; 589fbde4355SMichael Kruse const auto &EscapeMappingValue = EscapeMapping.second; 590ecff11dcSJohannes Doerfert const EscapeUserVectorTy &EscapeUsers = EscapeMappingValue.second; 59164c0ff41STobias Grosser Value *ScalarAddr = EscapeMappingValue.first; 592ecff11dcSJohannes Doerfert 593ecff11dcSJohannes Doerfert // Reload the demoted instruction in the optimized version of the SCoP. 594d8b6ad25SJohannes Doerfert Value *EscapeInstReload = 595ecff11dcSJohannes Doerfert Builder.CreateLoad(ScalarAddr, EscapeInst->getName() + ".final_reload"); 596d8b6ad25SJohannes Doerfert EscapeInstReload = 597d8b6ad25SJohannes Doerfert Builder.CreateBitOrPointerCast(EscapeInstReload, EscapeInst->getType()); 598ecff11dcSJohannes Doerfert 599ecff11dcSJohannes Doerfert // Create the merge PHI that merges the optimized and unoptimized version. 600ecff11dcSJohannes Doerfert PHINode *MergePHI = PHINode::Create(EscapeInst->getType(), 2, 601ecff11dcSJohannes Doerfert EscapeInst->getName() + ".merge"); 602b8f58b53SDuncan P. N. Exon Smith MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt()); 603ecff11dcSJohannes Doerfert 604ecff11dcSJohannes Doerfert // Add the respective values to the merge PHI. 605ecff11dcSJohannes Doerfert MergePHI->addIncoming(EscapeInstReload, OptExitBB); 606ecff11dcSJohannes Doerfert MergePHI->addIncoming(EscapeInst, ExitBB); 607ecff11dcSJohannes Doerfert 608ecff11dcSJohannes Doerfert // The information of scalar evolution about the escaping instruction needs 609ecff11dcSJohannes Doerfert // to be revoked so the new merged instruction will be used. 610ecff11dcSJohannes Doerfert if (SE.isSCEVable(EscapeInst->getType())) 611ecff11dcSJohannes Doerfert SE.forgetValue(EscapeInst); 612ecff11dcSJohannes Doerfert 613ecff11dcSJohannes Doerfert // Replace all uses of the demoted instruction with the merge PHI. 614ecff11dcSJohannes Doerfert for (Instruction *EUser : EscapeUsers) 615ecff11dcSJohannes Doerfert EUser->replaceUsesOfWith(EscapeInst, MergePHI); 616ecff11dcSJohannes Doerfert } 617ecff11dcSJohannes Doerfert } 618ecff11dcSJohannes Doerfert 619ffa2446fSTobias Grosser void BlockGenerator::findOutsideUsers(Scop &S) { 620d7754a12SRoman Gareev for (auto &Array : S.arrays()) { 621ffa2446fSTobias Grosser 622ffa2446fSTobias Grosser if (Array->getNumberOfDimensions() != 0) 623ffa2446fSTobias Grosser continue; 624ffa2446fSTobias Grosser 625a535dff4STobias Grosser if (Array->isPHIKind()) 626ffa2446fSTobias Grosser continue; 627ffa2446fSTobias Grosser 628ffa2446fSTobias Grosser auto *Inst = dyn_cast<Instruction>(Array->getBasePtr()); 629ffa2446fSTobias Grosser 630ffa2446fSTobias Grosser if (!Inst) 631ffa2446fSTobias Grosser continue; 632ffa2446fSTobias Grosser 633ffa2446fSTobias Grosser // Scop invariant hoisting moves some of the base pointers out of the scop. 634ffa2446fSTobias Grosser // We can ignore these, as the invariant load hoisting already registers the 635ffa2446fSTobias Grosser // relevant outside users. 636952b5304SJohannes Doerfert if (!S.contains(Inst)) 637ffa2446fSTobias Grosser continue; 638ffa2446fSTobias Grosser 63938a012c4SJohannes Doerfert handleOutsideUsers(S, Inst); 640ffa2446fSTobias Grosser } 641ffa2446fSTobias Grosser } 642ffa2446fSTobias Grosser 64327d742daSTobias Grosser void BlockGenerator::createExitPHINodeMerges(Scop &S) { 64427d742daSTobias Grosser if (S.hasSingleExitEdge()) 64527d742daSTobias Grosser return; 64627d742daSTobias Grosser 647ef74443cSJohannes Doerfert auto *ExitBB = S.getExitingBlock(); 648ef74443cSJohannes Doerfert auto *MergeBB = S.getExit(); 64927d742daSTobias Grosser auto *AfterMergeBB = MergeBB->getSingleSuccessor(); 65027d742daSTobias Grosser BasicBlock *OptExitBB = *(pred_begin(MergeBB)); 65127d742daSTobias Grosser if (OptExitBB == ExitBB) 65227d742daSTobias Grosser OptExitBB = *(++pred_begin(MergeBB)); 65327d742daSTobias Grosser 65427d742daSTobias Grosser Builder.SetInsertPoint(OptExitBB->getTerminator()); 65527d742daSTobias Grosser 656d7754a12SRoman Gareev for (auto &SAI : S.arrays()) { 65727d742daSTobias Grosser auto *Val = SAI->getBasePtr(); 65827d742daSTobias Grosser 659faedfcbfSMichael Kruse // Only Value-like scalars need a merge PHI. Exit block PHIs receive either 660faedfcbfSMichael Kruse // the original PHI's value or the reloaded incoming values from the 661faedfcbfSMichael Kruse // generated code. An llvm::Value is merged between the original code's 662faedfcbfSMichael Kruse // value or the generated one. 663fa53c86dSMichael Kruse if (!SAI->isExitPHIKind()) 664faedfcbfSMichael Kruse continue; 665faedfcbfSMichael Kruse 66627d742daSTobias Grosser PHINode *PHI = dyn_cast<PHINode>(Val); 66727d742daSTobias Grosser if (!PHI) 66827d742daSTobias Grosser continue; 66927d742daSTobias Grosser 670a3f6edaeSTobias Grosser if (PHI->getParent() != AfterMergeBB) 67127d742daSTobias Grosser continue; 67227d742daSTobias Grosser 67327d742daSTobias Grosser std::string Name = PHI->getName(); 67427d742daSTobias Grosser Value *ScalarAddr = getOrCreateScalarAlloca(PHI); 67527d742daSTobias Grosser Value *Reload = Builder.CreateLoad(ScalarAddr, Name + ".ph.final_reload"); 67627d742daSTobias Grosser Reload = Builder.CreateBitOrPointerCast(Reload, PHI->getType()); 67727d742daSTobias Grosser Value *OriginalValue = PHI->getIncomingValueForBlock(MergeBB); 678faedfcbfSMichael Kruse assert((!isa<Instruction>(OriginalValue) || 679faedfcbfSMichael Kruse cast<Instruction>(OriginalValue)->getParent() != MergeBB) && 680faedfcbfSMichael Kruse "Original value must no be one we just generated."); 68127d742daSTobias Grosser auto *MergePHI = PHINode::Create(PHI->getType(), 2, Name + ".ph.merge"); 682b8f58b53SDuncan P. N. Exon Smith MergePHI->insertBefore(&*MergeBB->getFirstInsertionPt()); 68327d742daSTobias Grosser MergePHI->addIncoming(Reload, OptExitBB); 68427d742daSTobias Grosser MergePHI->addIncoming(OriginalValue, ExitBB); 68527d742daSTobias Grosser int Idx = PHI->getBasicBlockIndex(MergeBB); 68627d742daSTobias Grosser PHI->setIncomingValue(Idx, MergePHI); 68727d742daSTobias Grosser } 68827d742daSTobias Grosser } 68927d742daSTobias Grosser 6901c184409STobias Grosser void BlockGenerator::invalidateScalarEvolution(Scop &S) { 6911c184409STobias Grosser for (auto &Stmt : S) 692b3224adfSRoman Gareev if (Stmt.isCopyStmt()) 693b3224adfSRoman Gareev continue; 694b3224adfSRoman Gareev else if (Stmt.isBlockStmt()) 6951c184409STobias Grosser for (auto &Inst : *Stmt.getBasicBlock()) 6961c184409STobias Grosser SE.forgetValue(&Inst); 6971c184409STobias Grosser else if (Stmt.isRegionStmt()) 6981c184409STobias Grosser for (auto *BB : Stmt.getRegion()->blocks()) 6991c184409STobias Grosser for (auto &Inst : *BB) 7001c184409STobias Grosser SE.forgetValue(&Inst); 7011c184409STobias Grosser else 7021c184409STobias Grosser llvm_unreachable("Unexpected statement type found"); 7031c184409STobias Grosser } 7041c184409STobias Grosser 705ffa2446fSTobias Grosser void BlockGenerator::finalizeSCoP(Scop &S) { 706ffa2446fSTobias Grosser findOutsideUsers(S); 707c0091a77STobias Grosser createScalarInitialization(S); 70827d742daSTobias Grosser createExitPHINodeMerges(S); 709ef74443cSJohannes Doerfert createScalarFinalization(S); 7101c184409STobias Grosser invalidateScalarEvolution(S); 7113b11a16aSHongbin Zheng } 7123b11a16aSHongbin Zheng 713be9c9117SJohannes Doerfert VectorBlockGenerator::VectorBlockGenerator(BlockGenerator &BlockGen, 714be9c9117SJohannes Doerfert std::vector<LoopToScevMapT> &VLTS, 715be9c9117SJohannes Doerfert isl_map *Schedule) 716bc132607STobias Grosser : BlockGenerator(BlockGen), VLTS(VLTS), Schedule(Schedule) { 717a00a0291SSebastian Pop assert(Schedule && "No statement domain provided"); 7183b11a16aSHongbin Zheng } 7193b11a16aSHongbin Zheng 7202f1acac6STobias Grosser Value *VectorBlockGenerator::getVectorValue(ScopStmt &Stmt, Value *Old, 721e602a076STobias Grosser ValueMapT &VectorMap, 722e602a076STobias Grosser VectorValueMapT &ScalarMaps, 723e602a076STobias Grosser Loop *L) { 724fe11e287SHongbin Zheng if (Value *NewValue = VectorMap.lookup(Old)) 725fe11e287SHongbin Zheng return NewValue; 7263b11a16aSHongbin Zheng 7273b11a16aSHongbin Zheng int Width = getVectorWidth(); 7283b11a16aSHongbin Zheng 7293b11a16aSHongbin Zheng Value *Vector = UndefValue::get(VectorType::get(Old->getType(), Width)); 7303b11a16aSHongbin Zheng 7313b11a16aSHongbin Zheng for (int Lane = 0; Lane < Width; Lane++) 732c14582f2STobias Grosser Vector = Builder.CreateInsertElement( 733bc132607STobias Grosser Vector, getNewValue(Stmt, Old, ScalarMaps[Lane], VLTS[Lane], L), 7347242ad92STobias Grosser Builder.getInt32(Lane)); 7353b11a16aSHongbin Zheng 7363b11a16aSHongbin Zheng VectorMap[Old] = Vector; 7373b11a16aSHongbin Zheng 7383b11a16aSHongbin Zheng return Vector; 7393b11a16aSHongbin Zheng } 7403b11a16aSHongbin Zheng 7413b11a16aSHongbin Zheng Type *VectorBlockGenerator::getVectorPtrTy(const Value *Val, int Width) { 7423b11a16aSHongbin Zheng PointerType *PointerTy = dyn_cast<PointerType>(Val->getType()); 7433b11a16aSHongbin Zheng assert(PointerTy && "PointerType expected"); 7443b11a16aSHongbin Zheng 7453b11a16aSHongbin Zheng Type *ScalarType = PointerTy->getElementType(); 7463b11a16aSHongbin Zheng VectorType *VectorType = VectorType::get(ScalarType, Width); 7473b11a16aSHongbin Zheng 7483b11a16aSHongbin Zheng return PointerType::getUnqual(VectorType); 7493b11a16aSHongbin Zheng } 7503b11a16aSHongbin Zheng 751be9c9117SJohannes Doerfert Value *VectorBlockGenerator::generateStrideOneLoad( 7522f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps, 7532d1ed0bfSTobias Grosser __isl_keep isl_id_to_ast_expr *NewAccesses, bool NegativeStride = false) { 7540dd463faSTobias Grosser unsigned VectorWidth = getVectorWidth(); 7559646e3feSTobias Grosser auto *Pointer = Load->getPointerOperand(); 7560dd463faSTobias Grosser Type *VectorPtrType = getVectorPtrTy(Pointer, VectorWidth); 7570dd463faSTobias Grosser unsigned Offset = NegativeStride ? VectorWidth - 1 : 0; 7580dd463faSTobias Grosser 7598f25b0cbSMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[Offset], 760bc132607STobias Grosser VLTS[Offset], NewAccesses); 761c14582f2STobias Grosser Value *VectorPtr = 762c14582f2STobias Grosser Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr"); 763c14582f2STobias Grosser LoadInst *VecLoad = 764c14582f2STobias Grosser Builder.CreateLoad(VectorPtr, Load->getName() + "_p_vec_full"); 7653b11a16aSHongbin Zheng if (!Aligned) 7663b11a16aSHongbin Zheng VecLoad->setAlignment(8); 7673b11a16aSHongbin Zheng 7680dd463faSTobias Grosser if (NegativeStride) { 7690dd463faSTobias Grosser SmallVector<Constant *, 16> Indices; 7700dd463faSTobias Grosser for (int i = VectorWidth - 1; i >= 0; i--) 7710dd463faSTobias Grosser Indices.push_back(ConstantInt::get(Builder.getInt32Ty(), i)); 7720dd463faSTobias Grosser Constant *SV = llvm::ConstantVector::get(Indices); 7730dd463faSTobias Grosser Value *RevVecLoad = Builder.CreateShuffleVector( 7740dd463faSTobias Grosser VecLoad, VecLoad, SV, Load->getName() + "_reverse"); 7750dd463faSTobias Grosser return RevVecLoad; 7760dd463faSTobias Grosser } 7770dd463faSTobias Grosser 7783b11a16aSHongbin Zheng return VecLoad; 7793b11a16aSHongbin Zheng } 7803b11a16aSHongbin Zheng 7812d1ed0bfSTobias Grosser Value *VectorBlockGenerator::generateStrideZeroLoad( 7822f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, ValueMapT &BBMap, 7832d1ed0bfSTobias Grosser __isl_keep isl_id_to_ast_expr *NewAccesses) { 7849646e3feSTobias Grosser auto *Pointer = Load->getPointerOperand(); 7853b11a16aSHongbin Zheng Type *VectorPtrType = getVectorPtrTy(Pointer, 1); 78670131d34SMichael Kruse Value *NewPointer = 78770131d34SMichael Kruse generateLocationAccessed(Stmt, Load, BBMap, VLTS[0], NewAccesses); 7883b11a16aSHongbin Zheng Value *VectorPtr = Builder.CreateBitCast(NewPointer, VectorPtrType, 7893b11a16aSHongbin Zheng Load->getName() + "_p_vec_p"); 790c14582f2STobias Grosser LoadInst *ScalarLoad = 791c14582f2STobias Grosser Builder.CreateLoad(VectorPtr, Load->getName() + "_p_splat_one"); 7923b11a16aSHongbin Zheng 7933b11a16aSHongbin Zheng if (!Aligned) 7943b11a16aSHongbin Zheng ScalarLoad->setAlignment(8); 7953b11a16aSHongbin Zheng 796c14582f2STobias Grosser Constant *SplatVector = Constant::getNullValue( 797c14582f2STobias Grosser VectorType::get(Builder.getInt32Ty(), getVectorWidth())); 7983b11a16aSHongbin Zheng 799c14582f2STobias Grosser Value *VectorLoad = Builder.CreateShuffleVector( 800c14582f2STobias Grosser ScalarLoad, ScalarLoad, SplatVector, Load->getName() + "_p_splat"); 8013b11a16aSHongbin Zheng return VectorLoad; 8023b11a16aSHongbin Zheng } 8033b11a16aSHongbin Zheng 804be9c9117SJohannes Doerfert Value *VectorBlockGenerator::generateUnknownStrideLoad( 8052f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, VectorValueMapT &ScalarMaps, 80609e3697fSJohannes Doerfert __isl_keep isl_id_to_ast_expr *NewAccesses) { 8073b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 8089646e3feSTobias Grosser auto *Pointer = Load->getPointerOperand(); 8093b11a16aSHongbin Zheng VectorType *VectorType = VectorType::get( 8103b11a16aSHongbin Zheng dyn_cast<PointerType>(Pointer->getType())->getElementType(), VectorWidth); 8113b11a16aSHongbin Zheng 8123b11a16aSHongbin Zheng Value *Vector = UndefValue::get(VectorType); 8133b11a16aSHongbin Zheng 8143b11a16aSHongbin Zheng for (int i = 0; i < VectorWidth; i++) { 81570131d34SMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Load, ScalarMaps[i], 81670131d34SMichael Kruse VLTS[i], NewAccesses); 817c14582f2STobias Grosser Value *ScalarLoad = 818c14582f2STobias Grosser Builder.CreateLoad(NewPointer, Load->getName() + "_p_scalar_"); 819c14582f2STobias Grosser Vector = Builder.CreateInsertElement( 820c14582f2STobias Grosser Vector, ScalarLoad, Builder.getInt32(i), Load->getName() + "_p_vec_"); 8213b11a16aSHongbin Zheng } 8223b11a16aSHongbin Zheng 8233b11a16aSHongbin Zheng return Vector; 8243b11a16aSHongbin Zheng } 8253b11a16aSHongbin Zheng 8262d1ed0bfSTobias Grosser void VectorBlockGenerator::generateLoad( 8272f1acac6STobias Grosser ScopStmt &Stmt, LoadInst *Load, ValueMapT &VectorMap, 8282d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 829c1db67e2SJohannes Doerfert if (Value *PreloadLoad = GlobalMap.lookup(Load)) { 830c1db67e2SJohannes Doerfert VectorMap[Load] = Builder.CreateVectorSplat(getVectorWidth(), PreloadLoad, 831c1db67e2SJohannes Doerfert Load->getName() + "_p"); 832c1db67e2SJohannes Doerfert return; 833c1db67e2SJohannes Doerfert } 834c1db67e2SJohannes Doerfert 8352873645cSTobias Grosser if (!VectorType::isValidElementType(Load->getType())) { 8363b11a16aSHongbin Zheng for (int i = 0; i < getVectorWidth(); i++) 837bc132607STobias Grosser ScalarMaps[i][Load] = 838888ab551SMichael Kruse generateArrayLoad(Stmt, Load, ScalarMaps[i], VLTS[i], NewAccesses); 8393b11a16aSHongbin Zheng return; 8403b11a16aSHongbin Zheng } 8413b11a16aSHongbin Zheng 842184a4926STobias Grosser const MemoryAccess &Access = Stmt.getArrayAccessFor(Load); 8433b11a16aSHongbin Zheng 84495493984STobias Grosser // Make sure we have scalar values available to access the pointer to 84595493984STobias Grosser // the data location. 84695493984STobias Grosser extractScalarValues(Load, VectorMap, ScalarMaps); 84795493984STobias Grosser 8483b11a16aSHongbin Zheng Value *NewLoad; 849a00a0291SSebastian Pop if (Access.isStrideZero(isl_map_copy(Schedule))) 8502d1ed0bfSTobias Grosser NewLoad = generateStrideZeroLoad(Stmt, Load, ScalarMaps[0], NewAccesses); 851a00a0291SSebastian Pop else if (Access.isStrideOne(isl_map_copy(Schedule))) 8522d1ed0bfSTobias Grosser NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses); 8530dd463faSTobias Grosser else if (Access.isStrideX(isl_map_copy(Schedule), -1)) 8542d1ed0bfSTobias Grosser NewLoad = generateStrideOneLoad(Stmt, Load, ScalarMaps, NewAccesses, true); 8553b11a16aSHongbin Zheng else 8562d1ed0bfSTobias Grosser NewLoad = generateUnknownStrideLoad(Stmt, Load, ScalarMaps, NewAccesses); 8573b11a16aSHongbin Zheng 8583b11a16aSHongbin Zheng VectorMap[Load] = NewLoad; 8593b11a16aSHongbin Zheng } 8603b11a16aSHongbin Zheng 8612f1acac6STobias Grosser void VectorBlockGenerator::copyUnaryInst(ScopStmt &Stmt, UnaryInstruction *Inst, 8623b11a16aSHongbin Zheng ValueMapT &VectorMap, 8633b11a16aSHongbin Zheng VectorValueMapT &ScalarMaps) { 8643b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 865be9c9117SJohannes Doerfert Value *NewOperand = getVectorValue(Stmt, Inst->getOperand(0), VectorMap, 8662c3ffc04SJohannes Doerfert ScalarMaps, getLoopForStmt(Stmt)); 8673b11a16aSHongbin Zheng 8683b11a16aSHongbin Zheng assert(isa<CastInst>(Inst) && "Can not generate vector code for instruction"); 8693b11a16aSHongbin Zheng 8703b11a16aSHongbin Zheng const CastInst *Cast = dyn_cast<CastInst>(Inst); 8713b11a16aSHongbin Zheng VectorType *DestType = VectorType::get(Inst->getType(), VectorWidth); 8723b11a16aSHongbin Zheng VectorMap[Inst] = Builder.CreateCast(Cast->getOpcode(), NewOperand, DestType); 8733b11a16aSHongbin Zheng } 8743b11a16aSHongbin Zheng 8752f1acac6STobias Grosser void VectorBlockGenerator::copyBinaryInst(ScopStmt &Stmt, BinaryOperator *Inst, 8763b11a16aSHongbin Zheng ValueMapT &VectorMap, 8773b11a16aSHongbin Zheng VectorValueMapT &ScalarMaps) { 8782c3ffc04SJohannes Doerfert Loop *L = getLoopForStmt(Stmt); 8793b11a16aSHongbin Zheng Value *OpZero = Inst->getOperand(0); 8803b11a16aSHongbin Zheng Value *OpOne = Inst->getOperand(1); 8813b11a16aSHongbin Zheng 8823b11a16aSHongbin Zheng Value *NewOpZero, *NewOpOne; 883be9c9117SJohannes Doerfert NewOpZero = getVectorValue(Stmt, OpZero, VectorMap, ScalarMaps, L); 884be9c9117SJohannes Doerfert NewOpOne = getVectorValue(Stmt, OpOne, VectorMap, ScalarMaps, L); 8853b11a16aSHongbin Zheng 8861bb59b0dSTobias Grosser Value *NewInst = Builder.CreateBinOp(Inst->getOpcode(), NewOpZero, NewOpOne, 8873b11a16aSHongbin Zheng Inst->getName() + "p_vec"); 8883b11a16aSHongbin Zheng VectorMap[Inst] = NewInst; 8893b11a16aSHongbin Zheng } 8903b11a16aSHongbin Zheng 8912d1ed0bfSTobias Grosser void VectorBlockGenerator::copyStore( 8922f1acac6STobias Grosser ScopStmt &Stmt, StoreInst *Store, ValueMapT &VectorMap, 8932d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 894184a4926STobias Grosser const MemoryAccess &Access = Stmt.getArrayAccessFor(Store); 8953b11a16aSHongbin Zheng 8969646e3feSTobias Grosser auto *Pointer = Store->getPointerOperand(); 897be9c9117SJohannes Doerfert Value *Vector = getVectorValue(Stmt, Store->getValueOperand(), VectorMap, 8982c3ffc04SJohannes Doerfert ScalarMaps, getLoopForStmt(Stmt)); 8993b11a16aSHongbin Zheng 90050fd7010STobias Grosser // Make sure we have scalar values available to access the pointer to 90150fd7010STobias Grosser // the data location. 90250fd7010STobias Grosser extractScalarValues(Store, VectorMap, ScalarMaps); 90350fd7010STobias Grosser 904a00a0291SSebastian Pop if (Access.isStrideOne(isl_map_copy(Schedule))) { 9051947f863SJohannes Doerfert Type *VectorPtrType = getVectorPtrTy(Pointer, getVectorWidth()); 90670131d34SMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[0], 90770131d34SMichael Kruse VLTS[0], NewAccesses); 9083b11a16aSHongbin Zheng 909c14582f2STobias Grosser Value *VectorPtr = 910c14582f2STobias Grosser Builder.CreateBitCast(NewPointer, VectorPtrType, "vector_ptr"); 9113b11a16aSHongbin Zheng StoreInst *Store = Builder.CreateStore(Vector, VectorPtr); 9123b11a16aSHongbin Zheng 9133b11a16aSHongbin Zheng if (!Aligned) 9143b11a16aSHongbin Zheng Store->setAlignment(8); 9153b11a16aSHongbin Zheng } else { 9163b11a16aSHongbin Zheng for (unsigned i = 0; i < ScalarMaps.size(); i++) { 9171bb59b0dSTobias Grosser Value *Scalar = Builder.CreateExtractElement(Vector, Builder.getInt32(i)); 91870131d34SMichael Kruse Value *NewPointer = generateLocationAccessed(Stmt, Store, ScalarMaps[i], 91970131d34SMichael Kruse VLTS[i], NewAccesses); 9203b11a16aSHongbin Zheng Builder.CreateStore(Scalar, NewPointer); 9213b11a16aSHongbin Zheng } 9223b11a16aSHongbin Zheng } 9233b11a16aSHongbin Zheng } 9243b11a16aSHongbin Zheng 9253b11a16aSHongbin Zheng bool VectorBlockGenerator::hasVectorOperands(const Instruction *Inst, 9263b11a16aSHongbin Zheng ValueMapT &VectorMap) { 92791f5b262STobias Grosser for (Value *Operand : Inst->operands()) 92891f5b262STobias Grosser if (VectorMap.count(Operand)) 9293b11a16aSHongbin Zheng return true; 9303b11a16aSHongbin Zheng return false; 9313b11a16aSHongbin Zheng } 9323b11a16aSHongbin Zheng 9333b11a16aSHongbin Zheng bool VectorBlockGenerator::extractScalarValues(const Instruction *Inst, 9343b11a16aSHongbin Zheng ValueMapT &VectorMap, 9353b11a16aSHongbin Zheng VectorValueMapT &ScalarMaps) { 9363b11a16aSHongbin Zheng bool HasVectorOperand = false; 9373b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 9383b11a16aSHongbin Zheng 93991f5b262STobias Grosser for (Value *Operand : Inst->operands()) { 94091f5b262STobias Grosser ValueMapT::iterator VecOp = VectorMap.find(Operand); 9413b11a16aSHongbin Zheng 9423b11a16aSHongbin Zheng if (VecOp == VectorMap.end()) 9433b11a16aSHongbin Zheng continue; 9443b11a16aSHongbin Zheng 9453b11a16aSHongbin Zheng HasVectorOperand = true; 9463b11a16aSHongbin Zheng Value *NewVector = VecOp->second; 9473b11a16aSHongbin Zheng 9483b11a16aSHongbin Zheng for (int i = 0; i < VectorWidth; ++i) { 9493b11a16aSHongbin Zheng ValueMapT &SM = ScalarMaps[i]; 9503b11a16aSHongbin Zheng 9513b11a16aSHongbin Zheng // If there is one scalar extracted, all scalar elements should have 9523b11a16aSHongbin Zheng // already been extracted by the code here. So no need to check for the 9532219d157STobias Grosser // existence of all of them. 95491f5b262STobias Grosser if (SM.count(Operand)) 9553b11a16aSHongbin Zheng break; 9563b11a16aSHongbin Zheng 95791f5b262STobias Grosser SM[Operand] = 95891f5b262STobias Grosser Builder.CreateExtractElement(NewVector, Builder.getInt32(i)); 9593b11a16aSHongbin Zheng } 9603b11a16aSHongbin Zheng } 9613b11a16aSHongbin Zheng 9623b11a16aSHongbin Zheng return HasVectorOperand; 9633b11a16aSHongbin Zheng } 9643b11a16aSHongbin Zheng 9652d1ed0bfSTobias Grosser void VectorBlockGenerator::copyInstScalarized( 9662f1acac6STobias Grosser ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap, 9672d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 9683b11a16aSHongbin Zheng bool HasVectorOperand; 9693b11a16aSHongbin Zheng int VectorWidth = getVectorWidth(); 9703b11a16aSHongbin Zheng 9713b11a16aSHongbin Zheng HasVectorOperand = extractScalarValues(Inst, VectorMap, ScalarMaps); 9723b11a16aSHongbin Zheng 9733b11a16aSHongbin Zheng for (int VectorLane = 0; VectorLane < getVectorWidth(); VectorLane++) 974be9c9117SJohannes Doerfert BlockGenerator::copyInstruction(Stmt, Inst, ScalarMaps[VectorLane], 975bc132607STobias Grosser VLTS[VectorLane], NewAccesses); 9763b11a16aSHongbin Zheng 9773b11a16aSHongbin Zheng if (!VectorType::isValidElementType(Inst->getType()) || !HasVectorOperand) 9783b11a16aSHongbin Zheng return; 9793b11a16aSHongbin Zheng 9803b11a16aSHongbin Zheng // Make the result available as vector value. 9813b11a16aSHongbin Zheng VectorType *VectorType = VectorType::get(Inst->getType(), VectorWidth); 9823b11a16aSHongbin Zheng Value *Vector = UndefValue::get(VectorType); 9833b11a16aSHongbin Zheng 9843b11a16aSHongbin Zheng for (int i = 0; i < VectorWidth; i++) 9853b11a16aSHongbin Zheng Vector = Builder.CreateInsertElement(Vector, ScalarMaps[i][Inst], 9863b11a16aSHongbin Zheng Builder.getInt32(i)); 9873b11a16aSHongbin Zheng 9883b11a16aSHongbin Zheng VectorMap[Inst] = Vector; 9893b11a16aSHongbin Zheng } 9903b11a16aSHongbin Zheng 991bc132607STobias Grosser int VectorBlockGenerator::getVectorWidth() { return VLTS.size(); } 9923b11a16aSHongbin Zheng 9932d1ed0bfSTobias Grosser void VectorBlockGenerator::copyInstruction( 9942f1acac6STobias Grosser ScopStmt &Stmt, Instruction *Inst, ValueMapT &VectorMap, 9952d1ed0bfSTobias Grosser VectorValueMapT &ScalarMaps, __isl_keep isl_id_to_ast_expr *NewAccesses) { 9963b11a16aSHongbin Zheng // Terminator instructions control the control flow. They are explicitly 9973b11a16aSHongbin Zheng // expressed in the clast and do not need to be copied. 9983b11a16aSHongbin Zheng if (Inst->isTerminator()) 9993b11a16aSHongbin Zheng return; 10003b11a16aSHongbin Zheng 10015dced269SJohannes Doerfert if (canSyntheziseInStmt(Stmt, Inst)) 1002e71c6ab5STobias Grosser return; 1003e71c6ab5STobias Grosser 10049646e3feSTobias Grosser if (auto *Load = dyn_cast<LoadInst>(Inst)) { 10052d1ed0bfSTobias Grosser generateLoad(Stmt, Load, VectorMap, ScalarMaps, NewAccesses); 10063b11a16aSHongbin Zheng return; 10073b11a16aSHongbin Zheng } 10083b11a16aSHongbin Zheng 10093b11a16aSHongbin Zheng if (hasVectorOperands(Inst, VectorMap)) { 10109646e3feSTobias Grosser if (auto *Store = dyn_cast<StoreInst>(Inst)) { 10112d1ed0bfSTobias Grosser copyStore(Stmt, Store, VectorMap, ScalarMaps, NewAccesses); 10123b11a16aSHongbin Zheng return; 10133b11a16aSHongbin Zheng } 10143b11a16aSHongbin Zheng 10159646e3feSTobias Grosser if (auto *Unary = dyn_cast<UnaryInstruction>(Inst)) { 1016be9c9117SJohannes Doerfert copyUnaryInst(Stmt, Unary, VectorMap, ScalarMaps); 10173b11a16aSHongbin Zheng return; 10183b11a16aSHongbin Zheng } 10193b11a16aSHongbin Zheng 10209646e3feSTobias Grosser if (auto *Binary = dyn_cast<BinaryOperator>(Inst)) { 1021be9c9117SJohannes Doerfert copyBinaryInst(Stmt, Binary, VectorMap, ScalarMaps); 10223b11a16aSHongbin Zheng return; 10233b11a16aSHongbin Zheng } 10243b11a16aSHongbin Zheng 10253b11a16aSHongbin Zheng // Falltrough: We generate scalar instructions, if we don't know how to 10263b11a16aSHongbin Zheng // generate vector code. 10273b11a16aSHongbin Zheng } 10283b11a16aSHongbin Zheng 10292d1ed0bfSTobias Grosser copyInstScalarized(Stmt, Inst, VectorMap, ScalarMaps, NewAccesses); 10303b11a16aSHongbin Zheng } 10313b11a16aSHongbin Zheng 1032a69d4f0dSTobias Grosser void VectorBlockGenerator::generateScalarVectorLoads( 1033a69d4f0dSTobias Grosser ScopStmt &Stmt, ValueMapT &VectorBlockMap) { 1034a69d4f0dSTobias Grosser for (MemoryAccess *MA : Stmt) { 1035a69d4f0dSTobias Grosser if (MA->isArrayKind() || MA->isWrite()) 1036a69d4f0dSTobias Grosser continue; 1037a69d4f0dSTobias Grosser 1038a69d4f0dSTobias Grosser auto *Address = getOrCreateAlloca(*MA); 1039a69d4f0dSTobias Grosser Type *VectorPtrType = getVectorPtrTy(Address, 1); 1040a69d4f0dSTobias Grosser Value *VectorPtr = Builder.CreateBitCast(Address, VectorPtrType, 1041a69d4f0dSTobias Grosser Address->getName() + "_p_vec_p"); 1042a69d4f0dSTobias Grosser auto *Val = Builder.CreateLoad(VectorPtr, Address->getName() + ".reload"); 1043a69d4f0dSTobias Grosser Constant *SplatVector = Constant::getNullValue( 1044a69d4f0dSTobias Grosser VectorType::get(Builder.getInt32Ty(), getVectorWidth())); 1045a69d4f0dSTobias Grosser 1046a69d4f0dSTobias Grosser Value *VectorVal = Builder.CreateShuffleVector( 1047a69d4f0dSTobias Grosser Val, Val, SplatVector, Address->getName() + "_p_splat"); 1048a69d4f0dSTobias Grosser VectorBlockMap[MA->getBaseAddr()] = VectorVal; 1049a69d4f0dSTobias Grosser } 1050a69d4f0dSTobias Grosser } 1051a69d4f0dSTobias Grosser 1052a69d4f0dSTobias Grosser void VectorBlockGenerator::verifyNoScalarStores(ScopStmt &Stmt) { 1053a69d4f0dSTobias Grosser for (MemoryAccess *MA : Stmt) { 1054a69d4f0dSTobias Grosser if (MA->isArrayKind() || MA->isRead()) 1055a69d4f0dSTobias Grosser continue; 1056a69d4f0dSTobias Grosser 1057a69d4f0dSTobias Grosser llvm_unreachable("Scalar stores not expected in vector loop"); 1058a69d4f0dSTobias Grosser } 1059a69d4f0dSTobias Grosser } 1060a69d4f0dSTobias Grosser 10612d1ed0bfSTobias Grosser void VectorBlockGenerator::copyStmt( 10622d1ed0bfSTobias Grosser ScopStmt &Stmt, __isl_keep isl_id_to_ast_expr *NewAccesses) { 106321a059afSTobias Grosser assert(Stmt.isBlockStmt() && 106421a059afSTobias Grosser "TODO: Only block statements can be copied by the vector block " 106521a059afSTobias Grosser "generator"); 1066275a1756SJohannes Doerfert 1067be9c9117SJohannes Doerfert BasicBlock *BB = Stmt.getBasicBlock(); 1068b8f58b53SDuncan P. N. Exon Smith BasicBlock *CopyBB = SplitBlock(Builder.GetInsertBlock(), 1069b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 10703b11a16aSHongbin Zheng CopyBB->setName("polly.stmt." + BB->getName()); 1071b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&CopyBB->front()); 10723b11a16aSHongbin Zheng 10733b11a16aSHongbin Zheng // Create two maps that store the mapping from the original instructions of 10743b11a16aSHongbin Zheng // the old basic block to their copies in the new basic block. Those maps 10753b11a16aSHongbin Zheng // are basic block local. 10763b11a16aSHongbin Zheng // 10773b11a16aSHongbin Zheng // As vector code generation is supported there is one map for scalar values 10783b11a16aSHongbin Zheng // and one for vector values. 10793b11a16aSHongbin Zheng // 10803b11a16aSHongbin Zheng // In case we just do scalar code generation, the vectorMap is not used and 10813b11a16aSHongbin Zheng // the scalarMap has just one dimension, which contains the mapping. 10823b11a16aSHongbin Zheng // 10833b11a16aSHongbin Zheng // In case vector code generation is done, an instruction may either appear 10843b11a16aSHongbin Zheng // in the vector map once (as it is calculating >vectorwidth< values at a 10853b11a16aSHongbin Zheng // time. Or (if the values are calculated using scalar operations), it 10863b11a16aSHongbin Zheng // appears once in every dimension of the scalarMap. 10873b11a16aSHongbin Zheng VectorValueMapT ScalarBlockMap(getVectorWidth()); 10883b11a16aSHongbin Zheng ValueMapT VectorBlockMap; 10893b11a16aSHongbin Zheng 1090a69d4f0dSTobias Grosser generateScalarVectorLoads(Stmt, VectorBlockMap); 1091a69d4f0dSTobias Grosser 109291f5b262STobias Grosser for (Instruction &Inst : *BB) 10932d1ed0bfSTobias Grosser copyInstruction(Stmt, &Inst, VectorBlockMap, ScalarBlockMap, NewAccesses); 1094a69d4f0dSTobias Grosser 1095a69d4f0dSTobias Grosser verifyNoScalarStores(Stmt); 10963b11a16aSHongbin Zheng } 1097275a1756SJohannes Doerfert 1098ecff11dcSJohannes Doerfert BasicBlock *RegionGenerator::repairDominance(BasicBlock *BB, 1099ecff11dcSJohannes Doerfert BasicBlock *BBCopy) { 1100514f6efaSJohannes Doerfert 1101514f6efaSJohannes Doerfert BasicBlock *BBIDom = DT.getNode(BB)->getIDom()->getBlock(); 1102514f6efaSJohannes Doerfert BasicBlock *BBCopyIDom = BlockMap.lookup(BBIDom); 1103514f6efaSJohannes Doerfert 1104514f6efaSJohannes Doerfert if (BBCopyIDom) 1105514f6efaSJohannes Doerfert DT.changeImmediateDominator(BBCopy, BBCopyIDom); 1106514f6efaSJohannes Doerfert 1107514f6efaSJohannes Doerfert return BBCopyIDom; 1108514f6efaSJohannes Doerfert } 1109514f6efaSJohannes Doerfert 1110f33c125dSMichael Kruse // This is to determine whether an llvm::Value (defined in @p BB) is usable when 1111f33c125dSMichael Kruse // leaving a subregion. The straight-forward DT.dominates(BB, R->getExitBlock()) 1112f33c125dSMichael Kruse // does not work in cases where the exit block has edges from outside the 1113f33c125dSMichael Kruse // region. In that case the llvm::Value would never be usable in in the exit 1114f33c125dSMichael Kruse // block. The RegionGenerator however creates an new exit block ('ExitBBCopy') 1115f33c125dSMichael Kruse // for the subregion's exiting edges only. We need to determine whether an 1116f33c125dSMichael Kruse // llvm::Value is usable in there. We do this by checking whether it dominates 1117f33c125dSMichael Kruse // all exiting blocks individually. 1118f33c125dSMichael Kruse static bool isDominatingSubregionExit(const DominatorTree &DT, Region *R, 1119f33c125dSMichael Kruse BasicBlock *BB) { 1120f33c125dSMichael Kruse for (auto ExitingBB : predecessors(R->getExit())) { 1121f33c125dSMichael Kruse // Check for non-subregion incoming edges. 1122f33c125dSMichael Kruse if (!R->contains(ExitingBB)) 1123f33c125dSMichael Kruse continue; 1124f33c125dSMichael Kruse 1125f33c125dSMichael Kruse if (!DT.dominates(BB, ExitingBB)) 1126f33c125dSMichael Kruse return false; 1127f33c125dSMichael Kruse } 1128f33c125dSMichael Kruse 1129f33c125dSMichael Kruse return true; 1130f33c125dSMichael Kruse } 1131f33c125dSMichael Kruse 1132f33c125dSMichael Kruse // Find the direct dominator of the subregion's exit block if the subregion was 1133f33c125dSMichael Kruse // simplified. 1134f33c125dSMichael Kruse static BasicBlock *findExitDominator(DominatorTree &DT, Region *R) { 1135f33c125dSMichael Kruse BasicBlock *Common = nullptr; 1136f33c125dSMichael Kruse for (auto ExitingBB : predecessors(R->getExit())) { 1137f33c125dSMichael Kruse // Check for non-subregion incoming edges. 1138f33c125dSMichael Kruse if (!R->contains(ExitingBB)) 1139f33c125dSMichael Kruse continue; 1140f33c125dSMichael Kruse 1141f33c125dSMichael Kruse // First exiting edge. 1142f33c125dSMichael Kruse if (!Common) { 1143f33c125dSMichael Kruse Common = ExitingBB; 1144f33c125dSMichael Kruse continue; 1145f33c125dSMichael Kruse } 1146f33c125dSMichael Kruse 1147f33c125dSMichael Kruse Common = DT.findNearestCommonDominator(Common, ExitingBB); 1148f33c125dSMichael Kruse } 1149f33c125dSMichael Kruse 1150f33c125dSMichael Kruse assert(Common && R->contains(Common)); 1151f33c125dSMichael Kruse return Common; 1152f33c125dSMichael Kruse } 1153f33c125dSMichael Kruse 1154bc132607STobias Grosser void RegionGenerator::copyStmt(ScopStmt &Stmt, LoopToScevMapT <S, 11552d1ed0bfSTobias Grosser isl_id_to_ast_expr *IdToAstExp) { 1156275a1756SJohannes Doerfert assert(Stmt.isRegionStmt() && 1157d3f21833STobias Grosser "Only region statements can be copied by the region generator"); 1158275a1756SJohannes Doerfert 1159ecff11dcSJohannes Doerfert // Forget all old mappings. 1160ecff11dcSJohannes Doerfert BlockMap.clear(); 1161ecff11dcSJohannes Doerfert RegionMaps.clear(); 1162ecff11dcSJohannes Doerfert IncompletePHINodeMap.clear(); 1163ecff11dcSJohannes Doerfert 1164225f0d1eSMichael Kruse // Collection of all values related to this subregion. 1165225f0d1eSMichael Kruse ValueMapT ValueMap; 1166225f0d1eSMichael Kruse 1167275a1756SJohannes Doerfert // The region represented by the statement. 1168275a1756SJohannes Doerfert Region *R = Stmt.getRegion(); 1169275a1756SJohannes Doerfert 1170ecff11dcSJohannes Doerfert // Create a dedicated entry for the region where we can reload all demoted 1171ecff11dcSJohannes Doerfert // inputs. 1172ecff11dcSJohannes Doerfert BasicBlock *EntryBB = R->getEntry(); 1173b8f58b53SDuncan P. N. Exon Smith BasicBlock *EntryBBCopy = SplitBlock(Builder.GetInsertBlock(), 1174b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 1175ecff11dcSJohannes Doerfert EntryBBCopy->setName("polly.stmt." + EntryBB->getName() + ".entry"); 1176b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&EntryBBCopy->front()); 1177514f6efaSJohannes Doerfert 1178c993739eSMichael Kruse ValueMapT &EntryBBMap = RegionMaps[EntryBBCopy]; 11792fa35194SMichael Kruse generateScalarLoads(Stmt, LTS, EntryBBMap, IdToAstExp); 1180225f0d1eSMichael Kruse 1181ecff11dcSJohannes Doerfert for (auto PI = pred_begin(EntryBB), PE = pred_end(EntryBB); PI != PE; ++PI) 1182ecff11dcSJohannes Doerfert if (!R->contains(*PI)) 1183ecff11dcSJohannes Doerfert BlockMap[*PI] = EntryBBCopy; 1184275a1756SJohannes Doerfert 1185275a1756SJohannes Doerfert // Iterate over all blocks in the region in a breadth-first search. 1186275a1756SJohannes Doerfert std::deque<BasicBlock *> Blocks; 11875b1abfc8SMandeep Singh Grang SmallSetVector<BasicBlock *, 8> SeenBlocks; 1188ecff11dcSJohannes Doerfert Blocks.push_back(EntryBB); 1189ecff11dcSJohannes Doerfert SeenBlocks.insert(EntryBB); 1190275a1756SJohannes Doerfert 1191275a1756SJohannes Doerfert while (!Blocks.empty()) { 1192275a1756SJohannes Doerfert BasicBlock *BB = Blocks.front(); 1193275a1756SJohannes Doerfert Blocks.pop_front(); 1194275a1756SJohannes Doerfert 1195514f6efaSJohannes Doerfert // First split the block and update dominance information. 1196514f6efaSJohannes Doerfert BasicBlock *BBCopy = splitBB(BB); 1197ecff11dcSJohannes Doerfert BasicBlock *BBCopyIDom = repairDominance(BB, BBCopy); 1198ecff11dcSJohannes Doerfert 1199c993739eSMichael Kruse // Get the mapping for this block and initialize it with either the scalar 1200c993739eSMichael Kruse // loads from the generated entering block (which dominates all blocks of 1201c993739eSMichael Kruse // this subregion) or the maps of the immediate dominator, if part of the 1202c993739eSMichael Kruse // subregion. The latter necessarily includes the former. 1203c993739eSMichael Kruse ValueMapT *InitBBMap; 1204c993739eSMichael Kruse if (BBCopyIDom) { 1205c993739eSMichael Kruse assert(RegionMaps.count(BBCopyIDom)); 1206c993739eSMichael Kruse InitBBMap = &RegionMaps[BBCopyIDom]; 1207c993739eSMichael Kruse } else 1208c993739eSMichael Kruse InitBBMap = &EntryBBMap; 1209c993739eSMichael Kruse auto Inserted = RegionMaps.insert(std::make_pair(BBCopy, *InitBBMap)); 1210c993739eSMichael Kruse ValueMapT &RegionMap = Inserted.first->second; 1211514f6efaSJohannes Doerfert 1212275a1756SJohannes Doerfert // Copy the block with the BlockGenerator. 1213b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&BBCopy->front()); 1214bc132607STobias Grosser copyBB(Stmt, BB, BBCopy, RegionMap, LTS, IdToAstExp); 1215275a1756SJohannes Doerfert 1216ecff11dcSJohannes Doerfert // In order to remap PHI nodes we store also basic block mappings. 1217ecff11dcSJohannes Doerfert BlockMap[BB] = BBCopy; 1218ecff11dcSJohannes Doerfert 1219ecff11dcSJohannes Doerfert // Add values to incomplete PHI nodes waiting for this block to be copied. 1220ecff11dcSJohannes Doerfert for (const PHINodePairTy &PHINodePair : IncompletePHINodeMap[BB]) 1221bc132607STobias Grosser addOperandToPHI(Stmt, PHINodePair.first, PHINodePair.second, BB, LTS); 1222ecff11dcSJohannes Doerfert IncompletePHINodeMap[BB].clear(); 1223ecff11dcSJohannes Doerfert 1224275a1756SJohannes Doerfert // And continue with new successors inside the region. 1225275a1756SJohannes Doerfert for (auto SI = succ_begin(BB), SE = succ_end(BB); SI != SE; SI++) 12265b1abfc8SMandeep Singh Grang if (R->contains(*SI) && SeenBlocks.insert(*SI)) 1227275a1756SJohannes Doerfert Blocks.push_back(*SI); 1228ebffcbeeSMichael Kruse 1229ebffcbeeSMichael Kruse // Remember value in case it is visible after this subregion. 1230f33c125dSMichael Kruse if (isDominatingSubregionExit(DT, R, BB)) 1231ebffcbeeSMichael Kruse ValueMap.insert(RegionMap.begin(), RegionMap.end()); 1232275a1756SJohannes Doerfert } 1233275a1756SJohannes Doerfert 1234275a1756SJohannes Doerfert // Now create a new dedicated region exit block and add it to the region map. 1235b8f58b53SDuncan P. N. Exon Smith BasicBlock *ExitBBCopy = SplitBlock(Builder.GetInsertBlock(), 1236b8f58b53SDuncan P. N. Exon Smith &*Builder.GetInsertPoint(), &DT, &LI); 1237ecff11dcSJohannes Doerfert ExitBBCopy->setName("polly.stmt." + R->getExit()->getName() + ".exit"); 1238514f6efaSJohannes Doerfert BlockMap[R->getExit()] = ExitBBCopy; 1239514f6efaSJohannes Doerfert 1240f33c125dSMichael Kruse BasicBlock *ExitDomBBCopy = BlockMap.lookup(findExitDominator(DT, R)); 124121a059afSTobias Grosser assert(ExitDomBBCopy && 124221a059afSTobias Grosser "Common exit dominator must be within region; at least the entry node " 124321a059afSTobias Grosser "must match"); 1244f33c125dSMichael Kruse DT.changeImmediateDominator(ExitBBCopy, ExitDomBBCopy); 1245275a1756SJohannes Doerfert 1246275a1756SJohannes Doerfert // As the block generator doesn't handle control flow we need to add the 1247275a1756SJohannes Doerfert // region control flow by hand after all blocks have been copied. 1248275a1756SJohannes Doerfert for (BasicBlock *BB : SeenBlocks) { 1249275a1756SJohannes Doerfert 1250514f6efaSJohannes Doerfert BasicBlock *BBCopy = BlockMap[BB]; 1251e114dc02SJohannes Doerfert TerminatorInst *TI = BB->getTerminator(); 1252e114dc02SJohannes Doerfert if (isa<UnreachableInst>(TI)) { 1253e114dc02SJohannes Doerfert while (!BBCopy->empty()) 1254e114dc02SJohannes Doerfert BBCopy->begin()->eraseFromParent(); 1255e114dc02SJohannes Doerfert new UnreachableInst(BBCopy->getContext(), BBCopy); 1256e114dc02SJohannes Doerfert continue; 1257e114dc02SJohannes Doerfert } 1258e114dc02SJohannes Doerfert 1259275a1756SJohannes Doerfert Instruction *BICopy = BBCopy->getTerminator(); 1260275a1756SJohannes Doerfert 1261514f6efaSJohannes Doerfert ValueMapT &RegionMap = RegionMaps[BBCopy]; 1262514f6efaSJohannes Doerfert RegionMap.insert(BlockMap.begin(), BlockMap.end()); 1263514f6efaSJohannes Doerfert 126445e7944bSTobias Grosser Builder.SetInsertPoint(BICopy); 12659a132f36SJohannes Doerfert copyInstScalar(Stmt, TI, RegionMap, LTS); 1266275a1756SJohannes Doerfert BICopy->eraseFromParent(); 1267275a1756SJohannes Doerfert } 1268275a1756SJohannes Doerfert 1269ecff11dcSJohannes Doerfert // Add counting PHI nodes to all loops in the region that can be used as 1270ecff11dcSJohannes Doerfert // replacement for SCEVs refering to the old loop. 1271ecff11dcSJohannes Doerfert for (BasicBlock *BB : SeenBlocks) { 1272ecff11dcSJohannes Doerfert Loop *L = LI.getLoopFor(BB); 1273bc29e0b2STobias Grosser if (L == nullptr || L->getHeader() != BB || !R->contains(L)) 1274ecff11dcSJohannes Doerfert continue; 1275ecff11dcSJohannes Doerfert 1276ecff11dcSJohannes Doerfert BasicBlock *BBCopy = BlockMap[BB]; 1277ecff11dcSJohannes Doerfert Value *NullVal = Builder.getInt32(0); 1278ecff11dcSJohannes Doerfert PHINode *LoopPHI = 1279ecff11dcSJohannes Doerfert PHINode::Create(Builder.getInt32Ty(), 2, "polly.subregion.iv"); 1280ecff11dcSJohannes Doerfert Instruction *LoopPHIInc = BinaryOperator::CreateAdd( 1281ecff11dcSJohannes Doerfert LoopPHI, Builder.getInt32(1), "polly.subregion.iv.inc"); 1282b8f58b53SDuncan P. N. Exon Smith LoopPHI->insertBefore(&BBCopy->front()); 1283ecff11dcSJohannes Doerfert LoopPHIInc->insertBefore(BBCopy->getTerminator()); 1284ecff11dcSJohannes Doerfert 1285ecff11dcSJohannes Doerfert for (auto *PredBB : make_range(pred_begin(BB), pred_end(BB))) { 1286ecff11dcSJohannes Doerfert if (!R->contains(PredBB)) 1287ecff11dcSJohannes Doerfert continue; 1288ecff11dcSJohannes Doerfert if (L->contains(PredBB)) 1289ecff11dcSJohannes Doerfert LoopPHI->addIncoming(LoopPHIInc, BlockMap[PredBB]); 1290ecff11dcSJohannes Doerfert else 1291ecff11dcSJohannes Doerfert LoopPHI->addIncoming(NullVal, BlockMap[PredBB]); 1292ecff11dcSJohannes Doerfert } 1293ecff11dcSJohannes Doerfert 1294ecff11dcSJohannes Doerfert for (auto *PredBBCopy : make_range(pred_begin(BBCopy), pred_end(BBCopy))) 1295ecff11dcSJohannes Doerfert if (LoopPHI->getBasicBlockIndex(PredBBCopy) < 0) 1296ecff11dcSJohannes Doerfert LoopPHI->addIncoming(NullVal, PredBBCopy); 1297ecff11dcSJohannes Doerfert 1298ecff11dcSJohannes Doerfert LTS[L] = SE.getUnknown(LoopPHI); 1299ecff11dcSJohannes Doerfert } 1300ecff11dcSJohannes Doerfert 1301225f0d1eSMichael Kruse // Continue generating code in the exit block. 1302b8f58b53SDuncan P. N. Exon Smith Builder.SetInsertPoint(&*ExitBBCopy->getFirstInsertionPt()); 1303225f0d1eSMichael Kruse 1304225f0d1eSMichael Kruse // Write values visible to other statements. 13052fa35194SMichael Kruse generateScalarStores(Stmt, LTS, ValueMap, IdToAstExp); 13063e956020STobias Grosser BlockMap.clear(); 13073e956020STobias Grosser RegionMaps.clear(); 13083e956020STobias Grosser IncompletePHINodeMap.clear(); 1309275a1756SJohannes Doerfert } 1310ecff11dcSJohannes Doerfert 1311ee6a4fc6SMichael Kruse PHINode *RegionGenerator::buildExitPHI(MemoryAccess *MA, LoopToScevMapT <S, 1312ee6a4fc6SMichael Kruse ValueMapT &BBMap, Loop *L) { 1313ee6a4fc6SMichael Kruse ScopStmt *Stmt = MA->getStatement(); 1314ee6a4fc6SMichael Kruse Region *SubR = Stmt->getRegion(); 1315ee6a4fc6SMichael Kruse auto Incoming = MA->getIncoming(); 1316ee6a4fc6SMichael Kruse 1317ee6a4fc6SMichael Kruse PollyIRBuilder::InsertPointGuard IPGuard(Builder); 1318ee6a4fc6SMichael Kruse PHINode *OrigPHI = cast<PHINode>(MA->getAccessInstruction()); 1319ee6a4fc6SMichael Kruse BasicBlock *NewSubregionExit = Builder.GetInsertBlock(); 1320ee6a4fc6SMichael Kruse 1321ee6a4fc6SMichael Kruse // This can happen if the subregion is simplified after the ScopStmts 1322ee6a4fc6SMichael Kruse // have been created; simplification happens as part of CodeGeneration. 1323ee6a4fc6SMichael Kruse if (OrigPHI->getParent() != SubR->getExit()) { 1324ee6a4fc6SMichael Kruse BasicBlock *FormerExit = SubR->getExitingBlock(); 1325ee6a4fc6SMichael Kruse if (FormerExit) 1326ee6a4fc6SMichael Kruse NewSubregionExit = BlockMap.lookup(FormerExit); 1327ee6a4fc6SMichael Kruse } 1328ee6a4fc6SMichael Kruse 1329ee6a4fc6SMichael Kruse PHINode *NewPHI = PHINode::Create(OrigPHI->getType(), Incoming.size(), 1330ee6a4fc6SMichael Kruse "polly." + OrigPHI->getName(), 1331ee6a4fc6SMichael Kruse NewSubregionExit->getFirstNonPHI()); 1332ee6a4fc6SMichael Kruse 1333ee6a4fc6SMichael Kruse // Add the incoming values to the PHI. 1334ee6a4fc6SMichael Kruse for (auto &Pair : Incoming) { 1335ee6a4fc6SMichael Kruse BasicBlock *OrigIncomingBlock = Pair.first; 1336ee6a4fc6SMichael Kruse BasicBlock *NewIncomingBlock = BlockMap.lookup(OrigIncomingBlock); 1337ee6a4fc6SMichael Kruse Builder.SetInsertPoint(NewIncomingBlock->getTerminator()); 1338ee6a4fc6SMichael Kruse assert(RegionMaps.count(NewIncomingBlock)); 1339ee6a4fc6SMichael Kruse ValueMapT *LocalBBMap = &RegionMaps[NewIncomingBlock]; 1340ee6a4fc6SMichael Kruse 1341ee6a4fc6SMichael Kruse Value *OrigIncomingValue = Pair.second; 1342ee6a4fc6SMichael Kruse Value *NewIncomingValue = 1343ee6a4fc6SMichael Kruse getNewValue(*Stmt, OrigIncomingValue, *LocalBBMap, LTS, L); 1344ee6a4fc6SMichael Kruse NewPHI->addIncoming(NewIncomingValue, NewIncomingBlock); 1345ee6a4fc6SMichael Kruse } 1346ee6a4fc6SMichael Kruse 1347ee6a4fc6SMichael Kruse return NewPHI; 1348ee6a4fc6SMichael Kruse } 1349ee6a4fc6SMichael Kruse 1350ee6a4fc6SMichael Kruse Value *RegionGenerator::getExitScalar(MemoryAccess *MA, LoopToScevMapT <S, 1351ee6a4fc6SMichael Kruse ValueMapT &BBMap) { 1352ee6a4fc6SMichael Kruse ScopStmt *Stmt = MA->getStatement(); 1353ee6a4fc6SMichael Kruse 1354ee6a4fc6SMichael Kruse // TODO: Add some test cases that ensure this is really the right choice. 1355ee6a4fc6SMichael Kruse Loop *L = LI.getLoopFor(Stmt->getRegion()->getExit()); 1356ee6a4fc6SMichael Kruse 1357ee6a4fc6SMichael Kruse if (MA->isAnyPHIKind()) { 1358ee6a4fc6SMichael Kruse auto Incoming = MA->getIncoming(); 1359ee6a4fc6SMichael Kruse assert(!Incoming.empty() && 1360ee6a4fc6SMichael Kruse "PHI WRITEs must have originate from at least one incoming block"); 1361ee6a4fc6SMichael Kruse 1362ee6a4fc6SMichael Kruse // If there is only one incoming value, we do not need to create a PHI. 1363ee6a4fc6SMichael Kruse if (Incoming.size() == 1) { 1364ee6a4fc6SMichael Kruse Value *OldVal = Incoming[0].second; 1365ee6a4fc6SMichael Kruse return getNewValue(*Stmt, OldVal, BBMap, LTS, L); 1366ee6a4fc6SMichael Kruse } 1367ee6a4fc6SMichael Kruse 1368ee6a4fc6SMichael Kruse return buildExitPHI(MA, LTS, BBMap, L); 1369ee6a4fc6SMichael Kruse } 1370ee6a4fc6SMichael Kruse 13714d5a9172STobias Grosser // MemoryKind::Value accesses leaving the subregion must dominate the exit 13724d5a9172STobias Grosser // block; just pass the copied value. 1373ee6a4fc6SMichael Kruse Value *OldVal = MA->getAccessValue(); 1374ee6a4fc6SMichael Kruse return getNewValue(*Stmt, OldVal, BBMap, LTS, L); 1375ee6a4fc6SMichael Kruse } 1376ee6a4fc6SMichael Kruse 13772fa35194SMichael Kruse void RegionGenerator::generateScalarStores( 13782fa35194SMichael Kruse ScopStmt &Stmt, LoopToScevMapT <S, ValueMapT &BBMap, 13792fa35194SMichael Kruse __isl_keep isl_id_to_ast_expr *NewAccesses) { 138075296901STobias Grosser assert(Stmt.getRegion() && 138175296901STobias Grosser "Block statements need to use the generateScalarStores() " 1382ecff11dcSJohannes Doerfert "function in the BlockGenerator"); 1383ecff11dcSJohannes Doerfert 1384ecff11dcSJohannes Doerfert for (MemoryAccess *MA : Stmt) { 13852fa35194SMichael Kruse if (MA->isOriginalArrayKind() || MA->isRead()) 1386ecff11dcSJohannes Doerfert continue; 1387ecff11dcSJohannes Doerfert 1388ee6a4fc6SMichael Kruse Value *NewVal = getExitScalar(MA, LTS, BBMap); 13892fa35194SMichael Kruse Value *Address = 13902fa35194SMichael Kruse getImplicitAddress(*MA, getLoopForStmt(Stmt), LTS, BBMap, NewAccesses); 1391eac9726eSMichael Kruse assert((!isa<Instruction>(NewVal) || 1392eac9726eSMichael Kruse DT.dominates(cast<Instruction>(NewVal)->getParent(), 1393eac9726eSMichael Kruse Builder.GetInsertBlock())) && 1394eac9726eSMichael Kruse "Domination violation"); 1395eac9726eSMichael Kruse assert((!isa<Instruction>(Address) || 1396eac9726eSMichael Kruse DT.dominates(cast<Instruction>(Address)->getParent(), 1397eac9726eSMichael Kruse Builder.GetInsertBlock())) && 1398eac9726eSMichael Kruse "Domination violation"); 1399ee6a4fc6SMichael Kruse Builder.CreateStore(NewVal, Address); 1400ecff11dcSJohannes Doerfert } 1401ecff11dcSJohannes Doerfert } 1402ecff11dcSJohannes Doerfert 1403943c369cSTobias Grosser void RegionGenerator::addOperandToPHI(ScopStmt &Stmt, PHINode *PHI, 1404ecff11dcSJohannes Doerfert PHINode *PHICopy, BasicBlock *IncomingBB, 1405ecff11dcSJohannes Doerfert LoopToScevMapT <S) { 1406ecff11dcSJohannes Doerfert Region *StmtR = Stmt.getRegion(); 1407ecff11dcSJohannes Doerfert 1408ecff11dcSJohannes Doerfert // If the incoming block was not yet copied mark this PHI as incomplete. 1409ecff11dcSJohannes Doerfert // Once the block will be copied the incoming value will be added. 1410ecff11dcSJohannes Doerfert BasicBlock *BBCopy = BlockMap[IncomingBB]; 1411ecff11dcSJohannes Doerfert if (!BBCopy) { 1412ecff11dcSJohannes Doerfert assert(StmtR->contains(IncomingBB) && 1413ecff11dcSJohannes Doerfert "Bad incoming block for PHI in non-affine region"); 1414ecff11dcSJohannes Doerfert IncompletePHINodeMap[IncomingBB].push_back(std::make_pair(PHI, PHICopy)); 1415ecff11dcSJohannes Doerfert return; 1416ecff11dcSJohannes Doerfert } 1417ecff11dcSJohannes Doerfert 1418*75dfaa1dSTobias Grosser assert(RegionMaps.count(BBCopy) && "Incoming PHI block did not have a BBMap"); 1419ecff11dcSJohannes Doerfert ValueMapT &BBCopyMap = RegionMaps[BBCopy]; 1420ecff11dcSJohannes Doerfert 1421*75dfaa1dSTobias Grosser Value *OpCopy = nullptr; 1422*75dfaa1dSTobias Grosser 1423*75dfaa1dSTobias Grosser if (StmtR->contains(IncomingBB)) { 1424ecff11dcSJohannes Doerfert Value *Op = PHI->getIncomingValueForBlock(IncomingBB); 1425dc122222SMichael Kruse 14266ba92714SJohannes Doerfert // If the current insert block is different from the PHIs incoming block 14276ba92714SJohannes Doerfert // change it, otherwise do not. 14286ba92714SJohannes Doerfert auto IP = Builder.GetInsertPoint(); 14296ba92714SJohannes Doerfert if (IP->getParent() != BBCopy) 1430dc122222SMichael Kruse Builder.SetInsertPoint(BBCopy->getTerminator()); 14312c3ffc04SJohannes Doerfert OpCopy = getNewValue(Stmt, Op, BBCopyMap, LTS, getLoopForStmt(Stmt)); 14326ba92714SJohannes Doerfert if (IP->getParent() != BBCopy) 14336ba92714SJohannes Doerfert Builder.SetInsertPoint(&*IP); 1434ecff11dcSJohannes Doerfert } else { 1435*75dfaa1dSTobias Grosser // All edges from outside the non-affine region become a single edge 1436*75dfaa1dSTobias Grosser // in the new copy of the non-affine region. Make sure to only add the 1437*75dfaa1dSTobias Grosser // corresponding edge the first time we encounter a basic block from 1438*75dfaa1dSTobias Grosser // outside the non-affine region. 1439ecff11dcSJohannes Doerfert if (PHICopy->getBasicBlockIndex(BBCopy) >= 0) 1440ecff11dcSJohannes Doerfert return; 1441ecff11dcSJohannes Doerfert 1442*75dfaa1dSTobias Grosser // Get the reloaded value. 1443*75dfaa1dSTobias Grosser OpCopy = getNewValue(Stmt, PHI, BBCopyMap, LTS, getLoopForStmt(Stmt)); 1444ecff11dcSJohannes Doerfert } 1445ecff11dcSJohannes Doerfert 1446ecff11dcSJohannes Doerfert assert(OpCopy && "Incoming PHI value was not copied properly"); 1447ecff11dcSJohannes Doerfert assert(BBCopy && "Incoming PHI block was not copied properly"); 1448ecff11dcSJohannes Doerfert PHICopy->addIncoming(OpCopy, BBCopy); 1449ecff11dcSJohannes Doerfert } 1450ecff11dcSJohannes Doerfert 14512b809d13STobias Grosser void RegionGenerator::copyPHIInstruction(ScopStmt &Stmt, PHINode *PHI, 1452ecff11dcSJohannes Doerfert ValueMapT &BBMap, 1453ecff11dcSJohannes Doerfert LoopToScevMapT <S) { 1454ecff11dcSJohannes Doerfert unsigned NumIncoming = PHI->getNumIncomingValues(); 1455ecff11dcSJohannes Doerfert PHINode *PHICopy = 1456ecff11dcSJohannes Doerfert Builder.CreatePHI(PHI->getType(), NumIncoming, "polly." + PHI->getName()); 1457ecff11dcSJohannes Doerfert PHICopy->moveBefore(PHICopy->getParent()->getFirstNonPHI()); 1458ecff11dcSJohannes Doerfert BBMap[PHI] = PHICopy; 1459ecff11dcSJohannes Doerfert 146097b84909STobias Grosser for (BasicBlock *IncomingBB : PHI->blocks()) 146197b84909STobias Grosser addOperandToPHI(Stmt, PHI, PHICopy, IncomingBB, LTS); 1462ecff11dcSJohannes Doerfert } 1463