X86FixupLEAs.cpp revision 341825
1251607Sdim//===-- X86FixupLEAs.cpp - use or replace LEA instructions -----------===//
2251607Sdim//
3251607Sdim//                     The LLVM Compiler Infrastructure
4251607Sdim//
5251607Sdim// This file is distributed under the University of Illinois Open Source
6251607Sdim// License. See LICENSE.TXT for details.
7251607Sdim//
8251607Sdim//===----------------------------------------------------------------------===//
9251607Sdim//
10276479Sdim// This file defines the pass that finds instructions that can be
11276479Sdim// re-written as LEA instructions in order to reduce pipeline delays.
12296417Sdim// When optimizing for size it replaces suitable LEAs with INC or DEC.
13251607Sdim//
14251607Sdim//===----------------------------------------------------------------------===//
15251607Sdim
16251607Sdim#include "X86.h"
17251607Sdim#include "X86InstrInfo.h"
18251607Sdim#include "X86Subtarget.h"
19251607Sdim#include "llvm/ADT/Statistic.h"
20251607Sdim#include "llvm/CodeGen/MachineFunctionPass.h"
21251607Sdim#include "llvm/CodeGen/MachineInstrBuilder.h"
22251607Sdim#include "llvm/CodeGen/Passes.h"
23341825Sdim#include "llvm/CodeGen/TargetSchedule.h"
24251607Sdim#include "llvm/Support/Debug.h"
25251607Sdim#include "llvm/Support/raw_ostream.h"
26251607Sdimusing namespace llvm;
27251607Sdim
28321369Sdimnamespace llvm {
29321369Sdimvoid initializeFixupLEAPassPass(PassRegistry &);
30321369Sdim}
31276479Sdim
32321369Sdim#define FIXUPLEA_DESC "X86 LEA Fixup"
33321369Sdim#define FIXUPLEA_NAME "x86-fixup-LEAs"
34321369Sdim
35321369Sdim#define DEBUG_TYPE FIXUPLEA_NAME
36321369Sdim
37251607SdimSTATISTIC(NumLEAs, "Number of LEA instructions created");
38251607Sdim
39251607Sdimnamespace {
40276479Sdimclass FixupLEAPass : public MachineFunctionPass {
41276479Sdim  enum RegUsageState { RU_NotUsed, RU_Write, RU_Read };
42321369Sdim
43341825Sdim  /// Loop over all of the instructions in the basic block
44276479Sdim  /// replacing applicable instructions with LEA instructions,
45276479Sdim  /// where appropriate.
46276479Sdim  bool processBasicBlock(MachineFunction &MF, MachineFunction::iterator MFI);
47251607Sdim
48251607Sdim
49341825Sdim  /// Given a machine register, look for the instruction
50276479Sdim  /// which writes it in the current basic block. If found,
51276479Sdim  /// try to replace it with an equivalent LEA instruction.
52288943Sdim  /// If replacement succeeds, then also process the newly created
53276479Sdim  /// instruction.
54276479Sdim  void seekLEAFixup(MachineOperand &p, MachineBasicBlock::iterator &I,
55276479Sdim                    MachineFunction::iterator MFI);
56251607Sdim
57341825Sdim  /// Given a memory access or LEA instruction
58276479Sdim  /// whose address mode uses a base and/or index register, look for
59276479Sdim  /// an opportunity to replace the instruction which sets the base or index
60276479Sdim  /// register with an equivalent LEA instruction.
61276479Sdim  void processInstruction(MachineBasicBlock::iterator &I,
62276479Sdim                          MachineFunction::iterator MFI);
63251607Sdim
64341825Sdim  /// Given a LEA instruction which is unprofitable
65276479Sdim  /// on Silvermont try to replace it with an equivalent ADD instruction
66276479Sdim  void processInstructionForSLM(MachineBasicBlock::iterator &I,
67276479Sdim                                MachineFunction::iterator MFI);
68251607Sdim
69321369Sdim
70341825Sdim  /// Given a LEA instruction which is unprofitable
71321369Sdim  /// on SNB+ try to replace it with other instructions.
72321369Sdim  /// According to Intel's Optimization Reference Manual:
73321369Sdim  /// " For LEA instructions with three source operands and some specific
74321369Sdim  ///   situations, instruction latency has increased to 3 cycles, and must
75321369Sdim  ///   dispatch via port 1:
76321369Sdim  /// - LEA that has all three source operands: base, index, and offset
77321369Sdim  /// - LEA that uses base and index registers where the base is EBP, RBP,
78321369Sdim  ///   or R13
79321369Sdim  /// - LEA that uses RIP relative addressing mode
80321369Sdim  /// - LEA that uses 16-bit addressing mode "
81321369Sdim  /// This function currently handles the first 2 cases only.
82321369Sdim  MachineInstr *processInstrForSlow3OpLEA(MachineInstr &MI,
83321369Sdim                                          MachineFunction::iterator MFI);
84321369Sdim
85341825Sdim  /// Look for LEAs that add 1 to reg or subtract 1 from reg
86296417Sdim  /// and convert them to INC or DEC respectively.
87296417Sdim  bool fixupIncDec(MachineBasicBlock::iterator &I,
88296417Sdim                   MachineFunction::iterator MFI) const;
89296417Sdim
90341825Sdim  /// Determine if an instruction references a machine register
91276479Sdim  /// and, if so, whether it reads or writes the register.
92276479Sdim  RegUsageState usesRegister(MachineOperand &p, MachineBasicBlock::iterator I);
93251607Sdim
94341825Sdim  /// Step backwards through a basic block, looking
95276479Sdim  /// for an instruction which writes a register within
96276479Sdim  /// a maximum of INSTR_DISTANCE_THRESHOLD instruction latency cycles.
97276479Sdim  MachineBasicBlock::iterator searchBackwards(MachineOperand &p,
98276479Sdim                                              MachineBasicBlock::iterator &I,
99276479Sdim                                              MachineFunction::iterator MFI);
100251607Sdim
101341825Sdim  /// if an instruction can be converted to an
102276479Sdim  /// equivalent LEA, insert the new instruction into the basic block
103276479Sdim  /// and return a pointer to it. Otherwise, return zero.
104276479Sdim  MachineInstr *postRAConvertToLEA(MachineFunction::iterator &MFI,
105276479Sdim                                   MachineBasicBlock::iterator &MBBI) const;
106251607Sdim
107276479Sdimpublic:
108321369Sdim  static char ID;
109251607Sdim
110321369Sdim  StringRef getPassName() const override { return FIXUPLEA_DESC; }
111321369Sdim
112321369Sdim  FixupLEAPass() : MachineFunctionPass(ID) {
113321369Sdim    initializeFixupLEAPassPass(*PassRegistry::getPassRegistry());
114321369Sdim  }
115321369Sdim
116341825Sdim  /// Loop over all of the basic blocks,
117276479Sdim  /// replacing instructions by equivalent LEA instructions
118276479Sdim  /// if needed and when possible.
119276479Sdim  bool runOnMachineFunction(MachineFunction &MF) override;
120251607Sdim
121309124Sdim  // This pass runs after regalloc and doesn't support VReg operands.
122309124Sdim  MachineFunctionProperties getRequiredProperties() const override {
123309124Sdim    return MachineFunctionProperties().set(
124314564Sdim        MachineFunctionProperties::Property::NoVRegs);
125309124Sdim  }
126309124Sdim
127276479Sdimprivate:
128341825Sdim  TargetSchedModel TSM;
129276479Sdim  MachineFunction *MF;
130276479Sdim  const X86InstrInfo *TII; // Machine instruction info.
131296417Sdim  bool OptIncDec;
132296417Sdim  bool OptLEA;
133276479Sdim};
134251607Sdim}
135251607Sdim
136321369Sdimchar FixupLEAPass::ID = 0;
137321369Sdim
138321369SdimINITIALIZE_PASS(FixupLEAPass, FIXUPLEA_NAME, FIXUPLEA_DESC, false, false)
139321369Sdim
140251607SdimMachineInstr *
141251607SdimFixupLEAPass::postRAConvertToLEA(MachineFunction::iterator &MFI,
142251607Sdim                                 MachineBasicBlock::iterator &MBBI) const {
143309124Sdim  MachineInstr &MI = *MBBI;
144309124Sdim  switch (MI.getOpcode()) {
145276479Sdim  case X86::MOV32rr:
146251607Sdim  case X86::MOV64rr: {
147309124Sdim    const MachineOperand &Src = MI.getOperand(1);
148309124Sdim    const MachineOperand &Dest = MI.getOperand(0);
149309124Sdim    MachineInstr *NewMI =
150309124Sdim        BuildMI(*MF, MI.getDebugLoc(),
151309124Sdim                TII->get(MI.getOpcode() == X86::MOV32rr ? X86::LEA32r
152309124Sdim                                                        : X86::LEA64r))
153321369Sdim            .add(Dest)
154321369Sdim            .add(Src)
155309124Sdim            .addImm(1)
156309124Sdim            .addReg(0)
157309124Sdim            .addImm(0)
158309124Sdim            .addReg(0);
159276479Sdim    MFI->insert(MBBI, NewMI); // Insert the new inst
160251607Sdim    return NewMI;
161251607Sdim  }
162251607Sdim  case X86::ADD64ri32:
163251607Sdim  case X86::ADD64ri8:
164251607Sdim  case X86::ADD64ri32_DB:
165251607Sdim  case X86::ADD64ri8_DB:
166251607Sdim  case X86::ADD32ri:
167251607Sdim  case X86::ADD32ri8:
168251607Sdim  case X86::ADD32ri_DB:
169251607Sdim  case X86::ADD32ri8_DB:
170251607Sdim  case X86::ADD16ri:
171251607Sdim  case X86::ADD16ri8:
172251607Sdim  case X86::ADD16ri_DB:
173251607Sdim  case X86::ADD16ri8_DB:
174309124Sdim    if (!MI.getOperand(2).isImm()) {
175251607Sdim      // convertToThreeAddress will call getImm()
176251607Sdim      // which requires isImm() to be true
177276479Sdim      return nullptr;
178251607Sdim    }
179255978Sdim    break;
180255978Sdim  case X86::ADD16rr:
181255978Sdim  case X86::ADD16rr_DB:
182309124Sdim    if (MI.getOperand(1).getReg() != MI.getOperand(2).getReg()) {
183255978Sdim      // if src1 != src2, then convertToThreeAddress will
184255978Sdim      // need to create a Virtual register, which we cannot do
185255978Sdim      // after register allocation.
186276479Sdim      return nullptr;
187255978Sdim    }
188251607Sdim  }
189309124Sdim  return TII->convertToThreeAddress(MFI, MI, nullptr);
190251607Sdim}
191251607Sdim
192276479SdimFunctionPass *llvm::createX86FixupLEAs() { return new FixupLEAPass(); }
193251607Sdim
194251607Sdimbool FixupLEAPass::runOnMachineFunction(MachineFunction &Func) {
195327952Sdim  if (skipFunction(Func.getFunction()))
196309124Sdim    return false;
197309124Sdim
198251607Sdim  MF = &Func;
199288943Sdim  const X86Subtarget &ST = Func.getSubtarget<X86Subtarget>();
200327952Sdim  OptIncDec = !ST.slowIncDec() || Func.getFunction().optForMinSize();
201321369Sdim  OptLEA = ST.LEAusesAG() || ST.slowLEA() || ST.slow3OpsLEA();
202296417Sdim
203296417Sdim  if (!OptLEA && !OptIncDec)
204276479Sdim    return false;
205251607Sdim
206341825Sdim  TSM.init(&Func.getSubtarget());
207288943Sdim  TII = ST.getInstrInfo();
208276479Sdim
209341825Sdim  LLVM_DEBUG(dbgs() << "Start X86FixupLEAs\n";);
210251607Sdim  // Process all basic blocks.
211251607Sdim  for (MachineFunction::iterator I = Func.begin(), E = Func.end(); I != E; ++I)
212251607Sdim    processBasicBlock(Func, I);
213341825Sdim  LLVM_DEBUG(dbgs() << "End X86FixupLEAs\n";);
214251607Sdim
215251607Sdim  return true;
216251607Sdim}
217251607Sdim
218276479SdimFixupLEAPass::RegUsageState
219276479SdimFixupLEAPass::usesRegister(MachineOperand &p, MachineBasicBlock::iterator I) {
220251607Sdim  RegUsageState RegUsage = RU_NotUsed;
221309124Sdim  MachineInstr &MI = *I;
222251607Sdim
223309124Sdim  for (unsigned int i = 0; i < MI.getNumOperands(); ++i) {
224309124Sdim    MachineOperand &opnd = MI.getOperand(i);
225276479Sdim    if (opnd.isReg() && opnd.getReg() == p.getReg()) {
226251607Sdim      if (opnd.isDef())
227251607Sdim        return RU_Write;
228251607Sdim      RegUsage = RU_Read;
229251607Sdim    }
230251607Sdim  }
231251607Sdim  return RegUsage;
232251607Sdim}
233251607Sdim
234251607Sdim/// getPreviousInstr - Given a reference to an instruction in a basic
235251607Sdim/// block, return a reference to the previous instruction in the block,
236251607Sdim/// wrapping around to the last instruction of the block if the block
237251607Sdim/// branches to itself.
238276479Sdimstatic inline bool getPreviousInstr(MachineBasicBlock::iterator &I,
239251607Sdim                                    MachineFunction::iterator MFI) {
240251607Sdim  if (I == MFI->begin()) {
241296417Sdim    if (MFI->isPredecessor(&*MFI)) {
242251607Sdim      I = --MFI->end();
243251607Sdim      return true;
244276479Sdim    } else
245251607Sdim      return false;
246251607Sdim  }
247251607Sdim  --I;
248251607Sdim  return true;
249251607Sdim}
250251607Sdim
251276479SdimMachineBasicBlock::iterator
252276479SdimFixupLEAPass::searchBackwards(MachineOperand &p, MachineBasicBlock::iterator &I,
253276479Sdim                              MachineFunction::iterator MFI) {
254251607Sdim  int InstrDistance = 1;
255251607Sdim  MachineBasicBlock::iterator CurInst;
256251607Sdim  static const int INSTR_DISTANCE_THRESHOLD = 5;
257251607Sdim
258251607Sdim  CurInst = I;
259251607Sdim  bool Found;
260251607Sdim  Found = getPreviousInstr(CurInst, MFI);
261276479Sdim  while (Found && I != CurInst) {
262251607Sdim    if (CurInst->isCall() || CurInst->isInlineAsm())
263251607Sdim      break;
264251607Sdim    if (InstrDistance > INSTR_DISTANCE_THRESHOLD)
265251607Sdim      break; // too far back to make a difference
266276479Sdim    if (usesRegister(p, CurInst) == RU_Write) {
267251607Sdim      return CurInst;
268251607Sdim    }
269341825Sdim    InstrDistance += TSM.computeInstrLatency(&*CurInst);
270251607Sdim    Found = getPreviousInstr(CurInst, MFI);
271251607Sdim  }
272309124Sdim  return MachineBasicBlock::iterator();
273251607Sdim}
274251607Sdim
275321369Sdimstatic inline bool isLEA(const int Opcode) {
276321369Sdim  return Opcode == X86::LEA16r || Opcode == X86::LEA32r ||
277321369Sdim         Opcode == X86::LEA64r || Opcode == X86::LEA64_32r;
278296417Sdim}
279296417Sdim
280321369Sdimstatic inline bool isInefficientLEAReg(unsigned int Reg) {
281321369Sdim  return Reg == X86::EBP || Reg == X86::RBP || Reg == X86::R13;
282321369Sdim}
283321369Sdim
284321369Sdimstatic inline bool isRegOperand(const MachineOperand &Op) {
285321369Sdim  return Op.isReg() && Op.getReg() != X86::NoRegister;
286321369Sdim}
287321369Sdim/// hasIneffecientLEARegs - LEA that uses base and index registers
288321369Sdim/// where the base is EBP, RBP, or R13
289341825Sdim// TODO: use a variant scheduling class to model the latency profile
290341825Sdim// of LEA instructions, and implement this logic as a scheduling predicate.
291321369Sdimstatic inline bool hasInefficientLEABaseReg(const MachineOperand &Base,
292321369Sdim                                            const MachineOperand &Index) {
293321369Sdim  return Base.isReg() && isInefficientLEAReg(Base.getReg()) &&
294321369Sdim         isRegOperand(Index);
295321369Sdim}
296321369Sdim
297321369Sdimstatic inline bool hasLEAOffset(const MachineOperand &Offset) {
298321369Sdim  return (Offset.isImm() && Offset.getImm() != 0) || Offset.isGlobal();
299321369Sdim}
300321369Sdim
301321369Sdimstatic inline int getADDrrFromLEA(int LEAOpcode) {
302321369Sdim  switch (LEAOpcode) {
303321369Sdim  default:
304321369Sdim    llvm_unreachable("Unexpected LEA instruction");
305321369Sdim  case X86::LEA16r:
306321369Sdim    return X86::ADD16rr;
307321369Sdim  case X86::LEA32r:
308321369Sdim    return X86::ADD32rr;
309321369Sdim  case X86::LEA64_32r:
310321369Sdim  case X86::LEA64r:
311321369Sdim    return X86::ADD64rr;
312321369Sdim  }
313321369Sdim}
314321369Sdim
315321369Sdimstatic inline int getADDriFromLEA(int LEAOpcode, const MachineOperand &Offset) {
316321369Sdim  bool IsInt8 = Offset.isImm() && isInt<8>(Offset.getImm());
317321369Sdim  switch (LEAOpcode) {
318321369Sdim  default:
319321369Sdim    llvm_unreachable("Unexpected LEA instruction");
320321369Sdim  case X86::LEA16r:
321321369Sdim    return IsInt8 ? X86::ADD16ri8 : X86::ADD16ri;
322321369Sdim  case X86::LEA32r:
323321369Sdim  case X86::LEA64_32r:
324321369Sdim    return IsInt8 ? X86::ADD32ri8 : X86::ADD32ri;
325321369Sdim  case X86::LEA64r:
326321369Sdim    return IsInt8 ? X86::ADD64ri8 : X86::ADD64ri32;
327321369Sdim  }
328321369Sdim}
329321369Sdim
330296417Sdim/// isLEASimpleIncOrDec - Does this LEA have one these forms:
331296417Sdim/// lea  %reg, 1(%reg)
332296417Sdim/// lea  %reg, -1(%reg)
333309124Sdimstatic inline bool isLEASimpleIncOrDec(MachineInstr &LEA) {
334309124Sdim  unsigned SrcReg = LEA.getOperand(1 + X86::AddrBaseReg).getReg();
335309124Sdim  unsigned DstReg = LEA.getOperand(0).getReg();
336296417Sdim  unsigned AddrDispOp = 1 + X86::AddrDisp;
337296417Sdim  return SrcReg == DstReg &&
338309124Sdim         LEA.getOperand(1 + X86::AddrIndexReg).getReg() == 0 &&
339309124Sdim         LEA.getOperand(1 + X86::AddrSegmentReg).getReg() == 0 &&
340309124Sdim         LEA.getOperand(AddrDispOp).isImm() &&
341309124Sdim         (LEA.getOperand(AddrDispOp).getImm() == 1 ||
342309124Sdim          LEA.getOperand(AddrDispOp).getImm() == -1);
343296417Sdim}
344296417Sdim
345296417Sdimbool FixupLEAPass::fixupIncDec(MachineBasicBlock::iterator &I,
346296417Sdim                               MachineFunction::iterator MFI) const {
347309124Sdim  MachineInstr &MI = *I;
348309124Sdim  int Opcode = MI.getOpcode();
349296417Sdim  if (!isLEA(Opcode))
350296417Sdim    return false;
351296417Sdim
352296417Sdim  if (isLEASimpleIncOrDec(MI) && TII->isSafeToClobberEFLAGS(*MFI, I)) {
353296417Sdim    int NewOpcode;
354309124Sdim    bool isINC = MI.getOperand(4).getImm() == 1;
355296417Sdim    switch (Opcode) {
356296417Sdim    case X86::LEA16r:
357296417Sdim      NewOpcode = isINC ? X86::INC16r : X86::DEC16r;
358296417Sdim      break;
359296417Sdim    case X86::LEA32r:
360296417Sdim    case X86::LEA64_32r:
361296417Sdim      NewOpcode = isINC ? X86::INC32r : X86::DEC32r;
362296417Sdim      break;
363296417Sdim    case X86::LEA64r:
364296417Sdim      NewOpcode = isINC ? X86::INC64r : X86::DEC64r;
365296417Sdim      break;
366296417Sdim    }
367296417Sdim
368296417Sdim    MachineInstr *NewMI =
369309124Sdim        BuildMI(*MFI, I, MI.getDebugLoc(), TII->get(NewOpcode))
370321369Sdim            .add(MI.getOperand(0))
371321369Sdim            .add(MI.getOperand(1));
372296417Sdim    MFI->erase(I);
373296417Sdim    I = static_cast<MachineBasicBlock::iterator>(NewMI);
374296417Sdim    return true;
375296417Sdim  }
376296417Sdim  return false;
377296417Sdim}
378296417Sdim
379276479Sdimvoid FixupLEAPass::processInstruction(MachineBasicBlock::iterator &I,
380251607Sdim                                      MachineFunction::iterator MFI) {
381251607Sdim  // Process a load, store, or LEA instruction.
382309124Sdim  MachineInstr &MI = *I;
383309124Sdim  const MCInstrDesc &Desc = MI.getDesc();
384309124Sdim  int AddrOffset = X86II::getMemoryOperandNo(Desc.TSFlags);
385251607Sdim  if (AddrOffset >= 0) {
386251607Sdim    AddrOffset += X86II::getOperandBias(Desc);
387309124Sdim    MachineOperand &p = MI.getOperand(AddrOffset + X86::AddrBaseReg);
388251607Sdim    if (p.isReg() && p.getReg() != X86::ESP) {
389251607Sdim      seekLEAFixup(p, I, MFI);
390251607Sdim    }
391309124Sdim    MachineOperand &q = MI.getOperand(AddrOffset + X86::AddrIndexReg);
392251607Sdim    if (q.isReg() && q.getReg() != X86::ESP) {
393251607Sdim      seekLEAFixup(q, I, MFI);
394251607Sdim    }
395251607Sdim  }
396251607Sdim}
397251607Sdim
398276479Sdimvoid FixupLEAPass::seekLEAFixup(MachineOperand &p,
399276479Sdim                                MachineBasicBlock::iterator &I,
400251607Sdim                                MachineFunction::iterator MFI) {
401251607Sdim  MachineBasicBlock::iterator MBI = searchBackwards(p, I, MFI);
402309124Sdim  if (MBI != MachineBasicBlock::iterator()) {
403276479Sdim    MachineInstr *NewMI = postRAConvertToLEA(MFI, MBI);
404251607Sdim    if (NewMI) {
405251607Sdim      ++NumLEAs;
406341825Sdim      LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MBI->dump(););
407251607Sdim      // now to replace with an equivalent LEA...
408341825Sdim      LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: "; NewMI->dump(););
409251607Sdim      MFI->erase(MBI);
410251607Sdim      MachineBasicBlock::iterator J =
411276479Sdim          static_cast<MachineBasicBlock::iterator>(NewMI);
412251607Sdim      processInstruction(J, MFI);
413251607Sdim    }
414251607Sdim  }
415251607Sdim}
416251607Sdim
417276479Sdimvoid FixupLEAPass::processInstructionForSLM(MachineBasicBlock::iterator &I,
418276479Sdim                                            MachineFunction::iterator MFI) {
419309124Sdim  MachineInstr &MI = *I;
420321369Sdim  const int Opcode = MI.getOpcode();
421321369Sdim  if (!isLEA(Opcode))
422276479Sdim    return;
423309124Sdim  if (MI.getOperand(5).getReg() != 0 || !MI.getOperand(4).isImm() ||
424276479Sdim      !TII->isSafeToClobberEFLAGS(*MFI, I))
425276479Sdim    return;
426309124Sdim  const unsigned DstR = MI.getOperand(0).getReg();
427309124Sdim  const unsigned SrcR1 = MI.getOperand(1).getReg();
428309124Sdim  const unsigned SrcR2 = MI.getOperand(3).getReg();
429276479Sdim  if ((SrcR1 == 0 || SrcR1 != DstR) && (SrcR2 == 0 || SrcR2 != DstR))
430276479Sdim    return;
431309124Sdim  if (MI.getOperand(2).getImm() > 1)
432276479Sdim    return;
433341825Sdim  LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; I->dump(););
434341825Sdim  LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: ";);
435276479Sdim  MachineInstr *NewMI = nullptr;
436276479Sdim  // Make ADD instruction for two registers writing to LEA's destination
437276479Sdim  if (SrcR1 != 0 && SrcR2 != 0) {
438321369Sdim    const MCInstrDesc &ADDrr = TII->get(getADDrrFromLEA(Opcode));
439321369Sdim    const MachineOperand &Src = MI.getOperand(SrcR1 == DstR ? 3 : 1);
440321369Sdim    NewMI =
441321369Sdim        BuildMI(*MFI, I, MI.getDebugLoc(), ADDrr, DstR).addReg(DstR).add(Src);
442341825Sdim    LLVM_DEBUG(NewMI->dump(););
443276479Sdim  }
444276479Sdim  // Make ADD instruction for immediate
445309124Sdim  if (MI.getOperand(4).getImm() != 0) {
446321369Sdim    const MCInstrDesc &ADDri =
447321369Sdim        TII->get(getADDriFromLEA(Opcode, MI.getOperand(4)));
448309124Sdim    const MachineOperand &SrcR = MI.getOperand(SrcR1 == DstR ? 1 : 3);
449321369Sdim    NewMI = BuildMI(*MFI, I, MI.getDebugLoc(), ADDri, DstR)
450321369Sdim                .add(SrcR)
451309124Sdim                .addImm(MI.getOperand(4).getImm());
452341825Sdim    LLVM_DEBUG(NewMI->dump(););
453276479Sdim  }
454276479Sdim  if (NewMI) {
455276479Sdim    MFI->erase(I);
456321369Sdim    I = NewMI;
457276479Sdim  }
458276479Sdim}
459276479Sdim
460321369SdimMachineInstr *
461321369SdimFixupLEAPass::processInstrForSlow3OpLEA(MachineInstr &MI,
462321369Sdim                                        MachineFunction::iterator MFI) {
463321369Sdim
464321369Sdim  const int LEAOpcode = MI.getOpcode();
465321369Sdim  if (!isLEA(LEAOpcode))
466321369Sdim    return nullptr;
467321369Sdim
468321369Sdim  const MachineOperand &Dst = MI.getOperand(0);
469321369Sdim  const MachineOperand &Base = MI.getOperand(1);
470321369Sdim  const MachineOperand &Scale = MI.getOperand(2);
471321369Sdim  const MachineOperand &Index = MI.getOperand(3);
472321369Sdim  const MachineOperand &Offset = MI.getOperand(4);
473321369Sdim  const MachineOperand &Segment = MI.getOperand(5);
474321369Sdim
475341825Sdim  if (!(TII->isThreeOperandsLEA(MI) ||
476321369Sdim        hasInefficientLEABaseReg(Base, Index)) ||
477321369Sdim      !TII->isSafeToClobberEFLAGS(*MFI, MI) ||
478321369Sdim      Segment.getReg() != X86::NoRegister)
479321369Sdim    return nullptr;
480321369Sdim
481321369Sdim  unsigned int DstR = Dst.getReg();
482321369Sdim  unsigned int BaseR = Base.getReg();
483321369Sdim  unsigned int IndexR = Index.getReg();
484321369Sdim  unsigned SSDstR =
485321369Sdim      (LEAOpcode == X86::LEA64_32r) ? getX86SubSuperRegister(DstR, 64) : DstR;
486321369Sdim  bool IsScale1 = Scale.getImm() == 1;
487321369Sdim  bool IsInefficientBase = isInefficientLEAReg(BaseR);
488321369Sdim  bool IsInefficientIndex = isInefficientLEAReg(IndexR);
489321369Sdim
490321369Sdim  // Skip these cases since it takes more than 2 instructions
491321369Sdim  // to replace the LEA instruction.
492321369Sdim  if (IsInefficientBase && SSDstR == BaseR && !IsScale1)
493321369Sdim    return nullptr;
494321369Sdim  if (LEAOpcode == X86::LEA64_32r && IsInefficientBase &&
495321369Sdim      (IsInefficientIndex || !IsScale1))
496321369Sdim    return nullptr;
497321369Sdim
498321369Sdim  const DebugLoc DL = MI.getDebugLoc();
499321369Sdim  const MCInstrDesc &ADDrr = TII->get(getADDrrFromLEA(LEAOpcode));
500321369Sdim  const MCInstrDesc &ADDri = TII->get(getADDriFromLEA(LEAOpcode, Offset));
501321369Sdim
502341825Sdim  LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MI.dump(););
503341825Sdim  LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: ";);
504321369Sdim
505321369Sdim  // First try to replace LEA with one or two (for the 3-op LEA case)
506321369Sdim  // add instructions:
507321369Sdim  // 1.lea (%base,%index,1), %base => add %index,%base
508321369Sdim  // 2.lea (%base,%index,1), %index => add %base,%index
509321369Sdim  if (IsScale1 && (DstR == BaseR || DstR == IndexR)) {
510321369Sdim    const MachineOperand &Src = DstR == BaseR ? Index : Base;
511321369Sdim    MachineInstr *NewMI =
512321369Sdim        BuildMI(*MFI, MI, DL, ADDrr, DstR).addReg(DstR).add(Src);
513341825Sdim    LLVM_DEBUG(NewMI->dump(););
514321369Sdim    // Create ADD instruction for the Offset in case of 3-Ops LEA.
515321369Sdim    if (hasLEAOffset(Offset)) {
516321369Sdim      NewMI = BuildMI(*MFI, MI, DL, ADDri, DstR).addReg(DstR).add(Offset);
517341825Sdim      LLVM_DEBUG(NewMI->dump(););
518321369Sdim    }
519321369Sdim    return NewMI;
520321369Sdim  }
521321369Sdim  // If the base is inefficient try switching the index and base operands,
522321369Sdim  // otherwise just break the 3-Ops LEA inst into 2-Ops LEA + ADD instruction:
523321369Sdim  // lea offset(%base,%index,scale),%dst =>
524321369Sdim  // lea (%base,%index,scale); add offset,%dst
525321369Sdim  if (!IsInefficientBase || (!IsInefficientIndex && IsScale1)) {
526321369Sdim    MachineInstr *NewMI = BuildMI(*MFI, MI, DL, TII->get(LEAOpcode))
527321369Sdim                              .add(Dst)
528321369Sdim                              .add(IsInefficientBase ? Index : Base)
529321369Sdim                              .add(Scale)
530321369Sdim                              .add(IsInefficientBase ? Base : Index)
531321369Sdim                              .addImm(0)
532321369Sdim                              .add(Segment);
533341825Sdim    LLVM_DEBUG(NewMI->dump(););
534321369Sdim    // Create ADD instruction for the Offset in case of 3-Ops LEA.
535321369Sdim    if (hasLEAOffset(Offset)) {
536321369Sdim      NewMI = BuildMI(*MFI, MI, DL, ADDri, DstR).addReg(DstR).add(Offset);
537341825Sdim      LLVM_DEBUG(NewMI->dump(););
538321369Sdim    }
539321369Sdim    return NewMI;
540321369Sdim  }
541321369Sdim  // Handle the rest of the cases with inefficient base register:
542321369Sdim  assert(SSDstR != BaseR && "SSDstR == BaseR should be handled already!");
543321369Sdim  assert(IsInefficientBase && "efficient base should be handled already!");
544321369Sdim
545321369Sdim  // lea (%base,%index,1), %dst => mov %base,%dst; add %index,%dst
546321369Sdim  if (IsScale1 && !hasLEAOffset(Offset)) {
547341825Sdim    bool BIK = Base.isKill() && BaseR != IndexR;
548341825Sdim    TII->copyPhysReg(*MFI, MI, DL, DstR, BaseR, BIK);
549341825Sdim    LLVM_DEBUG(MI.getPrevNode()->dump(););
550321369Sdim
551321369Sdim    MachineInstr *NewMI =
552321369Sdim        BuildMI(*MFI, MI, DL, ADDrr, DstR).addReg(DstR).add(Index);
553341825Sdim    LLVM_DEBUG(NewMI->dump(););
554321369Sdim    return NewMI;
555321369Sdim  }
556321369Sdim  // lea offset(%base,%index,scale), %dst =>
557321369Sdim  // lea offset( ,%index,scale), %dst; add %base,%dst
558321369Sdim  MachineInstr *NewMI = BuildMI(*MFI, MI, DL, TII->get(LEAOpcode))
559321369Sdim                            .add(Dst)
560321369Sdim                            .addReg(0)
561321369Sdim                            .add(Scale)
562321369Sdim                            .add(Index)
563321369Sdim                            .add(Offset)
564321369Sdim                            .add(Segment);
565341825Sdim  LLVM_DEBUG(NewMI->dump(););
566321369Sdim
567321369Sdim  NewMI = BuildMI(*MFI, MI, DL, ADDrr, DstR).addReg(DstR).add(Base);
568341825Sdim  LLVM_DEBUG(NewMI->dump(););
569321369Sdim  return NewMI;
570321369Sdim}
571321369Sdim
572251607Sdimbool FixupLEAPass::processBasicBlock(MachineFunction &MF,
573251607Sdim                                     MachineFunction::iterator MFI) {
574251607Sdim
575276479Sdim  for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I) {
576296417Sdim    if (OptIncDec)
577296417Sdim      if (fixupIncDec(I, MFI))
578296417Sdim        continue;
579296417Sdim
580296417Sdim    if (OptLEA) {
581341825Sdim      if (MF.getSubtarget<X86Subtarget>().slowLEA())
582296417Sdim        processInstructionForSLM(I, MFI);
583321369Sdim
584321369Sdim      else {
585321369Sdim        if (MF.getSubtarget<X86Subtarget>().slow3OpsLEA()) {
586321369Sdim          if (auto *NewMI = processInstrForSlow3OpLEA(*I, MFI)) {
587321369Sdim            MFI->erase(I);
588321369Sdim            I = NewMI;
589321369Sdim          }
590321369Sdim        } else
591321369Sdim          processInstruction(I, MFI);
592321369Sdim      }
593296417Sdim    }
594276479Sdim  }
595251607Sdim  return false;
596251607Sdim}
597