48#define DEBUG_TYPE "select-optimize"
51 "Number of select groups considered for conversion to branch");
53 "Number of select groups converted due to expensive cold operand");
55 "Number of select groups converted due to high-predictability");
57 "Number of select groups not converted due to unpredictability");
59 "Number of select groups not converted due to cold basic block");
61 "Number of select groups converted due to loop-level analysis");
62STATISTIC(NumSelectsConverted,
"Number of selects converted");
70class SelectOptimizeImpl {
71 const CodeGenOptions *Opts =
nullptr;
72 const TargetMachine *TM =
nullptr;
73 const TargetSubtargetInfo *TSI =
nullptr;
74 const TargetLowering *TLI =
nullptr;
75 const TargetTransformInfo *TTI =
nullptr;
76 const LoopInfo *LI =
nullptr;
77 BlockFrequencyInfo *BFI;
78 ProfileSummaryInfo *PSI =
nullptr;
79 OptimizationRemarkEmitter *ORE =
nullptr;
80 TargetSchedModel TSchedModel;
83 SelectOptimizeImpl() =
default;
84 SelectOptimizeImpl(
const TargetMachine *TM) : TM(TM){};
88 using Scaled64 = ScaledNumber<uint64_t>;
105 bool Inverted =
false;
112 SelectLike(Instruction *I,
bool Inverted =
false,
unsigned CondIdx = 0)
113 : I(I), Inverted(Inverted), CondIdx(CondIdx) {}
120 unsigned getConditionOpIndex() {
return CondIdx; };
126 Value *getTrueValue(
bool HonorInverts =
true)
const {
127 if (Inverted && HonorInverts)
128 return getFalseValue(
false);
130 return Sel->getTrueValue();
142 Value *getFalseValue(
bool HonorInverts =
true)
const {
143 if (Inverted && HonorInverts)
144 return getTrueValue(
false);
146 return Sel->getFalseValue();
151 return BO->getOperand(1 - CondIdx);
159 Scaled64 getOpCostOnBranch(
160 bool IsTrue,
const DenseMap<const Instruction *, CostInfo> &InstCostMap,
161 const TargetTransformInfo *
TTI) {
162 auto *
V = IsTrue ? getTrueValue() : getFalseValue();
165 auto It = InstCostMap.
find(
IV);
166 return It != InstCostMap.
end() ? It->second.NonPredCost
177 {TargetTransformInfo::OK_AnyValue, TargetTransformInfo::OP_None},
178 {TTI::OK_UniformConstantValue, TTI::OP_PowerOf2});
181 auto It = InstCostMap.find(OpI);
182 if (It != InstCostMap.end())
183 TotalCost += It->second.NonPredCost;
197 bool isUnpredictable()
const {
198 return any_of(Selects, [](
const SelectLike &SI) {
199 return SI.getI()->getMetadata(LLVMContext::MD_unpredictable);
203 using SelectGroups = SmallVector<SelectGroup, 2>;
213 void optimizeSelectsBase(
Function &
F, SelectGroups &ProfSIGroups);
214 void optimizeSelectsInnerLoops(
Function &
F, SelectGroups &ProfSIGroups);
218 void convertProfitableSIGroups(SelectGroups &ProfSIGroups);
221 void collectSelectGroups(BasicBlock &BB, SelectGroups &SIGroups);
225 void findProfitableSIGroupsBase(SelectGroups &SIGroups,
226 SelectGroups &ProfSIGroups);
227 void findProfitableSIGroupsInnerLoops(
const Loop *L, SelectGroups &SIGroups,
228 SelectGroups &ProfSIGroups);
232 bool isConvertToBranchProfitableBase(
const SelectGroup &ASI);
237 bool hasExpensiveColdOperand(
const SelectGroup &ASI);
243 void getExclBackwardsSlice(Instruction *
I, std::stack<Instruction *> &Slice,
244 Instruction *SI,
bool ForSinking =
false,
245 const SelectGroup *Group =
nullptr);
248 bool isSelectHighlyPredictable(
const SelectLike SI);
252 bool checkLoopHeuristics(
const Loop *L,
const CostInfo LoopDepth[2]);
256 bool computeLoopCosts(
const Loop *L,
const SelectGroups &SIGroups,
257 DenseMap<const Instruction *, CostInfo> &InstCostMap,
261 SmallDenseMap<const Instruction *, SelectLike, 2>
262 getSImap(
const SelectGroups &SIGroups);
266 SmallDenseMap<const Instruction *, const SelectGroup *, 2>
267 getSGmap(
const SelectGroups &SIGroups);
270 std::optional<uint64_t> computeInstCost(
const Instruction *
I);
273 Scaled64 getMispredictionCost(
const SelectLike SI,
const Scaled64 CondCost);
276 Scaled64 getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
277 const SelectLike SI);
280 bool isSelectKindSupported(
const SelectLike SI);
284 SelectOptimizeImpl Impl;
289 SelectOptimize() : FunctionPass(ID) {}
295 return Impl.runOnFunction(
F, *
this);
298 void getAnalysisUsage(AnalysisUsage &AU)
const override {
304 AU.
addRequired<OptimizationRemarkEmitterWrapperPass>();
312 SelectOptimizeImpl Impl(TM);
313 return Impl.run(
F,
FAM);
316char SelectOptimize::ID = 0;
345 if (!
TTI->enableSelectOptimize())
349 .getCachedResult<ProfileSummaryAnalysis>(*
F.getParent());
352 "analysis to be available");
361 TSchedModel.
init(TSI);
382 if (!
TTI->enableSelectOptimize())
389 TSchedModel.
init(TSI);
395 return optimizeSelects(
F);
398bool SelectOptimizeImpl::optimizeSelects(
Function &
F) {
401 SelectGroups ProfSIGroups;
403 optimizeSelectsBase(
F, ProfSIGroups);
405 optimizeSelectsInnerLoops(
F, ProfSIGroups);
409 convertProfitableSIGroups(ProfSIGroups);
412 return !ProfSIGroups.empty();
415void SelectOptimizeImpl::optimizeSelectsBase(
Function &
F,
416 SelectGroups &ProfSIGroups) {
418 SelectGroups SIGroups;
422 if (L &&
L->isInnermost())
424 collectSelectGroups(BB, SIGroups);
428 findProfitableSIGroupsBase(SIGroups, ProfSIGroups);
431void SelectOptimizeImpl::optimizeSelectsInnerLoops(
Function &
F,
432 SelectGroups &ProfSIGroups) {
435 for (
unsigned long i = 0; i <
Loops.size(); ++i)
439 if (!
L->isInnermost())
442 SelectGroups SIGroups;
444 collectSelectGroups(*BB, SIGroups);
446 findProfitableSIGroupsInnerLoops(L, SIGroups, ProfSIGroups);
462 SelectOptimizeImpl::SelectLike &
SI,
bool isTrue,
465 Value *
V = isTrue ?
SI.getTrueValue() :
SI.getFalseValue();
468 if (
auto It = OptSelects.find(
IV); It != OptSelects.end())
469 return isTrue ? It->second.first : It->second.second;
474 assert((BO->getOpcode() == Instruction::Add ||
475 BO->getOpcode() == Instruction::Or ||
476 BO->getOpcode() == Instruction::Sub) &&
477 "Only currently handling Add, Or and Sub binary operators.");
479 auto *CBO = BO->clone();
480 auto CondIdx =
SI.getConditionOpIndex();
483 CBO->setOperand(CondIdx, ConstantInt::get(CBO->getType(), 1));
486 "Unexpected opcode");
490 unsigned OtherIdx = 1 - CondIdx;
492 if (
auto It = OptSelects.find(
IV); It != OptSelects.end())
493 CBO->setOperand(OtherIdx, isTrue ? It->second.first : It->second.second);
495 CBO->insertBefore(
B->getTerminator()->getIterator());
499void SelectOptimizeImpl::convertProfitableSIGroups(SelectGroups &ProfSIGroups) {
500 for (SelectGroup &ASI : ProfSIGroups) {
540 typedef std::stack<Instruction *>::size_type StackSizeType;
541 StackSizeType maxTrueSliceLen = 0, maxFalseSliceLen = 0;
543 bool SelectWithProfileIsInverted =
false;
544 for (SelectLike &
SI : ASI.Selects) {
550 std::stack<Instruction *> TrueSlice;
551 getExclBackwardsSlice(TI, TrueSlice,
SI.getI(),
true, &ASI);
552 maxTrueSliceLen = std::max(maxTrueSliceLen, TrueSlice.size());
557 std::stack<Instruction *> FalseSlice;
558 getExclBackwardsSlice(FI, FalseSlice,
SI.getI(),
true, &ASI);
559 maxFalseSliceLen = std::max(maxFalseSliceLen, FalseSlice.size());
566 if (
hasProfMD(*
SI.getI()) && ASI.Condition == SelectCondition) {
567 SelectWithProfile =
SI.getI();
570 SelectWithProfile =
SI.getI();
571 SelectWithProfileIsInverted =
true;
585 for (StackSizeType IS = 0;
IS < maxTrueSliceLen; ++
IS) {
586 for (
auto &S : TrueSlices) {
588 TrueSlicesInterleaved.
push_back(S.top());
593 for (StackSizeType IS = 0;
IS < maxFalseSliceLen; ++
IS) {
594 for (
auto &S : FalseSlices) {
596 FalseSlicesInterleaved.
push_back(S.top());
603 SelectLike &
SI = ASI.Selects.front();
604 SelectLike &LastSI = ASI.Selects.back();
612 SplitPt.setHeadBit(
true);
621 auto DIt =
SI.getI()->getIterator();
622 auto NIt = ASI.Selects.begin();
623 while (&*DIt != LastSI.getI()) {
624 if (NIt != ASI.Selects.end() && &*DIt == NIt->getI())
630 for (
auto *HI : HoistInstrs)
631 HI->moveBefore(
SI.getI()->getIterator());
648 std::next(LastSI.getI()->getIterator()));
653 BasicBlock *TrueBlock =
nullptr, *FalseBlock =
nullptr;
654 UncondBrInst *TrueBranch =
nullptr, *FalseBranch =
nullptr;
656 auto HasSelectLike = [](SelectGroup &SG,
bool IsTrue) {
657 for (
auto &SL : SG.Selects) {
658 if ((IsTrue ? SL.getTrueValue() : SL.getFalseValue()) ==
nullptr)
663 if (!TrueSlicesInterleaved.
empty() || HasSelectLike(ASI,
true)) {
667 TrueBranch->
setDebugLoc(LastSI.getI()->getDebugLoc());
668 for (
Instruction *TrueInst : TrueSlicesInterleaved)
671 if (!FalseSlicesInterleaved.
empty() || HasSelectLike(ASI,
false)) {
676 FalseBranch->setDebugLoc(LastSI.getI()->getDebugLoc());
677 for (
Instruction *FalseInst : FalseSlicesInterleaved)
678 FalseInst->moveBefore(FalseBranch->getIterator());
682 if (TrueBlock == FalseBlock) {
683 assert(TrueBlock ==
nullptr &&
684 "Unexpected basic block transform while optimizing select");
689 FalseBranch->setDebugLoc(
SI.getI()->getDebugLoc());
698 if (TrueBlock ==
nullptr) {
701 TrueBlock = StartBlock;
702 }
else if (FalseBlock ==
nullptr) {
705 FalseBlock = StartBlock;
712 IB.CreateFreeze(ASI.Condition, ASI.Condition->getName() +
".frozen");
719 auto InsertionPoint = EndBlock->
begin();
720 for (SelectLike &
SI : ASI.Selects) {
728 for (
auto &SG : ProfSIGroups) {
729 if (SG.Condition ==
SI.getI())
733 SI.getI()->replaceAllUsesWith(PN);
740 ++NumSelectsConverted;
744 CondBr->
copyMetadata(*SelectWithProfile, {llvm::LLVMContext::MD_prof});
745 if (SelectWithProfileIsInverted)
752 for (SelectLike &
SI : ASI.Selects)
753 SI.getI()->eraseFromParent();
757void SelectOptimizeImpl::collectSelectGroups(
BasicBlock &BB,
758 SelectGroups &SIGroups) {
768 struct SelectLikeInfo {
772 unsigned ConditionIdx;
783 auto ProcessSelectInfo = [&SelectInfo, &SeenCmp](
Instruction *
I) {
786 return SelectInfo.
end();
791 Cond->getType()->isIntegerTy(1)) {
793 return SelectInfo.
insert({
I, {
Cond,
true, Inverted, 0}}).first;
797 return SelectInfo.
insert({
I, {
Cond,
true,
true, 0}}).first;
803 return SelectInfo.
insert({
I, {
Cond,
false, Inverted, 0}}).first;
808 I->getType()->getIntegerBitWidth() == Shift->
getZExtValue() + 1) {
809 for (
auto *CmpI : SeenCmp) {
810 auto Pred = CmpI->getPredicate();
811 if (Val != CmpI->getOperand(0))
823 return SelectInfo.
insert({
I, {CmpI,
true, Inverted, 0}}).first;
826 return SelectInfo.
end();
834 auto MatchZExtOrSExtPattern =
836 auto MatchShiftPattern =
841 if ((
match(
I, MatchZExtOrSExtPattern) &&
X->getType()->isIntegerTy(1)) ||
842 (
match(
I, MatchShiftPattern) &&
843 X->getType()->getIntegerBitWidth() == Shift->
getZExtValue() + 1)) {
844 if (
I->getOpcode() != Instruction::Add &&
845 I->getOpcode() != Instruction::Sub &&
846 I->getOpcode() != Instruction::Or)
847 return SelectInfo.
end();
854 if (
I->getType()->isIntegerTy(1))
855 return SelectInfo.
end();
861 unsigned Idx =
I->getOpcode() == Instruction::Sub ? 1 : 0;
863 auto *
Op =
I->getOperand(Idx);
864 auto It = SelectInfo.
find(
Op);
865 if (It != SelectInfo.
end() && It->second.IsAuxiliary) {
866 Cond = It->second.Cond;
867 bool Inverted = It->second.IsInverted;
868 return SelectInfo.
insert({
I, {
Cond,
false, Inverted,
Idx}}).first;
872 return SelectInfo.
end();
875 bool AlreadyProcessed =
false;
878 while (BBIt != BB.
end()) {
883 if (!AlreadyProcessed)
884 It = ProcessSelectInfo(
I);
886 AlreadyProcessed =
false;
888 if (It == SelectInfo.
end() || It->second.IsAuxiliary)
891 if (!
TTI->shouldTreatInstructionLikeSelect(
I))
896 if (!
Cond->getType()->isIntegerTy(1))
899 SelectGroup SIGroup = {
Cond, {}};
900 SIGroup.Selects.emplace_back(
I, It->second.IsInverted,
901 It->second.ConditionIdx);
905 if (!isSelectKindSupported(SIGroup.Selects.front()))
908 while (BBIt != BB.
end()) {
917 It = ProcessSelectInfo(NI);
918 if (It == SelectInfo.
end()) {
919 AlreadyProcessed =
true;
924 auto [CurrCond, IsAux, IsRev, CondIdx] = It->second;
925 if (
Cond != CurrCond) {
926 AlreadyProcessed =
true;
931 SIGroup.Selects.emplace_back(NI, IsRev, CondIdx);
935 dbgs() <<
"New Select group (" << SIGroup.Selects.size() <<
") with\n";
936 for (
auto &
SI : SIGroup.Selects)
937 dbgs() <<
" " << *
SI.getI() <<
"\n";
940 SIGroups.push_back(SIGroup);
944void SelectOptimizeImpl::findProfitableSIGroupsBase(
945 SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
946 for (SelectGroup &ASI : SIGroups) {
947 ++NumSelectOptAnalyzed;
948 if (isConvertToBranchProfitableBase(ASI))
949 ProfSIGroups.push_back(ASI);
959void SelectOptimizeImpl::findProfitableSIGroupsInnerLoops(
960 const Loop *L, SelectGroups &SIGroups, SelectGroups &ProfSIGroups) {
961 NumSelectOptAnalyzed += SIGroups.size();
973 erase_if(SIGroups, [&](
const SelectGroup &ASI) {
974 if (!ASI.isUnpredictable())
978 ASI.Selects.front().getI());
979 ORmiss <<
"Not converted to branch because of unpredictable branch. ";
985 CostInfo LoopCost[2] = {{Scaled64::getZero(), Scaled64::getZero()},
986 {Scaled64::getZero(), Scaled64::getZero()}};
987 if (!computeLoopCosts(L, SIGroups, InstCostMap, LoopCost) ||
988 !checkLoopHeuristics(L, LoopCost)) {
992 for (SelectGroup &ASI : SIGroups) {
995 Scaled64 SelectCost = Scaled64::getZero(), BranchCost = Scaled64::getZero();
996 for (SelectLike &
SI : ASI.Selects) {
997 const auto &ICM = InstCostMap[
SI.getI()];
998 SelectCost = std::max(SelectCost, ICM.PredCost);
999 BranchCost = std::max(BranchCost, ICM.NonPredCost);
1001 if (BranchCost < SelectCost) {
1003 ASI.Selects.front().getI());
1004 OR <<
"Profitable to convert to branch (loop analysis). BranchCost="
1005 << BranchCost.toString() <<
", SelectCost=" << SelectCost.toString()
1008 ++NumSelectConvertedLoop;
1009 ProfSIGroups.push_back(ASI);
1012 ASI.Selects.front().getI());
1013 ORmiss <<
"Select is more profitable (loop analysis). BranchCost="
1014 << BranchCost.toString()
1015 <<
", SelectCost=" << SelectCost.toString() <<
". ";
1021bool SelectOptimizeImpl::isConvertToBranchProfitableBase(
1022 const SelectGroup &ASI) {
1023 const SelectLike &
SI = ASI.Selects.front();
1032 ORmiss <<
"Not converted to branch because of cold basic block. ";
1038 if (
SI.getI()->getMetadata(LLVMContext::MD_unpredictable)) {
1040 ORmiss <<
"Not converted to branch because of unpredictable branch. ";
1048 ++NumSelectConvertedHighPred;
1049 OR <<
"Converted to branch because of highly predictable branch. ";
1056 if (hasExpensiveColdOperand(ASI)) {
1057 ++NumSelectConvertedExpColdOperand;
1058 OR <<
"Converted to branch because of expensive cold operand.";
1066 auto *BB =
SI.getI()->getParent();
1068 if (L && !
L->isInnermost() &&
L->getLoopLatch() == BB &&
1069 ASI.Selects.size() >= 3) {
1070 OR <<
"Converted to branch because select group in the latch block is big.";
1075 ORmiss <<
"Not profitable to convert to branch (base heuristic).";
1082 return (Numerator + (Denominator / 2)) / Denominator;
1092bool SelectOptimizeImpl::hasExpensiveColdOperand(
const SelectGroup &ASI) {
1093 bool ColdOperand =
false;
1094 uint64_t TrueWeight, FalseWeight, TotalWeight;
1096 uint64_t MinWeight = std::min(TrueWeight, FalseWeight);
1097 TotalWeight = TrueWeight + FalseWeight;
1099 ColdOperand = TotalWeight * Opts->cold_operand_threshold > 100 * MinWeight;
1102 ASI.Selects.front().getI());
1103 ORmiss <<
"Profile data available but missing branch-weights metadata for "
1104 "select instruction. ";
1111 for (SelectLike
SI : ASI.Selects) {
1114 if (TrueWeight < FalseWeight) {
1116 HotWeight = FalseWeight;
1119 HotWeight = TrueWeight;
1122 std::stack<Instruction *> ColdSlice;
1123 getExclBackwardsSlice(ColdI, ColdSlice,
SI.getI());
1125 while (!ColdSlice.empty()) {
1126 SliceCost +=
TTI->getInstructionCost(ColdSlice.top(),
1136 if (AdjSliceCost >= Opts->cold_operand_max_cost_multiplier *
1152 while (&*It !=
SI) {
1153 if (It->mayWriteToMemory())
1166void SelectOptimizeImpl::getExclBackwardsSlice(
Instruction *
I,
1167 std::stack<Instruction *> &Slice,
1169 const SelectGroup *Group) {
1171 std::queue<Instruction *> Worklist;
1173 while (!Worklist.empty()) {
1181 if (!
II->hasOneUse())
1187 if (ForSinking && (
II->isTerminator() ||
II->mayHaveSideEffects() ||
1193 if (ForSinking && Group &&
1194 llvm::any_of(Group->Selects, [&](
auto &S) { return S.getI() == II; }))
1219bool SelectOptimizeImpl::isSelectHighlyPredictable(
const SelectLike
SI) {
1223 uint64_t Sum = TrueWeight + FalseWeight;
1226 if (Probability >
TTI->getPredictableBranchThreshold())
1233bool SelectOptimizeImpl::checkLoopHeuristics(
const Loop *L,
1234 const CostInfo LoopCost[2]) {
1238 if (!Opts->select_opti_loop_level_heuristics)
1242 &*
L->getHeader()->getFirstNonPHIIt());
1244 if (LoopCost[0].NonPredCost > LoopCost[0].PredCost ||
1245 LoopCost[1].NonPredCost >= LoopCost[1].PredCost) {
1246 ORmissL <<
"No select conversion in the loop due to no reduction of loop's "
1252 Scaled64 Gain[2] = {LoopCost[0].PredCost - LoopCost[0].NonPredCost,
1253 LoopCost[1].PredCost - LoopCost[1].NonPredCost};
1258 if (Gain[1] < Scaled64::get(Opts->select_opti_loop_cycle_gain_threshold) ||
1259 Gain[1] * Scaled64::get(Opts->select_opti_loop_relative_gain_threshold) <
1260 LoopCost[1].PredCost) {
1261 Scaled64 RelativeGain = Scaled64::get(100) * Gain[1] / LoopCost[1].PredCost;
1262 ORmissL <<
"No select conversion in the loop due to small reduction of "
1263 "loop's critical path. Gain="
1264 << Gain[1].toString()
1265 <<
", RelativeGain=" << RelativeGain.toString() <<
"%. ";
1275 if (Gain[1] > Gain[0]) {
1276 Scaled64 GradientGain = Scaled64::get(100) * (Gain[1] - Gain[0]) /
1277 (LoopCost[1].PredCost - LoopCost[0].PredCost);
1279 Scaled64::get(Opts->select_opti_loop_gradient_gain_threshold)) {
1280 ORmissL <<
"No select conversion in the loop due to small gradient gain. "
1282 << GradientGain.toString() <<
"%. ";
1288 else if (Gain[1] < Gain[0]) {
1290 <<
"No select conversion in the loop due to negative gradient gain. ";
1304bool SelectOptimizeImpl::computeLoopCosts(
1305 const Loop *L,
const SelectGroups &SIGroups,
1307 LLVM_DEBUG(
dbgs() <<
"Calculating Latency / IPredCost / INonPredCost of loop "
1308 <<
L->getHeader()->getName() <<
"\n");
1309 const auto SImap = getSImap(SIGroups);
1310 const auto SGmap = getSGmap(SIGroups);
1313 const unsigned Iterations = 2;
1314 for (
unsigned Iter = 0; Iter < Iterations; ++Iter) {
1316 CostInfo &MaxCost = LoopCost[Iter];
1322 Scaled64 IPredCost = Scaled64::getZero(),
1323 INonPredCost = Scaled64::getZero();
1328 for (
const Use &U :
I.operands()) {
1332 if (
auto It = InstCostMap.
find(UI); It != InstCostMap.
end()) {
1333 IPredCost = std::max(IPredCost, It->second.PredCost);
1334 INonPredCost = std::max(INonPredCost, It->second.NonPredCost);
1337 auto ILatency = computeInstCost(&
I);
1340 ORmissL <<
"Invalid instruction cost preventing analysis and "
1341 "optimization of the inner-most loop containing this "
1346 IPredCost += Scaled64::get(*ILatency);
1347 INonPredCost += Scaled64::get(*ILatency);
1355 if (
auto It = SImap.find(&
I); It != SImap.end()) {
1356 auto SI = It->second;
1357 const auto *SG = SGmap.at(&
I);
1358 Scaled64 TrueOpCost =
SI.getOpCostOnBranch(
true, InstCostMap,
TTI);
1359 Scaled64 FalseOpCost =
SI.getOpCostOnBranch(
false, InstCostMap,
TTI);
1360 Scaled64 PredictedPathCost =
1361 getPredictedPathCost(TrueOpCost, FalseOpCost,
SI);
1363 Scaled64 CondCost = Scaled64::getZero();
1365 if (
auto It = InstCostMap.
find(CI); It != InstCostMap.
end())
1366 CondCost = It->second.NonPredCost;
1367 Scaled64 MispredictCost = getMispredictionCost(
SI, CondCost);
1369 INonPredCost = PredictedPathCost + MispredictCost;
1372 << INonPredCost <<
" for " <<
I <<
"\n");
1374 InstCostMap[&
I] = {IPredCost, INonPredCost};
1375 MaxCost.PredCost = std::max(MaxCost.PredCost, IPredCost);
1376 MaxCost.NonPredCost = std::max(MaxCost.NonPredCost, INonPredCost);
1380 <<
" MaxCost = " << MaxCost.PredCost <<
" "
1381 << MaxCost.NonPredCost <<
"\n");
1387SelectOptimizeImpl::getSImap(
const SelectGroups &SIGroups) {
1389 for (
const SelectGroup &ASI : SIGroups)
1390 for (
const SelectLike &
SI : ASI.Selects)
1396SelectOptimizeImpl::getSGmap(
const SelectGroups &SIGroups) {
1398 for (
const SelectGroup &ASI : SIGroups)
1399 for (
const SelectLike &
SI : ASI.Selects)
1404std::optional<uint64_t>
1405SelectOptimizeImpl::computeInstCost(
const Instruction *
I) {
1409 return std::optional<uint64_t>(ICost.
getValue());
1410 return std::nullopt;
1414SelectOptimizeImpl::getMispredictionCost(
const SelectLike
SI,
1415 const Scaled64 CondCost) {
1420 uint64_t MispredictRate = Opts->mispredict_default_rate;
1423 if (isSelectHighlyPredictable(
SI))
1429 Scaled64 MispredictCost =
1430 std::max(Scaled64::get(MispredictPenalty), CondCost) *
1431 Scaled64::get(MispredictRate);
1432 MispredictCost /= Scaled64::get(100);
1434 return MispredictCost;
1440SelectOptimizeImpl::getPredictedPathCost(Scaled64 TrueCost, Scaled64 FalseCost,
1441 const SelectLike
SI) {
1442 Scaled64 PredPathCost;
1445 uint64_t SumWeight = TrueWeight + FalseWeight;
1446 if (SumWeight != 0) {
1447 PredPathCost = TrueCost * Scaled64::get(TrueWeight) +
1448 FalseCost * Scaled64::get(FalseWeight);
1449 PredPathCost /= Scaled64::get(SumWeight);
1450 return PredPathCost;
1455 PredPathCost = std::max(TrueCost * Scaled64::get(3) + FalseCost,
1456 FalseCost * Scaled64::get(3) + TrueCost);
1457 PredPathCost /= Scaled64::get(4);
1458 return PredPathCost;
1461bool SelectOptimizeImpl::isSelectKindSupported(
const SelectLike
SI) {
1463 if (
SI.getType()->isVectorTy())
const TargetLowering & TLI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static Value * getTrueOrFalseValue(SelectInst *SI, bool isTrue, const SmallPtrSet< const Instruction *, 2 > &Selects)
If isTrue is true, return the true value of SI, otherwise return false value of SI.
static bool runOnFunction(Function &F, bool PostInlining)
SmallVector< MachineOperand, 4 > Cond
if(!TBB||Cond.size()< 1) return false
print mir2vec MIR2Vec Vocabulary Printer Pass
uint64_t IntrinsicInst * II
FunctionAnalysisManager FAM
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
This file contains the declarations for profiling metadata utility functions.
const GCNTargetMachine & getTM(const GCNSubtarget *STI)
static bool isSafeToSinkLoad(Instruction *LoadI, Instruction *SI)
static void EmitAndPrintRemark(OptimizationRemarkEmitter *ORE, DiagnosticInfoOptimizationBase &Rem)
This file contains the declaration of the SelectOptimizePass class, its corresponding pass name is se...
This file implements a set that has insertion order iteration characteristics.
This file defines the SmallVector class.
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static SymbolRef::Type getType(const Symbol *Sym)
This file describes how to lower LLVM code to machine code.
Target-Independent Code Generator Pass Configuration Options pass.
static const uint32_t IV[8]
AnalysisUsage & addRequired()
LLVM Basic Block Representation.
iterator begin()
Instruction iterator methods.
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...
LLVM_ABI BasicBlock * splitBasicBlock(iterator I, const Twine &BBName="")
Split the basic block into two basic blocks at the specified instruction.
const Function * getParent() const
Return the enclosing method, or null if none.
LLVM_ABI void insertDbgRecordBefore(DbgRecord *DR, InstListType::iterator Here)
Insert a DbgRecord into a block at the position given by Here.
static BasicBlock * Create(LLVMContext &Context, const Twine &Name="", Function *Parent=nullptr, BasicBlock *InsertBefore=nullptr)
Creates a new BasicBlock.
InstListType::iterator iterator
Instruction iterators...
LLVM_ABI LLVMContext & getContext() const
Get the context in which this basic block lives.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction; assumes that the block is well-formed.
Analysis pass which computes BlockFrequencyInfo.
Legacy analysis pass which computes BlockFrequencyInfo.
LLVM_ABI void setBlockFreq(const BasicBlock *BB, BlockFrequency Freq)
LLVM_ABI BlockFrequency getBlockFreq(const BasicBlock *BB) const
getblockFreq - Return block frequency.
static LLVM_ABI BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
@ ICMP_SLT
signed less than
@ ICMP_SLE
signed less or equal
@ ICMP_SGT
signed greater than
@ ICMP_SGE
signed greater or equal
This is the shared class of boolean and integer constants.
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static LLVM_ABI Constant * getAllOnesValue(Type *Ty)
Base class for non-instruction debug metadata records that have positions within IR.
LLVM_ABI void removeFromParent()
iterator find(const_arg_type_t< KeyT > Val)
DenseMapIterator< KeyT, ValueT, KeyInfoT, BucketT > iterator
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&...Args)
Common features for diagnostics dealing with optimization remarks that are used by both IR and MIR pa...
std::string getMsg() const
FunctionPass class - This class is used to implement most global optimizations.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
CostType getValue() const
This function is intended to be used as sparingly as possible, since the class provides the full rang...
LLVM_ABI void insertBefore(InstListType::iterator InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified position.
LLVM_ABI InstListType::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
LLVM_ABI void swapProfMetadata()
If the instruction has "branch_weights" MD_prof metadata and the MDNode has three operands (including...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM_ABI void copyMetadata(const Instruction &SrcInst, ArrayRef< unsigned > WL=ArrayRef< unsigned >())
Copy metadata from SrcInst to this instruction.
Analysis pass that exposes the LoopInfo for a function.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
The legacy pass manager's analysis pass to compute loop information.
Represents a single loop in the control flow graph.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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...
Pass interface - Implemented by all 'passes'.
A set of analyses that are preserved following a run of a transformation pass.
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
bool hasProfileSummary() const
Returns true if profile summary is available.
bool isColdBlock(const BBType *BB, BFIT *BFI) const
Returns true if BasicBlock BB is considered cold.
Simple representation of a scaled number.
static ScaledNumber get(uint64_t N)
static ScaledNumber getZero()
LLVM_ABI PreservedAnalyses run(Function &F, FunctionAnalysisManager &FAM)
bool insert(const value_type &X)
Insert a new element into the SetVector.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements.
A SetVector that performs no allocations if smaller than a certain size.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Analysis pass providing the TargetTransformInfo.
virtual bool isSelectSupported(SelectSupportKind) const
SelectSupportKind
Enum that describes what type of support for selects the target has.
bool isPredictableSelectExpensive() const
Return true if selects are only cheaper than branches if the branch is unlikely to be predicted right...
virtual const TargetSubtargetInfo * getSubtargetImpl(const Function &) const
Virtual method implemented by subclasses that returns a reference to that target's TargetSubtargetInf...
Target-Independent Code Generator Pass Configuration Options.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
virtual unsigned getMispredictionPenalty() const
Return the number of extra cycles the processor takes to recover from a branch misprediction.
virtual const TargetLowering * getTargetLowering() const
bool isIntegerTy() const
True if this is an instance of IntegerType.
Unconditional Branch instruction.
static UncondBrInst * Create(BasicBlock *Target, InsertPosition InsertBefore=nullptr)
A Use represents the edge between a Value definition and its users.
LLVM Value Representation.
Type * getType() const
All values are typed, get the type of this value.
LLVM_ABI void takeName(Value *V)
Transfer the name from V to this value.
const ParentTy * getParent() const
self_iterator getIterator()
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
BinaryOp_match< SrcTy, SpecificConstantMatch, TargetOpcode::G_XOR, true > m_Not(const SrcTy &&Src)
Matches a register not-ed by a G_XOR.
OneUse_match< SubPat > m_OneUse(const SubPat &SP)
bool match(Val *V, const Pattern &P)
BinOpPred_match< LHS, RHS, is_right_shift_op > m_Shr(const LHS &L, const RHS &R)
Matches logical shift operations.
ThreeOps_match< Cond, LHS, RHS, Instruction::Select > m_Select(const Cond &C, const LHS &L, const RHS &R)
Matches SelectInst.
auto m_Value()
Match an arbitrary value and ignore it.
is_zero< true > m_Zero()
Match any null constant or a vector with all elements equal to 0.
AnyBinaryOp_match< LHS, RHS, true > m_c_BinOp(const LHS &L, const RHS &R)
Matches a BinaryOperator with LHS and RHS in either order.
match_combine_or< CastInst_match< OpTy, ZExtInst >, CastInst_match< OpTy, SExtInst > > m_ZExtOrSExt(const OpTy &Op)
auto m_ConstantInt()
Match an arbitrary ConstantInt and ignore it.
PointerTypeMap run(const Module &M)
Compute the PointerTypeMap for the module M.
friend class Instruction
Iterator for Instructions in a `BasicBlock.
unsigned getOpcode(const VPValue *V)
Return the instruction opcode for the recipe defining V or 0 for unsupported recipes and VPValues not...
This is an optimization pass for GlobalISel generic memory operations.
LLVM_ABI cl::opt< bool > ProfcheckDisableMetadataFixes
UnaryFunction for_each(R &&Range, UnaryFunction F)
Provide wrappers to std::for_each which take ranges instead of having to pass begin/end explicitly.
LLVM_ABI void setExplicitlyUnknownBranchWeightsIfProfiled(Instruction &I, StringRef PassName, const Function *F=nullptr)
Like setExplicitlyUnknownBranchWeights(...), but only sets unknown branch weights in the new instruct...
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
OuterAnalysisManagerProxy< ModuleAnalysisManager, Function > ModuleAnalysisManagerFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
LLVM_ABI FunctionPass * createSelectOptimizePass()
This pass converts conditional moves to conditional jumps when profitable.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void append_range(Container &C, Range &&R)
Wrapper function to append range R to container C.
LLVM_ABI bool shouldOptimizeForSize(const MachineFunction *MF, ProfileSummaryInfo *PSI, const MachineBlockFrequencyInfo *BFI, PGSOQueryType QueryType=PGSOQueryType::Other)
Returns true if machine function MF is suggested to be size-optimized based on the profile.
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...
RelativeUniformCounterPtr ValuesPtrExpr VTableAddr Value
constexpr T divideNearest(U Numerator, V Denominator)
Returns (Numerator / Denominator) rounded by round-half-up.
auto dyn_cast_or_null(const Y &Val)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
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...
LLVM_ABI bool hasProfMD(const Instruction &I)
Checks if an Instruction has MD_prof Metadata.
DWARFExpression::Operation Op
LLVM_ABI bool extractBranchWeights(const MDNode *ProfileData, SmallVectorImpl< uint32_t > &Weights)
Extract branch weights from MD_prof metadata.
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
void erase_if(Container &C, UnaryPredicate P)
Provide a container algorithm similar to C++ Library Fundamentals v2's erase_if which is equivalent t...
AnalysisManager< Function > FunctionAnalysisManager
Convenience typedef for the Function analysis manager.
const CodeGenOptions & getCodeGenOptions(const LLVMContext &C)
LLVM_ABI void reportFatalUsageError(Error Err)
Report a fatal error that does not indicate a bug in LLVM.