#include "X86.h"
#include "X86InstrBuilder.h"
#include "X86InstrInfo.h"
#include "X86Subtarget.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/PostOrderIterator.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/ScopeExit.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/SparseBitVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/CodeGen/MachineBasicBlock.h"
#include "llvm/CodeGen/MachineConstantPool.h"
#include "llvm/CodeGen/MachineDominators.h"
#include "llvm/CodeGen/MachineFunction.h"
#include "llvm/CodeGen/MachineFunctionPass.h"
#include "llvm/CodeGen/MachineInstr.h"
#include "llvm/CodeGen/MachineInstrBuilder.h"
#include "llvm/CodeGen/MachineModuleInfo.h"
#include "llvm/CodeGen/MachineOperand.h"
#include "llvm/CodeGen/MachineRegisterInfo.h"
#include "llvm/CodeGen/MachineSSAUpdater.h"
#include "llvm/CodeGen/TargetInstrInfo.h"
#include "llvm/CodeGen/TargetRegisterInfo.h"
#include "llvm/CodeGen/TargetSchedule.h"
#include "llvm/CodeGen/TargetSubtargetInfo.h"
#include "llvm/IR/DebugLoc.h"
#include "llvm/MC/MCSchedule.h"
#include "llvm/Pass.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Debug.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <utility>
using namespace llvm;
#define PASS_KEY "x86-flags-copy-lowering"
#define DEBUG_TYPE PASS_KEY
STATISTIC(NumCopiesEliminated, "Number of copies of EFLAGS eliminated");
STATISTIC(NumSetCCsInserted, "Number of setCC instructions inserted");
STATISTIC(NumTestsInserted, "Number of test instructions inserted");
STATISTIC(NumAddsInserted, "Number of adds instructions inserted");
namespace {
using CondRegArray = std::array<unsigned, X86::LAST_VALID_COND + 1>;
class X86FlagsCopyLoweringPass : public MachineFunctionPass {
public:
X86FlagsCopyLoweringPass() : MachineFunctionPass(ID) { }
StringRef getPassName() const override { return "X86 EFLAGS copy lowering"; }
bool runOnMachineFunction(MachineFunction &MF) override;
void getAnalysisUsage(AnalysisUsage &AU) const override;
static char ID;
private:
MachineRegisterInfo *MRI = nullptr;
const X86Subtarget *Subtarget = nullptr;
const X86InstrInfo *TII = nullptr;
const TargetRegisterInfo *TRI = nullptr;
const TargetRegisterClass *PromoteRC = nullptr;
MachineDominatorTree *MDT = nullptr;
CondRegArray collectCondsInRegs(MachineBasicBlock &MBB,
MachineBasicBlock::iterator CopyDefI);
Register promoteCondToReg(MachineBasicBlock &MBB,
MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc, X86::CondCode Cond);
std::pair<unsigned, bool> getCondOrInverseInReg(
MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc, X86::CondCode Cond, CondRegArray &CondRegs);
void insertTest(MachineBasicBlock &MBB, MachineBasicBlock::iterator Pos,
const DebugLoc &Loc, unsigned Reg);
void rewriteArithmetic(MachineBasicBlock &TestMBB,
MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc, MachineInstr &MI,
MachineOperand &FlagUse, CondRegArray &CondRegs);
void rewriteCMov(MachineBasicBlock &TestMBB,
MachineBasicBlock::iterator TestPos, const DebugLoc &TestLoc,
MachineInstr &CMovI, MachineOperand &FlagUse,
CondRegArray &CondRegs);
void rewriteFCMov(MachineBasicBlock &TestMBB,
MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc, MachineInstr &CMovI,
MachineOperand &FlagUse, CondRegArray &CondRegs);
void rewriteCondJmp(MachineBasicBlock &TestMBB,
MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc, MachineInstr &JmpI,
CondRegArray &CondRegs);
void rewriteCopy(MachineInstr &MI, MachineOperand &FlagUse,
MachineInstr &CopyDefI);
void rewriteSetCC(MachineBasicBlock &TestMBB,
MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc, MachineInstr &SetCCI,
MachineOperand &FlagUse, CondRegArray &CondRegs);
};
}
INITIALIZE_PASS_BEGIN(X86FlagsCopyLoweringPass, DEBUG_TYPE,
"X86 EFLAGS copy lowering", false, false)
INITIALIZE_PASS_END(X86FlagsCopyLoweringPass, DEBUG_TYPE,
"X86 EFLAGS copy lowering", false, false)
FunctionPass *llvm::createX86FlagsCopyLoweringPass() {
return new X86FlagsCopyLoweringPass();
}
char X86FlagsCopyLoweringPass::ID = 0;
void X86FlagsCopyLoweringPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<MachineDominatorTree>();
MachineFunctionPass::getAnalysisUsage(AU);
}
namespace {
enum class FlagArithMnemonic {
ADC,
ADCX,
ADOX,
RCL,
RCR,
SBB,
SETB,
};
}
static FlagArithMnemonic getMnemonicFromOpcode(unsigned Opcode) {
switch (Opcode) {
default:
report_fatal_error("No support for lowering a copy into EFLAGS when used "
"by this instruction!");
#define LLVM_EXPAND_INSTR_SIZES(MNEMONIC, SUFFIX) \
case X86::MNEMONIC##8##SUFFIX: \
case X86::MNEMONIC##16##SUFFIX: \
case X86::MNEMONIC##32##SUFFIX: \
case X86::MNEMONIC##64##SUFFIX:
#define LLVM_EXPAND_ADC_SBB_INSTR(MNEMONIC) \
LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rr) \
LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rr_REV) \
LLVM_EXPAND_INSTR_SIZES(MNEMONIC, rm) \
LLVM_EXPAND_INSTR_SIZES(MNEMONIC, mr) \
case X86::MNEMONIC##8ri: \
case X86::MNEMONIC##16ri8: \
case X86::MNEMONIC##32ri8: \
case X86::MNEMONIC##64ri8: \
case X86::MNEMONIC##16ri: \
case X86::MNEMONIC##32ri: \
case X86::MNEMONIC##64ri32: \
case X86::MNEMONIC##8mi: \
case X86::MNEMONIC##16mi8: \
case X86::MNEMONIC##32mi8: \
case X86::MNEMONIC##64mi8: \
case X86::MNEMONIC##16mi: \
case X86::MNEMONIC##32mi: \
case X86::MNEMONIC##64mi32: \
case X86::MNEMONIC##8i8: \
case X86::MNEMONIC##16i16: \
case X86::MNEMONIC##32i32: \
case X86::MNEMONIC##64i32:
LLVM_EXPAND_ADC_SBB_INSTR(ADC)
return FlagArithMnemonic::ADC;
LLVM_EXPAND_ADC_SBB_INSTR(SBB)
return FlagArithMnemonic::SBB;
#undef LLVM_EXPAND_ADC_SBB_INSTR
LLVM_EXPAND_INSTR_SIZES(RCL, rCL)
LLVM_EXPAND_INSTR_SIZES(RCL, r1)
LLVM_EXPAND_INSTR_SIZES(RCL, ri)
return FlagArithMnemonic::RCL;
LLVM_EXPAND_INSTR_SIZES(RCR, rCL)
LLVM_EXPAND_INSTR_SIZES(RCR, r1)
LLVM_EXPAND_INSTR_SIZES(RCR, ri)
return FlagArithMnemonic::RCR;
#undef LLVM_EXPAND_INSTR_SIZES
case X86::ADCX32rr:
case X86::ADCX64rr:
case X86::ADCX32rm:
case X86::ADCX64rm:
return FlagArithMnemonic::ADCX;
case X86::ADOX32rr:
case X86::ADOX64rr:
case X86::ADOX32rm:
case X86::ADOX64rm:
return FlagArithMnemonic::ADOX;
case X86::SETB_C32r:
case X86::SETB_C64r:
return FlagArithMnemonic::SETB;
}
}
static MachineBasicBlock &splitBlock(MachineBasicBlock &MBB,
MachineInstr &SplitI,
const X86InstrInfo &TII) {
MachineFunction &MF = *MBB.getParent();
assert(SplitI.getParent() == &MBB &&
"Split instruction must be in the split block!");
assert(SplitI.isBranch() &&
"Only designed to split a tail of branch instructions!");
assert(X86::getCondFromBranch(SplitI) != X86::COND_INVALID &&
"Must split on an actual jCC instruction!");
MachineInstr &PrevI = *std::prev(SplitI.getIterator());
assert(PrevI.isBranch() && "Must split after a branch!");
assert(X86::getCondFromBranch(PrevI) != X86::COND_INVALID &&
"Must split after an actual jCC instruction!");
assert(!std::prev(PrevI.getIterator())->isTerminator() &&
"Must only have this one terminator prior to the split!");
MachineBasicBlock &UnsplitSucc = *PrevI.getOperand(0).getMBB();
bool IsEdgeSplit =
std::any_of(SplitI.getIterator(), MBB.instr_end(),
[&](MachineInstr &MI) {
assert(MI.isTerminator() &&
"Should only have spliced terminators!");
return llvm::any_of(
MI.operands(), [&](MachineOperand &MOp) {
return MOp.isMBB() && MOp.getMBB() == &UnsplitSucc;
});
}) ||
MBB.getFallThrough() == &UnsplitSucc;
MachineBasicBlock &NewMBB = *MF.CreateMachineBasicBlock();
MF.insert(std::next(MachineFunction::iterator(&MBB)), &NewMBB);
NewMBB.splice(NewMBB.end(), &MBB, SplitI.getIterator(), MBB.end());
for (auto SI = MBB.succ_begin(), SE = MBB.succ_end(); SI != SE; ++SI)
if (IsEdgeSplit || *SI != &UnsplitSucc)
NewMBB.copySuccessor(&MBB, SI);
if (!IsEdgeSplit)
NewMBB.normalizeSuccProbs();
for (MachineBasicBlock *Succ : NewMBB.successors())
if (Succ != &UnsplitSucc)
MBB.replaceSuccessor(Succ, &NewMBB);
assert(MBB.isSuccessor(&NewMBB) &&
"Failed to make the new block a successor!");
for (MachineBasicBlock *Succ : NewMBB.successors()) {
for (MachineInstr &MI : *Succ) {
if (!MI.isPHI())
break;
for (int OpIdx = 1, NumOps = MI.getNumOperands(); OpIdx < NumOps;
OpIdx += 2) {
MachineOperand &OpV = MI.getOperand(OpIdx);
MachineOperand &OpMBB = MI.getOperand(OpIdx + 1);
assert(OpMBB.isMBB() && "Block operand to a PHI is not a block!");
if (OpMBB.getMBB() != &MBB)
continue;
if (!IsEdgeSplit || Succ != &UnsplitSucc) {
OpMBB.setMBB(&NewMBB);
continue;
}
MI.addOperand(MF, OpV);
MI.addOperand(MF, MachineOperand::CreateMBB(&NewMBB));
break;
}
}
}
return NewMBB;
}
static X86::CondCode getCondFromFCMOV(unsigned Opcode) {
switch (Opcode) {
default: return X86::COND_INVALID;
case X86::CMOVBE_Fp32: case X86::CMOVBE_Fp64: case X86::CMOVBE_Fp80:
return X86::COND_BE;
case X86::CMOVB_Fp32: case X86::CMOVB_Fp64: case X86::CMOVB_Fp80:
return X86::COND_B;
case X86::CMOVE_Fp32: case X86::CMOVE_Fp64: case X86::CMOVE_Fp80:
return X86::COND_E;
case X86::CMOVNBE_Fp32: case X86::CMOVNBE_Fp64: case X86::CMOVNBE_Fp80:
return X86::COND_A;
case X86::CMOVNB_Fp32: case X86::CMOVNB_Fp64: case X86::CMOVNB_Fp80:
return X86::COND_AE;
case X86::CMOVNE_Fp32: case X86::CMOVNE_Fp64: case X86::CMOVNE_Fp80:
return X86::COND_NE;
case X86::CMOVNP_Fp32: case X86::CMOVNP_Fp64: case X86::CMOVNP_Fp80:
return X86::COND_NP;
case X86::CMOVP_Fp32: case X86::CMOVP_Fp64: case X86::CMOVP_Fp80:
return X86::COND_P;
}
}
bool X86FlagsCopyLoweringPass::runOnMachineFunction(MachineFunction &MF) {
LLVM_DEBUG(dbgs() << "********** " << getPassName() << " : " << MF.getName()
<< " **********\n");
Subtarget = &MF.getSubtarget<X86Subtarget>();
MRI = &MF.getRegInfo();
TII = Subtarget->getInstrInfo();
TRI = Subtarget->getRegisterInfo();
MDT = &getAnalysis<MachineDominatorTree>();
PromoteRC = &X86::GR8RegClass;
if (MF.begin() == MF.end())
return false;
SmallVector<MachineInstr *, 4> Copies;
ReversePostOrderTraversal<MachineFunction *> RPOT(&MF);
for (MachineBasicBlock *MBB : RPOT)
for (MachineInstr &MI : *MBB)
if (MI.getOpcode() == TargetOpcode::COPY &&
MI.getOperand(0).getReg() == X86::EFLAGS)
Copies.push_back(&MI);
for (MachineInstr *CopyI : Copies) {
MachineBasicBlock &MBB = *CopyI->getParent();
MachineOperand &VOp = CopyI->getOperand(1);
assert(VOp.isReg() &&
"The input to the copy for EFLAGS should always be a register!");
MachineInstr &CopyDefI = *MRI->getVRegDef(VOp.getReg());
if (CopyDefI.getOpcode() != TargetOpcode::COPY) {
LLVM_DEBUG(
dbgs() << "ERROR: Encountered unexpected def of an eflags copy: ";
CopyDefI.dump());
report_fatal_error(
"Cannot lower EFLAGS copy unless it is defined in turn by a copy!");
}
auto Cleanup = make_scope_exit([&] {
CopyI->eraseFromParent();
if (MRI->use_empty(CopyDefI.getOperand(0).getReg()))
CopyDefI.eraseFromParent();
++NumCopiesEliminated;
});
MachineOperand &DOp = CopyI->getOperand(0);
assert(DOp.isDef() && "Expected register def!");
assert(DOp.getReg() == X86::EFLAGS && "Unexpected copy def register!");
if (DOp.isDead())
continue;
MachineBasicBlock *TestMBB = CopyDefI.getParent();
auto TestPos = CopyDefI.getIterator();
DebugLoc TestLoc = CopyDefI.getDebugLoc();
LLVM_DEBUG(dbgs() << "Rewriting copy: "; CopyI->dump());
auto HasEFLAGSClobber = [&](MachineBasicBlock::iterator Begin,
MachineBasicBlock::iterator End) {
return llvm::any_of(
llvm::reverse(llvm::make_range(Begin, End)), [&](MachineInstr &MI) {
return &MI != CopyI && MI.findRegisterDefOperand(X86::EFLAGS);
});
};
auto HasEFLAGSClobberPath = [&](MachineBasicBlock *BeginMBB,
MachineBasicBlock *EndMBB) {
assert(MDT->dominates(BeginMBB, EndMBB) &&
"Only support paths down the dominator tree!");
SmallPtrSet<MachineBasicBlock *, 4> Visited;
SmallVector<MachineBasicBlock *, 4> Worklist;
Visited.insert(BeginMBB);
Worklist.push_back(EndMBB);
do {
auto *MBB = Worklist.pop_back_val();
for (auto *PredMBB : MBB->predecessors()) {
if (!Visited.insert(PredMBB).second)
continue;
if (HasEFLAGSClobber(PredMBB->begin(), PredMBB->end()))
return true;
Worklist.push_back(PredMBB);
}
} while (!Worklist.empty());
return false;
};
while (TestMBB->isLiveIn(X86::EFLAGS) && !TestMBB->pred_empty() &&
!HasEFLAGSClobber(TestMBB->begin(), TestPos)) {
MachineBasicBlock *HoistMBB =
std::accumulate(std::next(TestMBB->pred_begin()), TestMBB->pred_end(),
*TestMBB->pred_begin(),
[&](MachineBasicBlock *LHS, MachineBasicBlock *RHS) {
return MDT->findNearestCommonDominator(LHS, RHS);
});
if (HasEFLAGSClobberPath(HoistMBB, TestMBB))
break;
if (HasEFLAGSClobber(HoistMBB->getFirstTerminator()->getIterator(),
HoistMBB->instr_end()))
break;
TestMBB = HoistMBB;
TestPos = TestMBB->getFirstTerminator()->getIterator();
TestLoc = DebugLoc();
}
LLVM_DEBUG({
auto DefIt = llvm::find_if(
llvm::reverse(llvm::make_range(TestMBB->instr_begin(), TestPos)),
[&](MachineInstr &MI) {
return MI.findRegisterDefOperand(X86::EFLAGS);
});
if (DefIt.base() != TestMBB->instr_begin()) {
dbgs() << " Using EFLAGS defined by: ";
DefIt->dump();
} else {
dbgs() << " Using live-in flags for BB:\n";
TestMBB->dump();
}
});
SmallVector<MachineInstr *, 4> JmpIs;
CondRegArray CondRegs = collectCondsInRegs(*TestMBB, TestPos);
SmallVector<MachineBasicBlock *, 2> Blocks;
SmallPtrSet<MachineBasicBlock *, 2> VisitedBlocks;
Blocks.push_back(&MBB);
do {
MachineBasicBlock &UseMBB = *Blocks.pop_back_val();
bool FlagsKilled = false;
for (auto MII = (&UseMBB == &MBB && !VisitedBlocks.count(&UseMBB))
? std::next(CopyI->getIterator())
: UseMBB.instr_begin(),
MIE = UseMBB.instr_end();
MII != MIE;) {
MachineInstr &MI = *MII++;
if (&MI == CopyI || &MI == &CopyDefI) {
assert(&UseMBB == &MBB && VisitedBlocks.count(&MBB) &&
"Should only encounter these on the second pass over the "
"original block.");
break;
}
MachineOperand *FlagUse = MI.findRegisterUseOperand(X86::EFLAGS);
if (!FlagUse) {
if (MI.findRegisterDefOperand(X86::EFLAGS)) {
FlagsKilled = true;
break;
}
continue;
}
LLVM_DEBUG(dbgs() << " Rewriting use: "; MI.dump());
if (FlagUse->isKill())
FlagsKilled = true;
if (X86::getCondFromBranch(MI) != X86::COND_INVALID) {
auto JmpIt = MI.getIterator();
do {
JmpIs.push_back(&*JmpIt);
++JmpIt;
} while (JmpIt != UseMBB.instr_end() &&
X86::getCondFromBranch(*JmpIt) !=
X86::COND_INVALID);
break;
}
if (X86::getCondFromCMov(MI) != X86::COND_INVALID) {
rewriteCMov(*TestMBB, TestPos, TestLoc, MI, *FlagUse, CondRegs);
} else if (getCondFromFCMOV(MI.getOpcode()) != X86::COND_INVALID) {
rewriteFCMov(*TestMBB, TestPos, TestLoc, MI, *FlagUse, CondRegs);
} else if (X86::getCondFromSETCC(MI) != X86::COND_INVALID) {
rewriteSetCC(*TestMBB, TestPos, TestLoc, MI, *FlagUse, CondRegs);
} else if (MI.getOpcode() == TargetOpcode::COPY) {
rewriteCopy(MI, *FlagUse, CopyDefI);
} else {
assert(MI.findRegisterDefOperand(X86::EFLAGS) &&
"Expected a def of EFLAGS for this instruction!");
FlagsKilled = true;
rewriteArithmetic(*TestMBB, TestPos, TestLoc, MI, *FlagUse,
CondRegs);
}
if (FlagsKilled)
break;
}
if (FlagsKilled)
continue;
for (MachineBasicBlock *SuccMBB : UseMBB.successors())
if (SuccMBB->isLiveIn(X86::EFLAGS) &&
VisitedBlocks.insert(SuccMBB).second) {
if (SuccMBB == TestMBB || !MDT->dominates(TestMBB, SuccMBB)) {
LLVM_DEBUG({
dbgs()
<< "ERROR: Encountered use that is not dominated by our test "
"basic block! Rewriting this would require inserting PHI "
"nodes to track the flag state across the CFG.\n\nTest "
"block:\n";
TestMBB->dump();
dbgs() << "Use block:\n";
SuccMBB->dump();
});
report_fatal_error(
"Cannot lower EFLAGS copy when original copy def "
"does not dominate all uses.");
}
Blocks.push_back(SuccMBB);
SuccMBB->removeLiveIn(X86::EFLAGS);
}
} while (!Blocks.empty());
MachineBasicBlock *LastJmpMBB = nullptr;
for (MachineInstr *JmpI : JmpIs) {
if (JmpI->getParent() == LastJmpMBB)
splitBlock(*JmpI->getParent(), *JmpI, *TII);
else
LastJmpMBB = JmpI->getParent();
rewriteCondJmp(*TestMBB, TestPos, TestLoc, *JmpI, CondRegs);
}
}
#ifndef NDEBUG
for (MachineBasicBlock &MBB : MF)
for (MachineInstr &MI : MBB)
if (MI.getOpcode() == TargetOpcode::COPY &&
(MI.getOperand(0).getReg() == X86::EFLAGS ||
MI.getOperand(1).getReg() == X86::EFLAGS)) {
LLVM_DEBUG(dbgs() << "ERROR: Found a COPY involving EFLAGS: ";
MI.dump());
llvm_unreachable("Unlowered EFLAGS copy!");
}
#endif
return true;
}
CondRegArray X86FlagsCopyLoweringPass::collectCondsInRegs(
MachineBasicBlock &MBB, MachineBasicBlock::iterator TestPos) {
CondRegArray CondRegs = {};
for (MachineInstr &MI :
llvm::reverse(llvm::make_range(MBB.begin(), TestPos))) {
X86::CondCode Cond = X86::getCondFromSETCC(MI);
if (Cond != X86::COND_INVALID && !MI.mayStore() &&
MI.getOperand(0).isReg() && MI.getOperand(0).getReg().isVirtual()) {
assert(MI.getOperand(0).isDef() &&
"A non-storing SETcc should always define a register!");
CondRegs[Cond] = MI.getOperand(0).getReg();
}
if (MI.findRegisterDefOperand(X86::EFLAGS))
break;
}
return CondRegs;
}
Register X86FlagsCopyLoweringPass::promoteCondToReg(
MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc, X86::CondCode Cond) {
Register Reg = MRI->createVirtualRegister(PromoteRC);
auto SetI = BuildMI(TestMBB, TestPos, TestLoc,
TII->get(X86::SETCCr), Reg).addImm(Cond);
(void)SetI;
LLVM_DEBUG(dbgs() << " save cond: "; SetI->dump());
++NumSetCCsInserted;
return Reg;
}
std::pair<unsigned, bool> X86FlagsCopyLoweringPass::getCondOrInverseInReg(
MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc, X86::CondCode Cond, CondRegArray &CondRegs) {
unsigned &CondReg = CondRegs[Cond];
unsigned &InvCondReg = CondRegs[X86::GetOppositeBranchCondition(Cond)];
if (!CondReg && !InvCondReg)
CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);
if (CondReg)
return {CondReg, false};
else
return {InvCondReg, true};
}
void X86FlagsCopyLoweringPass::insertTest(MachineBasicBlock &MBB,
MachineBasicBlock::iterator Pos,
const DebugLoc &Loc, unsigned Reg) {
auto TestI =
BuildMI(MBB, Pos, Loc, TII->get(X86::TEST8rr)).addReg(Reg).addReg(Reg);
(void)TestI;
LLVM_DEBUG(dbgs() << " test cond: "; TestI->dump());
++NumTestsInserted;
}
void X86FlagsCopyLoweringPass::rewriteArithmetic(
MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc, MachineInstr &MI, MachineOperand &FlagUse,
CondRegArray &CondRegs) {
X86::CondCode Cond = X86::COND_INVALID;
int Addend = 0;
switch (getMnemonicFromOpcode(MI.getOpcode())) {
case FlagArithMnemonic::ADC:
case FlagArithMnemonic::ADCX:
case FlagArithMnemonic::RCL:
case FlagArithMnemonic::RCR:
case FlagArithMnemonic::SBB:
case FlagArithMnemonic::SETB:
Cond = X86::COND_B; Addend = 255;
break;
case FlagArithMnemonic::ADOX:
Cond = X86::COND_O; Addend = 127;
break;
}
unsigned &CondReg = CondRegs[Cond];
if (!CondReg)
CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);
MachineBasicBlock &MBB = *MI.getParent();
Register TmpReg = MRI->createVirtualRegister(PromoteRC);
auto AddI =
BuildMI(MBB, MI.getIterator(), MI.getDebugLoc(), TII->get(X86::ADD8ri))
.addDef(TmpReg, RegState::Dead)
.addReg(CondReg)
.addImm(Addend);
(void)AddI;
LLVM_DEBUG(dbgs() << " add cond: "; AddI->dump());
++NumAddsInserted;
FlagUse.setIsKill(true);
}
void X86FlagsCopyLoweringPass::rewriteCMov(MachineBasicBlock &TestMBB,
MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc,
MachineInstr &CMovI,
MachineOperand &FlagUse,
CondRegArray &CondRegs) {
X86::CondCode Cond = X86::getCondFromCMov(CMovI);
unsigned CondReg;
bool Inverted;
std::tie(CondReg, Inverted) =
getCondOrInverseInReg(TestMBB, TestPos, TestLoc, Cond, CondRegs);
MachineBasicBlock &MBB = *CMovI.getParent();
insertTest(MBB, CMovI.getIterator(), CMovI.getDebugLoc(), CondReg);
CMovI.getOperand(CMovI.getDesc().getNumOperands() - 1)
.setImm(Inverted ? X86::COND_E : X86::COND_NE);
FlagUse.setIsKill(true);
LLVM_DEBUG(dbgs() << " fixed cmov: "; CMovI.dump());
}
void X86FlagsCopyLoweringPass::rewriteFCMov(MachineBasicBlock &TestMBB,
MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc,
MachineInstr &CMovI,
MachineOperand &FlagUse,
CondRegArray &CondRegs) {
X86::CondCode Cond = getCondFromFCMOV(CMovI.getOpcode());
unsigned CondReg;
bool Inverted;
std::tie(CondReg, Inverted) =
getCondOrInverseInReg(TestMBB, TestPos, TestLoc, Cond, CondRegs);
MachineBasicBlock &MBB = *CMovI.getParent();
insertTest(MBB, CMovI.getIterator(), CMovI.getDebugLoc(), CondReg);
auto getFCMOVOpcode = [](unsigned Opcode, bool Inverted) {
switch (Opcode) {
default: llvm_unreachable("Unexpected opcode!");
case X86::CMOVBE_Fp32: case X86::CMOVNBE_Fp32:
case X86::CMOVB_Fp32: case X86::CMOVNB_Fp32:
case X86::CMOVE_Fp32: case X86::CMOVNE_Fp32:
case X86::CMOVP_Fp32: case X86::CMOVNP_Fp32:
return Inverted ? X86::CMOVE_Fp32 : X86::CMOVNE_Fp32;
case X86::CMOVBE_Fp64: case X86::CMOVNBE_Fp64:
case X86::CMOVB_Fp64: case X86::CMOVNB_Fp64:
case X86::CMOVE_Fp64: case X86::CMOVNE_Fp64:
case X86::CMOVP_Fp64: case X86::CMOVNP_Fp64:
return Inverted ? X86::CMOVE_Fp64 : X86::CMOVNE_Fp64;
case X86::CMOVBE_Fp80: case X86::CMOVNBE_Fp80:
case X86::CMOVB_Fp80: case X86::CMOVNB_Fp80:
case X86::CMOVE_Fp80: case X86::CMOVNE_Fp80:
case X86::CMOVP_Fp80: case X86::CMOVNP_Fp80:
return Inverted ? X86::CMOVE_Fp80 : X86::CMOVNE_Fp80;
}
};
CMovI.setDesc(TII->get(getFCMOVOpcode(CMovI.getOpcode(), Inverted)));
FlagUse.setIsKill(true);
LLVM_DEBUG(dbgs() << " fixed fcmov: "; CMovI.dump());
}
void X86FlagsCopyLoweringPass::rewriteCondJmp(
MachineBasicBlock &TestMBB, MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc, MachineInstr &JmpI, CondRegArray &CondRegs) {
X86::CondCode Cond = X86::getCondFromBranch(JmpI);
unsigned CondReg;
bool Inverted;
std::tie(CondReg, Inverted) =
getCondOrInverseInReg(TestMBB, TestPos, TestLoc, Cond, CondRegs);
MachineBasicBlock &JmpMBB = *JmpI.getParent();
insertTest(JmpMBB, JmpI.getIterator(), JmpI.getDebugLoc(), CondReg);
JmpI.getOperand(1).setImm(Inverted ? X86::COND_E : X86::COND_NE);
JmpI.findRegisterUseOperand(X86::EFLAGS)->setIsKill(true);
LLVM_DEBUG(dbgs() << " fixed jCC: "; JmpI.dump());
}
void X86FlagsCopyLoweringPass::rewriteCopy(MachineInstr &MI,
MachineOperand &FlagUse,
MachineInstr &CopyDefI) {
MRI->replaceRegWith(MI.getOperand(0).getReg(),
CopyDefI.getOperand(0).getReg());
MI.eraseFromParent();
}
void X86FlagsCopyLoweringPass::rewriteSetCC(MachineBasicBlock &TestMBB,
MachineBasicBlock::iterator TestPos,
const DebugLoc &TestLoc,
MachineInstr &SetCCI,
MachineOperand &FlagUse,
CondRegArray &CondRegs) {
X86::CondCode Cond = X86::getCondFromSETCC(SetCCI);
unsigned &CondReg = CondRegs[Cond];
if (!CondReg)
CondReg = promoteCondToReg(TestMBB, TestPos, TestLoc, Cond);
if (!SetCCI.mayStore()) {
assert(SetCCI.getOperand(0).isReg() &&
"Cannot have a non-register defined operand to SETcc!");
Register OldReg = SetCCI.getOperand(0).getReg();
MRI->clearKillFlags(OldReg);
MRI->replaceRegWith(OldReg, CondReg);
SetCCI.eraseFromParent();
return;
}
auto MIB = BuildMI(*SetCCI.getParent(), SetCCI.getIterator(),
SetCCI.getDebugLoc(), TII->get(X86::MOV8mr));
for (int i = 0; i < X86::AddrNumOperands; ++i)
MIB.add(SetCCI.getOperand(i));
MIB.addReg(CondReg);
MIB.setMemRefs(SetCCI.memoperands());
SetCCI.eraseFromParent();
}