79#define DEBUG_TYPE "x86-cmov-conversion"
81STATISTIC(NumOfSkippedCmovGroups,
"Number of unsupported CMOV-groups");
82STATISTIC(NumOfCmovGroupCandidate,
"Number of CMOV-group candidates");
83STATISTIC(NumOfLoopCandidate,
"Number of CMOV-conversion profitable loops");
84STATISTIC(NumOfOptimizedCmovGroups,
"Number of optimized CMOV-groups");
89class X86CmovConversionImpl {
96 MachineRegisterInfo *MRI =
nullptr;
97 const TargetInstrInfo *TII =
nullptr;
98 const X86Subtarget *STI =
nullptr;
99 MachineLoopInfo *MLI =
nullptr;
100 TargetSchedModel TSchedModel;
103 using CmovGroup = SmallVector<MachineInstr *, 2>;
104 using CmovGroups = SmallVector<CmovGroup, 2>;
117 CmovGroups &CmovInstGroups,
118 bool IncludeLoads =
false);
127 CmovGroups &CmovInstGroups);
132 void convertCmovInstsToBranches(SmallVectorImpl<MachineInstr *> &Group)
const;
137 X86CmovConversionLegacy() : MachineFunctionPass(ID) {}
139 StringRef getPassName()
const override {
return "X86 cmov Conversion"; }
141 void getAnalysisUsage(AnalysisUsage &AU)
const override;
149char X86CmovConversionLegacy::ID = 0;
151void X86CmovConversionLegacy::getAnalysisUsage(
AnalysisUsage &AU)
const {
159 const X86Options &CLOpts = STI->
getCLOpts();
161 if (!CLOpts.cmov_converter)
174 TSchedModel.
init(STI);
182 if (CLOpts.cmov_converter_force_mem_operand ||
183 CLOpts.cmov_converter_force_all) {
184 CmovGroups AllCmovGroups;
186 if (collectCmovCandidates(Blocks, AllCmovGroups,
true)) {
187 for (
auto &Group : AllCmovGroups) {
189 if (CLOpts.cmov_converter_force_mem_operand &&
190 !CLOpts.cmov_converter_force_all &&
191 llvm::none_of(Group, [&](MachineInstr *
I) { return I->mayLoad(); }))
198 convertCmovInstsToBranches(Group);
204 Changed |= unfoldNDDMemCmovs(MF);
206 if (CLOpts.cmov_converter_force_all)
237 for (
int i = 0; i < (int)
Loops.size(); ++i)
240 for (MachineLoop *CurrLoop :
Loops) {
242 if (!CurrLoop->getSubLoops().empty())
246 CmovGroups CmovInstGroups;
248 if (!collectCmovCandidates(CurrLoop->getBlocks(), CmovInstGroups))
251 if (!checkForProfitableCmovCandidates(CurrLoop->getBlocks(),
256 for (
auto &Group : CmovInstGroups)
257 convertCmovInstsToBranches(Group);
265 for (MachineBasicBlock &
MBB : MF) {
267 unsigned Opc =
MI.getOpcode();
268 if (
Opc != X86::CMOV16rm_ND &&
Opc != X86::CMOV32rm_ND &&
269 Opc != X86::CMOV64rm_ND)
271 const MachineOperand &
Base =
273 if (
Base.isReg() &&
Base.getReg() == X86::RIP)
278 SmallVector<MachineInstr *, 2> NewMIs;
279 [[maybe_unused]]
bool Unfolded =
280 TII->unfoldMemoryOperand(MF,
MI,
Reg,
true,
282 assert(Unfolded &&
"Should never fail to unfold a loading cmov!");
283 for (MachineInstr *NewMI : NewMIs)
285 MachineInstr *NewCmov = NewMIs.back();
287 if (
unsigned DebugInstrNum =
MI.peekDebugInstrNum())
290 MI.eraseFromParent();
297bool X86CmovConversionImpl::collectCmovCandidates(
321 for (
auto *
MBB : Blocks) {
328 bool FoundNonCMOVInst =
false;
330 bool SkipGroup =
false;
332 for (
auto &
I : *
MBB) {
334 if (
I.isDebugInstr())
341 !
I.getFlag(MachineInstr::MIFlag::Unpredictable) &&
342 (IncludeLoads || !
I.mayLoad()) && !
I.hasOrderedMemoryRef()) {
349 FoundNonCMOVInst =
false;
355 if (FoundNonCMOVInst || (
CC != FirstCC &&
CC != FirstOppCC))
362 else if (
CC != MemOpCC)
370 [&](MachineInstr &UseI) {
371 return UseI.getOpcode() == X86::SUBREG_TO_REG;
383 FoundNonCMOVInst =
true;
386 if (
I.definesRegister(X86::EFLAGS,
nullptr)) {
390 CmovInstGroups.push_back(Group);
392 ++NumOfSkippedCmovGroups;
401 CmovInstGroups.push_back(Group);
403 ++NumOfSkippedCmovGroups;
406 NumOfCmovGroupCandidate += CmovInstGroups.
size();
407 return !CmovInstGroups.empty();
419 divideCeil(TrueOpDepth * 3 + FalseOpDepth, 4),
420 divideCeil(FalseOpDepth * 3 + TrueOpDepth, 4));
423bool X86CmovConversionImpl::checkForProfitableCmovCandidates(
432 static const unsigned LoopIterations = 2;
433 DenseMap<MachineInstr *, DepthInfo> DepthMap;
434 DepthInfo LoopDepth[LoopIterations] = {{0, 0}, {0, 0}};
435 enum { PhyRegType = 0, VirRegType = 1, RegTypeNum = 2 };
437 DenseMap<Register, MachineInstr *> RegDefMaps[RegTypeNum];
440 DenseMap<MachineOperand *, MachineInstr *> OperandToDefMap;
443 DepthMap[
nullptr] = {0, 0};
445 SmallPtrSet<MachineInstr *, 4> CmovInstructions;
446 for (
auto &Group : CmovInstGroups)
472 for (DepthInfo &MaxDepth : LoopDepth) {
473 for (
auto *
MBB : Blocks) {
475 RegDefMaps[PhyRegType].
clear();
476 for (MachineInstr &
MI : *
MBB) {
478 if (
MI.isDebugInstr())
480 unsigned MIDepth = 0;
481 unsigned MIDepthOpt = 0;
482 bool IsCMOV = CmovInstructions.
count(&
MI);
483 for (
auto &MO :
MI.uses()) {
485 if (!MO.isReg() || !MO.isUse())
489 if (MachineInstr *
DefMI = RDM.lookup(
Reg)) {
490 OperandToDefMap[&MO] =
DefMI;
492 MIDepth = std::max(MIDepth,
Info.Depth);
494 MIDepthOpt = std::max(MIDepthOpt,
Info.OptDepth);
500 DepthMap[OperandToDefMap.
lookup(&
MI.getOperand(1))].OptDepth,
501 DepthMap[OperandToDefMap.
lookup(&
MI.getOperand(2))].OptDepth);
504 for (
auto &MO :
MI.operands()) {
505 if (!MO.isReg() || !MO.isDef())
511 unsigned Latency = TSchedModel.computeInstrLatency(&
MI);
513 MaxDepth.Depth = std::max(MaxDepth.Depth, MIDepth);
514 MaxDepth.OptDepth = std::max(MaxDepth.OptDepth, MIDepthOpt);
519 unsigned Diff[LoopIterations] = {LoopDepth[0].Depth - LoopDepth[0].OptDepth,
520 LoopDepth[1].Depth - LoopDepth[1].OptDepth};
550 if (Diff[1] < STI->
getCLOpts().cmov_converter_threshold)
553 bool WorthOptLoop =
false;
554 if (Diff[1] == Diff[0])
555 WorthOptLoop = Diff[0] * 8 >= LoopDepth[0].Depth;
556 else if (Diff[1] > Diff[0])
558 (Diff[1] - Diff[0]) * 2 >= (LoopDepth[1].
Depth - LoopDepth[0].
Depth) &&
559 (Diff[1] * 8 >= LoopDepth[1].Depth);
564 ++NumOfLoopCandidate;
577 unsigned MispredictPenalty = STI->getMispredictionPenalty();
578 CmovGroups TempGroups;
580 for (
auto &Group : TempGroups) {
581 bool WorthOpGroup =
true;
582 for (
auto *
MI : Group) {
588 unsigned Op = UIs.begin()->getOpcode();
589 if (
Op == X86::MOV64rm ||
Op == X86::MOV32rm) {
590 WorthOpGroup =
false;
596 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(4))].Depth;
598 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(1))].Depth,
599 DepthMap[OperandToDefMap.
lookup(&
MI->getOperand(2))].Depth);
600 if (ValCost > CondCost || (CondCost - ValCost) * 4 < MispredictPenalty) {
601 WorthOpGroup =
false;
607 CmovInstGroups.push_back(Group);
610 return !CmovInstGroups.empty();
614 if (
MI->killsRegister(X86::EFLAGS,
nullptr))
623 for (
auto I = std::next(ItrMI),
E = BB->
end();
I !=
E; ++
I) {
624 if (
I->readsRegister(X86::EFLAGS,
nullptr))
626 if (
I->definesRegister(X86::EFLAGS,
nullptr))
632 if (Succ->isLiveIn(X86::EFLAGS))
644 "Last instruction in a CMOV group must be a CMOV instruction");
647 for (
auto I =
First->getIterator(),
E =
Last->getIterator();
I !=
E;
I++) {
648 if (
I->isDebugInstr())
654 for (
auto *
MI : DBGInstructions)
655 MBB->insertAfter(
Last,
MI->removeFromParent());
658void X86CmovConversionImpl::convertCmovInstsToBranches(
659 SmallVectorImpl<MachineInstr *> &Group)
const {
660 assert(!Group.
empty() &&
"No CMOV instructions to convert");
661 ++NumOfOptimizedCmovGroups;
697 MachineInstr &
MI = *Group.
front();
698 MachineInstr *LastCMOV = Group.
back();
717 MachineBasicBlock *FalseMBB =
F->CreateMachineBasicBlock(BB);
718 MachineBasicBlock *SinkMBB =
F->CreateMachineBasicBlock(BB);
719 F->insert(It, FalseMBB);
720 F->insert(It, SinkMBB);
744 MachineInstrBuilder MIB;
755 DenseMap<Register, Register> FalseBBRegRewriteTable;
765 auto FRIt = FalseBBRegRewriteTable.
find(FalseReg);
766 if (FRIt == FalseBBRegRewriteTable.
end())
768 FalseReg = FRIt->second;
770 FalseBBRegRewriteTable[
MI.getOperand(0).getReg()] = FalseReg;
778 "Can only handle memory-operand cmov instructions with a condition "
779 "opposite to the selected branch direction.");
807 unsigned OldDebugInstrNum =
MI.peekDebugInstrNum();
808 SmallVector<MachineInstr *, 4> NewMIs;
813 assert(Unfolded &&
"Should never fail to unfold a loading cmov!");
819 "Last new instruction isn't the expected CMOV!");
822 if (&*MIItBegin == &
MI)
825 if (OldDebugInstrNum)
826 NewCMOV->setDebugInstrNum(OldDebugInstrNum);
830 for (
auto *NewMI : NewMIs) {
832 FalseMBB->
insert(FalseInsertionPoint, NewMI);
834 for (
auto &MOp : NewMI->uses()) {
837 auto It = FalseBBRegRewriteTable.
find(MOp.getReg());
838 if (It == FalseBBRegRewriteTable.
end())
841 MOp.setReg(It->second);
847 MOp.setIsKill(
false);
853 FalseBBRegRewriteTable[NewCMOV->getOperand(0).getReg()] = TmpReg;
862 DenseMap<Register, std::pair<Register, Register>> RegRewriteTable;
865 Register DestReg = MIIt->getOperand(0).getReg();
866 Register Op1Reg = MIIt->getOperand(1).getReg();
867 Register Op2Reg = MIIt->getOperand(2).getReg();
875 auto Op1Itr = RegRewriteTable.
find(Op1Reg);
876 if (Op1Itr != RegRewriteTable.
end())
877 Op1Reg = Op1Itr->second.first;
879 auto Op2Itr = RegRewriteTable.
find(Op2Reg);
880 if (Op2Itr != RegRewriteTable.
end())
881 Op2Reg = Op2Itr->second.second;
886 MIB =
BuildMI(*SinkMBB, SinkInsertionPoint,
DL,
TII->get(X86::PHI), DestReg)
897 if (
unsigned InstrNum = MIIt->peekDebugInstrNum())
901 RegRewriteTable[DestReg] = std::make_pair(Op1Reg, Op2Reg);
906 if (MIItBegin != MIItEnd)
907 F->getProperties().resetNoPHIs();
914 L->addBasicBlockToLoop(FalseMBB, *MLI);
915 L->addBasicBlockToLoop(SinkMBB, *MLI);
920 "X86 cmov Conversion",
false,
false)
926 return new X86CmovConversionLegacy();
929bool X86CmovConversionLegacy::runOnMachineFunction(
MachineFunction &MF) {
932 MachineLoopInfo *MLI = &getAnalysis<MachineLoopInfoWrapperPass>().getLI();
933 X86CmovConversionImpl Impl(MLI);
934 return Impl.runOnMachineFunction(MF);
941 X86CmovConversionImpl Impl(MLI);
942 bool Changed = Impl.runOnMachineFunction(MF);
MachineInstrBuilder MachineInstrBuilder & DefMI
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This file defines the DenseMap class.
Promote Memory to Register
#define INITIALIZE_PASS_DEPENDENCY(depName)
#define INITIALIZE_PASS_END(passName, arg, name, cfg, analysis)
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
MachineRegisterInfo & MRI
This file defines the SmallPtrSet class.
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 bool checkEFLAGSLive(MachineInstr *MI)
static unsigned getDepthOfOptCmov(unsigned TrueOpDepth, unsigned FalseOpDepth)
static void packCmovGroup(MachineInstr *First, MachineInstr *Last)
Given /p First CMOV instruction and /p Last CMOV instruction representing a group of CMOV instruction...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Represent the analysis usage information of a pass.
AnalysisUsage & addRequired()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
iterator find(const_arg_type_t< KeyT > Val)
ValueT lookup(const_arg_type_t< KeyT > Val) const
Return the entry for the specified key, or a default constructed value if no such entry exists.
FunctionPass class - This class is used to implement most global optimizations.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
LLVM_ABI void transferSuccessorsAndUpdatePHIs(MachineBasicBlock *FromMBB)
Transfers all the successors, as in transferSuccessors, and update PHI operands in the successor bloc...
LLVM_ABI instr_iterator insert(instr_iterator I, MachineInstr *M)
Insert MI into the instruction list before I, possibly inside a bundle.
const BasicBlock * getBasicBlock() const
Return the LLVM basic block that this instance corresponded to originally.
LLVM_ABI void addSuccessor(MachineBasicBlock *Succ, BranchProbability Prob=BranchProbability::getUnknown())
Add Succ as a successor of this MachineBasicBlock.
void addLiveIn(MCRegister PhysReg, LaneBitmask LaneMask=LaneBitmask::getAll())
Adds the specified register as a live in.
const MachineFunction * getParent() const
Return the MachineFunction containing this basic block.
LLVM_ABI instr_iterator erase(instr_iterator I)
Remove an instruction from the instruction list and delete it.
iterator_range< succ_iterator > successors()
void splice(iterator Where, MachineBasicBlock *Other, iterator From)
Take an instruction from MBB 'Other' at the position From, and insert it into this MBB right before '...
MachineInstrBundleIterator< MachineInstr > iterator
MachineFunctionPass - This class adapts the FunctionPass interface to allow convenient creation of pa...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - Subclasses that override getAnalysisUsage must call this.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
StringRef getName() const
getName - Return the name of the corresponding LLVM function.
MachineRegisterInfo & getRegInfo()
getRegInfo - Return information about the registers currently in use.
Function & getFunction()
Return the LLVM function that this machine code represents.
BasicBlockListType::iterator iterator
const TargetMachine & getTarget() const
getTarget - Return the target machine this machine code is compiled with
const MachineInstrBuilder & addReg(Register RegNo, RegState Flags={}, unsigned SubReg=0) const
Add a new virtual register operand.
const MachineInstrBuilder & addImm(int64_t Val) const
Add a new immediate operand.
const MachineInstrBuilder & addMBB(MachineBasicBlock *MBB, unsigned TargetFlags=0) const
Representation of each machine instruction.
void setFlags(unsigned flags)
void setDebugInstrNum(unsigned Num)
Set instruction number of this MachineInstr.
LLVM_ABI void dump() const
Analysis pass that exposes the MachineLoopInfo for a machine function.
const TargetRegisterClass * getRegClass(Register Reg) const
Return the register class of the specified virtual register.
LLVM_ABI Register createVirtualRegister(const TargetRegisterClass *RegClass, StringRef Name="")
createVirtualRegister - Create and return a new virtual register in the function with the specified r...
iterator_range< use_instr_nodbg_iterator > use_nodbg_instructions(Register Reg) const
iterator_range< use_instr_iterator > use_instructions(Register Reg) const
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
constexpr bool isVirtual() const
Return true if the specified register number is in the virtual register namespace.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
void insert_range(Range &&R)
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
LLVM_ABI void init(const TargetSubtargetInfo *TSInfo, bool EnableSModel=true, bool EnableSItins=true)
Initialize the machine model for instruction scheduling.
PreservedAnalyses run(MachineFunction &MF, MachineFunctionAnalysisManager &MFAM)
const X86InstrInfo * getInstrInfo() const override
const X86Options & getCLOpts() const
self_iterator getIterator()
@ BasicBlock
Various leaf nodes.
int getFirstAddrOperandIdx(const MachineInstr &MI)
Return the index of the instruction's first address operand, if it has a memory reference,...
CondCode GetOppositeBranchCondition(CondCode CC)
GetOppositeBranchCondition - Return the inverse of the specified cond, e.g.
bool foldNDDCmovLoads(const X86Subtarget &STI, const TargetMachine &TM)
Return true if ISel folds non-RIP-relative loads into NDD CMOVs so that X86CmovConversion converts th...
CondCode getCondFromCMov(const MachineInstr &MI)
This is an optimization pass for GlobalISel generic memory operations.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
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...
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly.
FunctionPass * createX86CmovConversionLegacyPass()
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
bool none_of(R &&Range, UnaryPredicate P)
Provide wrappers to std::none_of which take ranges instead of having to pass begin/end explicitly.
bool hasSingleElement(ContainerTy &&C)
Returns true if the given container only contains a single element.
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
LLVM_ABI CGPassBuilderOption getCGPassBuilderOption(const TargetMachine &TM)
constexpr T divideCeil(U Numerator, V Denominator)
Returns the integer ceil(Numerator / Denominator).
@ First
Helpers to iterate all locations in the MemoryEffectsBase class.
DWARFExpression::Operation Op
ArrayRef(const T &OneElt) -> ArrayRef< T >
iterator_range< pointer_iterator< WrappedIteratorT > > make_pointer_range(RangeT &&Range)
MCRegisterClass TargetRegisterClass
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
bool DisableSelectOptimize