81 using namespace jumpthreading;
83 #define DEBUG_TYPE "jump-threading" 85 STATISTIC(NumThreads,
"Number of jumps threaded");
86 STATISTIC(NumFolds,
"Number of terminators folded");
87 STATISTIC(NumDupes,
"Number of branch blocks duplicated to eliminate phi");
91 cl::desc(
"Max block size to duplicate for jump threading"),
96 "jump-threading-implication-search-threshold",
97 cl::desc(
"The number of predecessors to search for a stronger " 98 "condition to use to thread over a weaker condition"),
102 "print-lvi-after-jump-threading",
103 cl::desc(
"Print the LazyValueInfo cache after JumpThreading"),
cl::init(
false),
153 "Jump Threading",
false,
false)
163 return new JumpThreading(Threshold);
211 uint64_t TrueWeight, FalseWeight;
217 auto GetPredOutEdge =
219 BasicBlock *PhiBB) -> std::pair<BasicBlock *, BasicBlock *> {
220 auto *PredBB = IncomingBB;
221 auto *SuccBB = PhiBB;
225 return {PredBB, SuccBB};
226 auto *SinglePredBB = PredBB->getSinglePredecessor();
228 return {
nullptr,
nullptr};
230 PredBB = SinglePredBB;
242 TrueWeight, TrueWeight + FalseWeight)
244 FalseWeight, TrueWeight + FalseWeight));
247 if (!PredOutEdge.first)
253 uint64_t PredTrueWeight, PredFalseWeight;
276 .createBranchWeights(Weights));
284 auto TLI = &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
287 auto DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
288 auto LVI = &getAnalysis<LazyValueInfoWrapperPass>().getLVI();
289 auto AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
291 std::unique_ptr<BlockFrequencyInfo>
BFI;
292 std::unique_ptr<BranchProbabilityInfo> BPI;
294 if (HasProfileData) {
300 bool Changed = Impl.
runImpl(F, TLI, LVI, AA, &DTU, HasProfileData,
301 std::move(BFI), std::move(BPI));
303 dbgs() <<
"LVI for function '" << F.
getName() <<
"':\n";
304 LVI->printLVI(F, *DT,
dbgs());
319 std::unique_ptr<BlockFrequencyInfo>
BFI;
320 std::unique_ptr<BranchProbabilityInfo> BPI;
327 bool Changed =
runImpl(F, &TLI, &LVI, &AA, &DTU, HasProfileData,
328 std::move(BFI), std::move(BPI));
342 std::unique_ptr<BlockFrequencyInfo> BFI_,
343 std::unique_ptr<BranchProbabilityInfo> BPI_) {
353 HasProfileData = HasProfileData_;
356 HasGuards = GuardDecl && !GuardDecl->
use_empty();
357 if (HasProfileData) {
358 BPI = std::move(BPI_);
359 BFI = std::move(BFI_);
365 assert(DTU &&
"DTU isn't passed into JumpThreading before using it.");
366 assert(DTU->hasDomTree() &&
"JumpThreading relies on DomTree to proceed.");
369 if (!DT.isReachableFromEntry(&BB))
374 bool EverChanged =
false;
379 if (Unreachable.
count(&BB))
386 if (&BB == &F.getEntryBlock() || DTU->isBBPendingDeletion(&BB))
393 <<
"' with terminator: " << *BB.getTerminator()
395 LoopHeaders.erase(&BB);
396 LVI->eraseBlock(&BB);
405 if (BI && BI->isUnconditional() &&
407 BB.getFirstNonPHIOrDbg()->isTerminator() &&
410 !LoopHeaders.count(&BB) && !LoopHeaders.count(BI->getSuccessor(0)) &&
414 LVI->eraseBlock(&BB);
418 EverChanged |= Changed;
451 I.replaceUsesOfWith(Cond, ToVal);
463 assert(StopAt->
getParent() == BB &&
"Not an instruction from proper BB?");
475 if (isa<SwitchInst>(StopAt))
479 if (isa<IndirectBrInst>(StopAt))
490 for (; &*
I != StopAt; ++
I) {
493 if (Size > Threshold)
497 if (isa<DbgInfoIntrinsic>(
I))
continue;
500 if (isa<BitCastInst>(
I) &&
I->getType()->isPointerTy())
505 if (
I->getType()->isTokenTy() &&
I->isUsedOutsideOfBlock(BB))
515 if (
const CallInst *CI = dyn_cast<CallInst>(
I)) {
516 if (CI->cannotDuplicate() || CI->isConvergent())
520 else if (!isa<IntrinsicInst>(CI))
522 else if (!CI->getType()->isVectorTy())
527 return Size > Bonus ? Size - Bonus : 0;
548 for (
const auto &Edge : Edges)
549 LoopHeaders.insert(Edge.second);
562 if (
UndefValue *U = dyn_cast<UndefValue>(Val))
580 DenseSet<std::pair<Value *, BasicBlock *>> &RecursionSet,
586 if (!RecursionSet.insert(std::make_pair(V, BB)).second)
592 Result.
push_back(std::make_pair(KC, Pred));
594 return !Result.
empty();
615 if (DTU->hasPendingDomTreeUpdates())
622 Constant *PredCst = LVI->getConstantOnEdge(V,
P, BB, CxtI);
627 return !Result.
empty();
631 if (
PHINode *PN = dyn_cast<PHINode>(I)) {
632 if (DTU->hasPendingDomTreeUpdates())
636 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i) {
637 Value *InVal = PN->getIncomingValue(i);
639 Result.
push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
641 Constant *CI = LVI->getConstantOnEdge(InVal,
642 PN->getIncomingBlock(i),
645 Result.
push_back(std::make_pair(KC, PN->getIncomingBlock(i)));
649 return !Result.
empty();
654 if (
CastInst *CI = dyn_cast<CastInst>(I)) {
656 if (!isa<PHINode>(Source) && !isa<CmpInst>(Source))
658 ComputeValueKnownInPredecessorsImpl(Source, BB, Result, Preference,
664 for (
auto &R : Result)
679 ComputeValueKnownInPredecessorsImpl(I->
getOperand(0), BB, LHSVals,
681 ComputeValueKnownInPredecessorsImpl(I->
getOperand(1), BB, RHSVals,
684 if (LHSVals.empty() && RHSVals.empty())
697 for (
const auto &LHSVal : LHSVals)
698 if (LHSVal.first == InterestingVal || isa<UndefValue>(LHSVal.first)) {
700 LHSKnownBBs.insert(LHSVal.second);
702 for (
const auto &RHSVal : RHSVals)
703 if (RHSVal.first == InterestingVal || isa<UndefValue>(RHSVal.first)) {
706 if (!LHSKnownBBs.count(RHSVal.second))
710 return !Result.
empty();
714 if (I->
getOpcode() == Instruction::Xor &&
716 cast<ConstantInt>(I->
getOperand(1))->isOne()) {
717 ComputeValueKnownInPredecessorsImpl(I->
getOperand(0), BB, Result,
723 for (
auto &R : Result)
732 &&
"A binary operator creating a block address?");
733 if (
ConstantInt *CI = dyn_cast<ConstantInt>(BO->getOperand(1))) {
735 ComputeValueKnownInPredecessorsImpl(BO->getOperand(0), BB, LHSVals,
739 for (
const auto &LHSVal : LHSVals) {
744 Result.
push_back(std::make_pair(KC, LHSVal.second));
748 return !Result.
empty();
752 if (
CmpInst *Cmp = dyn_cast<CmpInst>(I)) {
754 Type *CmpType = Cmp->getType();
755 Value *CmpLHS = Cmp->getOperand(0);
756 Value *CmpRHS = Cmp->getOperand(1);
766 if (DTU->hasPendingDomTreeUpdates())
782 if (!isa<Constant>(RHS))
787 if (LHSInst && LHSInst->getParent() == BB)
791 ResT = LVI->getPredicateOnEdge(Pred, LHS,
792 cast<Constant>(RHS), PredBB, BB,
800 Result.
push_back(std::make_pair(KC, PredBB));
803 return !Result.
empty();
808 if (isa<Constant>(CmpRHS) && !CmpType->
isVectorTy()) {
809 Constant *CmpConst = cast<Constant>(CmpRHS);
811 if (!isa<Instruction>(CmpLHS) ||
812 cast<Instruction>(CmpLHS)->
getParent() != BB) {
813 if (DTU->hasPendingDomTreeUpdates())
821 LVI->getPredicateOnEdge(Pred, CmpLHS,
822 CmpConst,
P, BB, CxtI ? CxtI : Cmp);
830 return !Result.
empty();
841 if (isa<ConstantInt>(CmpConst) &&
843 if (!isa<Instruction>(AddLHS) ||
844 cast<Instruction>(AddLHS)->
getParent() != BB) {
845 if (DTU->hasPendingDomTreeUpdates())
854 AddLHS,
P, BB, CxtI ? CxtI : cast<Instruction>(CmpLHS));
860 Pred, cast<ConstantInt>(CmpConst)->getValue());
873 return !Result.
empty();
881 ComputeValueKnownInPredecessorsImpl(I->
getOperand(0), BB, LHSVals,
884 for (
const auto &LHSVal : LHSVals) {
888 Result.
push_back(std::make_pair(KC, LHSVal.second));
891 return !Result.
empty();
901 if ((TrueVal || FalseVal) &&
902 ComputeValueKnownInPredecessorsImpl(
SI->getCondition(), BB, Conds,
904 for (
auto &
C : Conds) {
909 if (
ConstantInt *CI = dyn_cast<ConstantInt>(Cond)) {
911 KnownCond = CI->isOne();
913 assert(isa<UndefValue>(Cond) &&
"Unexpected condition value");
917 KnownCond = (TrueVal !=
nullptr);
921 if (
Constant *Val = KnownCond ? TrueVal : FalseVal)
922 Result.
push_back(std::make_pair(Val,
C.second));
925 return !Result.
empty();
930 if (DTU->hasPendingDomTreeUpdates())
934 Constant *CI = LVI->getConstant(V, BB, CxtI);
937 Result.
push_back(std::make_pair(KC, Pred));
940 return !Result.
empty();
950 unsigned MinSucc = 0;
953 unsigned MinNumPreds =
pred_size(TestBB);
957 if (NumPreds < MinNumPreds) {
959 MinNumPreds = NumPreds;
981 if (DTU->isBBPendingDeletion(BB) ||
990 const Instruction *TI = SinglePred->getTerminator();
994 if (LoopHeaders.erase(SinglePred))
995 LoopHeaders.insert(BB);
997 LVI->eraseBlock(SinglePred);
1028 LVI->eraseBlock(BB);
1033 if (TryToUnfoldSelectInCurrBB(BB))
1037 if (HasGuards && ProcessGuards(BB))
1047 if (
BranchInst *BI = dyn_cast<BranchInst>(Terminator)) {
1049 if (BI->isUnconditional())
return false;
1050 Condition = BI->getCondition();
1051 }
else if (
SwitchInst *
SI = dyn_cast<SwitchInst>(Terminator)) {
1052 Condition =
SI->getCondition();
1053 }
else if (
IndirectBrInst *IB = dyn_cast<IndirectBrInst>(Terminator)) {
1055 if (IB->getNumSuccessors() == 0)
return false;
1064 if (
Instruction *
I = dyn_cast<Instruction>(Condition)) {
1068 I->replaceAllUsesWith(SimpleVal);
1070 I->eraseFromParent();
1071 Condition = SimpleVal;
1077 if (isa<UndefValue>(Condition)) {
1079 std::vector<DominatorTree::UpdateType> Updates;
1085 if (i == BestSucc)
continue;
1092 <<
"' folding undef terminator: " << *BBTerm <<
'\n');
1095 DTU->applyUpdates(Updates);
1116 if (ProcessThreadableEdges(Condition, BB, Preference, Terminator))
1121 if (
CmpInst *CondCmp = dyn_cast<CmpInst>(CondInst)) {
1128 if (CondBr && CondConst) {
1134 if (DTU->hasPendingDomTreeUpdates())
1139 LVI->getPredicateAt(CondCmp->getPredicate(), CondCmp->getOperand(0),
1148 if (CondCmp->use_empty())
1149 CondCmp->eraseFromParent();
1157 else if (CondCmp->getParent() == BB) {
1163 DTU->deleteEdgeRelaxed(BB, ToRemoveSucc);
1169 if (TryToUnfoldSelect(CondCmp, BB))
1175 TryToUnfoldSelect(
SI, BB);
1181 Value *SimplifyValue = CondInst;
1182 if (
CmpInst *CondCmp = dyn_cast<CmpInst>(SimplifyValue))
1183 if (isa<Constant>(CondCmp->getOperand(1)))
1184 SimplifyValue = CondCmp->getOperand(0);
1188 if (
LoadInst *LoadI = dyn_cast<LoadInst>(SimplifyValue))
1189 if (SimplifyPartiallyRedundantLoad(LoadI))
1193 if (
PHINode *PN = dyn_cast<PHINode>(CondInst))
1194 if (PN->getParent() == BB && isa<BranchInst>(BB->
getTerminator()))
1200 if (ProcessThreadableEdges(CondInst, BB, Preference, Terminator))
1205 if (
PHINode *PN = dyn_cast<PHINode>(CondInst))
1206 if (PN->getParent() == BB && isa<BranchInst>(BB->
getTerminator()))
1207 return ProcessBranchOnPHI(PN);
1210 if (CondInst->
getOpcode() == Instruction::Xor &&
1212 return ProcessBranchOnXOR(cast<BinaryOperator>(CondInst));
1216 if (ProcessImpliedCondition(BB))
1224 if (!BI || !BI->isConditional())
1227 Value *Cond = BI->getCondition();
1236 if (!PBI || !PBI->isConditional())
1238 if (PBI->getSuccessor(0) != CurrentBB && PBI->getSuccessor(1) != CurrentBB)
1245 BasicBlock *KeepSucc = BI->getSuccessor(*Implication ? 0 : 1);
1246 BasicBlock *RemoveSucc = BI->getSuccessor(*Implication ? 1 : 0);
1249 BI->eraseFromParent();
1250 DTU->deleteEdgeRelaxed(BB, RemoveSucc);
1253 CurrentBB = CurrentPred;
1262 if (
Instruction *OpInst = dyn_cast<Instruction>(Op))
1263 if (OpInst->getParent() == BB)
1305 LoadInst *NLoadI = cast<LoadInst>(AvailableVal);
1311 if (AvailableVal == LoadI)
1313 if (AvailableVal->getType() != LoadI->
getType())
1315 AvailableVal, LoadI->
getType(),
"", LoadI);
1324 if (BBIt != LoadBB->
begin())
1336 AvailablePredsTy AvailablePreds;
1344 if (!PredsScanned.
insert(PredBB).second)
1347 BBIt = PredBB->end();
1348 unsigned NumScanedInst = 0;
1349 Value *PredAvailable =
nullptr;
1353 "Attempting to CSE volatile or atomic loads");
1364 while (!PredAvailable && SinglePredBB && BBIt == SinglePredBB->begin() &&
1368 BBIt = SinglePredBB->
end();
1371 (DefMaxInstsToScan - NumScanedInst), AA, &IsLoadCSE,
1376 if (!PredAvailable) {
1377 OneUnavailablePred = PredBB;
1382 CSELoads.
push_back(cast<LoadInst>(PredAvailable));
1386 AvailablePreds.push_back(std::make_pair(PredBB, PredAvailable));
1391 if (AvailablePreds.empty())
return false;
1408 if (PredsScanned.
size() != AvailablePreds.size() &&
1410 for (
auto I = LoadBB->
begin(); &*
I != LoadI; ++
I)
1417 if (PredsScanned.
size() == AvailablePreds.size()+1 &&
1419 UnavailablePred = OneUnavailablePred;
1420 }
else if (PredsScanned.
size() != AvailablePreds.size()) {
1426 for (
const auto &AvailablePred : AvailablePreds)
1427 AvailablePredSet.
insert(AvailablePred.first);
1432 if (isa<IndirectBrInst>(
P->getTerminator()))
1435 if (!AvailablePredSet.
count(
P))
1440 UnavailablePred = SplitBlockPreds(LoadBB, PredsToSplit,
"thread-pre-split");
1446 if (UnavailablePred) {
1448 "Can't handle critical edge here!");
1456 NewVal->setAAMetadata(AATags);
1458 AvailablePreds.push_back(std::make_pair(UnavailablePred, NewVal));
1476 AvailablePredsTy::iterator
I =
1478 std::make_pair(P, (
Value*)
nullptr));
1480 assert(I != AvailablePreds.end() && I->first == P &&
1481 "Didn't find entry for predecessor!");
1487 Value *&PredV = I->second;
1488 if (PredV->getType() != LoadI->
getType())
1495 for (
LoadInst *PredLoadI : CSELoads) {
1512 assert(!PredToDestList.empty());
1519 for (
const auto &PredToDest : PredToDestList)
1520 if (PredToDest.second)
1521 DestPopularity[PredToDest.second]++;
1523 if (DestPopularity.empty())
1529 unsigned Popularity = DPI->second;
1532 for (++DPI; DPI != DestPopularity.
end(); ++DPI) {
1535 if (DPI->second < Popularity)
1537 else if (DPI->second == Popularity) {
1542 SamePopularity.
clear();
1543 MostPopularDest = DPI->first;
1544 Popularity = DPI->second;
1552 if (!SamePopularity.
empty()) {
1553 SamePopularity.
push_back(MostPopularDest);
1555 for (
unsigned i = 0; ; ++i) {
1567 return MostPopularDest;
1575 if (LoopHeaders.count(BB))
1579 if (!ComputeValueKnownInPredecessors(Cond, BB, PredValues, Preference, CxtI))
1583 "ComputeValueKnownInPredecessors returned true with no values");
1586 for (
const auto &PredValue : PredValues) {
1588 <<
"': FOUND condition = " << *PredValue.first
1589 <<
" for pred '" << PredValue.second->getName() <<
"'.\n";
1604 unsigned PredWithKnownDest = 0;
1605 for (
const auto &PredValue : PredValues) {
1607 if (!SeenPreds.insert(Pred).second)
1613 if (isa<UndefValue>(Val))
1616 assert(isa<ConstantInt>(Val) &&
"Expecting a constant integer");
1617 DestBB = BI->getSuccessor(cast<ConstantInt>(Val)->
isZero());
1619 assert(isa<ConstantInt>(Val) &&
"Expecting a constant integer");
1620 DestBB =
SI->findCaseValue(cast<ConstantInt>(Val))->getCaseSuccessor();
1623 &&
"Unexpected terminator");
1624 assert(isa<BlockAddress>(Val) &&
"Expecting a constant blockaddress");
1625 DestBB = cast<BlockAddress>(Val)->getBasicBlock();
1629 if (PredToDestList.
empty()) {
1633 if (OnlyDest != DestBB)
1634 OnlyDest = MultipleDestSentinel;
1638 OnlyVal = MultipleVal;
1642 ++PredWithKnownDest;
1649 PredToDestList.
push_back(std::make_pair(Pred, DestBB));
1653 if (PredToDestList.
empty())
1659 if (OnlyDest && OnlyDest != MultipleDestSentinel) {
1660 if (PredWithKnownDest == (
size_t)
pred_size(BB)) {
1661 bool SeenFirstBranchToOnlyDest =
false;
1662 std::vector <DominatorTree::UpdateType> Updates;
1665 if (SuccBB == OnlyDest && !SeenFirstBranchToOnlyDest) {
1666 SeenFirstBranchToOnlyDest =
true;
1668 SuccBB->removePredecessor(BB,
true);
1677 DTU->applyUpdates(Updates);
1681 if (
auto *CondInst = dyn_cast<Instruction>(Cond)) {
1682 if (CondInst->use_empty() && !CondInst->mayHaveSideEffects())
1683 CondInst->eraseFromParent();
1691 else if (OnlyVal && OnlyVal != MultipleVal &&
1692 CondInst->getParent() == BB)
1705 if (MostPopularDest == MultipleDestSentinel) {
1710 [&](
const std::pair<BasicBlock *, BasicBlock *> &PredToDest) {
1711 return LoopHeaders.count(PredToDest.second) != 0;
1714 if (PredToDestList.
empty())
1723 for (
const auto &PredToDest : PredToDestList)
1724 if (PredToDest.second == MostPopularDest) {
1737 if (!MostPopularDest)
1742 return ThreadEdge(BB, PredsToFactor, MostPopularDest);
1763 if (PredBr->isUnconditional()) {
1764 PredBBs[0] = PredBB;
1766 if (DuplicateCondBranchOnPHIIntoPred(BB, PredBBs))
1788 if (!isa<PHINode>(BB->
front()))
1815 if (!ComputeValueKnownInPredecessors(BO->
getOperand(0), BB, XorOpValues,
1817 assert(XorOpValues.empty());
1818 if (!ComputeValueKnownInPredecessors(BO->
getOperand(1), BB, XorOpValues,
1824 assert(!XorOpValues.empty() &&
1825 "ComputeValueKnownInPredecessors returned true with no values");
1829 unsigned NumTrue = 0, NumFalse = 0;
1830 for (
const auto &XorOpValue : XorOpValues) {
1831 if (isa<UndefValue>(XorOpValue.first))
1834 if (cast<ConstantInt>(XorOpValue.first)->isZero())
1842 if (NumTrue > NumFalse)
1844 else if (NumTrue != 0 || NumFalse != 0)
1850 for (
const auto &XorOpValue : XorOpValues) {
1851 if (XorOpValue.first != SplitVal && !isa<UndefValue>(XorOpValue.first))
1854 BlocksToFoldInto.
push_back(XorOpValue.second);
1859 if (BlocksToFoldInto.size() ==
1860 cast<PHINode>(BB->
front()).getNumIncomingValues()) {
1865 }
else if (SplitVal->
isZero()) {
1878 return DuplicateCondBranchOnPHIIntoPred(BB, BlocksToFoldInto);
1891 Value *IV = PN.getIncomingValueForBlock(OldPred);
1894 if (
Instruction *Inst = dyn_cast<Instruction>(IV)) {
1896 if (I != ValueMap.
end())
1900 PN.addIncoming(IV, NewPred);
1913 <<
"' - would thread to self!\n");
1919 if (LoopHeaders.count(BB) || LoopHeaders.count(SuccBB)) {
1921 bool BBIsHeader = LoopHeaders.count(BB);
1922 bool SuccIsHeader = LoopHeaders.count(SuccBB);
1923 dbgs() <<
" Not threading across " 1924 << (BBIsHeader ?
"loop header BB '" :
"block BB '") << BB->
getName()
1925 <<
"' to dest " << (SuccIsHeader ?
"loop header BB '" :
"block BB '")
1926 << SuccBB->
getName() <<
"' - it might create an irreducible loop!\n";
1931 unsigned JumpThreadCost =
1933 if (JumpThreadCost > BBDupThreshold) {
1935 <<
"' - Cost is too high: " << JumpThreadCost <<
"\n");
1941 if (PredBBs.
size() == 1)
1942 PredBB = PredBBs[0];
1945 <<
" common predecessors.\n");
1946 PredBB = SplitBlockPreds(BB, PredBBs,
".thr_comm");
1951 <<
"' to '" << SuccBB->
getName()
1952 <<
"' with cost: " << JumpThreadCost
1953 <<
", across block:\n " << *BB <<
"\n");
1955 if (DTU->hasPendingDomTreeUpdates())
1959 LVI->threadEdge(PredBB, BB, SuccBB);
1972 if (HasProfileData) {
1974 BFI->getBlockFreq(PredBB) * BPI->getEdgeProbability(PredBB, BB);
1975 BFI->setBlockFreq(NewBB, NewBBFreq.getFrequency());
1984 for (; !BI->isTerminator(); ++BI) {
1988 ValueMapping[&*BI] = New;
1994 if (I != ValueMapping.
end())
2034 for (
Use &U :
I.uses()) {
2036 if (
PHINode *UserPN = dyn_cast<PHINode>(User)) {
2037 if (UserPN->getIncomingBlock(U) == BB)
2046 if (UsesToRename.
empty())
2048 LLVM_DEBUG(
dbgs() <<
"JT: Renaming non-local uses of: " <<
I <<
"\n");
2057 while (!UsesToRename.
empty())
2068 UpdateBlockFreqAndEdgeWeight(PredBB, BB, NewBB, SuccBB);
2080 const char *Suffix) {
2087 for (
auto Pred : Preds)
2088 FreqMap.
insert(std::make_pair(
2089 Pred,
BFI->getBlockFreq(Pred) * BPI->getEdgeProbability(Pred, BB)));
2094 std::string NewName = std::string(Suffix) +
".split-lp";
2100 std::vector<DominatorTree::UpdateType> Updates;
2101 Updates.reserve((2 * Preds.size()) + NewBBs.
size());
2102 for (
auto NewBB : NewBBs) {
2109 NewBBFreq += FreqMap.
lookup(Pred);
2115 DTU->applyUpdates(Updates);
2119 bool JumpThreadingPass::doesBlockHaveProfileData(
BasicBlock *BB) {
2127 MDString *MDName = cast<MDString>(WeightsNode->getOperand(0));
2128 if (MDName->
getString() !=
"branch_weights")
2139 void JumpThreadingPass::UpdateBlockFreqAndEdgeWeight(
BasicBlock *PredBB,
2143 if (!HasProfileData)
2146 assert(
BFI && BPI &&
"BFI & BPI should have been created here");
2150 auto BBOrigFreq =
BFI->getBlockFreq(BB);
2151 auto NewBBFreq =
BFI->getBlockFreq(NewBB);
2152 auto BB2SuccBBFreq = BBOrigFreq * BPI->getEdgeProbability(BB, SuccBB);
2153 auto BBNewFreq = BBOrigFreq - NewBBFreq;
2154 BFI->setBlockFreq(BB, BBNewFreq.getFrequency());
2160 auto SuccFreq = (Succ == SuccBB)
2161 ? BB2SuccBBFreq - NewBBFreq
2162 : BBOrigFreq * BPI->getEdgeProbability(BB, Succ);
2163 BBSuccFreq.
push_back(SuccFreq.getFrequency());
2166 uint64_t MaxBBSuccFreq =
2167 *std::max_element(BBSuccFreq.
begin(), BBSuccFreq.
end());
2170 if (MaxBBSuccFreq == 0)
2172 {1,
static_cast<unsigned>(BBSuccFreq.
size())});
2174 for (uint64_t Freq : BBSuccFreq)
2175 BBSuccProbs.push_back(
2183 for (
int I = 0,
E = BBSuccProbs.size();
I <
E;
I++)
2184 BPI->setEdgeProbability(BB,
I, BBSuccProbs[
I]);
2220 if (BBSuccProbs.size() >= 2 && doesBlockHaveProfileData(BB)) {
2222 for (
auto Prob : BBSuccProbs)
2228 MDBuilder(TI->getParent()->getContext()).createBranchWeights(Weights));
2239 assert(!PredBBs.
empty() &&
"Can't handle an empty set");
2244 if (LoopHeaders.count(BB)) {
2246 <<
"' into predecessor block '" << PredBBs[0]->getName()
2247 <<
"' - it might create an irreducible loop!\n");
2251 unsigned DuplicationCost =
2253 if (DuplicationCost > BBDupThreshold) {
2255 <<
"' - Cost is too high: " << DuplicationCost <<
"\n");
2260 std::vector<DominatorTree::UpdateType> Updates;
2262 if (PredBBs.
size() == 1)
2263 PredBB = PredBBs[0];
2266 <<
" common predecessors.\n");
2267 PredBB = SplitBlockPreds(BB, PredBBs,
".thr_comm");
2274 <<
"' into end of '" << PredBB->
getName()
2275 <<
"' to eliminate branch on phi. Cost: " 2276 << DuplicationCost <<
" block is:" << *BB <<
"\n");
2282 if (!OldPredBranch || !OldPredBranch->isUnconditional()) {
2300 for (; BI != BB->
end(); ++BI) {
2307 if (I != ValueMapping.end())
2317 ValueMapping[&*BI] = IV;
2323 ValueMapping[&*BI] = New;
2353 for (
Use &U :
I.uses()) {
2355 if (
PHINode *UserPN = dyn_cast<PHINode>(User)) {
2356 if (UserPN->getIncomingBlock(U) == BB)
2365 if (UsesToRename.
empty())
2368 LLVM_DEBUG(
dbgs() <<
"JT: Renaming non-local uses of: " <<
I <<
"\n");
2373 SSAUpdate.Initialize(
I.getType(),
I.getName());
2374 SSAUpdate.AddAvailableValue(BB, &
I);
2375 SSAUpdate.AddAvailableValue(PredBB, ValueMapping[&
I]);
2377 while (!UsesToRename.
empty())
2384 BB->removePredecessor(PredBB,
true);
2387 OldPredBranch->eraseFromParent();
2388 DTU->applyUpdates(Updates);
2416 NewBB->getInstList().insert(NewBB->end(), PredTerm);
2437 if (!CondPHI || CondPHI->
getParent() != BB)
2454 UnfoldSelectInstr(Pred, BB, PredSI, CondPHI,
I);
2478 CondLHS->getParent() != BB)
2481 for (
unsigned I = 0,
E = CondLHS->getNumIncomingValues();
I !=
E; ++
I) {
2497 if (DTU->hasPendingDomTreeUpdates())
2503 CondRHS, Pred, BB, CondCmp);
2506 CondRHS, Pred, BB, CondCmp);
2509 LHSFolds != RHSFolds) {
2510 UnfoldSelectInstr(Pred, BB, SI, CondLHS,
I);
2540 if (LoopHeaders.count(BB))
2547 [](
Value *V) {
return !isa<ConstantInt>(V); }))
2560 if (
ICmpInst *Cmp = dyn_cast<ICmpInst>(U.getUser())) {
2563 if (Cmp->getParent() == BB && Cmp->
hasOneUse() &&
2564 isa<ConstantInt>(Cmp->getOperand(1 - U.getOperandNo())))
2565 if (
SelectInst *SelectI = dyn_cast<SelectInst>(Cmp->user_back()))
2566 if (isUnfoldCandidate(SelectI, Cmp->use_begin()->get())) {
2570 }
else if (
SelectInst *SelectI = dyn_cast<SelectInst>(U.getUser())) {
2572 if (isUnfoldCandidate(SelectI, U.get())) {
2592 std::vector<DominatorTree::UpdateType> Updates;
2593 Updates.reserve((2 * SplitBB->getTerminator()->getNumSuccessors()) + 3);
2602 DTU->applyUpdates(Updates);
2650 if (
auto *BI = dyn_cast<BranchInst>(Parent->getTerminator()))
2652 if (
isGuard(&
I) && ThreadGuard(BB, cast<IntrinsicInst>(&
I), BI))
2671 bool TrueDestIsSafe =
false;
2672 bool FalseDestIsSafe =
false;
2677 TrueDestIsSafe =
true;
2682 FalseDestIsSafe =
true;
2685 if (!TrueDestIsSafe && !FalseDestIsSafe)
2688 BasicBlock *PredUnguardedBlock = TrueDestIsSafe ? TrueDest : FalseDest;
2689 BasicBlock *PredGuardedBlock = FalseDestIsSafe ? TrueDest : FalseDest;
2694 if (Cost > BBDupThreshold)
2699 BB, PredGuardedBlock, AfterGuard, GuardedMapping, *DTU);
2700 assert(GuardedBlock &&
"Could not create the guarded block?");
2705 BB, PredUnguardedBlock, Guard, UnguardedMapping, *DTU);
2706 assert(UnguardedBlock &&
"Could not create the unguarded block?");
2708 << GuardedBlock->
getName() <<
"\n");
2713 for (
auto BI = BB->
begin(); &*BI != AfterGuard; ++BI)
2714 if (!isa<PHINode>(&*BI))
2718 assert(InsertionPoint &&
"Empty block?");
2720 for (
auto *Inst :
reverse(ToRemove)) {
2721 if (!Inst->use_empty()) {
2723 NewPN->
addIncoming(UnguardedMapping[Inst], UnguardedBlock);
2724 NewPN->
addIncoming(GuardedMapping[Inst], GuardedBlock);
2726 Inst->replaceAllUsesWith(NewPN);
2728 Inst->eraseFromParent();
Legacy wrapper pass to provide the GlobalsAAResult object.
bool ThreadEdge(BasicBlock *BB, const SmallVectorImpl< BasicBlock *> &PredBBs, BasicBlock *SuccBB)
ThreadEdge - We have decided that it is safe and profitable to factor the blocks in PredBBs to one pr...
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
IntegerType * getType() const
getType - Specialize the getType() method to always return an IntegerType, which reduces the amount o...
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
iterator_range< use_iterator > uses()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
void removePredecessor(BasicBlock *Pred, bool DontDeleteUselessPHIs=false)
Notify the BasicBlock that the predecessor Pred is no longer able to reach it.
static IntegerType * getInt1Ty(LLVMContext &C)
Helper class for SSA formation on a set of values defined in multiple blocks.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
BranchProbability getCompl() const
BasicBlock * DuplicateInstructionsInSplitBetween(BasicBlock *BB, BasicBlock *PredBB, Instruction *StopAt, ValueToValueMapTy &ValueMapping, DomTreeUpdater &DTU)
Split edge between BB and PredBB and duplicate all non-Phi instructions from BB between its beginning...
NodeTy * getNextNode()
Get the next node, or nullptr for the list tail.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
Wrapper around LazyValueInfo.
This is the interface for a simple mod/ref and alias analysis over globals.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
bool ConstantFoldTerminator(BasicBlock *BB, bool DeleteDeadConditions=false, const TargetLibraryInfo *TLI=nullptr, DomTreeUpdater *DTU=nullptr)
If a terminator instruction is predicated on a constant value, convert it into an unconditional branc...
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
void initializeJumpThreadingPass(PassRegistry &)
Implements a dense probed hash-table based set.
void push_back(const T &Elt)
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
This class represents a function call, abstracting a target machine's calling convention.
cl::opt< unsigned > DefMaxInstsToScan
The default number of maximum instructions to scan in the block, used by FindAvailableLoadedValue().
Value * getCondition() const
const Value * getTrueValue() const
uint64_t getFrequency() const
Returns the frequency as a fixpoint number scaled by the entry frequency.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
void DeleteDeadBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
Delete the specified block, which must have no predecessors.
LLVMContext & getContext() const
All values hold a context through their type.
static CastInst * CreateBitOrPointerCast(Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Create a BitCast, a PtrToInt, or an IntToPTr cast instruction.
void deleteValue()
Delete a pointer to a generic Value.
static cl::opt< unsigned > ImplicationSearchThreshold("jump-threading-implication-search-threshold", cl::desc("The number of predecessors to search for a stronger " "condition to use to thread over a weaker condition"), cl::init(3), cl::Hidden)
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Value * FindAvailablePtrLoadStore(Value *Ptr, Type *AccessTy, bool AtLeastAtomic, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan, AliasAnalysis *AA, bool *IsLoad, unsigned *NumScanedInst)
Scan backwards to see if we have the value of the given pointer available locally within a small numb...
static BasicBlock * FindMostPopularDest(BasicBlock *BB, const SmallVectorImpl< std::pair< BasicBlock *, BasicBlock *>> &PredToDestList)
FindMostPopularDest - The specified list contains multiple possible threadable destinations.
BasicBlock * getSuccessor(unsigned i) const
STATISTIC(NumFunctions, "Total number of functions")
bool SimplifyInstructionsInBlock(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Scan the specified basic block and try to simplify any instructions in it and recursively delete dead...
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
Value * getCondition() const
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
bool isVectorTy() const
True if this is an instance of VectorType.
This defines the Use class.
const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
LLVMContext & getContext() const
Get the context in which this basic block lives.
FunctionPass * createJumpThreadingPass(int Threshold=-1)
iterator begin()
Instruction iterator methods.
BasicBlock * SplitEdge(BasicBlock *From, BasicBlock *To, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
Split the edge connecting specified block.
Value * getArgOperand(unsigned i) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
bool runImpl(Function &F, TargetLibraryInfo *TLI_, LazyValueInfo *LVI_, AliasAnalysis *AA_, DomTreeUpdater *DTU_, bool HasProfileData_, std::unique_ptr< BlockFrequencyInfo > BFI_, std::unique_ptr< BranchProbabilityInfo > BPI_)
The address of a basic block.
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
void MergeBasicBlockIntoOnlyPred(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is a block with one predecessor and its predecessor is known to have one successor (BB!)...
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
This class represents the LLVM 'select' instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
static constexpr UpdateKind Delete
This is the base class for all instructions that perform data casts.
static cl::opt< unsigned > BBDuplicateThreshold("jump-threading-threshold", cl::desc("Max block size to duplicate for jump threading"), cl::init(6), cl::Hidden)
'undef' values are things that do not have specified contents.
Value * FindAvailableLoadedValue(LoadInst *Load, BasicBlock *ScanBB, BasicBlock::iterator &ScanFrom, unsigned MaxInstsToScan=DefMaxInstsToScan, AliasAnalysis *AA=nullptr, bool *IsLoadCSE=nullptr, unsigned *NumScanedInst=nullptr)
Scan backwards to see if we have the value of the given load available locally within a small number ...
unsigned getNumSuccessors() const
A Use represents the edge between a Value definition and its users.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isIntegerTy() const
True if this is an instance of IntegerType.
void setName(const Twine &Name)
Change the name of the value.
bool contains(const APInt &Val) const
Return true if the specified value is in the set.
bool TryToUnfoldSelectInCurrBB(BasicBlock *BB)
TryToUnfoldSelectInCurrBB - Look for PHI/Select or PHI/CMP/Select in the same BB in the form bb: p = ...
BinaryOp_match< LHS, RHS, Instruction::Add > m_Add(const LHS &L, const RHS &R)
void assign(size_type NumElts, const T &Elt)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
bool ComputeValueKnownInPredecessorsImpl(Value *V, BasicBlock *BB, jumpthreading::PredValueInfo &Result, jumpthreading::ConstantPreference Preference, DenseSet< std::pair< Value *, BasicBlock *>> &RecursionSet, Instruction *CxtI=nullptr)
ComputeValueKnownInPredecessors - Given a basic block BB and a value V, see if we can infer that the ...
Value * SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
Type * getType() const
All values are typed, get the type of this value.
static void normalizeProbabilities(ProbabilityIter Begin, ProbabilityIter End)
bool TryToSimplifyUncondBranchFromEmptyBlock(BasicBlock *BB, DomTreeUpdater *DTU=nullptr)
BB is known to contain an unconditional branch, and contains no instructions other than PHI nodes...
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
class_match< ConstantInt > m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
const APInt & getValue() const
Return the constant as an APInt value reference.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
auto lower_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::lower_bound which take ranges instead of having to pass begin/end explicitly...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
static bool ProcessBlock(BasicBlock &BB, DominatorTree &DT, LoopInfo &LI, AAResults &AA)
void takeName(Value *V)
Transfer the name from V to this value.
static Constant * getKnownConstant(Value *Val, ConstantPreference Preference)
getKnownConstant - Helper method to determine if we can thread over a terminator with the given value...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
void removeDeadConstantUsers() const
If there are any dead constant users dangling off of this constant, remove them.
void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock *> Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock *> &NewBBs, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method transforms the landing pad, OrigBB, by introducing two new basic blocks into the function...
iterator find(const_arg_type_t< KeyT > Val)
StringRef getString() const
const BasicBlock & getEntryBlock() const
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
static bool runOnFunction(Function &F, bool PostInlining)
BasicBlock * SplitBlockPredecessors(BasicBlock *BB, ArrayRef< BasicBlock *> Preds, const char *Suffix, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method introduces at least one new basic block into the function and moves some of the predecess...
initializer< Ty > init(const Ty &Val)
bool isGuaranteedToTransferExecutionToSuccessor(const Instruction *I)
Return true if this function can prove that the instruction I will always transfer execution to one o...
void array_pod_sort(IteratorTy Start, IteratorTy End)
array_pod_sort - This sorts an array with the specified start and end extent.
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
A set of analyses that are preserved following a run of a transformation pass.
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
static constexpr UpdateKind Insert
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Conditional or Unconditional Branch instruction.
static BlockAddress * get(Function *F, BasicBlock *BB)
Return a BlockAddress for the specified function and basic block.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
static bool isOpDefinedInBlock(Value *Op, BasicBlock *BB)
Return true if Op is an instruction defined in the given block.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
const Instruction & front() const
Indirect Branch Instruction.
A manager for alias analyses.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
Constant * ConstantFoldInstruction(Instruction *I, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstruction - Try to constant fold the specified instruction.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Represent the analysis usage information of a pass.
This instruction compares its operands according to the predicate given to the constructor.
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
JumpThreadingPass(int T=-1)
FunctionPass class - This class is used to implement most global optimizations.
ConstantRange add(const ConstantRange &Other) const
Return a new range representing the possible values resulting from an addition of a value in this ran...
Interval::pred_iterator pred_end(Interval *I)
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool pred_empty(const BasicBlock *BB)
static Constant * getNot(Constant *C)
void FindLoopHeaders(Function &F)
FindLoopHeaders - We do not want jump threading to turn proper loop structures into irreducible loops...
const Value * getCondition() const
static void updatePredecessorProfileMetadata(PHINode *PN, BasicBlock *BB)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
const Value * stripPointerCasts() const
Strip off pointer casts, all-zero GEPs, and aliases.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
bool isExceptionalTerminator() const
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
void setMetadata(unsigned KindID, MDNode *Node)
Set the metadata of the specified kind to the specified node.
static unsigned GetBestDestForJumpOnUndef(BasicBlock *BB)
GetBestDestForBranchOnUndef - If we determine that the specified block ends in an undefined jump...
Tristate
This is used to return true/false/dunno results.
bool ProcessBranchOnPHI(PHINode *PN)
ProcessBranchOnPHI - We have an otherwise unthreadable conditional branch on a PHI node in the curren...
bool isLandingPad() const
Return true if this basic block is a landing pad.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
const InstListType & getInstList() const
Return the underlying instruction list container.
static cl::opt< bool > PrintLVIAfterJumpThreading("print-lvi-after-jump-threading", cl::desc("Print the LazyValueInfo cache after JumpThreading"), cl::init(false), cl::Hidden)
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
static ConstantRange makeExactICmpRegion(CmpInst::Predicate Pred, const APInt &Other)
Produce the exact range such that all values in the returned range satisfy the given predicate with a...
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
This pass performs 'jump threading', which looks at blocks that have multiple predecessors and multip...
This class represents a range of values.
static BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_NODISCARD T pop_back_val()
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
bool SimplifyPartiallyRedundantLoad(LoadInst *LI)
SimplifyPartiallyRedundantLoad - If LoadI is an obviously partially redundant load instruction...
static BranchInst * Create(BasicBlock *IfTrue, Instruction *InsertBefore=nullptr)
bool isConditional() const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
pred_range predecessors(BasicBlock *BB)
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static ConstantInt * getTrue(LLVMContext &Context)
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
bool isGuard(const User *U)
Returns true iff U has semantics of a guard.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static unsigned getJumpThreadDuplicationCost(BasicBlock *BB, Instruction *StopAt, unsigned Threshold)
Return the cost of duplicating a piece of this block from first non-phi and before StopAt instruction...
Function * getFunction(StringRef Name) const
Look up the specified function in the module symbol table.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
void push_back(pointer val)
static cl::opt< unsigned > Threshold("loop-unswitch-threshold", cl::desc("Max loop size to unswitch"), cl::init(100), cl::Hidden)
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
const Value * getFalseValue() const
void removeFromParent()
This method unlinks 'this' from the containing basic block, but does not delete it.
Instruction * SplitBlockAndInsertIfThen(Value *Cond, Instruction *SplitBefore, bool Unreachable, MDNode *BranchWeights=nullptr, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr)
Split the containing block at the specified instruction - everything before SplitBefore stays in the ...
Predicate getPredicate() const
Return the predicate for this instruction.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Analysis providing branch probability information.
iterator insert(iterator where, pointer New)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
void emplace_back(ArgTypes &&... Args)
LLVM_NODISCARD bool empty() const
void UnfoldSelectInstr(BasicBlock *Pred, BasicBlock *BB, SelectInst *SI, PHINode *SIUse, unsigned Idx)
bool ProcessBranchOnXOR(BinaryOperator *BO)
ProcessBranchOnXOR - We have an otherwise unthreadable conditional branch on a xor instruction in the...
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
bool ProcessImpliedCondition(BasicBlock *BB)
unsigned pred_size(const BasicBlock *BB)
Get the number of predecessors of BB.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static void ReplaceFoldableUses(Instruction *Cond, Value *ToVal)
void preserve()
Mark an analysis as preserved.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
bool isUnconditional() const
static void AddPHINodeEntriesForMappedBlock(BasicBlock *PHIBB, BasicBlock *OldPred, BasicBlock *NewPred, DenseMap< Instruction *, Value *> &ValueMap)
AddPHINodeEntriesForMappedBlock - We're adding 'NewPred' as a new predecessor to the PHIBB block...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
bool ProcessThreadableEdges(Value *Cond, BasicBlock *BB, jumpthreading::ConstantPreference Preference, Instruction *CxtI=nullptr)
Optional< bool > isImpliedCondition(const Value *LHS, const Value *RHS, const DataLayout &DL, bool LHSIsTrue=true, unsigned Depth=0)
Return true if RHS is known to be implied true by LHS.
void FindFunctionBackedges(const Function &F, SmallVectorImpl< std::pair< const BasicBlock *, const BasicBlock *> > &Result)
Analyze the specified function to find all of the loop backedges in the function and return them...
Analysis pass providing the TargetLibraryInfo.
Helper struct that represents how a value is mapped through different register banks.
This pass computes, caches, and vends lazy value constraint information.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
See the comments on JumpThreadingPass.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
bool isEHPad() const
Return true if this basic block is an exception handling block.
unsigned getPrimitiveSizeInBits() const LLVM_READONLY
Return the basic size of this type if it is a primitive type.
bool ThreadGuard(BasicBlock *BB, IntrinsicInst *Guard, BranchInst *BI)
Try to propagate the guard from BB which is the lower block of a diamond to one of its branches...
bool ProcessGuards(BasicBlock *BB)
Try to propagate a guard from the current BB into one of its predecessors in case if another branch o...
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
succ_range successors(Instruction *I)
bool ProcessBlock(BasicBlock *BB)
ProcessBlock - If there are any predecessors whose control can be threaded through to a successor...
static const Function * getParent(const Value *V)
void combineMetadataForCSE(Instruction *K, const Instruction *J, bool DoesKMove)
Combine the metadata of two instructions so that K can replace J.
bool hasOneUse() const
Return true if there is exactly one user of this value.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
This header defines various interfaces for pass management in LLVM.
void setIncomingValue(unsigned i, Value *V)
INITIALIZE_PASS_BEGIN(JumpThreading, "jump-threading", "Jump Threading", false, false) INITIALIZE_PASS_END(JumpThreading
bool extractProfMetadata(uint64_t &TrueVal, uint64_t &FalseVal) const
Retrieve the raw weight values of a conditional branch or select.
op_range incoming_values()
ConstantRange inverse() const
Return a new range that is the logical not of the current set.
void RewriteUse(Use &U)
Rewrite a use of the symbolic value.
bool DuplicateCondBranchOnPHIIntoPred(BasicBlock *BB, const SmallVectorImpl< BasicBlock *> &PredBBs)
DuplicateCondBranchOnPHIIntoPred - PredBB contains an unconditional branch to BB which contains an i1...
static bool hasAddressTakenAndUsed(BasicBlock *BB)
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
bool hasProfileData() const
Return true if the function is annotated with profile data.
uint32_t getNumerator() const
unsigned replaceNonLocalUsesWith(Instruction *From, Value *To)
Analysis to compute lazy value information.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
bool TryToUnfoldSelect(CmpInst *CondCmp, BasicBlock *BB)
TryToUnfoldSelect - Look for blocks of the form bb1: a = select br bb2.
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.