80#ifdef EXPENSIVE_CHECKS
86#define DEBUG_TYPE "dfa-jump-threading"
88STATISTIC(NumTransforms,
"Number of transformations done");
90STATISTIC(NumPaths,
"Number of individual paths threaded");
94 cl::desc(
"View the CFG before DFA Jump Threading"),
98 "dfa-early-exit-heuristic",
99 cl::desc(
"Exit early if an unpredictable value come from the same loop"),
103 "dfa-max-path-length",
104 cl::desc(
"Max number of blocks searched to find a threading path"),
108 "dfa-max-num-visited-paths",
110 "Max number of blocks visited while enumerating paths around a switch"),
115 cl::desc(
"Max number of paths enumerated around a switch"),
120 cl::desc(
"Maximum cost accepted for the transformation"),
125class SelectInstToUnfold {
132 SelectInst *getInst() {
return SI; }
133 PHINode *getUse() {
return SIUse; }
135 explicit operator bool()
const {
return SI && SIUse; }
139 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
140 std::vector<BasicBlock *> *NewBBs);
142class DFAJumpThreading {
144 DFAJumpThreading(AssumptionCache *AC, DominatorTree *DT, LoopInfo *LI,
145 TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE)
146 : AC(AC), DT(DT), LI(LI), TTI(TTI), ORE(ORE) {}
148 bool run(Function &
F);
153 unfoldSelectInstrs(DominatorTree *DT,
155 DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Eager);
158 while (!
Stack.empty()) {
159 SelectInstToUnfold SIToUnfold =
Stack.pop_back_val();
161 std::vector<SelectInstToUnfold> NewSIsToUnfold;
162 std::vector<BasicBlock *> NewBBs;
163 unfold(&DTU, LI, SIToUnfold, &NewSIsToUnfold, &NewBBs);
173 TargetTransformInfo *TTI;
174 OptimizationRemarkEmitter *ORE;
189 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
190 std::vector<BasicBlock *> *NewBBs) {
192 PHINode *SIUse = SIToUnfold.getUse();
204 SI->getContext(),
Twine(
SI->getName(),
".si.unfold.false"),
206 NewBBs->push_back(NewBlock);
215 Value *SIOp1 =
SI->getTrueValue();
216 Value *SIOp2 =
SI->getFalseValue();
227 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlock);
236 Twine(
SI->getName(),
".si.unfold.phi"),
239 if (Pred != StartBlock && Pred != NewBlock)
250 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, SIUse));
252 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, NewPhi));
262 SI->getContext(),
Twine(
SI->getName(),
".si.unfold.true"),
265 SI->getContext(),
Twine(
SI->getName(),
".si.unfold.false"),
268 NewBBs->push_back(NewBlockT);
269 NewBBs->push_back(NewBlockF);
309 NewSIsToUnfold->push_back(SelectInstToUnfold(TrueSI, NewPhiT));
311 NewSIsToUnfold->push_back(SelectInstToUnfold(FalseSi, NewPhiF));
321 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlockT);
322 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlockF);
323 Phi.removeIncomingValue(StartBlock);
328 unsigned SuccNum = StartBlockTerm->
getSuccessor(1) == EndBlock ? 1 : 0;
337 L->addBasicBlockToLoop(NewBB, *LI);
341 assert(
SI->use_empty() &&
"Select must be dead now");
342 SI->eraseFromParent();
350typedef std::deque<BasicBlock *> PathType;
351typedef std::vector<PathType> PathsType;
353typedef std::vector<ClonedBlock> CloneList;
382struct ThreadingPath {
384 APInt getExitValue()
const {
return ExitVal; }
385 void setExitValue(
const ConstantInt *V) {
386 ExitVal =
V->getValue();
389 bool isExitValueSet()
const {
return IsExitValSet; }
392 const BasicBlock *getDeterminatorBB()
const {
return DBB; }
393 void setDeterminator(
const BasicBlock *BB) { DBB = BB; }
396 const PathType &getPath()
const {
return Path; }
397 void setPath(
const PathType &NewPath) { Path = NewPath; }
398 void push_back(BasicBlock *BB) { Path.push_back(BB); }
399 void push_front(BasicBlock *BB) { Path.push_front(BB); }
400 void appendExcludingFirst(
const PathType &OtherPath) {
404 void print(raw_ostream &OS)
const {
405 OS << Path <<
" [ " << ExitVal <<
", " << DBB->getName() <<
" ]";
412 bool IsExitValSet =
false;
423 MainSwitch(SwitchInst *SI, LoopInfo *LI, OptimizationRemarkEmitter *ORE)
429 return OptimizationRemarkMissed(
DEBUG_TYPE,
"SwitchNotPredictable", SI)
430 <<
"Switch instruction is not predictable.";
435 virtual ~MainSwitch() =
default;
437 SwitchInst *getInstr()
const {
return Instr; }
448 std::deque<std::pair<Value *, BasicBlock *>> Q;
449 SmallPtrSet<Value *, 16> SeenValues;
452 Value *SICond =
SI->getCondition();
458 const Loop *
L = LI->getLoopFor(
SI->getParent());
462 addToQueue(SICond,
nullptr, Q, SeenValues);
465 Value *Current = Q.front().first;
466 BasicBlock *CurrentIncomingBB = Q.front().second;
470 for (BasicBlock *IncomingBB :
Phi->blocks()) {
471 Value *Incoming =
Phi->getIncomingValueForBlock(IncomingBB);
472 addToQueue(Incoming, IncomingBB, Q, SeenValues);
476 if (!isValidSelectInst(SelI))
478 addToQueue(SelI->getTrueValue(), CurrentIncomingBB, Q, SeenValues);
479 addToQueue(SelI->getFalseValue(), CurrentIncomingBB, Q, SeenValues);
482 SelectInsts.push_back(SelectInstToUnfold(SelI, SelIUse));
498 L->contains(LI->getLoopFor(CurrentIncomingBB))) {
500 <<
"\tExiting early due to unpredictability heuristic.\n");
511 void addToQueue(
Value *Val, BasicBlock *BB,
512 std::deque<std::pair<Value *, BasicBlock *>> &Q,
513 SmallPtrSet<Value *, 16> &SeenValues) {
514 if (SeenValues.
insert(Val).second)
515 Q.push_back({Val, BB});
518 bool isValidSelectInst(SelectInst *SI) {
519 if (!
SI->hasOneUse())
542 for (SelectInstToUnfold SIToUnfold : SelectInsts) {
543 SelectInst *PrevSI = SIToUnfold.getInst();
553 SwitchInst *Instr =
nullptr;
557struct AllSwitchPaths {
558 AllSwitchPaths(
const MainSwitch *MSwitch, OptimizationRemarkEmitter *ORE,
559 LoopInfo *LI, Loop *L)
560 : Switch(MSwitch->getInstr()), SwitchBlock(Switch->
getParent()), ORE(ORE),
561 LI(LI), SwitchOuterLoop(
L) {}
563 std::vector<ThreadingPath> &getThreadingPaths() {
return TPaths; }
564 unsigned getNumThreadingPaths() {
return TPaths.size(); }
565 SwitchInst *getSwitchInst() {
return Switch; }
566 BasicBlock *getSwitchBlock() {
return SwitchBlock; }
569 StateDefMap StateDef = getStateDefMap();
570 if (StateDef.empty()) {
572 return OptimizationRemarkMissed(
DEBUG_TYPE,
"SwitchNotPredictable",
574 <<
"Switch instruction is not predictable.";
580 auto *SwitchPhiDefBB = SwitchPhi->getParent();
583 std::vector<ThreadingPath> PathsToPhiDef =
584 getPathsFromStateDefMap(StateDef, SwitchPhi, VB,
MaxNumPaths);
585 if (SwitchPhiDefBB == SwitchBlock || PathsToPhiDef.empty()) {
586 TPaths = std::move(PathsToPhiDef);
591 auto PathsLimit =
MaxNumPaths / PathsToPhiDef.size();
593 PathsType PathsToSwitchBB =
594 paths(SwitchPhiDefBB, SwitchBlock, VB, 1, PathsLimit);
595 if (PathsToSwitchBB.empty())
598 std::vector<ThreadingPath> TempList;
599 for (
const ThreadingPath &Path : PathsToPhiDef) {
600 for (
const PathType &PathToSw : PathsToSwitchBB) {
601 ThreadingPath PathCopy(Path);
602 PathCopy.appendExcludingFirst(PathToSw);
603 TempList.push_back(PathCopy);
606 TPaths = std::move(TempList);
612 typedef DenseMap<const BasicBlock *, const PHINode *> StateDefMap;
613 std::vector<ThreadingPath> getPathsFromStateDefMap(StateDefMap &StateDef,
616 unsigned PathsLimit) {
617 std::vector<ThreadingPath> Res;
618 auto *PhiBB =
Phi->getParent();
621 VisitedBlocks UniqueBlocks;
622 for (
auto *IncomingBB :
Phi->blocks()) {
623 if (Res.size() >= PathsLimit)
625 if (!UniqueBlocks.insert(IncomingBB).second)
627 if (!SwitchOuterLoop->contains(IncomingBB))
630 Value *IncomingValue =
Phi->getIncomingValueForBlock(IncomingBB);
634 if (PhiBB == SwitchBlock &&
635 SwitchBlock !=
cast<PHINode>(Switch->getOperand(0))->getParent())
637 ThreadingPath NewPath;
638 NewPath.setDeterminator(PhiBB);
639 NewPath.setExitValue(
C);
641 if (IncomingBB != SwitchBlock)
642 NewPath.push_back(IncomingBB);
643 NewPath.push_back(PhiBB);
644 Res.push_back(NewPath);
648 if (VB.contains(IncomingBB) || IncomingBB == SwitchBlock)
654 auto *IncomingPhiDefBB = IncomingPhi->getParent();
655 if (!StateDef.contains(IncomingPhiDefBB))
659 if (IncomingPhiDefBB == IncomingBB) {
660 assert(PathsLimit > Res.size());
661 std::vector<ThreadingPath> PredPaths = getPathsFromStateDefMap(
662 StateDef, IncomingPhi, VB, PathsLimit - Res.size());
663 for (ThreadingPath &Path : PredPaths) {
664 Path.push_back(PhiBB);
665 Res.push_back(std::move(Path));
671 if (VB.contains(IncomingPhiDefBB))
674 PathsType IntermediatePaths;
675 assert(PathsLimit > Res.size());
676 auto InterPathLimit = PathsLimit - Res.size();
677 IntermediatePaths = paths(IncomingPhiDefBB, IncomingBB, VB,
679 if (IntermediatePaths.empty())
682 assert(InterPathLimit >= IntermediatePaths.size());
683 auto PredPathLimit = InterPathLimit / IntermediatePaths.size();
684 std::vector<ThreadingPath> PredPaths =
685 getPathsFromStateDefMap(StateDef, IncomingPhi, VB, PredPathLimit);
686 for (
const ThreadingPath &Path : PredPaths) {
687 for (
const PathType &IPath : IntermediatePaths) {
688 ThreadingPath NewPath(Path);
689 NewPath.appendExcludingFirst(IPath);
690 NewPath.push_back(PhiBB);
691 Res.push_back(NewPath);
699 PathsType paths(BasicBlock *BB, BasicBlock *ToBB, VisitedBlocks &Visited,
700 unsigned PathDepth,
unsigned PathsLimit) {
706 return OptimizationRemarkAnalysis(
DEBUG_TYPE,
"MaxPathLengthReached",
708 <<
"Exploration stopped after visiting MaxPathLength="
720 if (!SwitchOuterLoop->contains(BB))
725 SmallPtrSet<BasicBlock *, 4> Successors;
727 if (Res.size() >= PathsLimit)
729 if (!Successors.
insert(Succ).second)
734 Res.push_back({BB, ToBB});
739 if (Visited.contains(Succ))
742 auto *CurrLoop = LI->getLoopFor(BB);
744 if (Succ == CurrLoop->getHeader())
748 if (LI->getLoopFor(Succ) != CurrLoop)
750 assert(PathsLimit > Res.size());
751 PathsType SuccPaths =
752 paths(Succ, ToBB, Visited, PathDepth + 1, PathsLimit - Res.size());
753 for (PathType &Path : SuccPaths) {
767 StateDefMap getStateDefMap()
const {
770 assert(FirstDef &&
"The first definition must be a phi.");
773 Stack.push_back(FirstDef);
774 SmallPtrSet<Value *, 16> SeenValues;
776 while (!
Stack.empty()) {
777 PHINode *CurPhi =
Stack.pop_back_val();
780 SeenValues.
insert(CurPhi);
782 for (BasicBlock *IncomingBB : CurPhi->
blocks()) {
783 PHINode *IncomingPhi =
787 bool IsOutsideLoops = !SwitchOuterLoop->contains(IncomingBB);
788 if (SeenValues.
contains(IncomingPhi) || IsOutsideLoops)
791 Stack.push_back(IncomingPhi);
798 unsigned NumVisited = 0;
801 OptimizationRemarkEmitter *ORE;
802 std::vector<ThreadingPath> TPaths;
804 Loop *SwitchOuterLoop;
808 TransformDFA(AllSwitchPaths *SwitchPaths, DominatorTree *DT,
809 AssumptionCache *AC, TargetTransformInfo *TTI,
810 OptimizationRemarkEmitter *ORE,
811 SmallPtrSet<const Value *, 32> EphValues)
812 : SwitchPaths(SwitchPaths), DT(DT), AC(AC), TTI(TTI), ORE(ORE),
813 EphValues(EphValues) {}
816 if (isLegalAndProfitableToTransform()) {
817 createAllExitPaths();
827 bool isLegalAndProfitableToTransform() {
829 SwitchInst *
Switch = SwitchPaths->getSwitchInst();
832 if (
Switch->getNumSuccessors() <= 1)
837 DuplicateBlockMap DuplicateMap;
839 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
840 PathType PathBBs = TPath.getPath();
841 APInt NextState = TPath.getExitValue();
842 const BasicBlock *Determinator = TPath.getDeterminatorBB();
845 BasicBlock *BB = SwitchPaths->getSwitchBlock();
846 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
848 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
849 DuplicateMap[BB].push_back({BB, NextState});
854 if (PathBBs.front() == Determinator)
859 auto DetIt =
llvm::find(PathBBs, Determinator);
860 for (
auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
862 VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
865 Metrics.analyzeBasicBlock(BB, *TTI, EphValues);
866 DuplicateMap[BB].push_back({BB, NextState});
870 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
871 <<
"non-duplicatable instructions.\n");
873 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NonDuplicatableInst",
875 <<
"Contains non-duplicatable instructions.";
881 if (
Metrics.Convergence != ConvergenceKind::None) {
882 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
883 <<
"convergent instructions.\n");
885 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ConvergentInst", Switch)
886 <<
"Contains convergent instructions.";
891 if (!
Metrics.NumInsts.isValid()) {
892 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
893 <<
"instructions with invalid cost.\n");
895 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ConvergentInst", Switch)
896 <<
"Contains instructions with invalid cost.";
904 unsigned JumpTableSize = 0;
905 TTI->getEstimatedNumberOfCaseClusters(*Switch, JumpTableSize,
nullptr,
907 if (JumpTableSize == 0) {
911 unsigned CondBranches =
912 APInt(32,
Switch->getNumSuccessors()).ceilLogBase2();
913 assert(CondBranches > 0 &&
914 "The threaded switch must have multiple branches");
915 DuplicationCost =
Metrics.NumInsts / CondBranches;
923 DuplicationCost =
Metrics.NumInsts / JumpTableSize;
926 LLVM_DEBUG(
dbgs() <<
"\nDFA Jump Threading: Cost to jump thread block "
927 << SwitchPaths->getSwitchBlock()->getName()
928 <<
" is: " << DuplicationCost <<
"\n\n");
931 LLVM_DEBUG(
dbgs() <<
"Not jump threading, duplication cost exceeds the "
932 <<
"cost threshold.\n");
934 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotProfitable", Switch)
935 <<
"Duplication cost exceeds the cost threshold (cost="
936 <<
ore::NV(
"Cost", DuplicationCost)
943 return OptimizationRemark(
DEBUG_TYPE,
"JumpThreaded", Switch)
944 <<
"Switch statement jump-threaded.";
951 void createAllExitPaths() {
952 DomTreeUpdater DTU(*DT, DomTreeUpdater::UpdateStrategy::Eager);
955 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock();
956 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
960 TPath.push_front(SwitchBlock);
964 DuplicateBlockMap DuplicateMap;
967 SmallPtrSet<BasicBlock *, 16> BlocksToClean;
970 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
971 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, &DTU);
977 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths())
978 updateLastSuccessor(TPath, DuplicateMap, &DTU);
984 for (BasicBlock *BB : BlocksToClean)
994 void createExitPath(DefMap &NewDefs, ThreadingPath &Path,
995 DuplicateBlockMap &DuplicateMap,
996 SmallPtrSet<BasicBlock *, 16> &BlocksToClean,
997 DomTreeUpdater *DTU) {
998 APInt NextState =
Path.getExitValue();
1000 PathType PathBBs =
Path.getPath();
1003 if (PathBBs.front() == Determinator)
1004 PathBBs.pop_front();
1006 auto DetIt =
llvm::find(PathBBs, Determinator);
1009 BasicBlock *PrevBB = PathBBs.size() == 1 ? *DetIt : *std::prev(DetIt);
1010 for (
auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
1012 BlocksToClean.
insert(BB);
1016 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap);
1018 updatePredecessor(PrevBB, BB, NextBB, DTU);
1024 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor(
1025 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU);
1026 DuplicateMap[BB].push_back({NewBB, NextState});
1027 BlocksToClean.
insert(NewBB);
1038 void updateSSA(DefMap &NewDefs) {
1039 SSAUpdaterBulk SSAUpdate;
1040 SmallVector<Use *, 16> UsesToRename;
1042 for (
const auto &KV : NewDefs) {
1045 std::vector<Instruction *> Cloned = KV.second;
1049 for (Use &U :
I->uses()) {
1052 if (UserPN->getIncomingBlock(U) == BB)
1054 }
else if (
User->getParent() == BB) {
1063 if (UsesToRename.
empty())
1071 unsigned VarNum = SSAUpdate.
AddVariable(
I->getName(),
I->getType());
1073 for (Instruction *New : Cloned)
1076 while (!UsesToRename.
empty())
1090 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB,
1091 const APInt &NextState,
1092 DuplicateBlockMap &DuplicateMap,
1094 DomTreeUpdater *DTU) {
1102 for (Instruction &
I : *NewBB) {
1111 AC->registerAssumption(
II);
1114 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap);
1115 updatePredecessor(PrevBB, BB, NewBB, DTU);
1116 updateDefMap(NewDefs, VMap);
1119 SmallPtrSet<BasicBlock *, 4> SuccSet;
1121 if (SuccSet.
insert(SuccBB).second)
1122 DTU->
applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}});
1132 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB,
1134 DuplicateBlockMap &DuplicateMap) {
1135 std::vector<BasicBlock *> BlocksToUpdate;
1139 if (BB == SwitchPaths->getSwitchBlock()) {
1140 SwitchInst *
Switch = SwitchPaths->getSwitchInst();
1141 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1142 BlocksToUpdate.push_back(NextCase);
1143 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap);
1145 BlocksToUpdate.push_back(ClonedSucc);
1150 BlocksToUpdate.push_back(Succ);
1155 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap);
1157 BlocksToUpdate.push_back(ClonedSucc);
1164 for (BasicBlock *Succ : BlocksToUpdate) {
1167 Value *Incoming =
Phi->getIncomingValueForBlock(BB);
1170 Phi->addIncoming(Incoming, ClonedBB);
1173 Value *ClonedVal = VMap[Incoming];
1175 Phi->addIncoming(ClonedVal, ClonedBB);
1177 Phi->addIncoming(Incoming, ClonedBB);
1185 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB,
1186 BasicBlock *NewBB, DomTreeUpdater *DTU) {
1189 if (!isPredecessor(OldBB, PrevBB))
1199 DTU->
applyUpdates({{DominatorTree::Delete, PrevBB, OldBB},
1200 {DominatorTree::Insert, PrevBB, NewBB}});
1209 for (
auto Entry : VMap) {
1221 NewDefsVector.
push_back({Inst, Cloned});
1225 sort(NewDefsVector, [](
const auto &
LHS,
const auto &
RHS) {
1226 if (
LHS.first ==
RHS.first)
1227 return LHS.second->comesBefore(
RHS.second);
1228 return LHS.first->comesBefore(
RHS.first);
1231 for (
const auto &KV : NewDefsVector)
1232 NewDefs[KV.first].push_back(KV.second);
1240 void updateLastSuccessor(ThreadingPath &TPath,
1241 DuplicateBlockMap &DuplicateMap,
1242 DomTreeUpdater *DTU) {
1243 APInt NextState = TPath.getExitValue();
1245 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap);
1252 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1254 std::vector<DominatorTree::UpdateType> DTUpdates;
1255 SmallPtrSet<BasicBlock *, 4> SuccSet;
1256 for (BasicBlock *Succ :
successors(LastBlock)) {
1257 if (Succ != NextCase && SuccSet.
insert(Succ).second)
1258 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ});
1261 Switch->eraseFromParent();
1269 void cleanPhiNodes(BasicBlock *BB) {
1272 std::vector<PHINode *> PhiToRemove;
1274 PhiToRemove.push_back(Phi);
1276 for (PHINode *PN : PhiToRemove) {
1278 PN->eraseFromParent();
1285 std::vector<BasicBlock *> BlocksToRemove;
1286 for (BasicBlock *IncomingBB :
Phi->blocks()) {
1287 if (!isPredecessor(BB, IncomingBB))
1288 BlocksToRemove.push_back(IncomingBB);
1290 for (BasicBlock *BB : BlocksToRemove)
1291 Phi->removeIncomingValue(BB);
1297 BasicBlock *getClonedBB(BasicBlock *BB,
const APInt &NextState,
1298 DuplicateBlockMap &DuplicateMap) {
1299 CloneList ClonedBBs = DuplicateMap[BB];
1303 auto It =
llvm::find_if(ClonedBBs, [NextState](
const ClonedBlock &
C) {
1304 return C.State == NextState;
1306 return It != ClonedBBs.end() ? (*It).BB :
nullptr;
1311 BasicBlock *getNextCaseSuccessor(SwitchInst *Switch,
const APInt &NextState) {
1313 for (
auto Case :
Switch->cases()) {
1314 if (Case.getCaseValue()->getValue() == NextState) {
1315 NextCase = Case.getCaseSuccessor();
1320 NextCase =
Switch->getDefaultDest();
1325 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) {
1329 AllSwitchPaths *SwitchPaths;
1331 AssumptionCache *AC;
1332 TargetTransformInfo *TTI;
1333 OptimizationRemarkEmitter *ORE;
1334 SmallPtrSet<const Value *, 32> EphValues;
1335 std::vector<ThreadingPath> TPaths;
1338bool DFAJumpThreading::run(
Function &
F) {
1339 LLVM_DEBUG(
dbgs() <<
"\nDFA Jump threading: " <<
F.getName() <<
"\n");
1341 if (
F.hasOptSize()) {
1342 LLVM_DEBUG(
dbgs() <<
"Skipping due to the 'minsize' attribute\n");
1350 bool MadeChanges =
false;
1351 LoopInfoBroken =
false;
1353 for (BasicBlock &BB :
F) {
1359 <<
" is a candidate\n");
1360 MainSwitch
Switch(SI, LI, ORE);
1362 if (!
Switch.getInstr()) {
1364 <<
"candidate for jump threading\n");
1369 <<
"candidate for jump threading\n");
1372 unfoldSelectInstrs(DT,
Switch.getSelectInsts());
1373 if (!
Switch.getSelectInsts().empty())
1376 AllSwitchPaths SwitchPaths(&Switch, ORE, LI,
1380 if (SwitchPaths.getNumThreadingPaths() > 0) {
1397 SmallPtrSet<const Value *, 32> EphValues;
1398 if (ThreadableLoops.
size() > 0)
1401 for (AllSwitchPaths SwitchPaths : ThreadableLoops) {
1402 TransformDFA Transform(&SwitchPaths, DT, AC,
TTI, ORE, EphValues);
1405 LoopInfoBroken =
true;
1408#ifdef EXPENSIVE_CHECKS
1409 assert(DT->
verify(DominatorTree::VerificationLevel::Full));
1426 DFAJumpThreading ThreadImpl(&AC, &DT, &LI, &
TTI, &ORE);
1427 if (!ThreadImpl.run(
F))
1432 if (!ThreadImpl.LoopInfoBroken)
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
This file implements a class to represent arbitrary precision integral constant values and operations...
static const Function * getParent(const Value *V)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< unsigned > MaxPathLength("dfa-max-path-length", cl::desc("Max number of blocks searched to find a threading path"), cl::Hidden, cl::init(20))
static cl::opt< unsigned > MaxNumVisitiedPaths("dfa-max-num-visited-paths", cl::desc("Max number of blocks visited while enumerating paths around a switch"), cl::Hidden, cl::init(2500))
static cl::opt< bool > ClViewCfgBefore("dfa-jump-view-cfg-before", cl::desc("View the CFG before DFA Jump Threading"), cl::Hidden, cl::init(false))
static cl::opt< unsigned > CostThreshold("dfa-cost-threshold", cl::desc("Maximum cost accepted for the transformation"), cl::Hidden, cl::init(50))
static cl::opt< bool > EarlyExitHeuristic("dfa-early-exit-heuristic", cl::desc("Exit early if an unpredictable value come from the same loop"), cl::Hidden, cl::init(true))
static cl::opt< unsigned > MaxNumPaths("dfa-max-num-paths", cl::desc("Max number of paths enumerated around a switch"), cl::Hidden, cl::init(200))
This file defines the DenseMap class.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
static bool isCandidate(const MachineInstr *MI, Register &DefedReg, Register FrameReg)
uint64_t IntrinsicInst * II
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
uint64_t getLimitedValue(uint64_t Limit=UINT64_MAX) const
If this value is smaller than the specified limit, return it, otherwise return the limit value.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
A function analysis which provides an AssumptionCache.
A cache of @llvm.assume calls within a function.
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
LLVM_ABI const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
const Function * getParent() const
Return the enclosing method, or null if none.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
LLVM_ABI void moveAfter(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it right after MovePos in the function M...
LLVM_ABI const BasicBlock * getUniqueSuccessor() const
Return the successor of this block if it has a unique successor.
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...
LLVM_ABI void removePredecessor(BasicBlock *Pred, bool KeepOneInputPHIs=false)
Update PHI nodes in this BasicBlock before removal of predecessor Pred.
Conditional or Unconditional Branch instruction.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
Analysis pass which computes a DominatorTree.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
static constexpr UpdateKind Delete
static constexpr UpdateKind Insert
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
LLVM_ABI unsigned getNumSuccessors() const LLVM_READONLY
Return the number of successors that this instruction has.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI BasicBlock * getSuccessor(unsigned Idx) const LLVM_READONLY
Return the specified successor. This instruction must be a terminator.
LLVM_ABI void setSuccessor(unsigned Idx, BasicBlock *BB)
Update the specified successor to point at the provided block.
Analysis pass that exposes the LoopInfo for a function.
const LoopT * getOutermostLoop() const
Get the outermost loop in which this loop is contained.
void verify(const DominatorTreeBase< BlockT, false > &DomTree) const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
Represents a single loop in the control flow graph.
This class implements a map that also provides access to all stored values in a deterministic order.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
iterator_range< const_block_iterator > blocks() const
LLVM_ABI Value * removeIncomingValue(unsigned Idx, bool DeletePHIIfEmpty=true)
Remove an incoming value.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", InsertPosition InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static LLVM_ABI PoisonValue * get(Type *T)
Static factory methods - Return an 'poison' object of the specified type.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
PreservedAnalyses & preserve()
Mark an analysis as preserved.
LLVM_ABI unsigned AddVariable(StringRef Name, Type *Ty)
Add a new variable to the SSA rewriter.
LLVM_ABI void AddAvailableValue(unsigned Var, BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value.
LLVM_ABI void RewriteAllUses(DominatorTree *DT, SmallVectorImpl< PHINode * > *InsertedPHIs=nullptr)
Perform all the necessary updates, including new PHI-nodes insertion and the requested uses update.
LLVM_ABI void AddUse(unsigned Var, Use *U)
Record a use of the symbolic value.
This class represents the LLVM 'select' instruction.
const Value * getFalseValue() const
const Value * getTrueValue() const
void insert_range(Range &&R)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool contains(ConstPtrType Ptr) const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
void reserve(size_type N)
void push_back(const T &Elt)
Analysis pass providing the TargetTransformInfo.
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI StringRef getName() const
Return a constant reference to the value's name.
const ParentTy * getParent() const
This class implements an extremely fast bulk output stream that can only output to a stream.
A raw_ostream that writes to an std::string.
@ C
The default llvm calling convention, compatible with C.
@ BasicBlock
Various leaf nodes.
initializer< Ty > init(const Ty &Val)
@ Switch
The "resume-switch" lowering, where there are separate resume and destroy functions that are shared b...
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
@ User
could "use" a pointer
DiagnosticInfoOptimizationBase::Argument NV
NodeAddr< PhiNode * > Phi
friend class Instruction
Iterator for Instructions in a `BasicBlock.
This is an optimization pass for GlobalISel generic memory operations.
auto drop_begin(T &&RangeOrContainer, size_t N=1)
Return a range covering RangeOrContainer with the first N elements excluded.
FunctionAddr VTableAddr Value
auto find(R &&Range, const T &Val)
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly.
Printable print(const GCNRegPressure &RP, const GCNSubtarget *ST=nullptr, unsigned DynamicVGPRBlockSize=0)
LLVM_ABI BasicBlock * CloneBasicBlock(const BasicBlock *BB, ValueToValueMapTy &VMap, const Twine &NameSuffix="", Function *F=nullptr, ClonedCodeInfo *CodeInfo=nullptr, bool MapAtoms=true)
Return a copy of the specified basic block, but without embedding the block into a particular functio...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
LLVM_ABI bool verifyFunction(const Function &F, raw_ostream *OS=nullptr)
Check a function for errors, useful for use when debugging a pass.
auto successors(const MachineBasicBlock *BB)
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
auto pred_size(const MachineBasicBlock *BB)
void sort(IteratorTy Start, IteratorTy End)
@ RF_IgnoreMissingLocals
If this flag is set, the remapper ignores missing function-local entries (Argument,...
@ RF_NoModuleLevelChanges
If this flag is set, the remapper knows that only local values within a function (such as an instruct...
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
bool isa(const From &Val)
isa<X> - Return true if the parameter to the template is an instance of one of the template type argu...
void RemapInstruction(Instruction *I, ValueToValueMapTy &VM, RemapFlags Flags=RF_None, ValueMapTypeRemapper *TypeMapper=nullptr, ValueMaterializer *Materializer=nullptr, const MetadataPredicate *IdentityMD=nullptr)
Convert the instruction operands from referencing the current values into those specified by VM.
raw_ostream & operator<<(raw_ostream &OS, const APFixedPoint &FX)
ValueMap< const Value *, WeakTrackingVH > ValueToValueMapTy
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
auto find_if(R &&Range, UnaryPredicate P)
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly.
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
bool pred_empty(const BasicBlock *BB)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
static LLVM_ABI void collectEphemeralValues(const Loop *L, AssumptionCache *AC, SmallPtrSetImpl< const Value * > &EphValues)
Collect a loop's ephemeral values (those used only by an assume or similar intrinsics in the loop).
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Integrate with the new Pass Manager.