1 //===-- X86FixupLEAs.cpp - use or replace LEA instructions -----------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the pass that finds instructions that can be
10 // re-written as LEA instructions in order to reduce pipeline delays.
11 // When optimizing for size it replaces suitable LEAs with INC or DEC.
13 //===----------------------------------------------------------------------===//
16 #include "X86InstrInfo.h"
17 #include "X86Subtarget.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/CodeGen/MachineFunctionPass.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/TargetSchedule.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/raw_ostream.h"
27 #define FIXUPLEA_DESC "X86 LEA Fixup"
28 #define FIXUPLEA_NAME "x86-fixup-LEAs"
30 #define DEBUG_TYPE FIXUPLEA_NAME
32 STATISTIC(NumLEAs
, "Number of LEA instructions created");
35 class FixupLEAPass
: public MachineFunctionPass
{
36 enum RegUsageState
{ RU_NotUsed
, RU_Write
, RU_Read
};
38 /// Loop over all of the instructions in the basic block
39 /// replacing applicable instructions with LEA instructions,
40 /// where appropriate.
41 bool processBasicBlock(MachineFunction
&MF
, MachineFunction::iterator MFI
,
42 bool IsSlowLEA
, bool IsSlow3OpsLEA
);
44 /// Given a machine register, look for the instruction
45 /// which writes it in the current basic block. If found,
46 /// try to replace it with an equivalent LEA instruction.
47 /// If replacement succeeds, then also process the newly created
49 void seekLEAFixup(MachineOperand
&p
, MachineBasicBlock::iterator
&I
,
50 MachineFunction::iterator MFI
);
52 /// Given a memory access or LEA instruction
53 /// whose address mode uses a base and/or index register, look for
54 /// an opportunity to replace the instruction which sets the base or index
55 /// register with an equivalent LEA instruction.
56 void processInstruction(MachineBasicBlock::iterator
&I
,
57 MachineFunction::iterator MFI
);
59 /// Given a LEA instruction which is unprofitable
60 /// on SlowLEA targets try to replace it with an equivalent ADD instruction.
61 void processInstructionForSlowLEA(MachineBasicBlock::iterator
&I
,
62 MachineFunction::iterator MFI
);
64 /// Given a LEA instruction which is unprofitable
65 /// on SNB+ try to replace it with other instructions.
66 /// According to Intel's Optimization Reference Manual:
67 /// " For LEA instructions with three source operands and some specific
68 /// situations, instruction latency has increased to 3 cycles, and must
69 /// dispatch via port 1:
70 /// - LEA that has all three source operands: base, index, and offset
71 /// - LEA that uses base and index registers where the base is EBP, RBP,
73 /// - LEA that uses RIP relative addressing mode
74 /// - LEA that uses 16-bit addressing mode "
75 /// This function currently handles the first 2 cases only.
76 MachineInstr
*processInstrForSlow3OpLEA(MachineInstr
&MI
,
77 MachineFunction::iterator MFI
);
79 /// Look for LEAs that add 1 to reg or subtract 1 from reg
80 /// and convert them to INC or DEC respectively.
81 bool fixupIncDec(MachineBasicBlock::iterator
&I
,
82 MachineFunction::iterator MFI
) const;
84 /// Determine if an instruction references a machine register
85 /// and, if so, whether it reads or writes the register.
86 RegUsageState
usesRegister(MachineOperand
&p
, MachineBasicBlock::iterator I
);
88 /// Step backwards through a basic block, looking
89 /// for an instruction which writes a register within
90 /// a maximum of INSTR_DISTANCE_THRESHOLD instruction latency cycles.
91 MachineBasicBlock::iterator
searchBackwards(MachineOperand
&p
,
92 MachineBasicBlock::iterator
&I
,
93 MachineFunction::iterator MFI
);
95 /// if an instruction can be converted to an
96 /// equivalent LEA, insert the new instruction into the basic block
97 /// and return a pointer to it. Otherwise, return zero.
98 MachineInstr
*postRAConvertToLEA(MachineFunction::iterator
&MFI
,
99 MachineBasicBlock::iterator
&MBBI
) const;
104 StringRef
getPassName() const override
{ return FIXUPLEA_DESC
; }
106 FixupLEAPass() : MachineFunctionPass(ID
) {
107 initializeFixupLEAPassPass(*PassRegistry::getPassRegistry());
110 /// Loop over all of the basic blocks,
111 /// replacing instructions by equivalent LEA instructions
112 /// if needed and when possible.
113 bool runOnMachineFunction(MachineFunction
&MF
) override
;
115 // This pass runs after regalloc and doesn't support VReg operands.
116 MachineFunctionProperties
getRequiredProperties() const override
{
117 return MachineFunctionProperties().set(
118 MachineFunctionProperties::Property::NoVRegs
);
122 TargetSchedModel TSM
;
124 const X86InstrInfo
*TII
; // Machine instruction info.
130 char FixupLEAPass::ID
= 0;
132 INITIALIZE_PASS(FixupLEAPass
, FIXUPLEA_NAME
, FIXUPLEA_DESC
, false, false)
135 FixupLEAPass::postRAConvertToLEA(MachineFunction::iterator
&MFI
,
136 MachineBasicBlock::iterator
&MBBI
) const {
137 MachineInstr
&MI
= *MBBI
;
138 switch (MI
.getOpcode()) {
141 const MachineOperand
&Src
= MI
.getOperand(1);
142 const MachineOperand
&Dest
= MI
.getOperand(0);
143 MachineInstr
*NewMI
=
144 BuildMI(*MF
, MI
.getDebugLoc(),
145 TII
->get(MI
.getOpcode() == X86::MOV32rr
? X86::LEA32r
153 MFI
->insert(MBBI
, NewMI
); // Insert the new inst
158 case X86::ADD64ri32_DB
:
159 case X86::ADD64ri8_DB
:
162 case X86::ADD32ri_DB
:
163 case X86::ADD32ri8_DB
:
166 case X86::ADD16ri_DB
:
167 case X86::ADD16ri8_DB
:
168 if (!MI
.getOperand(2).isImm()) {
169 // convertToThreeAddress will call getImm()
170 // which requires isImm() to be true
175 case X86::ADD16rr_DB
:
176 if (MI
.getOperand(1).getReg() != MI
.getOperand(2).getReg()) {
177 // if src1 != src2, then convertToThreeAddress will
178 // need to create a Virtual register, which we cannot do
179 // after register allocation.
183 return TII
->convertToThreeAddress(MFI
, MI
, nullptr);
186 FunctionPass
*llvm::createX86FixupLEAs() { return new FixupLEAPass(); }
188 bool FixupLEAPass::runOnMachineFunction(MachineFunction
&Func
) {
189 if (skipFunction(Func
.getFunction()))
193 const X86Subtarget
&ST
= Func
.getSubtarget
<X86Subtarget
>();
194 bool IsSlowLEA
= ST
.slowLEA();
195 bool IsSlow3OpsLEA
= ST
.slow3OpsLEA();
197 OptIncDec
= !ST
.slowIncDec() || Func
.getFunction().optForMinSize();
198 OptLEA
= ST
.LEAusesAG() || IsSlowLEA
|| IsSlow3OpsLEA
;
200 if (!OptLEA
&& !OptIncDec
)
203 TSM
.init(&Func
.getSubtarget());
204 TII
= ST
.getInstrInfo();
206 LLVM_DEBUG(dbgs() << "Start X86FixupLEAs\n";);
207 // Process all basic blocks.
208 for (MachineFunction::iterator I
= Func
.begin(), E
= Func
.end(); I
!= E
; ++I
)
209 processBasicBlock(Func
, I
, IsSlowLEA
, IsSlow3OpsLEA
);
210 LLVM_DEBUG(dbgs() << "End X86FixupLEAs\n";);
215 FixupLEAPass::RegUsageState
216 FixupLEAPass::usesRegister(MachineOperand
&p
, MachineBasicBlock::iterator I
) {
217 RegUsageState RegUsage
= RU_NotUsed
;
218 MachineInstr
&MI
= *I
;
220 for (unsigned int i
= 0; i
< MI
.getNumOperands(); ++i
) {
221 MachineOperand
&opnd
= MI
.getOperand(i
);
222 if (opnd
.isReg() && opnd
.getReg() == p
.getReg()) {
231 /// getPreviousInstr - Given a reference to an instruction in a basic
232 /// block, return a reference to the previous instruction in the block,
233 /// wrapping around to the last instruction of the block if the block
234 /// branches to itself.
235 static inline bool getPreviousInstr(MachineBasicBlock::iterator
&I
,
236 MachineFunction::iterator MFI
) {
237 if (I
== MFI
->begin()) {
238 if (MFI
->isPredecessor(&*MFI
)) {
248 MachineBasicBlock::iterator
249 FixupLEAPass::searchBackwards(MachineOperand
&p
, MachineBasicBlock::iterator
&I
,
250 MachineFunction::iterator MFI
) {
251 int InstrDistance
= 1;
252 MachineBasicBlock::iterator CurInst
;
253 static const int INSTR_DISTANCE_THRESHOLD
= 5;
257 Found
= getPreviousInstr(CurInst
, MFI
);
258 while (Found
&& I
!= CurInst
) {
259 if (CurInst
->isCall() || CurInst
->isInlineAsm())
261 if (InstrDistance
> INSTR_DISTANCE_THRESHOLD
)
262 break; // too far back to make a difference
263 if (usesRegister(p
, CurInst
) == RU_Write
) {
266 InstrDistance
+= TSM
.computeInstrLatency(&*CurInst
);
267 Found
= getPreviousInstr(CurInst
, MFI
);
269 return MachineBasicBlock::iterator();
272 static inline bool isLEA(const int Opcode
) {
273 return Opcode
== X86::LEA16r
|| Opcode
== X86::LEA32r
||
274 Opcode
== X86::LEA64r
|| Opcode
== X86::LEA64_32r
;
277 static inline bool isInefficientLEAReg(unsigned int Reg
) {
278 return Reg
== X86::EBP
|| Reg
== X86::RBP
||
279 Reg
== X86::R13D
|| Reg
== X86::R13
;
282 static inline bool isRegOperand(const MachineOperand
&Op
) {
283 return Op
.isReg() && Op
.getReg() != X86::NoRegister
;
286 /// Returns true if this LEA uses base an index registers, and the base register
287 /// is known to be inefficient for the subtarget.
288 // TODO: use a variant scheduling class to model the latency profile
289 // of LEA instructions, and implement this logic as a scheduling predicate.
290 static inline bool hasInefficientLEABaseReg(const MachineOperand
&Base
,
291 const MachineOperand
&Index
) {
292 return Base
.isReg() && isInefficientLEAReg(Base
.getReg()) &&
296 static inline bool hasLEAOffset(const MachineOperand
&Offset
) {
297 return (Offset
.isImm() && Offset
.getImm() != 0) || Offset
.isGlobal();
300 static inline int getADDrrFromLEA(int LEAOpcode
) {
303 llvm_unreachable("Unexpected LEA instruction");
314 static inline int getADDriFromLEA(int LEAOpcode
, const MachineOperand
&Offset
) {
315 bool IsInt8
= Offset
.isImm() && isInt
<8>(Offset
.getImm());
318 llvm_unreachable("Unexpected LEA instruction");
320 return IsInt8
? X86::ADD16ri8
: X86::ADD16ri
;
323 return IsInt8
? X86::ADD32ri8
: X86::ADD32ri
;
325 return IsInt8
? X86::ADD64ri8
: X86::ADD64ri32
;
329 /// isLEASimpleIncOrDec - Does this LEA have one these forms:
330 /// lea %reg, 1(%reg)
331 /// lea %reg, -1(%reg)
332 static inline bool isLEASimpleIncOrDec(MachineInstr
&LEA
) {
333 unsigned SrcReg
= LEA
.getOperand(1 + X86::AddrBaseReg
).getReg();
334 unsigned DstReg
= LEA
.getOperand(0).getReg();
335 const MachineOperand
&AddrDisp
= LEA
.getOperand(1 + X86::AddrDisp
);
336 return SrcReg
== DstReg
&&
337 LEA
.getOperand(1 + X86::AddrIndexReg
).getReg() == 0 &&
338 LEA
.getOperand(1 + X86::AddrSegmentReg
).getReg() == 0 &&
340 (AddrDisp
.getImm() == 1 || AddrDisp
.getImm() == -1);
343 bool FixupLEAPass::fixupIncDec(MachineBasicBlock::iterator
&I
,
344 MachineFunction::iterator MFI
) const {
345 MachineInstr
&MI
= *I
;
346 int Opcode
= MI
.getOpcode();
350 if (isLEASimpleIncOrDec(MI
) && TII
->isSafeToClobberEFLAGS(*MFI
, I
)) {
352 bool isINC
= MI
.getOperand(1 + X86::AddrDisp
).getImm() == 1;
355 NewOpcode
= isINC
? X86::INC16r
: X86::DEC16r
;
359 NewOpcode
= isINC
? X86::INC32r
: X86::DEC32r
;
362 NewOpcode
= isINC
? X86::INC64r
: X86::DEC64r
;
366 MachineInstr
*NewMI
=
367 BuildMI(*MFI
, I
, MI
.getDebugLoc(), TII
->get(NewOpcode
))
368 .add(MI
.getOperand(0))
369 .add(MI
.getOperand(1 + X86::AddrBaseReg
));
371 I
= static_cast<MachineBasicBlock::iterator
>(NewMI
);
377 void FixupLEAPass::processInstruction(MachineBasicBlock::iterator
&I
,
378 MachineFunction::iterator MFI
) {
379 // Process a load, store, or LEA instruction.
380 MachineInstr
&MI
= *I
;
381 const MCInstrDesc
&Desc
= MI
.getDesc();
382 int AddrOffset
= X86II::getMemoryOperandNo(Desc
.TSFlags
);
383 if (AddrOffset
>= 0) {
384 AddrOffset
+= X86II::getOperandBias(Desc
);
385 MachineOperand
&p
= MI
.getOperand(AddrOffset
+ X86::AddrBaseReg
);
386 if (p
.isReg() && p
.getReg() != X86::ESP
) {
387 seekLEAFixup(p
, I
, MFI
);
389 MachineOperand
&q
= MI
.getOperand(AddrOffset
+ X86::AddrIndexReg
);
390 if (q
.isReg() && q
.getReg() != X86::ESP
) {
391 seekLEAFixup(q
, I
, MFI
);
396 void FixupLEAPass::seekLEAFixup(MachineOperand
&p
,
397 MachineBasicBlock::iterator
&I
,
398 MachineFunction::iterator MFI
) {
399 MachineBasicBlock::iterator MBI
= searchBackwards(p
, I
, MFI
);
400 if (MBI
!= MachineBasicBlock::iterator()) {
401 MachineInstr
*NewMI
= postRAConvertToLEA(MFI
, MBI
);
404 LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MBI
->dump(););
405 // now to replace with an equivalent LEA...
406 LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: "; NewMI
->dump(););
408 MachineBasicBlock::iterator J
=
409 static_cast<MachineBasicBlock::iterator
>(NewMI
);
410 processInstruction(J
, MFI
);
415 void FixupLEAPass::processInstructionForSlowLEA(MachineBasicBlock::iterator
&I
,
416 MachineFunction::iterator MFI
) {
417 MachineInstr
&MI
= *I
;
418 const int Opcode
= MI
.getOpcode();
422 const MachineOperand
&Dst
= MI
.getOperand(0);
423 const MachineOperand
&Base
= MI
.getOperand(1 + X86::AddrBaseReg
);
424 const MachineOperand
&Scale
= MI
.getOperand(1 + X86::AddrScaleAmt
);
425 const MachineOperand
&Index
= MI
.getOperand(1 + X86::AddrIndexReg
);
426 const MachineOperand
&Offset
= MI
.getOperand(1 + X86::AddrDisp
);
427 const MachineOperand
&Segment
= MI
.getOperand(1 + X86::AddrSegmentReg
);
429 if (Segment
.getReg() != 0 || !Offset
.isImm() ||
430 !TII
->isSafeToClobberEFLAGS(*MFI
, I
))
432 const unsigned DstR
= Dst
.getReg();
433 const unsigned SrcR1
= Base
.getReg();
434 const unsigned SrcR2
= Index
.getReg();
435 if ((SrcR1
== 0 || SrcR1
!= DstR
) && (SrcR2
== 0 || SrcR2
!= DstR
))
437 if (Scale
.getImm() > 1)
439 LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; I
->dump(););
440 LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: ";);
441 MachineInstr
*NewMI
= nullptr;
442 // Make ADD instruction for two registers writing to LEA's destination
443 if (SrcR1
!= 0 && SrcR2
!= 0) {
444 const MCInstrDesc
&ADDrr
= TII
->get(getADDrrFromLEA(Opcode
));
445 const MachineOperand
&Src
= SrcR1
== DstR
? Index
: Base
;
447 BuildMI(*MFI
, I
, MI
.getDebugLoc(), ADDrr
, DstR
).addReg(DstR
).add(Src
);
448 LLVM_DEBUG(NewMI
->dump(););
450 // Make ADD instruction for immediate
451 if (Offset
.getImm() != 0) {
452 const MCInstrDesc
&ADDri
=
453 TII
->get(getADDriFromLEA(Opcode
, Offset
));
454 const MachineOperand
&SrcR
= SrcR1
== DstR
? Base
: Index
;
455 NewMI
= BuildMI(*MFI
, I
, MI
.getDebugLoc(), ADDri
, DstR
)
457 .addImm(Offset
.getImm());
458 LLVM_DEBUG(NewMI
->dump(););
467 FixupLEAPass::processInstrForSlow3OpLEA(MachineInstr
&MI
,
468 MachineFunction::iterator MFI
) {
470 const int LEAOpcode
= MI
.getOpcode();
471 if (!isLEA(LEAOpcode
))
474 const MachineOperand
&Dst
= MI
.getOperand(0);
475 const MachineOperand
&Base
= MI
.getOperand(1 + X86::AddrBaseReg
);
476 const MachineOperand
&Scale
= MI
.getOperand(1 + X86::AddrScaleAmt
);
477 const MachineOperand
&Index
= MI
.getOperand(1 + X86::AddrIndexReg
);
478 const MachineOperand
&Offset
= MI
.getOperand(1 + X86::AddrDisp
);
479 const MachineOperand
&Segment
= MI
.getOperand(1 + X86::AddrSegmentReg
);
481 if (!(TII
->isThreeOperandsLEA(MI
) ||
482 hasInefficientLEABaseReg(Base
, Index
)) ||
483 !TII
->isSafeToClobberEFLAGS(*MFI
, MI
) ||
484 Segment
.getReg() != X86::NoRegister
)
487 unsigned int DstR
= Dst
.getReg();
488 unsigned int BaseR
= Base
.getReg();
489 unsigned int IndexR
= Index
.getReg();
491 (LEAOpcode
== X86::LEA64_32r
) ? getX86SubSuperRegister(DstR
, 64) : DstR
;
492 bool IsScale1
= Scale
.getImm() == 1;
493 bool IsInefficientBase
= isInefficientLEAReg(BaseR
);
494 bool IsInefficientIndex
= isInefficientLEAReg(IndexR
);
496 // Skip these cases since it takes more than 2 instructions
497 // to replace the LEA instruction.
498 if (IsInefficientBase
&& SSDstR
== BaseR
&& !IsScale1
)
500 if (LEAOpcode
== X86::LEA64_32r
&& IsInefficientBase
&&
501 (IsInefficientIndex
|| !IsScale1
))
504 const DebugLoc DL
= MI
.getDebugLoc();
505 const MCInstrDesc
&ADDrr
= TII
->get(getADDrrFromLEA(LEAOpcode
));
506 const MCInstrDesc
&ADDri
= TII
->get(getADDriFromLEA(LEAOpcode
, Offset
));
508 LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MI
.dump(););
509 LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: ";);
511 // First try to replace LEA with one or two (for the 3-op LEA case)
513 // 1.lea (%base,%index,1), %base => add %index,%base
514 // 2.lea (%base,%index,1), %index => add %base,%index
515 if (IsScale1
&& (DstR
== BaseR
|| DstR
== IndexR
)) {
516 const MachineOperand
&Src
= DstR
== BaseR
? Index
: Base
;
517 MachineInstr
*NewMI
=
518 BuildMI(*MFI
, MI
, DL
, ADDrr
, DstR
).addReg(DstR
).add(Src
);
519 LLVM_DEBUG(NewMI
->dump(););
520 // Create ADD instruction for the Offset in case of 3-Ops LEA.
521 if (hasLEAOffset(Offset
)) {
522 NewMI
= BuildMI(*MFI
, MI
, DL
, ADDri
, DstR
).addReg(DstR
).add(Offset
);
523 LLVM_DEBUG(NewMI
->dump(););
527 // If the base is inefficient try switching the index and base operands,
528 // otherwise just break the 3-Ops LEA inst into 2-Ops LEA + ADD instruction:
529 // lea offset(%base,%index,scale),%dst =>
530 // lea (%base,%index,scale); add offset,%dst
531 if (!IsInefficientBase
|| (!IsInefficientIndex
&& IsScale1
)) {
532 MachineInstr
*NewMI
= BuildMI(*MFI
, MI
, DL
, TII
->get(LEAOpcode
))
534 .add(IsInefficientBase
? Index
: Base
)
536 .add(IsInefficientBase
? Base
: Index
)
539 LLVM_DEBUG(NewMI
->dump(););
540 // Create ADD instruction for the Offset in case of 3-Ops LEA.
541 if (hasLEAOffset(Offset
)) {
542 NewMI
= BuildMI(*MFI
, MI
, DL
, ADDri
, DstR
).addReg(DstR
).add(Offset
);
543 LLVM_DEBUG(NewMI
->dump(););
547 // Handle the rest of the cases with inefficient base register:
548 assert(SSDstR
!= BaseR
&& "SSDstR == BaseR should be handled already!");
549 assert(IsInefficientBase
&& "efficient base should be handled already!");
551 // lea (%base,%index,1), %dst => mov %base,%dst; add %index,%dst
552 if (IsScale1
&& !hasLEAOffset(Offset
)) {
553 bool BIK
= Base
.isKill() && BaseR
!= IndexR
;
554 TII
->copyPhysReg(*MFI
, MI
, DL
, DstR
, BaseR
, BIK
);
555 LLVM_DEBUG(MI
.getPrevNode()->dump(););
557 MachineInstr
*NewMI
=
558 BuildMI(*MFI
, MI
, DL
, ADDrr
, DstR
).addReg(DstR
).add(Index
);
559 LLVM_DEBUG(NewMI
->dump(););
562 // lea offset(%base,%index,scale), %dst =>
563 // lea offset( ,%index,scale), %dst; add %base,%dst
564 MachineInstr
*NewMI
= BuildMI(*MFI
, MI
, DL
, TII
->get(LEAOpcode
))
571 LLVM_DEBUG(NewMI
->dump(););
573 NewMI
= BuildMI(*MFI
, MI
, DL
, ADDrr
, DstR
).addReg(DstR
).add(Base
);
574 LLVM_DEBUG(NewMI
->dump(););
578 bool FixupLEAPass::processBasicBlock(MachineFunction
&MF
,
579 MachineFunction::iterator MFI
,
580 bool IsSlowLEA
, bool IsSlow3OpsLEA
) {
581 for (MachineBasicBlock::iterator I
= MFI
->begin(); I
!= MFI
->end(); ++I
) {
583 if (fixupIncDec(I
, MFI
))
588 processInstructionForSlowLEA(I
, MFI
);
593 if (auto *NewMI
= processInstrForSlow3OpLEA(*I
, MFI
)) {
600 processInstruction(I
, MFI
);