81#ifdef EXPENSIVE_CHECKS
87#define DEBUG_TYPE "dfa-jump-threading"
89STATISTIC(NumTransforms,
"Number of transformations done");
91STATISTIC(NumPaths,
"Number of individual paths threaded");
96 cl::desc(
"View the CFG before DFA Jump Threading"),
100 "dfa-early-exit-heuristic",
101 cl::desc(
"Exit early if an unpredictable value come from the same loop"),
105 "dfa-max-path-length",
106 cl::desc(
"Max number of blocks searched to find a threading path"),
110 "dfa-max-num-visited-paths",
112 "Max number of blocks visited while enumerating paths around a switch"),
117 cl::desc(
"Max number of paths enumerated around a switch"),
122 cl::desc(
"Maximum cost accepted for the transformation"),
130 "dfa-max-cloned-rate",
132 "Maximum cloned instructions rate accepted for the transformation"),
136class SelectInstToUnfold {
143 SelectInst *getInst() {
return SI; }
144 PHINode *getUse() {
return SIUse; }
146 explicit operator bool()
const {
return SI && SIUse; }
149class DFAJumpThreading {
151 DFAJumpThreading(AssumptionCache *AC, DomTreeUpdater *DTU, LoopInfo *LI,
152 TargetTransformInfo *TTI, OptimizationRemarkEmitter *ORE)
153 : AC(AC), DTU(DTU), LI(LI), TTI(TTI), ORE(ORE) {}
155 bool run(Function &
F);
163 while (!
Stack.empty()) {
164 SelectInstToUnfold SIToUnfold =
Stack.pop_back_val();
166 std::vector<SelectInstToUnfold> NewSIsToUnfold;
167 std::vector<BasicBlock *> NewBBs;
168 unfold(DTU, LI, SIToUnfold, &NewSIsToUnfold, &NewBBs);
175 static void unfold(DomTreeUpdater *DTU, LoopInfo *LI,
176 SelectInstToUnfold SIToUnfold,
177 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
178 std::vector<BasicBlock *> *NewBBs);
183 TargetTransformInfo *TTI;
184 OptimizationRemarkEmitter *ORE;
196 SelectInstToUnfold SIToUnfold,
197 std::vector<SelectInstToUnfold> *NewSIsToUnfold,
198 std::vector<BasicBlock *> *NewBBs) {
199 SelectInst *
SI = SIToUnfold.getInst();
200 PHINode *SIUse = SIToUnfold.getUse();
204 BranchInst *StartBlockTerm =
212 SI->getContext(), Twine(
SI->getName(),
".si.unfold.false"),
214 NewBBs->push_back(NewBlock);
216 DTU->
applyUpdates({{DominatorTree::Insert, NewBlock, EndBlock}});
223 Value *SIOp1 =
SI->getTrueValue();
224 Value *SIOp2 =
SI->getFalseValue();
227 Twine(SIOp2->
getName(),
".si.unfold.phi"),
232 for (PHINode &Phi : EndBlock->
phis()) {
235 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlock);
244 Twine(
SI->getName(),
".si.unfold.phi"),
247 if (Pred != StartBlock && Pred != NewBlock)
258 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, SIUse));
260 NewSIsToUnfold->push_back(SelectInstToUnfold(OpSi, NewPhi));
267 BI->setMetadata(LLVMContext::MD_prof,
268 SI->getMetadata(LLVMContext::MD_prof));
269 DTU->
applyUpdates({{DominatorTree::Insert, StartBlock, EndBlock},
270 {DominatorTree::Insert, StartBlock, NewBlock}});
274 SI->getContext(), Twine(
SI->getName(),
".si.unfold.true"),
277 SI->getContext(), Twine(
SI->getName(),
".si.unfold.false"),
280 NewBBs->push_back(NewBlockT);
281 NewBBs->push_back(NewBlockF);
306 BI->setMetadata(LLVMContext::MD_prof,
307 SI->getMetadata(LLVMContext::MD_prof));
308 DTU->
applyUpdates({{DominatorTree::Insert, NewBlockT, NewBlockF},
309 {DominatorTree::Insert, NewBlockT, EndBlock},
310 {DominatorTree::Insert, NewBlockF, EndBlock}});
325 NewSIsToUnfold->push_back(SelectInstToUnfold(TrueSI, NewPhiT));
327 NewSIsToUnfold->push_back(SelectInstToUnfold(FalseSi, NewPhiF));
334 for (PHINode &Phi : EndBlock->
phis()) {
337 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlockT);
338 Phi.addIncoming(
Phi.getIncomingValueForBlock(StartBlock), NewBlockF);
339 Phi.removeIncomingValue(StartBlock);
344 unsigned SuccNum = StartBlockTerm->
getSuccessor(1) == EndBlock ? 1 : 0;
346 DTU->
applyUpdates({{DominatorTree::Delete, StartBlock, EndBlock},
347 {DominatorTree::Insert, StartBlock, NewBlockT}});
352 for (BasicBlock *NewBB : *NewBBs)
353 L->addBasicBlockToLoop(NewBB, *LI);
357 assert(
SI->use_empty() &&
"Select must be dead now");
358 SI->eraseFromParent();
385 OS <<
"< " <<
llvm::join(BBNames,
", ") <<
" >";
394struct ThreadingPath {
396 APInt getExitValue()
const {
return ExitVal; }
397 void setExitValue(
const ConstantInt *V) {
398 ExitVal =
V->getValue();
401 void setExitValue(
const APInt &V) {
405 bool isExitValueSet()
const {
return IsExitValSet; }
408 const BasicBlock *getDeterminatorBB()
const {
return DBB; }
409 void setDeterminator(
const BasicBlock *BB) { DBB = BB; }
412 const PathType &getPath()
const {
return Path; }
413 void setPath(
const PathType &NewPath) { Path = NewPath; }
414 void push_back(BasicBlock *BB) { Path.push_back(BB); }
415 void push_front(BasicBlock *BB) { Path.push_front(BB); }
416 void appendExcludingFirst(
const PathType &OtherPath) {
420 void print(raw_ostream &OS)
const {
428 bool IsExitValSet =
false;
432inline raw_ostream &
operator<<(raw_ostream &OS,
const ThreadingPath &TPath) {
439 MainSwitch(SwitchInst *SI, LoopInfo *LI, OptimizationRemarkEmitter *ORE)
445 return OptimizationRemarkMissed(
DEBUG_TYPE,
"SwitchNotPredictable", SI)
446 <<
"Switch instruction is not predictable.";
451 virtual ~MainSwitch() =
default;
453 SwitchInst *getInstr()
const {
return Instr; }
464 std::deque<std::pair<Value *, BasicBlock *>> Q;
465 SmallPtrSet<Value *, 16> SeenValues;
468 Value *SICond =
SI->getCondition();
478 addToQueue(SICond,
nullptr, Q, SeenValues);
481 Value *Current = Q.front().first;
482 BasicBlock *CurrentIncomingBB = Q.front().second;
486 for (BasicBlock *IncomingBB :
Phi->blocks()) {
487 Value *Incoming =
Phi->getIncomingValueForBlock(IncomingBB);
488 addToQueue(Incoming, IncomingBB, Q, SeenValues);
492 if (!isValidSelectInst(SelI))
494 addToQueue(SelI->getTrueValue(), CurrentIncomingBB, Q, SeenValues);
495 addToQueue(SelI->getFalseValue(), CurrentIncomingBB, Q, SeenValues);
498 SelectInsts.push_back(SelectInstToUnfold(SelI, SelIUse));
516 <<
"\tExiting early due to unpredictability heuristic.\n");
527 void addToQueue(
Value *Val, BasicBlock *BB,
528 std::deque<std::pair<Value *, BasicBlock *>> &Q,
529 SmallPtrSet<Value *, 16> &SeenValues) {
530 if (SeenValues.
insert(Val).second)
531 Q.push_back({Val, BB});
534 bool isValidSelectInst(SelectInst *SI) {
535 if (!
SI->hasOneUse())
560 for (SelectInstToUnfold SIToUnfold : SelectInsts) {
561 SelectInst *PrevSI = SIToUnfold.getInst();
571 SwitchInst *Instr =
nullptr;
575struct AllSwitchPaths {
576 AllSwitchPaths(
const MainSwitch *MSwitch, OptimizationRemarkEmitter *ORE,
577 LoopInfo *LI, Loop *L)
578 : Switch(MSwitch->getInstr()), SwitchBlock(Switch->
getParent()), ORE(ORE),
579 LI(LI), SwitchOuterLoop(
L) {}
581 std::vector<ThreadingPath> &getThreadingPaths() {
return TPaths; }
582 unsigned getNumThreadingPaths() {
return TPaths.size(); }
583 SwitchInst *getSwitchInst() {
return Switch; }
584 BasicBlock *getSwitchBlock() {
return SwitchBlock; }
594 typedef DenseMap<const BasicBlock *, const PHINode *> StateDefMap;
595 std::vector<ThreadingPath> getPathsFromStateDefMap(StateDefMap &StateDef,
598 unsigned PathsLimit) {
599 std::vector<ThreadingPath> Res;
600 auto *PhiBB =
Phi->getParent();
604 for (
auto *IncomingBB :
Phi->blocks()) {
605 if (Res.size() >= PathsLimit)
607 if (!UniqueBlocks.
insert(IncomingBB).second)
609 if (!SwitchOuterLoop->
contains(IncomingBB))
612 Value *IncomingValue =
Phi->getIncomingValueForBlock(IncomingBB);
616 if (PhiBB == SwitchBlock &&
619 ThreadingPath NewPath;
620 NewPath.setDeterminator(PhiBB);
621 NewPath.setExitValue(
C);
623 if (IncomingBB != SwitchBlock)
624 NewPath.push_back(IncomingBB);
625 NewPath.push_back(PhiBB);
626 Res.push_back(NewPath);
630 if (VB.
contains(IncomingBB) || IncomingBB == SwitchBlock)
636 auto *IncomingPhiDefBB = IncomingPhi->getParent();
637 if (!StateDef.contains(IncomingPhiDefBB))
641 if (IncomingPhiDefBB == IncomingBB) {
642 assert(PathsLimit > Res.size());
643 std::vector<ThreadingPath> PredPaths = getPathsFromStateDefMap(
644 StateDef, IncomingPhi, VB, PathsLimit - Res.size());
645 for (ThreadingPath &Path : PredPaths) {
646 Path.push_back(PhiBB);
647 Res.push_back(std::move(Path));
657 assert(PathsLimit > Res.size());
658 auto InterPathLimit = PathsLimit - Res.size();
659 IntermediatePaths = paths(IncomingPhiDefBB, IncomingBB, VB,
661 if (IntermediatePaths.empty())
664 assert(InterPathLimit >= IntermediatePaths.size());
665 auto PredPathLimit = InterPathLimit / IntermediatePaths.size();
666 std::vector<ThreadingPath> PredPaths =
667 getPathsFromStateDefMap(StateDef, IncomingPhi, VB, PredPathLimit);
668 for (
const ThreadingPath &Path : PredPaths) {
669 for (
const PathType &IPath : IntermediatePaths) {
670 ThreadingPath NewPath(Path);
671 NewPath.appendExcludingFirst(IPath);
672 NewPath.push_back(PhiBB);
673 Res.push_back(NewPath);
682 unsigned PathDepth,
unsigned PathsLimit) {
688 return OptimizationRemarkAnalysis(
DEBUG_TYPE,
"MaxPathLengthReached",
690 <<
"Exploration stopped after visiting MaxPathLength="
707 SmallPtrSet<BasicBlock *, 4> Successors;
709 if (Res.size() >= PathsLimit)
711 if (!Successors.
insert(Succ).second)
716 Res.push_back({BB, ToBB});
726 if (Succ == CurrLoop->getHeader())
732 assert(PathsLimit > Res.size());
734 paths(Succ, ToBB, Visited, PathDepth + 1, PathsLimit - Res.size());
749 StateDefMap getStateDefMap()
const {
752 assert(FirstDef &&
"The first definition must be a phi.");
755 Stack.push_back(FirstDef);
756 SmallPtrSet<Value *, 16> SeenValues;
758 while (!
Stack.empty()) {
759 PHINode *CurPhi =
Stack.pop_back_val();
762 SeenValues.
insert(CurPhi);
764 for (BasicBlock *IncomingBB : CurPhi->
blocks()) {
765 PHINode *IncomingPhi =
769 bool IsOutsideLoops = !SwitchOuterLoop->
contains(IncomingBB);
770 if (SeenValues.
contains(IncomingPhi) || IsOutsideLoops)
773 Stack.push_back(IncomingPhi);
782 StateDefMap StateDef = getStateDefMap();
783 if (StateDef.empty()) {
785 return OptimizationRemarkMissed(
DEBUG_TYPE,
"SwitchNotPredictable",
787 <<
"Switch instruction is not predictable.";
793 auto *SwitchPhiDefBB = SwitchPhi->getParent();
796 std::vector<ThreadingPath> PathsToPhiDef =
797 getPathsFromStateDefMap(StateDef, SwitchPhi, VB,
MaxNumPaths);
798 if (SwitchPhiDefBB == SwitchBlock || PathsToPhiDef.empty()) {
799 TPaths = std::move(PathsToPhiDef);
804 auto PathsLimit =
MaxNumPaths / PathsToPhiDef.size();
807 paths(SwitchPhiDefBB, SwitchBlock, VB, 1, PathsLimit);
808 if (PathsToSwitchBB.empty())
811 std::vector<ThreadingPath> TempList;
812 for (
const ThreadingPath &Path : PathsToPhiDef) {
813 for (
const PathType &PathToSw : PathsToSwitchBB) {
814 ThreadingPath PathCopy(Path);
815 PathCopy.appendExcludingFirst(PathToSw);
816 TempList.push_back(PathCopy);
819 TPaths = std::move(TempList);
824 BasicBlock *getNextCaseSuccessor(
const APInt &NextState) {
826 if (CaseValToDest.empty()) {
827 for (
auto Case : Switch->
cases()) {
828 APInt CaseVal = Case.getCaseValue()->getValue();
829 CaseValToDest[CaseVal] = Case.getCaseSuccessor();
833 auto SuccIt = CaseValToDest.find(NextState);
841 SmallDenseMap<BasicBlock *, APInt> DestToState;
842 for (ThreadingPath &Path : TPaths) {
843 APInt NextState =
Path.getExitValue();
844 BasicBlock *Dest = getNextCaseSuccessor(NextState);
848 if (NextState != StateIt->second) {
849 LLVM_DEBUG(
dbgs() <<
"Next state in " << Path <<
" is equivalent to "
850 << StateIt->second <<
"\n");
851 Path.setExitValue(StateIt->second);
856 unsigned NumVisited = 0;
859 OptimizationRemarkEmitter *ORE;
860 std::vector<ThreadingPath> TPaths;
861 DenseMap<APInt, BasicBlock *> CaseValToDest;
863 Loop *SwitchOuterLoop;
867 TransformDFA(AllSwitchPaths *SwitchPaths, DomTreeUpdater *DTU,
868 AssumptionCache *AC, TargetTransformInfo *
TTI,
869 OptimizationRemarkEmitter *ORE,
870 SmallPtrSet<const Value *, 32> EphValues)
871 : SwitchPaths(SwitchPaths), DTU(DTU), AC(AC),
TTI(
TTI), ORE(ORE),
872 EphValues(EphValues) {}
875 if (isLegalAndProfitableToTransform()) {
876 createAllExitPaths();
888 bool isLegalAndProfitableToTransform() {
890 uint64_t NumClonedInst = 0;
891 SwitchInst *
Switch = SwitchPaths->getSwitchInst();
894 if (
Switch->getNumSuccessors() <= 1)
900 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
902 APInt NextState = TPath.getExitValue();
903 const BasicBlock *Determinator = TPath.getDeterminatorBB();
906 BasicBlock *BB = SwitchPaths->getSwitchBlock();
907 BasicBlock *VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
909 Metrics.analyzeBasicBlock(BB, *
TTI, EphValues);
911 DuplicateMap[BB].push_back({BB, NextState});
916 if (PathBBs.front() == Determinator)
921 auto DetIt =
llvm::find(PathBBs, Determinator);
922 for (
auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
924 VisitedBB = getClonedBB(BB, NextState, DuplicateMap);
927 Metrics.analyzeBasicBlock(BB, *
TTI, EphValues);
929 DuplicateMap[BB].push_back({BB, NextState});
933 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
934 <<
"non-duplicatable instructions.\n");
936 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NonDuplicatableInst",
938 <<
"Contains non-duplicatable instructions.";
944 if (
Metrics.Convergence != ConvergenceKind::None) {
945 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
946 <<
"convergent instructions.\n");
948 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ConvergentInst", Switch)
949 <<
"Contains convergent instructions.";
954 if (!
Metrics.NumInsts.isValid()) {
955 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, contains "
956 <<
"instructions with invalid cost.\n");
958 return OptimizationRemarkMissed(
DEBUG_TYPE,
"ConvergentInst", Switch)
959 <<
"Contains instructions with invalid cost.";
968 uint64_t NumOrigInst = 0;
969 for (
auto *BB : DuplicateMap.
keys())
971 if (
double(NumClonedInst) /
double(NumOrigInst) >
MaxClonedRate) {
972 LLVM_DEBUG(
dbgs() <<
"DFA Jump Threading: Not jump threading, too much "
973 "instructions wll be cloned\n");
975 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotProfitable", Switch)
976 <<
"Too much instructions will be cloned.";
983 unsigned JumpTableSize = 0;
986 if (JumpTableSize == 0) {
990 unsigned CondBranches =
991 APInt(32,
Switch->getNumSuccessors()).ceilLogBase2();
992 assert(CondBranches > 0 &&
993 "The threaded switch must have multiple branches");
994 DuplicationCost =
Metrics.NumInsts / CondBranches;
1002 DuplicationCost =
Metrics.NumInsts / JumpTableSize;
1005 LLVM_DEBUG(
dbgs() <<
"\nDFA Jump Threading: Cost to jump thread block "
1006 << SwitchPaths->getSwitchBlock()->getName()
1007 <<
" is: " << DuplicationCost <<
"\n\n");
1010 LLVM_DEBUG(
dbgs() <<
"Not jump threading, duplication cost exceeds the "
1011 <<
"cost threshold.\n");
1013 return OptimizationRemarkMissed(
DEBUG_TYPE,
"NotProfitable", Switch)
1014 <<
"Duplication cost exceeds the cost threshold (cost="
1015 <<
ore::NV(
"Cost", DuplicationCost)
1022 return OptimizationRemark(
DEBUG_TYPE,
"JumpThreaded", Switch)
1023 <<
"Switch statement jump-threaded.";
1030 void createAllExitPaths() {
1032 BasicBlock *SwitchBlock = SwitchPaths->getSwitchBlock();
1033 for (ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
1037 TPath.push_front(SwitchBlock);
1044 SmallPtrSet<BasicBlock *, 16> BlocksToClean;
1047 for (
const ThreadingPath &TPath : SwitchPaths->getThreadingPaths()) {
1048 createExitPath(NewDefs, TPath, DuplicateMap, BlocksToClean, DTU);
1054 for (
const ThreadingPath &TPath : SwitchPaths->getThreadingPaths())
1055 updateLastSuccessor(TPath, DuplicateMap, DTU);
1061 for (BasicBlock *BB : BlocksToClean)
1071 void createExitPath(
DefMap &NewDefs,
const ThreadingPath &Path,
1073 SmallPtrSet<BasicBlock *, 16> &BlocksToClean,
1074 DomTreeUpdater *DTU) {
1075 APInt NextState =
Path.getExitValue();
1080 if (PathBBs.front() == Determinator)
1081 PathBBs.pop_front();
1083 auto DetIt =
llvm::find(PathBBs, Determinator);
1086 BasicBlock *PrevBB = PathBBs.size() == 1 ? *DetIt : *std::prev(DetIt);
1087 for (
auto BBIt = DetIt; BBIt != PathBBs.end(); BBIt++) {
1089 BlocksToClean.
insert(BB);
1093 BasicBlock *NextBB = getClonedBB(BB, NextState, DuplicateMap);
1095 updatePredecessor(PrevBB, BB, NextBB, DTU);
1101 BasicBlock *NewBB = cloneBlockAndUpdatePredecessor(
1102 BB, PrevBB, NextState, DuplicateMap, NewDefs, DTU);
1103 DuplicateMap[BB].push_back({NewBB, NextState});
1104 BlocksToClean.
insert(NewBB);
1115 void updateSSA(
DefMap &NewDefs) {
1116 SSAUpdaterBulk SSAUpdate;
1117 SmallVector<Use *, 16> UsesToRename;
1119 for (
const auto &KV : NewDefs) {
1122 std::vector<Instruction *> Cloned = KV.second;
1126 for (Use &U :
I->uses()) {
1129 if (UserPN->getIncomingBlock(U) == BB)
1131 }
else if (
User->getParent() == BB) {
1140 if (UsesToRename.
empty())
1148 unsigned VarNum = SSAUpdate.
AddVariable(
I->getName(),
I->getType());
1150 for (Instruction *New : Cloned)
1153 while (!UsesToRename.
empty())
1167 static BasicBlock *getNextCaseSuccessor(SwitchInst *Switch,
1168 const APInt &NextState) {
1170 for (
auto Case :
Switch->cases()) {
1171 if (Case.getCaseValue()->getValue() == NextState) {
1172 NextCase = Case.getCaseSuccessor();
1177 NextCase =
Switch->getDefaultDest();
1185 BasicBlock *cloneBlockAndUpdatePredecessor(BasicBlock *BB, BasicBlock *PrevBB,
1186 const APInt &NextState,
1189 DomTreeUpdater *DTU) {
1197 for (Instruction &
I : *NewBB) {
1209 updateSuccessorPhis(BB, NewBB, NextState, VMap, DuplicateMap);
1210 updatePredecessor(PrevBB, BB, NewBB, DTU);
1211 updateDefMap(NewDefs, VMap);
1214 SmallPtrSet<BasicBlock *, 4> SuccSet;
1216 if (SuccSet.
insert(SuccBB).second)
1217 DTU->
applyUpdates({{DominatorTree::Insert, NewBB, SuccBB}});
1227 void updateSuccessorPhis(BasicBlock *BB, BasicBlock *ClonedBB,
1230 std::vector<BasicBlock *> BlocksToUpdate;
1234 if (BB == SwitchPaths->getSwitchBlock()) {
1235 SwitchInst *
Switch = SwitchPaths->getSwitchInst();
1236 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1237 BlocksToUpdate.push_back(NextCase);
1238 BasicBlock *ClonedSucc = getClonedBB(NextCase, NextState, DuplicateMap);
1240 BlocksToUpdate.push_back(ClonedSucc);
1245 BlocksToUpdate.push_back(Succ);
1250 BasicBlock *ClonedSucc = getClonedBB(Succ, NextState, DuplicateMap);
1252 BlocksToUpdate.push_back(ClonedSucc);
1259 for (BasicBlock *Succ : BlocksToUpdate) {
1260 for (PHINode &Phi : Succ->phis()) {
1261 Value *Incoming =
Phi.getIncomingValueForBlock(BB);
1264 Phi.addIncoming(Incoming, ClonedBB);
1267 Value *ClonedVal = VMap[Incoming];
1269 Phi.addIncoming(ClonedVal, ClonedBB);
1271 Phi.addIncoming(Incoming, ClonedBB);
1279 void updatePredecessor(BasicBlock *PrevBB, BasicBlock *OldBB,
1280 BasicBlock *NewBB, DomTreeUpdater *DTU) {
1283 if (!isPredecessor(OldBB, PrevBB))
1293 DTU->
applyUpdates({{DominatorTree::Delete, PrevBB, OldBB},
1294 {DominatorTree::Insert, PrevBB, NewBB}});
1303 for (
auto Entry : VMap) {
1315 NewDefsVector.
push_back({Inst, Cloned});
1319 sort(NewDefsVector, [](
const auto &
LHS,
const auto &
RHS) {
1320 if (
LHS.first ==
RHS.first)
1321 return LHS.second->comesBefore(
RHS.second);
1322 return LHS.first->comesBefore(
RHS.first);
1325 for (
const auto &KV : NewDefsVector)
1326 NewDefs[KV.first].push_back(KV.second);
1334 void updateLastSuccessor(
const ThreadingPath &TPath,
1336 DomTreeUpdater *DTU) {
1337 APInt NextState = TPath.getExitValue();
1339 BasicBlock *LastBlock = getClonedBB(BB, NextState, DuplicateMap);
1346 BasicBlock *NextCase = getNextCaseSuccessor(Switch, NextState);
1348 std::vector<DominatorTree::UpdateType> DTUpdates;
1349 SmallPtrSet<BasicBlock *, 4> SuccSet;
1350 for (BasicBlock *Succ :
successors(LastBlock)) {
1351 if (Succ != NextCase && SuccSet.
insert(Succ).second)
1352 DTUpdates.push_back({DominatorTree::Delete, LastBlock, Succ});
1355 Switch->eraseFromParent();
1363 void cleanPhiNodes(BasicBlock *BB) {
1368 PN.eraseFromParent();
1374 for (PHINode &Phi : BB->
phis())
1375 Phi.removeIncomingValueIf([&](
unsigned Index) {
1377 return !isPredecessor(BB, IncomingBB);
1383 BasicBlock *getClonedBB(BasicBlock *BB,
const APInt &NextState,
1389 auto It =
llvm::find_if(ClonedBBs, [NextState](
const ClonedBlock &
C) {
1390 return C.State == NextState;
1392 return It != ClonedBBs.end() ? (*It).BB :
nullptr;
1396 bool isPredecessor(BasicBlock *BB, BasicBlock *IncomingBB) {
1400 AllSwitchPaths *SwitchPaths;
1401 DomTreeUpdater *DTU;
1402 AssumptionCache *AC;
1403 TargetTransformInfo *
TTI;
1404 OptimizationRemarkEmitter *ORE;
1405 SmallPtrSet<const Value *, 32> EphValues;
1406 std::vector<ThreadingPath> TPaths;
1410bool DFAJumpThreading::run(Function &
F) {
1411 LLVM_DEBUG(
dbgs() <<
"\nDFA Jump threading: " <<
F.getName() <<
"\n");
1413 if (
F.hasOptSize()) {
1414 LLVM_DEBUG(
dbgs() <<
"Skipping due to the 'minsize' attribute\n");
1422 bool MadeChanges =
false;
1423 LoopInfoBroken =
false;
1425 for (BasicBlock &BB :
F) {
1431 <<
" is a candidate\n");
1432 MainSwitch
Switch(SI, LI, ORE);
1434 if (!
Switch.getInstr()) {
1436 <<
"candidate for jump threading\n");
1441 <<
"candidate for jump threading\n");
1444 unfoldSelectInstrs(
Switch.getSelectInsts());
1445 if (!
Switch.getSelectInsts().empty())
1448 AllSwitchPaths SwitchPaths(&Switch, ORE, LI,
1452 if (SwitchPaths.getNumThreadingPaths() > 0) {
1469 SmallPtrSet<const Value *, 32> EphValues;
1470 if (ThreadableLoops.
size() > 0)
1473 for (AllSwitchPaths SwitchPaths : ThreadableLoops) {
1474 TransformDFA Transform(&SwitchPaths, DTU, AC,
TTI, ORE, EphValues);
1475 if (Transform.run())
1476 MadeChanges = LoopInfoBroken =
true;
1481#ifdef EXPENSIVE_CHECKS
1499 DFAJumpThreading ThreadImpl(&AC, &DTU, &LI, &
TTI, &ORE);
1500 if (!ThreadImpl.run(
F))
1505 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 void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
static const Function * getParent(const Value *V)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
SmallPtrSet< const BasicBlock *, 8 > VisitedBlocks
std::deque< BasicBlock * > PathType
std::vector< PathType > PathsType
MapVector< Instruction *, std::vector< Instruction * > > DefMap
std::vector< ClonedBlock > CloneList
DenseMap< BasicBlock *, CloneList > DuplicateBlockMap
static cl::opt< double > MaxClonedRate("dfa-max-cloned-rate", cl::desc("Maximum cloned instructions rate accepted for the transformation"), cl::Hidden, cl::init(7.5))
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_ABI void registerAssumption(AssumeInst *CI)
Add an @llvm.assume intrinsic to this function's cache.
LLVM Basic Block Representation.
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.
LLVM_ABI filter_iterator< BasicBlock::const_iterator, std::function< bool(constInstruction &)> >::difference_type sizeWithoutDebug() const
Return the size of the basic block ignoring debug instructions.
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.
static BranchInst * Create(BasicBlock *IfTrue, InsertPosition InsertBefore=nullptr)
BasicBlock * getSuccessor(unsigned i) const
bool isUnconditional() const
void setSuccessor(unsigned idx, BasicBlock *NewSucc)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Analysis pass which computes a DominatorTree.
bool verify(VerificationLevel VL=VerificationLevel::Full) const
verify - checks if the tree is correct.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree.
DomTreeT & getDomTree()
Flush DomTree updates and return DomTree.
void applyUpdates(ArrayRef< UpdateT > Updates)
Submit updates to all available trees.
void flush()
Apply all pending updates to available trees and flush all BasicBlocks awaiting deletion.
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.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
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.
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
bool erase(PtrType Ptr)
Remove pointer from the set.
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)
BasicBlock * getDefaultDest() const
iterator_range< CaseIt > cases()
Iteration adapter for range-for loops.
Analysis pass providing the TargetTransformInfo.
LLVM_ABI bool replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
Value * getOperand(unsigned i) const
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI std::string getNameOrAsOperand() const
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.
@ 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.
static cl::opt< unsigned > MaxNumPaths("dfa-max-num-paths", cl::desc("Max number of paths enumerated around a switch"), cl::Hidden, cl::init(200))
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.
iterator_range< early_inc_iterator_impl< detail::IterOfRange< RangeT > > > make_early_inc_range(RangeT &&Range)
Make a range that does early increment to allow mutation of the underlying range without disrupting i...
auto pred_size(const MachineBasicBlock *BB)
static cl::opt< bool > ClViewCfgBefore("dfa-jump-view-cfg-before", cl::desc("View the CFG before DFA Jump Threading"), cl::Hidden, cl::init(false))
auto map_range(ContainerTy &&C, FuncTy F)
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...
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))
std::string join(IteratorT Begin, IteratorT End, StringRef Separator)
Joins the strings in the range [Begin, End), adding Separator between the elements.
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))
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.
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))
auto predecessors(const MachineBasicBlock *BB)
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
cl::opt< bool > ProfcheckDisableMetadataFixes("profcheck-disable-metadata-fixes", cl::Hidden, cl::init(false), cl::desc("Disable metadata propagation fixes discovered through Issue #147390"))
bool pred_empty(const BasicBlock *BB)
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
static cl::opt< unsigned > CostThreshold("dfa-cost-threshold", cl::desc("Maximum cost accepted for the transformation"), cl::Hidden, cl::init(50))
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.