30#define FIXUPLEA_DESC "X86 LEA Fixup"
31#define FIXUPLEA_NAME "x86-fixup-leas"
33#define DEBUG_TYPE FIXUPLEA_NAME
35STATISTIC(NumLEAs,
"Number of LEA instructions created");
39 enum RegUsageState { RU_NotUsed, RU_Write, RU_Read };
47 MachineBasicBlock &
MBB);
54 MachineBasicBlock &
MBB);
59 MachineBasicBlock &
MBB);
74 MachineBasicBlock &
MBB,
bool OptIncDec);
78 MachineInstr *buildOffsetAdd(MachineInstr &
MI, MachineBasicBlock &
MBB,
79 bool OptIncDec)
const;
84 MachineBasicBlock &
MBB,
bool OptIncDec,
85 bool UseLEAForSP)
const;
99 MachineBasicBlock &
MBB)
const;
108 bool &AluDestRef, MachineOperand **KilledBase,
109 MachineOperand **KilledIndex)
const;
120 MachineBasicBlock &
MBB);
125 MachineInstr *postRAConvertToLEA(MachineBasicBlock &
MBB,
129 FixupLEAsImpl(ProfileSummaryInfo *PSI, MachineBlockFrequencyInfo *MBFI)
130 : PSI(PSI), MBFI(MBFI) {}
138 TargetSchedModel TSM;
139 const X86InstrInfo *TII =
nullptr;
140 const X86RegisterInfo *TRI =
nullptr;
141 ProfileSummaryInfo *PSI;
142 MachineBlockFrequencyInfo *MBFI;
149 StringRef getPassName()
const override {
return FIXUPLEA_DESC; }
151 FixupLEAsLegacy() : MachineFunctionPass(ID) {}
156 MachineFunctionProperties getRequiredProperties()
const override {
157 return MachineFunctionProperties().setNoVRegs();
160 void getAnalysisUsage(AnalysisUsage &AU)
const override {
162 AU.
addRequired<LazyMachineBlockFrequencyInfoPass>();
168char FixupLEAsLegacy::ID = 0;
176 switch (
MI.getOpcode()) {
179 const MachineOperand &Src = MI.getOperand(1);
180 const MachineOperand &Dest = MI.getOperand(0);
181 MachineInstr *NewMI =
182 BuildMI(MBB, MBBI, MI.getDebugLoc(),
183 TII->get(MI.getOpcode() == X86::MOV32rr ? X86::LEA32r
195 if (!
MI.isConvertibleTo3Addr())
203 case X86::ADD64ri32_DB:
205 case X86::ADD32ri_DB:
206 if (!MI.getOperand(2).isImm()) {
219 case X86::ADD64rr_DB:
221 case X86::ADD32rr_DB:
225 return TII->convertToThreeAddress(
MI,
nullptr);
229 return new FixupLEAsLegacy();
233 return Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
234 Opcode == X86::LEA64_32r;
239 bool IsSlowLEA =
ST.slowLEA();
240 bool IsSlow3OpsLEA =
ST.slow3OpsLEA();
241 bool LEAUsesAG =
ST.leaUsesAG();
244 bool UseLEAForSP =
ST.useLeaForSP();
247 TII =
ST.getInstrInfo();
248 TRI =
ST.getRegisterInfo();
251 for (MachineBasicBlock &
MBB : MF) {
253 bool OptIncDecPerBB =
256 if (!
isLEA(
I->getOpcode()))
259 if (optTwoAddrLEA(
I,
MBB, OptIncDecPerBB, UseLEAForSP))
263 processInstructionForSlowLEA(
I,
MBB);
264 else if (IsSlow3OpsLEA)
265 processInstrForSlow3OpLEA(
I,
MBB, OptIncDecPerBB);
272 processInstruction(
I,
MBB);
281FixupLEAsImpl::RegUsageState
283 RegUsageState
RegUsage = RU_NotUsed;
284 MachineInstr &
MI = *
I;
286 for (
const MachineOperand &MO :
MI.operands()) {
287 if (MO.isReg() && MO.getReg() ==
p.getReg()) {
302 if (
I ==
MBB.begin()) {
303 if (
MBB.isPredecessor(&
MBB)) {
315 int InstrDistance = 1;
317 static const int INSTR_DISTANCE_THRESHOLD = 5;
322 while (Found &&
I != CurInst) {
323 if (CurInst->isCall() || CurInst->isInlineAsm())
325 if (InstrDistance > INSTR_DISTANCE_THRESHOLD)
327 if (usesRegister(p, CurInst) == RU_Write) {
330 InstrDistance += TSM.computeInstrLatency(&*CurInst);
337 return Reg == X86::EBP ||
Reg == X86::RBP ||
338 Reg == X86::R13D ||
Reg == X86::R13;
348 Index.getReg().isValid();
389 return X86::ADD64ri32;
401 return X86::SUB64ri32;
411 return IsINC ? X86::INC32r : X86::DEC32r;
413 return IsINC ? X86::INC64r : X86::DEC64r;
419 MachineBasicBlock &
MBB)
const {
421 unsigned InstrDistance = 1;
423 unsigned LEAOpcode =
I->getOpcode();
426 Register DestReg =
I->getOperand(0).getReg();
429 std::next(
I),
MBB.
end(),
false)) {
430 if (CurInst.isCall() || CurInst.isInlineAsm())
432 if (InstrDistance >
ST.getCLOpts().fixup_leas_search_distance_threshold)
436 for (
unsigned I = 0,
E = CurInst.getNumOperands();
I !=
E; ++
I) {
437 MachineOperand &Opnd = CurInst.getOperand(
I);
439 if (Opnd.
getReg() == DestReg) {
443 unsigned AluOpcode = CurInst.getOpcode();
444 if (AluOpcode != AddOpcode && AluOpcode != SubOpcode)
447 MachineOperand &Opnd2 = CurInst.getOperand(3 -
I);
448 MachineOperand AluDest = CurInst.getOperand(0);
455 if (!CurInst.registerDefIsDead(X86::EFLAGS,
TRI))
458 return CurInst.getIterator();
460 if (
TRI->regsOverlap(DestReg, Opnd.
getReg()))
472 bool &BaseIndexDef,
bool &AluDestRef,
473 MachineOperand **KilledBase,
474 MachineOperand **KilledIndex)
const {
475 BaseIndexDef = AluDestRef =
false;
476 *KilledBase = *KilledIndex =
nullptr;
479 Register AluDestReg = AluI->getOperand(0).getReg();
482 for (MachineOperand &Opnd : CurInst.operands()) {
486 if (
TRI->regsOverlap(
Reg, AluDestReg))
488 if (
TRI->regsOverlap(
Reg, BaseReg)) {
494 if (
TRI->regsOverlap(
Reg, IndexReg)) {
498 *KilledIndex = &Opnd;
505 MachineBasicBlock &
MBB)
const {
512 bool BaseIndexDef, AluDestRef;
513 MachineOperand *KilledBase, *KilledIndex;
514 checkRegUsage(
I, AluI, BaseIndexDef, AluDestRef, &KilledBase, &KilledIndex);
521 KilledBase = KilledIndex =
nullptr;
525 Register AluDestReg = AluI->getOperand(0).getReg();
528 if (
I->getOpcode() == X86::LEA64_32r) {
529 BaseReg =
TRI->getSubReg(BaseReg, X86::sub_32bit);
530 IndexReg =
TRI->getSubReg(IndexReg, X86::sub_32bit);
532 if (AluDestReg == IndexReg) {
533 if (BaseReg == IndexReg)
538 if (BaseReg == IndexReg)
539 KilledBase =
nullptr;
542 MachineInstr *NewMI1, *NewMI2;
543 unsigned NewOpcode = AluI->getOpcode();
544 NewMI1 =
BuildMI(
MBB, InsertPos, AluI->getDebugLoc(),
TII->get(NewOpcode),
546 .
addReg(AluDestReg, RegState::Kill)
549 NewMI2 =
BuildMI(
MBB, InsertPos, AluI->getDebugLoc(),
TII->get(NewOpcode),
551 .
addReg(AluDestReg, RegState::Kill)
569 MachineBasicBlock &
MBB,
bool OptIncDec,
570 bool UseLEAForSP)
const {
571 MachineInstr &
MI = *
I;
589 if (UseLEAForSP && (DestReg == X86::ESP || DestReg == X86::RSP))
593 if (
MI.getOpcode() == X86::LEA64_32r) {
595 BaseReg =
TRI->getSubReg(BaseReg, X86::sub_32bit);
597 IndexReg =
TRI->getSubReg(IndexReg, X86::sub_32bit);
600 MachineInstr *NewMI =
nullptr;
606 (DestReg == BaseReg || DestReg == IndexReg)) {
608 if (DestReg != BaseReg)
611 if (
MI.getOpcode() == X86::LEA64_32r) {
621 }
else if (DestReg == BaseReg && !IndexReg) {
629 if (OptIncDec && (Disp.
getImm() == 1 || Disp.
getImm() == -1)) {
630 bool IsINC = Disp.
getImm() == 1;
633 if (
MI.getOpcode() == X86::LEA64_32r) {
643 if (
MI.getOpcode() == X86::LEA64_32r) {
658 return optLEAALU(
I,
MBB);
669 MachineBasicBlock &
MBB) {
671 MachineInstr &
MI = *
I;
673 if (AddrOffset >= 0) {
675 if (
p.isReg() &&
p.getReg() != X86::ESP) {
676 seekLEAFixup(p,
I,
MBB);
679 if (
q.isReg() &&
q.getReg() != X86::ESP) {
680 seekLEAFixup(q,
I,
MBB);
685void FixupLEAsImpl::seekLEAFixup(MachineOperand &p,
687 MachineBasicBlock &
MBB) {
690 MachineInstr *NewMI = postRAConvertToLEA(
MBB, MBI);
693 LLVM_DEBUG(
dbgs() <<
"FixLEA: Candidate to replace:"; MBI->dump(););
700 processInstruction(J,
MBB);
706 MachineBasicBlock &
MBB) {
707 MachineInstr &
MI = *
I;
708 const unsigned Opcode =
MI.getOpcode();
710 const MachineOperand &Dst =
MI.getOperand(0);
724 if ((!SrcR1 || SrcR1 != DstR) && (!SrcR2 || SrcR2 != DstR))
730 MachineInstr *NewMI =
nullptr;
732 if (SrcR1 && SrcR2) {
734 const MachineOperand &Src = SrcR1 == DstR ?
Index :
Base;
740 if (
Offset.getImm() != 0) {
741 const MCInstrDesc &ADDri =
743 const MachineOperand &SrcR = SrcR1 == DstR ?
Base :
Index;
756MachineInstr *FixupLEAsImpl::buildOffsetAdd(MachineInstr &
MI,
757 MachineBasicBlock &
MBB,
758 bool OptIncDec)
const {
761 if (OptIncDec &&
Offset.isImm() &&
764 MachineInstr *AddMI =
775 MachineInstr *AddMI =
783 MachineInstr *AddMI =
792 MachineBasicBlock &
MBB,
794 MachineInstr &
MI = *
I;
795 const unsigned LEAOpcode =
MI.getOpcode();
797 const MachineOperand &Dest =
MI.getOperand(0);
814 if (
MI.getOpcode() == X86::LEA64_32r) {
816 BaseReg =
TRI->getSubReg(BaseReg, X86::sub_32bit);
818 IndexReg =
TRI->getSubReg(IndexReg, X86::sub_32bit);
821 bool IsScale1 = Scale.
getImm() == 1;
827 if (IsInefficientBase && DestReg == BaseReg && !IsScale1)
833 MachineInstr *NewMI =
nullptr;
834 bool BaseOrIndexIsDst = DestReg ==
BaseReg || DestReg == IndexReg;
841 if (IsScale1 && BaseReg == IndexReg &&
856 }
else if (IsScale1 && BaseOrIndexIsDst) {
864 assert(BaseReg != IndexReg &&
"lea D(%r,%r,1) is handled above");
867 buildOffsetAdd(
MI,
MBB, OptIncDec);
870 if (DestReg != BaseReg)
873 if (
MI.getOpcode() == X86::LEA64_32r) {
885 }
else if (!IsInefficientBase || (!IsInefficientIndex && IsScale1)) {
892 .
add(IsInefficientBase ? Index :
Base)
894 .
add(IsInefficientBase ?
Base : Index)
900 NewMI = buildOffsetAdd(
MI,
MBB, OptIncDec);
911 assert(DestReg != BaseReg &&
"DestReg == BaseReg should be handled already!");
912 assert(IsInefficientBase &&
"efficient base should be handled already!");
915 if (LEAOpcode == X86::LEA64_32r)
962 auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
963 auto *MBFI = (PSI && PSI->hasProfileSummary())
964 ? &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()
966 FixupLEAsImpl PassImpl(PSI, MBFI);
967 return PassImpl.runOnMachineFunction(MF);
974 .getCachedResult<ProfileSummaryAnalysis>(
981 FixupLEAsImpl PassImpl(PSI, MBFI);
982 bool Changed = PassImpl.runOnMachineFunction(MF);
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
const AArch64InstrInfo & TII
MachineBasicBlock MachineBasicBlock::iterator MBBI
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
===- LazyMachineBlockFrequencyInfo.h - Lazy Block Frequency -*- C++ -*–===//
Register const TargetRegisterInfo * TRI
Promote Memory to Register
#define INITIALIZE_PASS(passName, arg, name, cfg, analysis)
This file defines the 'Statistic' class, which is designed to be an easy way to expose various metric...
#define STATISTIC(VARNAME, DESC)
static unsigned getINCDECFromLEA(unsigned LEAOpcode, bool IsINC)
static bool isLEA(unsigned Opcode)
static unsigned getSUBriFromLEA(unsigned LEAOpcode)
static bool isInefficientLEAReg(Register Reg)
static bool hasInefficientLEABaseReg(const MachineOperand &Base, const MachineOperand &Index)
Returns true if this LEA uses base and index registers, and the base register is known to be ineffici...
static unsigned getADDriFromLEA(unsigned LEAOpcode, const MachineOperand &Offset)
static bool getPreviousInstr(MachineBasicBlock::iterator &I, MachineBasicBlock &MBB)
getPreviousInstr - Given a reference to an instruction in a basic block, return a reference to the pr...
static unsigned getADDrrFromLEA(unsigned LEAOpcode)
static unsigned getSUBrrFromLEA(unsigned LEAOpcode)
static bool mayHaveOffset(const MachineOperand &Offset)
void copyPhysReg(MachineBasicBlock &MBB, MachineBasicBlock::iterator I, const DebugLoc &DL, Register DestReg, Register SrcReg, bool KillSrc, bool RenamableDest=false, bool RenamableSrc=false) const override
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
AnalysisUsage & addRequired()
Represents analyses that only rely on functions' control flow.
FunctionPass class - This class is used to implement most global optimizations.
bool hasOptSize() const
Optimize this function for size (-Os) or minimum size (-Oz).
Module * getParent()
Get the module that this global value is contained inside of...
LLVM_ABI LivenessQueryResult computeRegisterLiveness(const TargetRegisterInfo *TRI, MCRegister Reg, const_iterator Before, unsigned Neighborhood=10) const
Return whether (physical) register Reg has been defined and not killed as of just before Before.
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.
MachineInstrBundleIterator< MachineInstr > iterator
@ LQR_Dead
Register is known to be fully dead.
MachineBlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate machine basic b...
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.
void substituteDebugValuesForInst(const MachineInstr &Old, MachineInstr &New, unsigned MaxOperand=UINT_MAX)
Create substitutions for any tracked values in Old, to point at New.
const TargetSubtargetInfo & getSubtarget() const
getSubtarget - Return the subtarget for which this machine code is being compiled.
Function & getFunction()
Return the LLVM function that this machine code represents.
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 & add(const MachineOperand &MO) const
Representation of each machine instruction.
LLVM_ABI void dump() const
const MachineOperand & getOperand(unsigned i) const
LLVM_ABI bool addRegisterDead(Register Reg, const TargetRegisterInfo *RegInfo, bool AddIfNotFound=false)
We have determined MI defined a register without a use.
MachineOperand class - Representation of each machine instruction operand.
bool isReg() const
isReg - Tests if this is a MO_Register operand.
bool isImm() const
isImm - Tests if this is a MO_Immediate operand.
void setIsKill(bool Val=true)
Register getReg() const
getReg - Returns the register number.
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 & preserveSet()
Mark an analysis set as preserved.
Analysis providing profile information.
Wrapper class representing virtual and physical registers.
constexpr bool isValid() const
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)
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
int getMemoryOperandIdx(const MCInstrDesc &Desc)
BaseReg
Stack frame base register. Bit 0 of FREInfo.Info.
This is an optimization pass for GlobalISel generic memory operations.
OuterAnalysisManagerProxy< ModuleAnalysisManager, MachineFunction > ModuleAnalysisManagerMachineFunctionProxy
Provide the ModuleAnalysisManager to Function proxy.
MachineInstrBuilder BuildMI(MachineFunction &MF, const MIMetadata &MIMD, const MCInstrDesc &MCID)
Builder interface. Specify how to create the initial instruction itself.
constexpr RegState getKillRegState(bool B)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
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.
AnalysisManager< MachineFunction > MachineFunctionAnalysisManager
LLVM_ABI PreservedAnalyses getMachineFunctionPassPreservedAnalyses()
Returns the minimum set of Analyses that all machine function passes must preserve.
LLVM_ABI raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
LLVM_ABI void report_fatal_error(Error Err, bool gen_crash_diag=true)
FunctionPass * createX86FixupLEAsLegacyPass()
auto instructionsWithoutDebug(IterT It, IterT End, bool SkipPseudoOp=true)
Construct a range iterator which begins at It and moves forwards until End is reached,...
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.