// Helper function for Scop // TODO: Add assertion to not allow parameter to be null //===----------------------------------------------------------------------===// // Temporary Hack for extended region tree. // Cast the region to loop if there is a loop have the same header and exit. Loop *polly::castToLoop(const Region &R, LoopInfo &LI) { BasicBlock *entry = R.getEntry(); if (!LI.isLoopHeader(entry)) return 0; Loop *L = LI.getLoopFor(entry); BasicBlock *exit = L->getExitBlock(); // Is the loop with multiple exits? if (!exit) return 0; if (exit != R.getExit()) { // SubRegion/ParentRegion with the same entry. assert((R.getNode(R.getEntry())->isSubRegion() || R.getParent()->getEntry() == entry) && "Expect the loop is the smaller or bigger region"); return 0; } return L; }
bool RangedAddressSanitizer::generateCallFor(Loop *L, Instruction *I) { if (!isa<LoadInst>(I) && !isa<StoreInst>(I)) return false; // Reduce memory access to array base pointer + offset Value *Array; unsigned Size; Expr Subscript; if (!reduceMemoryAccess(I, Array, Subscript, Size)) { return false; } #ifdef ENABLE_REUSE Loop *Final; Expr ReuseEx = RE_->getExecutionsRelativeTo(L, nullptr, Final); if (!ReuseEx.isValid()) { SPM_DEBUG(dbgs() << "RangedAddressSanitizer: could not calculate reuse for " "loop " << L->getHeader()->getName() << "\n"); return false; } SPM_DEBUG(dbgs() << "RangedAddressSanitizer: reuse of " << L->getHeader()->getName() << " relative to " << Final->getHeader()->getName() << ": " << ReuseEx << "\n"); #else /* ! ENABLE_REUSE */ // TODO find Final loop Loop * Final = L; // FIXME for (;Final->getParentLoop() != nullptr; Final = Final->getParentLoop()) {} #endif BasicBlock *Preheader = Final->getLoopPreheader(); typedef GraphTraits< BasicBlock * > CFG; typedef GraphTraits< Inverse< BasicBlock * > > InverseCFG; // typedef InverseCFG::pred_iterator pred_iterator; if (!Preheader) { SPM_DEBUG(dbgs() << "RangedAddressSanitizer: trying to recover pre-header\n" ); BasicBlock * header = Final->getHeader(); for (pred_iterator itPred = InverseCFG::child_begin(header); itPred != InverseCFG::child_end(header); ++itPred) { BasicBlock * pred = *itPred; if (! LI_->getLoopFor(pred)) { Preheader = pred; break; } } } assert(Preheader && "could not find nor recover pre-header"); BasicBlock *Exit = Final->getExitBlock(); if (!Exit) { errs() << "[ERROR] Non unique exit block in loop. Leaving loop uninstrumented " << *L << "\n"; return false; } assert(Exit && "loop w/o unique exit block"); // FIXME: instead of bailing, we should set the toplevel loop in the call to // getExecutionsRelativeTo. if (Instruction *AI = dyn_cast<Instruction>(Array)) { if (!DT_->dominates(AI->getParent(), Preheader) && AI->getParent() != Preheader) { SPM_DEBUG(dbgs() << "RangedAddressSanitizer: array does not dominate " "loop preheader\n"); return false; } } // Query array offset range Expr MinEx, MaxEx; if (!RMM_->getMinMax(Subscript, MinEx, MaxEx)) { SPM_DEBUG(dbgs() << "RangedAddressSanitizer: could calculate min/max for " " subscript " << Subscript << "\n"); return false; } SPM_DEBUG(dbgs() << "RangedAddressSanitizer: min/max for subscript " << Subscript << ": " << MinEx << ", " << MaxEx << "\n"); // Materialize expressions in the loop header IRBuilder<> IRB(Preheader->getTerminator()); #ifdef ENABLE_REUSE Value *Reuse = (ReuseEx * Size).getExprValue(64, IRB, Module_); #else Value *Reuse = ConstantInt::get(IntegerType::get(IRB.getContext(), 64), 0); // bogus #endif Value *Min = MinEx.getExprValue(64, IRB, Module_); Value *Max = MaxEx.getExprValue(64, IRB, Module_); SPM_DEBUG(dbgs() << "RangedAddressSanitizer: values for reuse, min, max: " << *Reuse << ", " << *Min << ", " << *Max << "\n"); // If there is already a range check for this array and loop cached, merge the intervals CallInfo CI = { Final, Preheader, Exit, Array, Min, Max, Reuse }; auto Call = Calls_.insert(CI); if (!Call.second) { IRBuilder<> IRB(Preheader->getTerminator()); CallInfo SCI = *Call.first; Value *CmpMin = IRB.CreateICmp(CmpInst::ICMP_SLT, SCI.Min, CI.Min); SCI.Min = IRB.CreateSelect(CmpMin, SCI.Min, CI.Min); Value *CmpMax = IRB.CreateICmp(CmpInst::ICMP_SGT, SCI.Max, CI.Max); SCI.Max = IRB.CreateSelect(CmpMax, SCI.Max, CI.Max); SCI.Reuse = IRB.CreateAdd(SCI.Reuse, CI.Reuse); Calls_.erase(SCI); Calls_.insert(SCI); } return true; }
/* This method performs Unroll and Jam. For a simple loop like: for (i = ..) Fore(i) for (j = ..) SubLoop(i, j) Aft(i) Instead of doing normal inner or outer unrolling, we do: for (i = .., i+=2) Fore(i) Fore(i+1) for (j = ..) SubLoop(i, j) SubLoop(i+1, j) Aft(i) Aft(i+1) So the outer loop is essetially unrolled and then the inner loops are fused ("jammed") together into a single loop. This can increase speed when there are loads in SubLoop that are invariant to i, as they become shared between the now jammed inner loops. We do this by spliting the blocks in the loop into Fore, Subloop and Aft. Fore blocks are those before the inner loop, Aft are those after. Normal Unroll code is used to copy each of these sets of blocks and the results are combined together into the final form above. isSafeToUnrollAndJam should be used prior to calling this to make sure the unrolling will be valid. Checking profitablility is also advisable. */ LoopUnrollResult llvm::UnrollAndJamLoop(Loop *L, unsigned Count, unsigned TripCount, unsigned TripMultiple, bool UnrollRemainder, LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT, AssumptionCache *AC, OptimizationRemarkEmitter *ORE) { // When we enter here we should have already checked that it is safe BasicBlock *Header = L->getHeader(); assert(L->getSubLoops().size() == 1); Loop *SubLoop = *L->begin(); // Don't enter the unroll code if there is nothing to do. if (TripCount == 0 && Count < 2) { LLVM_DEBUG(dbgs() << "Won't unroll; almost nothing to do\n"); return LoopUnrollResult::Unmodified; } assert(Count > 0); assert(TripMultiple > 0); assert(TripCount == 0 || TripCount % TripMultiple == 0); // Are we eliminating the loop control altogether? bool CompletelyUnroll = (Count == TripCount); // We use the runtime remainder in cases where we don't know trip multiple if (TripMultiple == 1 || TripMultiple % Count != 0) { if (!UnrollRuntimeLoopRemainder(L, Count, /*AllowExpensiveTripCount*/ false, /*UseEpilogRemainder*/ true, UnrollRemainder, LI, SE, DT, AC, true)) { LLVM_DEBUG(dbgs() << "Won't unroll-and-jam; remainder loop could not be " "generated when assuming runtime trip count\n"); return LoopUnrollResult::Unmodified; } } // Notify ScalarEvolution that the loop will be substantially changed, // if not outright eliminated. if (SE) { SE->forgetLoop(L); SE->forgetLoop(SubLoop); } using namespace ore; // Report the unrolling decision. if (CompletelyUnroll) { LLVM_DEBUG(dbgs() << "COMPLETELY UNROLL AND JAMMING loop %" << Header->getName() << " with trip count " << TripCount << "!\n"); ORE->emit(OptimizationRemark(DEBUG_TYPE, "FullyUnrolled", L->getStartLoc(), L->getHeader()) << "completely unroll and jammed loop with " << NV("UnrollCount", TripCount) << " iterations"); } else { auto DiagBuilder = [&]() { OptimizationRemark Diag(DEBUG_TYPE, "PartialUnrolled", L->getStartLoc(), L->getHeader()); return Diag << "unroll and jammed loop by a factor of " << NV("UnrollCount", Count); }; LLVM_DEBUG(dbgs() << "UNROLL AND JAMMING loop %" << Header->getName() << " by " << Count); if (TripMultiple != 1) { LLVM_DEBUG(dbgs() << " with " << TripMultiple << " trips per branch"); ORE->emit([&]() { return DiagBuilder() << " with " << NV("TripMultiple", TripMultiple) << " trips per branch"; }); } else { LLVM_DEBUG(dbgs() << " with run-time trip count"); ORE->emit([&]() { return DiagBuilder() << " with run-time trip count"; }); } LLVM_DEBUG(dbgs() << "!\n"); } BasicBlock *Preheader = L->getLoopPreheader(); BasicBlock *LatchBlock = L->getLoopLatch(); BranchInst *BI = dyn_cast<BranchInst>(LatchBlock->getTerminator()); assert(Preheader && LatchBlock && Header); assert(BI && !BI->isUnconditional()); bool ContinueOnTrue = L->contains(BI->getSuccessor(0)); BasicBlock *LoopExit = BI->getSuccessor(ContinueOnTrue); bool SubLoopContinueOnTrue = SubLoop->contains( SubLoop->getLoopLatch()->getTerminator()->getSuccessor(0)); // Partition blocks in an outer/inner loop pair into blocks before and after // the loop BasicBlockSet SubLoopBlocks; BasicBlockSet ForeBlocks; BasicBlockSet AftBlocks; partitionOuterLoopBlocks(L, SubLoop, ForeBlocks, SubLoopBlocks, AftBlocks, DT); // We keep track of the entering/first and exiting/last block of each of // Fore/SubLoop/Aft in each iteration. This helps make the stapling up of // blocks easier. std::vector<BasicBlock *> ForeBlocksFirst; std::vector<BasicBlock *> ForeBlocksLast; std::vector<BasicBlock *> SubLoopBlocksFirst; std::vector<BasicBlock *> SubLoopBlocksLast; std::vector<BasicBlock *> AftBlocksFirst; std::vector<BasicBlock *> AftBlocksLast; ForeBlocksFirst.push_back(Header); ForeBlocksLast.push_back(SubLoop->getLoopPreheader()); SubLoopBlocksFirst.push_back(SubLoop->getHeader()); SubLoopBlocksLast.push_back(SubLoop->getExitingBlock()); AftBlocksFirst.push_back(SubLoop->getExitBlock()); AftBlocksLast.push_back(L->getExitingBlock()); // Maps Blocks[0] -> Blocks[It] ValueToValueMapTy LastValueMap; // Move any instructions from fore phi operands from AftBlocks into Fore. moveHeaderPhiOperandsToForeBlocks( Header, LatchBlock, SubLoop->getLoopPreheader()->getTerminator(), AftBlocks); // The current on-the-fly SSA update requires blocks to be processed in // reverse postorder so that LastValueMap contains the correct value at each // exit. LoopBlocksDFS DFS(L); DFS.perform(LI); // Stash the DFS iterators before adding blocks to the loop. LoopBlocksDFS::RPOIterator BlockBegin = DFS.beginRPO(); LoopBlocksDFS::RPOIterator BlockEnd = DFS.endRPO(); if (Header->getParent()->isDebugInfoForProfiling()) for (BasicBlock *BB : L->getBlocks()) for (Instruction &I : *BB) if (!isa<DbgInfoIntrinsic>(&I)) if (const DILocation *DIL = I.getDebugLoc()) I.setDebugLoc(DIL->cloneWithDuplicationFactor(Count)); // Copy all blocks for (unsigned It = 1; It != Count; ++It) { std::vector<BasicBlock *> NewBlocks; // Maps Blocks[It] -> Blocks[It-1] DenseMap<Value *, Value *> PrevItValueMap; for (LoopBlocksDFS::RPOIterator BB = BlockBegin; BB != BlockEnd; ++BB) { ValueToValueMapTy VMap; BasicBlock *New = CloneBasicBlock(*BB, VMap, "." + Twine(It)); Header->getParent()->getBasicBlockList().push_back(New); if (ForeBlocks.count(*BB)) { L->addBasicBlockToLoop(New, *LI); if (*BB == ForeBlocksFirst[0]) ForeBlocksFirst.push_back(New); if (*BB == ForeBlocksLast[0]) ForeBlocksLast.push_back(New); } else if (SubLoopBlocks.count(*BB)) { SubLoop->addBasicBlockToLoop(New, *LI); if (*BB == SubLoopBlocksFirst[0]) SubLoopBlocksFirst.push_back(New); if (*BB == SubLoopBlocksLast[0]) SubLoopBlocksLast.push_back(New); } else if (AftBlocks.count(*BB)) { L->addBasicBlockToLoop(New, *LI); if (*BB == AftBlocksFirst[0]) AftBlocksFirst.push_back(New); if (*BB == AftBlocksLast[0]) AftBlocksLast.push_back(New); } else { llvm_unreachable("BB being cloned should be in Fore/Sub/Aft"); } // Update our running maps of newest clones PrevItValueMap[New] = (It == 1 ? *BB : LastValueMap[*BB]); LastValueMap[*BB] = New; for (ValueToValueMapTy::iterator VI = VMap.begin(), VE = VMap.end(); VI != VE; ++VI) { PrevItValueMap[VI->second] = const_cast<Value *>(It == 1 ? VI->first : LastValueMap[VI->first]); LastValueMap[VI->first] = VI->second; } NewBlocks.push_back(New); // Update DomTree: if (*BB == ForeBlocksFirst[0]) DT->addNewBlock(New, ForeBlocksLast[It - 1]); else if (*BB == SubLoopBlocksFirst[0]) DT->addNewBlock(New, SubLoopBlocksLast[It - 1]); else if (*BB == AftBlocksFirst[0]) DT->addNewBlock(New, AftBlocksLast[It - 1]); else { // Each set of blocks (Fore/Sub/Aft) will have the same internal domtree // structure. auto BBDomNode = DT->getNode(*BB); auto BBIDom = BBDomNode->getIDom(); BasicBlock *OriginalBBIDom = BBIDom->getBlock(); assert(OriginalBBIDom); assert(LastValueMap[cast<Value>(OriginalBBIDom)]); DT->addNewBlock( New, cast<BasicBlock>(LastValueMap[cast<Value>(OriginalBBIDom)])); } } // Remap all instructions in the most recent iteration for (BasicBlock *NewBlock : NewBlocks) { for (Instruction &I : *NewBlock) { ::remapInstruction(&I, LastValueMap); if (auto *II = dyn_cast<IntrinsicInst>(&I)) if (II->getIntrinsicID() == Intrinsic::assume) AC->registerAssumption(II); } } // Alter the ForeBlocks phi's, pointing them at the latest version of the // value from the previous iteration's phis for (PHINode &Phi : ForeBlocksFirst[It]->phis()) { Value *OldValue = Phi.getIncomingValueForBlock(AftBlocksLast[It]); assert(OldValue && "should have incoming edge from Aft[It]"); Value *NewValue = OldValue; if (Value *PrevValue = PrevItValueMap[OldValue]) NewValue = PrevValue; assert(Phi.getNumOperands() == 2); Phi.setIncomingBlock(0, ForeBlocksLast[It - 1]); Phi.setIncomingValue(0, NewValue); Phi.removeIncomingValue(1); } } // Now that all the basic blocks for the unrolled iterations are in place, // finish up connecting the blocks and phi nodes. At this point LastValueMap // is the last unrolled iterations values. // Update Phis in BB from OldBB to point to NewBB auto updatePHIBlocks = [](BasicBlock *BB, BasicBlock *OldBB, BasicBlock *NewBB) { for (PHINode &Phi : BB->phis()) { int I = Phi.getBasicBlockIndex(OldBB); Phi.setIncomingBlock(I, NewBB); } }; // Update Phis in BB from OldBB to point to NewBB and use the latest value // from LastValueMap auto updatePHIBlocksAndValues = [](BasicBlock *BB, BasicBlock *OldBB, BasicBlock *NewBB, ValueToValueMapTy &LastValueMap) { for (PHINode &Phi : BB->phis()) { for (unsigned b = 0; b < Phi.getNumIncomingValues(); ++b) { if (Phi.getIncomingBlock(b) == OldBB) { Value *OldValue = Phi.getIncomingValue(b); if (Value *LastValue = LastValueMap[OldValue]) Phi.setIncomingValue(b, LastValue); Phi.setIncomingBlock(b, NewBB); break; } } } }; // Move all the phis from Src into Dest auto movePHIs = [](BasicBlock *Src, BasicBlock *Dest) { Instruction *insertPoint = Dest->getFirstNonPHI(); while (PHINode *Phi = dyn_cast<PHINode>(Src->begin())) Phi->moveBefore(insertPoint); }; // Update the PHI values outside the loop to point to the last block updatePHIBlocksAndValues(LoopExit, AftBlocksLast[0], AftBlocksLast.back(), LastValueMap); // Update ForeBlocks successors and phi nodes BranchInst *ForeTerm = cast<BranchInst>(ForeBlocksLast.back()->getTerminator()); BasicBlock *Dest = SubLoopBlocksFirst[0]; ForeTerm->setSuccessor(0, Dest); if (CompletelyUnroll) { while (PHINode *Phi = dyn_cast<PHINode>(ForeBlocksFirst[0]->begin())) { Phi->replaceAllUsesWith(Phi->getIncomingValueForBlock(Preheader)); Phi->getParent()->getInstList().erase(Phi); } } else { // Update the PHI values to point to the last aft block updatePHIBlocksAndValues(ForeBlocksFirst[0], AftBlocksLast[0], AftBlocksLast.back(), LastValueMap); } for (unsigned It = 1; It != Count; It++) { // Remap ForeBlock successors from previous iteration to this BranchInst *ForeTerm = cast<BranchInst>(ForeBlocksLast[It - 1]->getTerminator()); BasicBlock *Dest = ForeBlocksFirst[It]; ForeTerm->setSuccessor(0, Dest); } // Subloop successors and phis BranchInst *SubTerm = cast<BranchInst>(SubLoopBlocksLast.back()->getTerminator()); SubTerm->setSuccessor(!SubLoopContinueOnTrue, SubLoopBlocksFirst[0]); SubTerm->setSuccessor(SubLoopContinueOnTrue, AftBlocksFirst[0]); updatePHIBlocks(SubLoopBlocksFirst[0], ForeBlocksLast[0], ForeBlocksLast.back()); updatePHIBlocks(SubLoopBlocksFirst[0], SubLoopBlocksLast[0], SubLoopBlocksLast.back()); for (unsigned It = 1; It != Count; It++) { // Replace the conditional branch of the previous iteration subloop with an // unconditional one to this one BranchInst *SubTerm = cast<BranchInst>(SubLoopBlocksLast[It - 1]->getTerminator()); BranchInst::Create(SubLoopBlocksFirst[It], SubTerm); SubTerm->eraseFromParent(); updatePHIBlocks(SubLoopBlocksFirst[It], ForeBlocksLast[It], ForeBlocksLast.back()); updatePHIBlocks(SubLoopBlocksFirst[It], SubLoopBlocksLast[It], SubLoopBlocksLast.back()); movePHIs(SubLoopBlocksFirst[It], SubLoopBlocksFirst[0]); } // Aft blocks successors and phis BranchInst *Term = cast<BranchInst>(AftBlocksLast.back()->getTerminator()); if (CompletelyUnroll) { BranchInst::Create(LoopExit, Term); Term->eraseFromParent(); } else { Term->setSuccessor(!ContinueOnTrue, ForeBlocksFirst[0]); } updatePHIBlocks(AftBlocksFirst[0], SubLoopBlocksLast[0], SubLoopBlocksLast.back()); for (unsigned It = 1; It != Count; It++) { // Replace the conditional branch of the previous iteration subloop with an // unconditional one to this one BranchInst *AftTerm = cast<BranchInst>(AftBlocksLast[It - 1]->getTerminator()); BranchInst::Create(AftBlocksFirst[It], AftTerm); AftTerm->eraseFromParent(); updatePHIBlocks(AftBlocksFirst[It], SubLoopBlocksLast[It], SubLoopBlocksLast.back()); movePHIs(AftBlocksFirst[It], AftBlocksFirst[0]); } // Dominator Tree. Remove the old links between Fore, Sub and Aft, adding the // new ones required. if (Count != 1) { SmallVector<DominatorTree::UpdateType, 4> DTUpdates; DTUpdates.emplace_back(DominatorTree::UpdateKind::Delete, ForeBlocksLast[0], SubLoopBlocksFirst[0]); DTUpdates.emplace_back(DominatorTree::UpdateKind::Delete, SubLoopBlocksLast[0], AftBlocksFirst[0]); DTUpdates.emplace_back(DominatorTree::UpdateKind::Insert, ForeBlocksLast.back(), SubLoopBlocksFirst[0]); DTUpdates.emplace_back(DominatorTree::UpdateKind::Insert, SubLoopBlocksLast.back(), AftBlocksFirst[0]); DT->applyUpdates(DTUpdates); } // Merge adjacent basic blocks, if possible. SmallPtrSet<BasicBlock *, 16> MergeBlocks; MergeBlocks.insert(ForeBlocksLast.begin(), ForeBlocksLast.end()); MergeBlocks.insert(SubLoopBlocksLast.begin(), SubLoopBlocksLast.end()); MergeBlocks.insert(AftBlocksLast.begin(), AftBlocksLast.end()); while (!MergeBlocks.empty()) { BasicBlock *BB = *MergeBlocks.begin(); BranchInst *Term = dyn_cast<BranchInst>(BB->getTerminator()); if (Term && Term->isUnconditional() && L->contains(Term->getSuccessor(0))) { BasicBlock *Dest = Term->getSuccessor(0); if (BasicBlock *Fold = foldBlockIntoPredecessor(Dest, LI, SE, DT)) { // Don't remove BB and add Fold as they are the same BB assert(Fold == BB); (void)Fold; MergeBlocks.erase(Dest); } else MergeBlocks.erase(BB); } else MergeBlocks.erase(BB); } // At this point, the code is well formed. We now do a quick sweep over the // inserted code, doing constant propagation and dead code elimination as we // go. simplifyLoopAfterUnroll(SubLoop, true, LI, SE, DT, AC); simplifyLoopAfterUnroll(L, !CompletelyUnroll && Count > 1, LI, SE, DT, AC); NumCompletelyUnrolledAndJammed += CompletelyUnroll; ++NumUnrolledAndJammed; #ifndef NDEBUG // We shouldn't have done anything to break loop simplify form or LCSSA. Loop *OuterL = L->getParentLoop(); Loop *OutestLoop = OuterL ? OuterL : (!CompletelyUnroll ? L : SubLoop); assert(OutestLoop->isRecursivelyLCSSAForm(*DT, *LI)); if (!CompletelyUnroll) assert(L->isLoopSimplifyForm()); assert(SubLoop->isLoopSimplifyForm()); assert(DT->verify()); #endif // Update LoopInfo if the loop is completely removed. if (CompletelyUnroll) LI->erase(L); return CompletelyUnroll ? LoopUnrollResult::FullyUnrolled : LoopUnrollResult::PartiallyUnrolled; }