1 //===-- X86FixupLEAs.cpp - use or replace LEA instructions -----------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8 //
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 // It replaces LEAs with ADD/INC/DEC when that is better for size/speed.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "X86.h"
16 #include "X86InstrInfo.h"
17 #include "X86Subtarget.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/ProfileSummaryInfo.h"
20 #include "llvm/CodeGen/LazyMachineBlockFrequencyInfo.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineSizeOpts.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/CodeGen/TargetSchedule.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 using namespace llvm;
29 
30 #define FIXUPLEA_DESC "X86 LEA Fixup"
31 #define FIXUPLEA_NAME "x86-fixup-LEAs"
32 
33 #define DEBUG_TYPE FIXUPLEA_NAME
34 
35 STATISTIC(NumLEAs, "Number of LEA instructions created");
36 
37 namespace {
38 class FixupLEAPass : public MachineFunctionPass {
39   enum RegUsageState { RU_NotUsed, RU_Write, RU_Read };
40 
41   /// Given a machine register, look for the instruction
42   /// which writes it in the current basic block. If found,
43   /// try to replace it with an equivalent LEA instruction.
44   /// If replacement succeeds, then also process the newly created
45   /// instruction.
46   void seekLEAFixup(MachineOperand &p, MachineBasicBlock::iterator &I,
47                     MachineBasicBlock &MBB);
48 
49   /// Given a memory access or LEA instruction
50   /// whose address mode uses a base and/or index register, look for
51   /// an opportunity to replace the instruction which sets the base or index
52   /// register with an equivalent LEA instruction.
53   void processInstruction(MachineBasicBlock::iterator &I,
54                           MachineBasicBlock &MBB);
55 
56   /// Given a LEA instruction which is unprofitable
57   /// on SlowLEA targets try to replace it with an equivalent ADD instruction.
58   void processInstructionForSlowLEA(MachineBasicBlock::iterator &I,
59                                     MachineBasicBlock &MBB);
60 
61   /// Given a LEA instruction which is unprofitable
62   /// on SNB+ try to replace it with other instructions.
63   /// According to Intel's Optimization Reference Manual:
64   /// " For LEA instructions with three source operands and some specific
65   ///   situations, instruction latency has increased to 3 cycles, and must
66   ///   dispatch via port 1:
67   /// - LEA that has all three source operands: base, index, and offset
68   /// - LEA that uses base and index registers where the base is EBP, RBP,
69   ///   or R13
70   /// - LEA that uses RIP relative addressing mode
71   /// - LEA that uses 16-bit addressing mode "
72   /// This function currently handles the first 2 cases only.
73   void processInstrForSlow3OpLEA(MachineBasicBlock::iterator &I,
74                                  MachineBasicBlock &MBB, bool OptIncDec);
75 
76   /// Look for LEAs that are really two address LEAs that we might be able to
77   /// turn into regular ADD instructions.
78   bool optTwoAddrLEA(MachineBasicBlock::iterator &I,
79                      MachineBasicBlock &MBB, bool OptIncDec,
80                      bool UseLEAForSP) const;
81 
82   /// Look for and transform the sequence
83   ///     lea (reg1, reg2), reg3
84   ///     sub reg3, reg4
85   /// to
86   ///     sub reg1, reg4
87   ///     sub reg2, reg4
88   /// It can also optimize the sequence lea/add similarly.
89   bool optLEAALU(MachineBasicBlock::iterator &I, MachineBasicBlock &MBB) const;
90 
91   /// Step forwards in MBB, looking for an ADD/SUB instruction which uses
92   /// the dest register of LEA instruction I.
93   MachineBasicBlock::iterator searchALUInst(MachineBasicBlock::iterator &I,
94                                             MachineBasicBlock &MBB) const;
95 
96   /// Check instructions between LeaI and AluI (exclusively).
97   /// Set BaseIndexDef to true if base or index register from LeaI is defined.
98   /// Set AluDestRef to true if the dest register of AluI is used or defined.
99   void checkRegUsage(MachineBasicBlock::iterator &LeaI,
100                      MachineBasicBlock::iterator &AluI, bool &BaseIndexDef,
101                      bool &AluDestRef) const;
102 
103   /// Determine if an instruction references a machine register
104   /// and, if so, whether it reads or writes the register.
105   RegUsageState usesRegister(MachineOperand &p, MachineBasicBlock::iterator I);
106 
107   /// Step backwards through a basic block, looking
108   /// for an instruction which writes a register within
109   /// a maximum of INSTR_DISTANCE_THRESHOLD instruction latency cycles.
110   MachineBasicBlock::iterator searchBackwards(MachineOperand &p,
111                                               MachineBasicBlock::iterator &I,
112                                               MachineBasicBlock &MBB);
113 
114   /// if an instruction can be converted to an
115   /// equivalent LEA, insert the new instruction into the basic block
116   /// and return a pointer to it. Otherwise, return zero.
117   MachineInstr *postRAConvertToLEA(MachineBasicBlock &MBB,
118                                    MachineBasicBlock::iterator &MBBI) const;
119 
120 public:
121   static char ID;
122 
123   StringRef getPassName() const override { return FIXUPLEA_DESC; }
124 
125   FixupLEAPass() : MachineFunctionPass(ID) { }
126 
127   /// Loop over all of the basic blocks,
128   /// replacing instructions by equivalent LEA instructions
129   /// if needed and when possible.
130   bool runOnMachineFunction(MachineFunction &MF) override;
131 
132   // This pass runs after regalloc and doesn't support VReg operands.
133   MachineFunctionProperties getRequiredProperties() const override {
134     return MachineFunctionProperties().set(
135         MachineFunctionProperties::Property::NoVRegs);
136   }
137 
138   void getAnalysisUsage(AnalysisUsage &AU) const override {
139     AU.addRequired<ProfileSummaryInfoWrapperPass>();
140     AU.addRequired<LazyMachineBlockFrequencyInfoPass>();
141     MachineFunctionPass::getAnalysisUsage(AU);
142   }
143 
144 private:
145   TargetSchedModel TSM;
146   const X86InstrInfo *TII = nullptr;
147   const X86RegisterInfo *TRI = nullptr;
148 };
149 }
150 
151 char FixupLEAPass::ID = 0;
152 
153 INITIALIZE_PASS(FixupLEAPass, FIXUPLEA_NAME, FIXUPLEA_DESC, false, false)
154 
155 MachineInstr *
156 FixupLEAPass::postRAConvertToLEA(MachineBasicBlock &MBB,
157                                  MachineBasicBlock::iterator &MBBI) const {
158   MachineInstr &MI = *MBBI;
159   switch (MI.getOpcode()) {
160   case X86::MOV32rr:
161   case X86::MOV64rr: {
162     const MachineOperand &Src = MI.getOperand(1);
163     const MachineOperand &Dest = MI.getOperand(0);
164     MachineInstr *NewMI =
165         BuildMI(MBB, MBBI, MI.getDebugLoc(),
166                 TII->get(MI.getOpcode() == X86::MOV32rr ? X86::LEA32r
167                                                         : X86::LEA64r))
168             .add(Dest)
169             .add(Src)
170             .addImm(1)
171             .addReg(0)
172             .addImm(0)
173             .addReg(0);
174     return NewMI;
175   }
176   }
177 
178   if (!MI.isConvertibleTo3Addr())
179     return nullptr;
180 
181   switch (MI.getOpcode()) {
182   default:
183     // Only convert instructions that we've verified are safe.
184     return nullptr;
185   case X86::ADD64ri32:
186   case X86::ADD64ri8:
187   case X86::ADD64ri32_DB:
188   case X86::ADD64ri8_DB:
189   case X86::ADD32ri:
190   case X86::ADD32ri8:
191   case X86::ADD32ri_DB:
192   case X86::ADD32ri8_DB:
193     if (!MI.getOperand(2).isImm()) {
194       // convertToThreeAddress will call getImm()
195       // which requires isImm() to be true
196       return nullptr;
197     }
198     break;
199   case X86::SHL64ri:
200   case X86::SHL32ri:
201   case X86::INC64r:
202   case X86::INC32r:
203   case X86::DEC64r:
204   case X86::DEC32r:
205   case X86::ADD64rr:
206   case X86::ADD64rr_DB:
207   case X86::ADD32rr:
208   case X86::ADD32rr_DB:
209     // These instructions are all fine to convert.
210     break;
211   }
212   MachineFunction::iterator MFI = MBB.getIterator();
213   return TII->convertToThreeAddress(MFI, MI, nullptr);
214 }
215 
216 FunctionPass *llvm::createX86FixupLEAs() { return new FixupLEAPass(); }
217 
218 static bool isLEA(unsigned Opcode) {
219   return Opcode == X86::LEA32r || Opcode == X86::LEA64r ||
220          Opcode == X86::LEA64_32r;
221 }
222 
223 bool FixupLEAPass::runOnMachineFunction(MachineFunction &MF) {
224   if (skipFunction(MF.getFunction()))
225     return false;
226 
227   const X86Subtarget &ST = MF.getSubtarget<X86Subtarget>();
228   bool IsSlowLEA = ST.slowLEA();
229   bool IsSlow3OpsLEA = ST.slow3OpsLEA();
230   bool LEAUsesAG = ST.LEAusesAG();
231 
232   bool OptIncDec = !ST.slowIncDec() || MF.getFunction().hasOptSize();
233   bool UseLEAForSP = ST.useLeaForSP();
234 
235   TSM.init(&ST);
236   TII = ST.getInstrInfo();
237   TRI = ST.getRegisterInfo();
238   auto *PSI = &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
239   auto *MBFI = (PSI && PSI->hasProfileSummary())
240                    ? &getAnalysis<LazyMachineBlockFrequencyInfoPass>().getBFI()
241                    : nullptr;
242 
243   LLVM_DEBUG(dbgs() << "Start X86FixupLEAs\n";);
244   for (MachineBasicBlock &MBB : MF) {
245     // First pass. Try to remove or optimize existing LEAs.
246     bool OptIncDecPerBB =
247         OptIncDec || llvm::shouldOptimizeForSize(&MBB, PSI, MBFI);
248     for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I) {
249       if (!isLEA(I->getOpcode()))
250         continue;
251 
252       if (optTwoAddrLEA(I, MBB, OptIncDecPerBB, UseLEAForSP))
253         continue;
254 
255       if (IsSlowLEA)
256         processInstructionForSlowLEA(I, MBB);
257       else if (IsSlow3OpsLEA)
258         processInstrForSlow3OpLEA(I, MBB, OptIncDecPerBB);
259     }
260 
261     // Second pass for creating LEAs. This may reverse some of the
262     // transformations above.
263     if (LEAUsesAG) {
264       for (MachineBasicBlock::iterator I = MBB.begin(); I != MBB.end(); ++I)
265         processInstruction(I, MBB);
266     }
267   }
268 
269   LLVM_DEBUG(dbgs() << "End X86FixupLEAs\n";);
270 
271   return true;
272 }
273 
274 FixupLEAPass::RegUsageState
275 FixupLEAPass::usesRegister(MachineOperand &p, MachineBasicBlock::iterator I) {
276   RegUsageState RegUsage = RU_NotUsed;
277   MachineInstr &MI = *I;
278 
279   for (unsigned i = 0; i < MI.getNumOperands(); ++i) {
280     MachineOperand &opnd = MI.getOperand(i);
281     if (opnd.isReg() && opnd.getReg() == p.getReg()) {
282       if (opnd.isDef())
283         return RU_Write;
284       RegUsage = RU_Read;
285     }
286   }
287   return RegUsage;
288 }
289 
290 /// getPreviousInstr - Given a reference to an instruction in a basic
291 /// block, return a reference to the previous instruction in the block,
292 /// wrapping around to the last instruction of the block if the block
293 /// branches to itself.
294 static inline bool getPreviousInstr(MachineBasicBlock::iterator &I,
295                                     MachineBasicBlock &MBB) {
296   if (I == MBB.begin()) {
297     if (MBB.isPredecessor(&MBB)) {
298       I = --MBB.end();
299       return true;
300     } else
301       return false;
302   }
303   --I;
304   return true;
305 }
306 
307 MachineBasicBlock::iterator
308 FixupLEAPass::searchBackwards(MachineOperand &p, MachineBasicBlock::iterator &I,
309                               MachineBasicBlock &MBB) {
310   int InstrDistance = 1;
311   MachineBasicBlock::iterator CurInst;
312   static const int INSTR_DISTANCE_THRESHOLD = 5;
313 
314   CurInst = I;
315   bool Found;
316   Found = getPreviousInstr(CurInst, MBB);
317   while (Found && I != CurInst) {
318     if (CurInst->isCall() || CurInst->isInlineAsm())
319       break;
320     if (InstrDistance > INSTR_DISTANCE_THRESHOLD)
321       break; // too far back to make a difference
322     if (usesRegister(p, CurInst) == RU_Write) {
323       return CurInst;
324     }
325     InstrDistance += TSM.computeInstrLatency(&*CurInst);
326     Found = getPreviousInstr(CurInst, MBB);
327   }
328   return MachineBasicBlock::iterator();
329 }
330 
331 static inline bool isInefficientLEAReg(unsigned Reg) {
332   return Reg == X86::EBP || Reg == X86::RBP ||
333          Reg == X86::R13D || Reg == X86::R13;
334 }
335 
336 /// Returns true if this LEA uses base an index registers, and the base register
337 /// is known to be inefficient for the subtarget.
338 // TODO: use a variant scheduling class to model the latency profile
339 // of LEA instructions, and implement this logic as a scheduling predicate.
340 static inline bool hasInefficientLEABaseReg(const MachineOperand &Base,
341                                             const MachineOperand &Index) {
342   return Base.isReg() && isInefficientLEAReg(Base.getReg()) && Index.isReg() &&
343          Index.getReg() != X86::NoRegister;
344 }
345 
346 static inline bool hasLEAOffset(const MachineOperand &Offset) {
347   return (Offset.isImm() && Offset.getImm() != 0) || Offset.isGlobal();
348 }
349 
350 static inline unsigned getADDrrFromLEA(unsigned LEAOpcode) {
351   switch (LEAOpcode) {
352   default:
353     llvm_unreachable("Unexpected LEA instruction");
354   case X86::LEA32r:
355   case X86::LEA64_32r:
356     return X86::ADD32rr;
357   case X86::LEA64r:
358     return X86::ADD64rr;
359   }
360 }
361 
362 static inline unsigned getSUBrrFromLEA(unsigned LEAOpcode) {
363   switch (LEAOpcode) {
364   default:
365     llvm_unreachable("Unexpected LEA instruction");
366   case X86::LEA32r:
367   case X86::LEA64_32r:
368     return X86::SUB32rr;
369   case X86::LEA64r:
370     return X86::SUB64rr;
371   }
372 }
373 
374 static inline unsigned getADDriFromLEA(unsigned LEAOpcode,
375                                        const MachineOperand &Offset) {
376   bool IsInt8 = Offset.isImm() && isInt<8>(Offset.getImm());
377   switch (LEAOpcode) {
378   default:
379     llvm_unreachable("Unexpected LEA instruction");
380   case X86::LEA32r:
381   case X86::LEA64_32r:
382     return IsInt8 ? X86::ADD32ri8 : X86::ADD32ri;
383   case X86::LEA64r:
384     return IsInt8 ? X86::ADD64ri8 : X86::ADD64ri32;
385   }
386 }
387 
388 static inline unsigned getINCDECFromLEA(unsigned LEAOpcode, bool IsINC) {
389   switch (LEAOpcode) {
390   default:
391     llvm_unreachable("Unexpected LEA instruction");
392   case X86::LEA32r:
393   case X86::LEA64_32r:
394     return IsINC ? X86::INC32r : X86::DEC32r;
395   case X86::LEA64r:
396     return IsINC ? X86::INC64r : X86::DEC64r;
397   }
398 }
399 
400 MachineBasicBlock::iterator
401 FixupLEAPass::searchALUInst(MachineBasicBlock::iterator &I,
402                             MachineBasicBlock &MBB) const {
403   const int InstrDistanceThreshold = 5;
404   int InstrDistance = 1;
405   MachineBasicBlock::iterator CurInst = std::next(I);
406 
407   unsigned LEAOpcode = I->getOpcode();
408   unsigned AddOpcode = getADDrrFromLEA(LEAOpcode);
409   unsigned SubOpcode = getSUBrrFromLEA(LEAOpcode);
410   Register DestReg = I->getOperand(0).getReg();
411 
412   while (CurInst != MBB.end()) {
413     if (CurInst->isCall() || CurInst->isInlineAsm())
414       break;
415     if (InstrDistance > InstrDistanceThreshold)
416       break;
417 
418     // Check if the lea dest register is used in an add/sub instruction only.
419     for (unsigned I = 0, E = CurInst->getNumOperands(); I != E; ++I) {
420       MachineOperand &Opnd = CurInst->getOperand(I);
421       if (Opnd.isReg() && Opnd.getReg() == DestReg) {
422         if (Opnd.isDef() || !Opnd.isKill())
423           return MachineBasicBlock::iterator();
424 
425         unsigned AluOpcode = CurInst->getOpcode();
426         if (AluOpcode != AddOpcode && AluOpcode != SubOpcode)
427           return MachineBasicBlock::iterator();
428 
429         MachineOperand &Opnd2 = CurInst->getOperand(3 - I);
430         MachineOperand AluDest = CurInst->getOperand(0);
431         if (Opnd2.getReg() != AluDest.getReg())
432           return MachineBasicBlock::iterator();
433 
434         // X - (Y + Z) may generate different flags than (X - Y) - Z when there
435         // is overflow. So we can't change the alu instruction if the flags
436         // register is live.
437         if (!CurInst->registerDefIsDead(X86::EFLAGS, TRI))
438           return MachineBasicBlock::iterator();
439 
440         return CurInst;
441       }
442     }
443 
444     InstrDistance++;
445     ++CurInst;
446   }
447   return MachineBasicBlock::iterator();
448 }
449 
450 void FixupLEAPass::checkRegUsage(MachineBasicBlock::iterator &LeaI,
451                                  MachineBasicBlock::iterator &AluI,
452                                  bool &BaseIndexDef, bool &AluDestRef) const {
453   BaseIndexDef = AluDestRef = false;
454   Register BaseReg = LeaI->getOperand(1 + X86::AddrBaseReg).getReg();
455   Register IndexReg = LeaI->getOperand(1 + X86::AddrIndexReg).getReg();
456   Register AluDestReg = AluI->getOperand(0).getReg();
457 
458   MachineBasicBlock::iterator CurInst = std::next(LeaI);
459   while (CurInst != AluI) {
460     for (unsigned I = 0, E = CurInst->getNumOperands(); I != E; ++I) {
461       MachineOperand &Opnd = CurInst->getOperand(I);
462       if (!Opnd.isReg())
463         continue;
464       Register Reg = Opnd.getReg();
465       if (TRI->regsOverlap(Reg, AluDestReg))
466         AluDestRef = true;
467       if (Opnd.isDef() &&
468           (TRI->regsOverlap(Reg, BaseReg) || TRI->regsOverlap(Reg, IndexReg))) {
469         BaseIndexDef = true;
470       }
471     }
472     ++CurInst;
473   }
474 }
475 
476 bool FixupLEAPass::optLEAALU(MachineBasicBlock::iterator &I,
477                              MachineBasicBlock &MBB) const {
478   // Look for an add/sub instruction which uses the result of lea.
479   MachineBasicBlock::iterator AluI = searchALUInst(I, MBB);
480   if (AluI == MachineBasicBlock::iterator())
481     return false;
482 
483   // Check if there are any related register usage between lea and alu.
484   bool BaseIndexDef, AluDestRef;
485   checkRegUsage(I, AluI, BaseIndexDef, AluDestRef);
486 
487   MachineBasicBlock::iterator InsertPos = AluI;
488   if (BaseIndexDef) {
489     if (AluDestRef)
490       return false;
491     InsertPos = I;
492   }
493 
494   // Check if there are same registers.
495   Register AluDestReg = AluI->getOperand(0).getReg();
496   Register BaseReg = I->getOperand(1 + X86::AddrBaseReg).getReg();
497   Register IndexReg = I->getOperand(1 + X86::AddrIndexReg).getReg();
498   if (I->getOpcode() == X86::LEA64_32r) {
499     BaseReg = TRI->getSubReg(BaseReg, X86::sub_32bit);
500     IndexReg = TRI->getSubReg(IndexReg, X86::sub_32bit);
501   }
502   if (AluDestReg == IndexReg) {
503     if (BaseReg == IndexReg)
504       return false;
505     std::swap(BaseReg, IndexReg);
506   }
507 
508   // Now it's safe to change instructions.
509   MachineInstr *NewMI1, *NewMI2;
510   unsigned NewOpcode = AluI->getOpcode();
511   NewMI1 = BuildMI(MBB, InsertPos, AluI->getDebugLoc(), TII->get(NewOpcode),
512                    AluDestReg)
513                .addReg(AluDestReg)
514                .addReg(BaseReg);
515   NewMI1->addRegisterDead(X86::EFLAGS, TRI);
516   NewMI2 = BuildMI(MBB, InsertPos, AluI->getDebugLoc(), TII->get(NewOpcode),
517                    AluDestReg)
518                .addReg(AluDestReg)
519                .addReg(IndexReg);
520   NewMI2->addRegisterDead(X86::EFLAGS, TRI);
521 
522   MBB.getParent()->substituteDebugValuesForInst(*AluI, *NewMI1, 1);
523   MBB.getParent()->substituteDebugValuesForInst(*AluI, *NewMI2, 1);
524   MBB.erase(I);
525   MBB.erase(AluI);
526   I = NewMI1;
527   return true;
528 }
529 
530 bool FixupLEAPass::optTwoAddrLEA(MachineBasicBlock::iterator &I,
531                                  MachineBasicBlock &MBB, bool OptIncDec,
532                                  bool UseLEAForSP) const {
533   MachineInstr &MI = *I;
534 
535   const MachineOperand &Base =    MI.getOperand(1 + X86::AddrBaseReg);
536   const MachineOperand &Scale =   MI.getOperand(1 + X86::AddrScaleAmt);
537   const MachineOperand &Index =   MI.getOperand(1 + X86::AddrIndexReg);
538   const MachineOperand &Disp =    MI.getOperand(1 + X86::AddrDisp);
539   const MachineOperand &Segment = MI.getOperand(1 + X86::AddrSegmentReg);
540 
541   if (Segment.getReg() != 0 || !Disp.isImm() || Scale.getImm() > 1 ||
542       MBB.computeRegisterLiveness(TRI, X86::EFLAGS, I) !=
543           MachineBasicBlock::LQR_Dead)
544     return false;
545 
546   Register DestReg = MI.getOperand(0).getReg();
547   Register BaseReg = Base.getReg();
548   Register IndexReg = Index.getReg();
549 
550   // Don't change stack adjustment LEAs.
551   if (UseLEAForSP && (DestReg == X86::ESP || DestReg == X86::RSP))
552     return false;
553 
554   // LEA64_32 has 64-bit operands but 32-bit result.
555   if (MI.getOpcode() == X86::LEA64_32r) {
556     if (BaseReg != 0)
557       BaseReg = TRI->getSubReg(BaseReg, X86::sub_32bit);
558     if (IndexReg != 0)
559       IndexReg = TRI->getSubReg(IndexReg, X86::sub_32bit);
560   }
561 
562   MachineInstr *NewMI = nullptr;
563 
564   // Case 1.
565   // Look for lea(%reg1, %reg2), %reg1 or lea(%reg2, %reg1), %reg1
566   // which can be turned into add %reg2, %reg1
567   if (BaseReg != 0 && IndexReg != 0 && Disp.getImm() == 0 &&
568       (DestReg == BaseReg || DestReg == IndexReg)) {
569     unsigned NewOpcode = getADDrrFromLEA(MI.getOpcode());
570     if (DestReg != BaseReg)
571       std::swap(BaseReg, IndexReg);
572 
573     if (MI.getOpcode() == X86::LEA64_32r) {
574       // TODO: Do we need the super register implicit use?
575       NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
576         .addReg(BaseReg).addReg(IndexReg)
577         .addReg(Base.getReg(), RegState::Implicit)
578         .addReg(Index.getReg(), RegState::Implicit);
579     } else {
580       NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
581         .addReg(BaseReg).addReg(IndexReg);
582     }
583   } else if (DestReg == BaseReg && IndexReg == 0) {
584     // Case 2.
585     // This is an LEA with only a base register and a displacement,
586     // We can use ADDri or INC/DEC.
587 
588     // Does this LEA have one these forms:
589     // lea  %reg, 1(%reg)
590     // lea  %reg, -1(%reg)
591     if (OptIncDec && (Disp.getImm() == 1 || Disp.getImm() == -1)) {
592       bool IsINC = Disp.getImm() == 1;
593       unsigned NewOpcode = getINCDECFromLEA(MI.getOpcode(), IsINC);
594 
595       if (MI.getOpcode() == X86::LEA64_32r) {
596         // TODO: Do we need the super register implicit use?
597         NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
598           .addReg(BaseReg).addReg(Base.getReg(), RegState::Implicit);
599       } else {
600         NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
601           .addReg(BaseReg);
602       }
603     } else {
604       unsigned NewOpcode = getADDriFromLEA(MI.getOpcode(), Disp);
605       if (MI.getOpcode() == X86::LEA64_32r) {
606         // TODO: Do we need the super register implicit use?
607         NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
608           .addReg(BaseReg).addImm(Disp.getImm())
609           .addReg(Base.getReg(), RegState::Implicit);
610       } else {
611         NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpcode), DestReg)
612           .addReg(BaseReg).addImm(Disp.getImm());
613       }
614     }
615   } else if (BaseReg != 0 && IndexReg != 0 && Disp.getImm() == 0) {
616     // Case 3.
617     // Look for and transform the sequence
618     //     lea (reg1, reg2), reg3
619     //     sub reg3, reg4
620     return optLEAALU(I, MBB);
621   } else
622     return false;
623 
624   MBB.getParent()->substituteDebugValuesForInst(*I, *NewMI, 1);
625   MBB.erase(I);
626   I = NewMI;
627   return true;
628 }
629 
630 void FixupLEAPass::processInstruction(MachineBasicBlock::iterator &I,
631                                       MachineBasicBlock &MBB) {
632   // Process a load, store, or LEA instruction.
633   MachineInstr &MI = *I;
634   const MCInstrDesc &Desc = MI.getDesc();
635   int AddrOffset = X86II::getMemoryOperandNo(Desc.TSFlags);
636   if (AddrOffset >= 0) {
637     AddrOffset += X86II::getOperandBias(Desc);
638     MachineOperand &p = MI.getOperand(AddrOffset + X86::AddrBaseReg);
639     if (p.isReg() && p.getReg() != X86::ESP) {
640       seekLEAFixup(p, I, MBB);
641     }
642     MachineOperand &q = MI.getOperand(AddrOffset + X86::AddrIndexReg);
643     if (q.isReg() && q.getReg() != X86::ESP) {
644       seekLEAFixup(q, I, MBB);
645     }
646   }
647 }
648 
649 void FixupLEAPass::seekLEAFixup(MachineOperand &p,
650                                 MachineBasicBlock::iterator &I,
651                                 MachineBasicBlock &MBB) {
652   MachineBasicBlock::iterator MBI = searchBackwards(p, I, MBB);
653   if (MBI != MachineBasicBlock::iterator()) {
654     MachineInstr *NewMI = postRAConvertToLEA(MBB, MBI);
655     if (NewMI) {
656       ++NumLEAs;
657       LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MBI->dump(););
658       // now to replace with an equivalent LEA...
659       LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: "; NewMI->dump(););
660       MBB.getParent()->substituteDebugValuesForInst(*MBI, *NewMI, 1);
661       MBB.erase(MBI);
662       MachineBasicBlock::iterator J =
663           static_cast<MachineBasicBlock::iterator>(NewMI);
664       processInstruction(J, MBB);
665     }
666   }
667 }
668 
669 void FixupLEAPass::processInstructionForSlowLEA(MachineBasicBlock::iterator &I,
670                                                 MachineBasicBlock &MBB) {
671   MachineInstr &MI = *I;
672   const unsigned Opcode = MI.getOpcode();
673 
674   const MachineOperand &Dst =     MI.getOperand(0);
675   const MachineOperand &Base =    MI.getOperand(1 + X86::AddrBaseReg);
676   const MachineOperand &Scale =   MI.getOperand(1 + X86::AddrScaleAmt);
677   const MachineOperand &Index =   MI.getOperand(1 + X86::AddrIndexReg);
678   const MachineOperand &Offset =  MI.getOperand(1 + X86::AddrDisp);
679   const MachineOperand &Segment = MI.getOperand(1 + X86::AddrSegmentReg);
680 
681   if (Segment.getReg() != 0 || !Offset.isImm() ||
682       MBB.computeRegisterLiveness(TRI, X86::EFLAGS, I, 4) !=
683           MachineBasicBlock::LQR_Dead)
684     return;
685   const Register DstR = Dst.getReg();
686   const Register SrcR1 = Base.getReg();
687   const Register SrcR2 = Index.getReg();
688   if ((SrcR1 == 0 || SrcR1 != DstR) && (SrcR2 == 0 || SrcR2 != DstR))
689     return;
690   if (Scale.getImm() > 1)
691     return;
692   LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; I->dump(););
693   LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: ";);
694   MachineInstr *NewMI = nullptr;
695   // Make ADD instruction for two registers writing to LEA's destination
696   if (SrcR1 != 0 && SrcR2 != 0) {
697     const MCInstrDesc &ADDrr = TII->get(getADDrrFromLEA(Opcode));
698     const MachineOperand &Src = SrcR1 == DstR ? Index : Base;
699     NewMI =
700         BuildMI(MBB, I, MI.getDebugLoc(), ADDrr, DstR).addReg(DstR).add(Src);
701     LLVM_DEBUG(NewMI->dump(););
702   }
703   // Make ADD instruction for immediate
704   if (Offset.getImm() != 0) {
705     const MCInstrDesc &ADDri =
706         TII->get(getADDriFromLEA(Opcode, Offset));
707     const MachineOperand &SrcR = SrcR1 == DstR ? Base : Index;
708     NewMI = BuildMI(MBB, I, MI.getDebugLoc(), ADDri, DstR)
709                 .add(SrcR)
710                 .addImm(Offset.getImm());
711     LLVM_DEBUG(NewMI->dump(););
712   }
713   if (NewMI) {
714     MBB.getParent()->substituteDebugValuesForInst(*I, *NewMI, 1);
715     MBB.erase(I);
716     I = NewMI;
717   }
718 }
719 
720 void FixupLEAPass::processInstrForSlow3OpLEA(MachineBasicBlock::iterator &I,
721                                              MachineBasicBlock &MBB,
722                                              bool OptIncDec) {
723   MachineInstr &MI = *I;
724   const unsigned LEAOpcode = MI.getOpcode();
725 
726   const MachineOperand &Dest =    MI.getOperand(0);
727   const MachineOperand &Base =    MI.getOperand(1 + X86::AddrBaseReg);
728   const MachineOperand &Scale =   MI.getOperand(1 + X86::AddrScaleAmt);
729   const MachineOperand &Index =   MI.getOperand(1 + X86::AddrIndexReg);
730   const MachineOperand &Offset =  MI.getOperand(1 + X86::AddrDisp);
731   const MachineOperand &Segment = MI.getOperand(1 + X86::AddrSegmentReg);
732 
733   if (!(TII->isThreeOperandsLEA(MI) || hasInefficientLEABaseReg(Base, Index)) ||
734       MBB.computeRegisterLiveness(TRI, X86::EFLAGS, I, 4) !=
735           MachineBasicBlock::LQR_Dead ||
736       Segment.getReg() != X86::NoRegister)
737     return;
738 
739   Register DestReg = Dest.getReg();
740   Register BaseReg = Base.getReg();
741   Register IndexReg = Index.getReg();
742 
743   if (MI.getOpcode() == X86::LEA64_32r) {
744     if (BaseReg != 0)
745       BaseReg = TRI->getSubReg(BaseReg, X86::sub_32bit);
746     if (IndexReg != 0)
747       IndexReg = TRI->getSubReg(IndexReg, X86::sub_32bit);
748   }
749 
750   bool IsScale1 = Scale.getImm() == 1;
751   bool IsInefficientBase = isInefficientLEAReg(BaseReg);
752   bool IsInefficientIndex = isInefficientLEAReg(IndexReg);
753 
754   // Skip these cases since it takes more than 2 instructions
755   // to replace the LEA instruction.
756   if (IsInefficientBase && DestReg == BaseReg && !IsScale1)
757     return;
758 
759   LLVM_DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MI.dump(););
760   LLVM_DEBUG(dbgs() << "FixLEA: Replaced by: ";);
761 
762   MachineInstr *NewMI = nullptr;
763 
764   // First try to replace LEA with one or two (for the 3-op LEA case)
765   // add instructions:
766   // 1.lea (%base,%index,1), %base => add %index,%base
767   // 2.lea (%base,%index,1), %index => add %base,%index
768   if (IsScale1 && (DestReg == BaseReg || DestReg == IndexReg)) {
769     unsigned NewOpc = getADDrrFromLEA(MI.getOpcode());
770     if (DestReg != BaseReg)
771       std::swap(BaseReg, IndexReg);
772 
773     if (MI.getOpcode() == X86::LEA64_32r) {
774       // TODO: Do we need the super register implicit use?
775       NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
776                   .addReg(BaseReg)
777                   .addReg(IndexReg)
778                   .addReg(Base.getReg(), RegState::Implicit)
779                   .addReg(Index.getReg(), RegState::Implicit);
780     } else {
781       NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
782                   .addReg(BaseReg)
783                   .addReg(IndexReg);
784     }
785   } else if (!IsInefficientBase || (!IsInefficientIndex && IsScale1)) {
786     // If the base is inefficient try switching the index and base operands,
787     // otherwise just break the 3-Ops LEA inst into 2-Ops LEA + ADD instruction:
788     // lea offset(%base,%index,scale),%dst =>
789     // lea (%base,%index,scale); add offset,%dst
790     NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(LEAOpcode))
791                 .add(Dest)
792                 .add(IsInefficientBase ? Index : Base)
793                 .add(Scale)
794                 .add(IsInefficientBase ? Base : Index)
795                 .addImm(0)
796                 .add(Segment);
797     LLVM_DEBUG(NewMI->dump(););
798   }
799 
800   // If either replacement succeeded above, add the offset if needed, then
801   // replace the instruction.
802   if (NewMI) {
803     // Create ADD instruction for the Offset in case of 3-Ops LEA.
804     if (hasLEAOffset(Offset)) {
805       if (OptIncDec && Offset.isImm() &&
806           (Offset.getImm() == 1 || Offset.getImm() == -1)) {
807         unsigned NewOpc =
808             getINCDECFromLEA(MI.getOpcode(), Offset.getImm() == 1);
809         NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
810                     .addReg(DestReg);
811         LLVM_DEBUG(NewMI->dump(););
812       } else {
813         unsigned NewOpc = getADDriFromLEA(MI.getOpcode(), Offset);
814         NewMI = BuildMI(MBB, I, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
815                     .addReg(DestReg)
816                     .add(Offset);
817         LLVM_DEBUG(NewMI->dump(););
818       }
819     }
820 
821     MBB.getParent()->substituteDebugValuesForInst(*I, *NewMI, 1);
822     MBB.erase(I);
823     I = NewMI;
824     return;
825   }
826 
827   // Handle the rest of the cases with inefficient base register:
828   assert(DestReg != BaseReg && "DestReg == BaseReg should be handled already!");
829   assert(IsInefficientBase && "efficient base should be handled already!");
830 
831   // FIXME: Handle LEA64_32r.
832   if (LEAOpcode == X86::LEA64_32r)
833     return;
834 
835   // lea (%base,%index,1), %dst => mov %base,%dst; add %index,%dst
836   if (IsScale1 && !hasLEAOffset(Offset)) {
837     bool BIK = Base.isKill() && BaseReg != IndexReg;
838     TII->copyPhysReg(MBB, MI, MI.getDebugLoc(), DestReg, BaseReg, BIK);
839     LLVM_DEBUG(MI.getPrevNode()->dump(););
840 
841     unsigned NewOpc = getADDrrFromLEA(MI.getOpcode());
842     NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
843                 .addReg(DestReg)
844                 .add(Index);
845     LLVM_DEBUG(NewMI->dump(););
846 
847     MBB.getParent()->substituteDebugValuesForInst(*I, *NewMI, 1);
848     MBB.erase(I);
849     I = NewMI;
850     return;
851   }
852 
853   // lea offset(%base,%index,scale), %dst =>
854   // lea offset( ,%index,scale), %dst; add %base,%dst
855   NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(LEAOpcode))
856               .add(Dest)
857               .addReg(0)
858               .add(Scale)
859               .add(Index)
860               .add(Offset)
861               .add(Segment);
862   LLVM_DEBUG(NewMI->dump(););
863 
864   unsigned NewOpc = getADDrrFromLEA(MI.getOpcode());
865   NewMI = BuildMI(MBB, MI, MI.getDebugLoc(), TII->get(NewOpc), DestReg)
866               .addReg(DestReg)
867               .add(Base);
868   LLVM_DEBUG(NewMI->dump(););
869 
870   MBB.getParent()->substituteDebugValuesForInst(*I, *NewMI, 1);
871   MBB.erase(I);
872   I = NewMI;
873 }
874