1 //===-- X86OptimizeLEAs.cpp - optimize usage of LEA instructions ----------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines the pass that performs some optimizations with LEA
11 // instructions in order to improve performance and code size.
12 // Currently, it does two things:
13 // 1) If there are two LEA instructions calculating addresses which only differ
14 //    by displacement inside a basic block, one of them is removed.
15 // 2) Address calculations in load and store instructions are replaced by
16 //    existing LEA def registers where possible.
17 //
18 //===----------------------------------------------------------------------===//
19 
20 #include "X86.h"
21 #include "X86InstrInfo.h"
22 #include "X86Subtarget.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/LiveVariables.h"
25 #include "llvm/CodeGen/MachineFunctionPass.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineOperand.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/Passes.h"
30 #include "llvm/IR/Function.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/raw_ostream.h"
33 #include "llvm/Target/TargetInstrInfo.h"
34 
35 using namespace llvm;
36 
37 #define DEBUG_TYPE "x86-optimize-LEAs"
38 
39 static cl::opt<bool>
40     DisableX86LEAOpt("disable-x86-lea-opt", cl::Hidden,
41                      cl::desc("X86: Disable LEA optimizations."),
42                      cl::init(false));
43 
44 STATISTIC(NumSubstLEAs, "Number of LEA instruction substitutions");
45 STATISTIC(NumRedundantLEAs, "Number of redundant LEA instructions removed");
46 
47 /// \brief Returns true if two machine operands are identical and they are not
48 /// physical registers.
49 static inline bool isIdenticalOp(const MachineOperand &MO1,
50                                  const MachineOperand &MO2);
51 
52 /// \brief Returns true if two address displacement operands are of the same
53 /// type and use the same symbol/index/address regardless of the offset.
54 static bool isSimilarDispOp(const MachineOperand &MO1,
55                             const MachineOperand &MO2);
56 
57 /// \brief Returns true if the instruction is LEA.
58 static inline bool isLEA(const MachineInstr &MI);
59 
60 namespace {
61 /// A key based on instruction's memory operands.
62 class MemOpKey {
63 public:
64   MemOpKey(const MachineOperand *Base, const MachineOperand *Scale,
65            const MachineOperand *Index, const MachineOperand *Segment,
66            const MachineOperand *Disp)
67       : Disp(Disp) {
68     Operands[0] = Base;
69     Operands[1] = Scale;
70     Operands[2] = Index;
71     Operands[3] = Segment;
72   }
73 
74   bool operator==(const MemOpKey &Other) const {
75     // Addresses' bases, scales, indices and segments must be identical.
76     for (int i = 0; i < 4; ++i)
77       if (!isIdenticalOp(*Operands[i], *Other.Operands[i]))
78         return false;
79 
80     // Addresses' displacements don't have to be exactly the same. It only
81     // matters that they use the same symbol/index/address. Immediates' or
82     // offsets' differences will be taken care of during instruction
83     // substitution.
84     return isSimilarDispOp(*Disp, *Other.Disp);
85   }
86 
87   // Address' base, scale, index and segment operands.
88   const MachineOperand *Operands[4];
89 
90   // Address' displacement operand.
91   const MachineOperand *Disp;
92 };
93 } // end anonymous namespace
94 
95 /// Provide DenseMapInfo for MemOpKey.
96 namespace llvm {
97 template <> struct DenseMapInfo<MemOpKey> {
98   typedef DenseMapInfo<const MachineOperand *> PtrInfo;
99 
100   static inline MemOpKey getEmptyKey() {
101     return MemOpKey(PtrInfo::getEmptyKey(), PtrInfo::getEmptyKey(),
102                     PtrInfo::getEmptyKey(), PtrInfo::getEmptyKey(),
103                     PtrInfo::getEmptyKey());
104   }
105 
106   static inline MemOpKey getTombstoneKey() {
107     return MemOpKey(PtrInfo::getTombstoneKey(), PtrInfo::getTombstoneKey(),
108                     PtrInfo::getTombstoneKey(), PtrInfo::getTombstoneKey(),
109                     PtrInfo::getTombstoneKey());
110   }
111 
112   static unsigned getHashValue(const MemOpKey &Val) {
113     // Checking any field of MemOpKey is enough to determine if the key is
114     // empty or tombstone.
115     assert(Val.Disp != PtrInfo::getEmptyKey() && "Cannot hash the empty key");
116     assert(Val.Disp != PtrInfo::getTombstoneKey() &&
117            "Cannot hash the tombstone key");
118 
119     hash_code Hash = hash_combine(*Val.Operands[0], *Val.Operands[1],
120                                   *Val.Operands[2], *Val.Operands[3]);
121 
122     // If the address displacement is an immediate, it should not affect the
123     // hash so that memory operands which differ only be immediate displacement
124     // would have the same hash. If the address displacement is something else,
125     // we should reflect symbol/index/address in the hash.
126     switch (Val.Disp->getType()) {
127     case MachineOperand::MO_Immediate:
128       break;
129     case MachineOperand::MO_ConstantPoolIndex:
130     case MachineOperand::MO_JumpTableIndex:
131       Hash = hash_combine(Hash, Val.Disp->getIndex());
132       break;
133     case MachineOperand::MO_ExternalSymbol:
134       Hash = hash_combine(Hash, Val.Disp->getSymbolName());
135       break;
136     case MachineOperand::MO_GlobalAddress:
137       Hash = hash_combine(Hash, Val.Disp->getGlobal());
138       break;
139     case MachineOperand::MO_BlockAddress:
140       Hash = hash_combine(Hash, Val.Disp->getBlockAddress());
141       break;
142     case MachineOperand::MO_MCSymbol:
143       Hash = hash_combine(Hash, Val.Disp->getMCSymbol());
144       break;
145     case MachineOperand::MO_MachineBasicBlock:
146       Hash = hash_combine(Hash, Val.Disp->getMBB());
147       break;
148     default:
149       llvm_unreachable("Invalid address displacement operand");
150     }
151 
152     return (unsigned)Hash;
153   }
154 
155   static bool isEqual(const MemOpKey &LHS, const MemOpKey &RHS) {
156     // Checking any field of MemOpKey is enough to determine if the key is
157     // empty or tombstone.
158     if (RHS.Disp == PtrInfo::getEmptyKey())
159       return LHS.Disp == PtrInfo::getEmptyKey();
160     if (RHS.Disp == PtrInfo::getTombstoneKey())
161       return LHS.Disp == PtrInfo::getTombstoneKey();
162     return LHS == RHS;
163   }
164 };
165 }
166 
167 /// \brief Returns a hash table key based on memory operands of \p MI. The
168 /// number of the first memory operand of \p MI is specified through \p N.
169 static inline MemOpKey getMemOpKey(const MachineInstr &MI, unsigned N) {
170   assert((isLEA(MI) || MI.mayLoadOrStore()) &&
171          "The instruction must be a LEA, a load or a store");
172   return MemOpKey(&MI.getOperand(N + X86::AddrBaseReg),
173                   &MI.getOperand(N + X86::AddrScaleAmt),
174                   &MI.getOperand(N + X86::AddrIndexReg),
175                   &MI.getOperand(N + X86::AddrSegmentReg),
176                   &MI.getOperand(N + X86::AddrDisp));
177 }
178 
179 static inline bool isIdenticalOp(const MachineOperand &MO1,
180                                  const MachineOperand &MO2) {
181   return MO1.isIdenticalTo(MO2) &&
182          (!MO1.isReg() ||
183           !TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
184 }
185 
186 #ifndef NDEBUG
187 static bool isValidDispOp(const MachineOperand &MO) {
188   return MO.isImm() || MO.isCPI() || MO.isJTI() || MO.isSymbol() ||
189          MO.isGlobal() || MO.isBlockAddress() || MO.isMCSymbol() || MO.isMBB();
190 }
191 #endif
192 
193 static bool isSimilarDispOp(const MachineOperand &MO1,
194                             const MachineOperand &MO2) {
195   assert(isValidDispOp(MO1) && isValidDispOp(MO2) &&
196          "Address displacement operand is not valid");
197   return (MO1.isImm() && MO2.isImm()) ||
198          (MO1.isCPI() && MO2.isCPI() && MO1.getIndex() == MO2.getIndex()) ||
199          (MO1.isJTI() && MO2.isJTI() && MO1.getIndex() == MO2.getIndex()) ||
200          (MO1.isSymbol() && MO2.isSymbol() &&
201           MO1.getSymbolName() == MO2.getSymbolName()) ||
202          (MO1.isGlobal() && MO2.isGlobal() &&
203           MO1.getGlobal() == MO2.getGlobal()) ||
204          (MO1.isBlockAddress() && MO2.isBlockAddress() &&
205           MO1.getBlockAddress() == MO2.getBlockAddress()) ||
206          (MO1.isMCSymbol() && MO2.isMCSymbol() &&
207           MO1.getMCSymbol() == MO2.getMCSymbol()) ||
208          (MO1.isMBB() && MO2.isMBB() && MO1.getMBB() == MO2.getMBB());
209 }
210 
211 static inline bool isLEA(const MachineInstr &MI) {
212   unsigned Opcode = MI.getOpcode();
213   return Opcode == X86::LEA16r || Opcode == X86::LEA32r ||
214          Opcode == X86::LEA64r || Opcode == X86::LEA64_32r;
215 }
216 
217 namespace {
218 class OptimizeLEAPass : public MachineFunctionPass {
219 public:
220   OptimizeLEAPass() : MachineFunctionPass(ID) {}
221 
222   StringRef getPassName() const override { return "X86 LEA Optimize"; }
223 
224   /// \brief Loop over all of the basic blocks, replacing address
225   /// calculations in load and store instructions, if it's already
226   /// been calculated by LEA. Also, remove redundant LEAs.
227   bool runOnMachineFunction(MachineFunction &MF) override;
228 
229 private:
230   typedef DenseMap<MemOpKey, SmallVector<MachineInstr *, 16>> MemOpMap;
231 
232   /// \brief Returns a distance between two instructions inside one basic block.
233   /// Negative result means, that instructions occur in reverse order.
234   int calcInstrDist(const MachineInstr &First, const MachineInstr &Last);
235 
236   /// \brief Choose the best \p LEA instruction from the \p List to replace
237   /// address calculation in \p MI instruction. Return the address displacement
238   /// and the distance between \p MI and the choosen \p BestLEA in
239   /// \p AddrDispShift and \p Dist.
240   bool chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
241                      const MachineInstr &MI, MachineInstr *&BestLEA,
242                      int64_t &AddrDispShift, int &Dist);
243 
244   /// \brief Returns the difference between addresses' displacements of \p MI1
245   /// and \p MI2. The numbers of the first memory operands for the instructions
246   /// are specified through \p N1 and \p N2.
247   int64_t getAddrDispShift(const MachineInstr &MI1, unsigned N1,
248                            const MachineInstr &MI2, unsigned N2) const;
249 
250   /// \brief Returns true if the \p Last LEA instruction can be replaced by the
251   /// \p First. The difference between displacements of the addresses calculated
252   /// by these LEAs is returned in \p AddrDispShift. It'll be used for proper
253   /// replacement of the \p Last LEA's uses with the \p First's def register.
254   bool isReplaceable(const MachineInstr &First, const MachineInstr &Last,
255                      int64_t &AddrDispShift) const;
256 
257   /// \brief Find all LEA instructions in the basic block. Also, assign position
258   /// numbers to all instructions in the basic block to speed up calculation of
259   /// distance between them.
260   void findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs);
261 
262   /// \brief Removes redundant address calculations.
263   bool removeRedundantAddrCalc(MemOpMap &LEAs);
264 
265   /// \brief Removes LEAs which calculate similar addresses.
266   bool removeRedundantLEAs(MemOpMap &LEAs);
267 
268   DenseMap<const MachineInstr *, unsigned> InstrPos;
269 
270   MachineRegisterInfo *MRI;
271   const X86InstrInfo *TII;
272   const X86RegisterInfo *TRI;
273 
274   static char ID;
275 };
276 char OptimizeLEAPass::ID = 0;
277 }
278 
279 FunctionPass *llvm::createX86OptimizeLEAs() { return new OptimizeLEAPass(); }
280 
281 int OptimizeLEAPass::calcInstrDist(const MachineInstr &First,
282                                    const MachineInstr &Last) {
283   // Both instructions must be in the same basic block and they must be
284   // presented in InstrPos.
285   assert(Last.getParent() == First.getParent() &&
286          "Instructions are in different basic blocks");
287   assert(InstrPos.find(&First) != InstrPos.end() &&
288          InstrPos.find(&Last) != InstrPos.end() &&
289          "Instructions' positions are undefined");
290 
291   return InstrPos[&Last] - InstrPos[&First];
292 }
293 
294 // Find the best LEA instruction in the List to replace address recalculation in
295 // MI. Such LEA must meet these requirements:
296 // 1) The address calculated by the LEA differs only by the displacement from
297 //    the address used in MI.
298 // 2) The register class of the definition of the LEA is compatible with the
299 //    register class of the address base register of MI.
300 // 3) Displacement of the new memory operand should fit in 1 byte if possible.
301 // 4) The LEA should be as close to MI as possible, and prior to it if
302 //    possible.
303 bool OptimizeLEAPass::chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
304                                     const MachineInstr &MI,
305                                     MachineInstr *&BestLEA,
306                                     int64_t &AddrDispShift, int &Dist) {
307   const MachineFunction *MF = MI.getParent()->getParent();
308   const MCInstrDesc &Desc = MI.getDesc();
309   int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags) +
310                 X86II::getOperandBias(Desc);
311 
312   BestLEA = nullptr;
313 
314   // Loop over all LEA instructions.
315   for (auto DefMI : List) {
316     // Get new address displacement.
317     int64_t AddrDispShiftTemp = getAddrDispShift(MI, MemOpNo, *DefMI, 1);
318 
319     // Make sure address displacement fits 4 bytes.
320     if (!isInt<32>(AddrDispShiftTemp))
321       continue;
322 
323     // Check that LEA def register can be used as MI address base. Some
324     // instructions can use a limited set of registers as address base, for
325     // example MOV8mr_NOREX. We could constrain the register class of the LEA
326     // def to suit MI, however since this case is very rare and hard to
327     // reproduce in a test it's just more reliable to skip the LEA.
328     if (TII->getRegClass(Desc, MemOpNo + X86::AddrBaseReg, TRI, *MF) !=
329         MRI->getRegClass(DefMI->getOperand(0).getReg()))
330       continue;
331 
332     // Choose the closest LEA instruction from the list, prior to MI if
333     // possible. Note that we took into account resulting address displacement
334     // as well. Also note that the list is sorted by the order in which the LEAs
335     // occur, so the break condition is pretty simple.
336     int DistTemp = calcInstrDist(*DefMI, MI);
337     assert(DistTemp != 0 &&
338            "The distance between two different instructions cannot be zero");
339     if (DistTemp > 0 || BestLEA == nullptr) {
340       // Do not update return LEA, if the current one provides a displacement
341       // which fits in 1 byte, while the new candidate does not.
342       if (BestLEA != nullptr && !isInt<8>(AddrDispShiftTemp) &&
343           isInt<8>(AddrDispShift))
344         continue;
345 
346       BestLEA = DefMI;
347       AddrDispShift = AddrDispShiftTemp;
348       Dist = DistTemp;
349     }
350 
351     // FIXME: Maybe we should not always stop at the first LEA after MI.
352     if (DistTemp < 0)
353       break;
354   }
355 
356   return BestLEA != nullptr;
357 }
358 
359 // Get the difference between the addresses' displacements of the two
360 // instructions \p MI1 and \p MI2. The numbers of the first memory operands are
361 // passed through \p N1 and \p N2.
362 int64_t OptimizeLEAPass::getAddrDispShift(const MachineInstr &MI1, unsigned N1,
363                                           const MachineInstr &MI2,
364                                           unsigned N2) const {
365   const MachineOperand &Op1 = MI1.getOperand(N1 + X86::AddrDisp);
366   const MachineOperand &Op2 = MI2.getOperand(N2 + X86::AddrDisp);
367 
368   assert(isSimilarDispOp(Op1, Op2) &&
369          "Address displacement operands are not compatible");
370 
371   // After the assert above we can be sure that both operands are of the same
372   // valid type and use the same symbol/index/address, thus displacement shift
373   // calculation is rather simple.
374   if (Op1.isJTI())
375     return 0;
376   return Op1.isImm() ? Op1.getImm() - Op2.getImm()
377                      : Op1.getOffset() - Op2.getOffset();
378 }
379 
380 // Check that the Last LEA can be replaced by the First LEA. To be so,
381 // these requirements must be met:
382 // 1) Addresses calculated by LEAs differ only by displacement.
383 // 2) Def registers of LEAs belong to the same class.
384 // 3) All uses of the Last LEA def register are replaceable, thus the
385 //    register is used only as address base.
386 bool OptimizeLEAPass::isReplaceable(const MachineInstr &First,
387                                     const MachineInstr &Last,
388                                     int64_t &AddrDispShift) const {
389   assert(isLEA(First) && isLEA(Last) &&
390          "The function works only with LEA instructions");
391 
392   // Get new address displacement.
393   AddrDispShift = getAddrDispShift(Last, 1, First, 1);
394 
395   // Make sure that LEA def registers belong to the same class. There may be
396   // instructions (like MOV8mr_NOREX) which allow a limited set of registers to
397   // be used as their operands, so we must be sure that replacing one LEA
398   // with another won't lead to putting a wrong register in the instruction.
399   if (MRI->getRegClass(First.getOperand(0).getReg()) !=
400       MRI->getRegClass(Last.getOperand(0).getReg()))
401     return false;
402 
403   // Loop over all uses of the Last LEA to check that its def register is
404   // used only as address base for memory accesses. If so, it can be
405   // replaced, otherwise - no.
406   for (auto &MO : MRI->use_operands(Last.getOperand(0).getReg())) {
407     MachineInstr &MI = *MO.getParent();
408 
409     // Get the number of the first memory operand.
410     const MCInstrDesc &Desc = MI.getDesc();
411     int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags);
412 
413     // If the use instruction has no memory operand - the LEA is not
414     // replaceable.
415     if (MemOpNo < 0)
416       return false;
417 
418     MemOpNo += X86II::getOperandBias(Desc);
419 
420     // If the address base of the use instruction is not the LEA def register -
421     // the LEA is not replaceable.
422     if (!isIdenticalOp(MI.getOperand(MemOpNo + X86::AddrBaseReg), MO))
423       return false;
424 
425     // If the LEA def register is used as any other operand of the use
426     // instruction - the LEA is not replaceable.
427     for (unsigned i = 0; i < MI.getNumOperands(); i++)
428       if (i != (unsigned)(MemOpNo + X86::AddrBaseReg) &&
429           isIdenticalOp(MI.getOperand(i), MO))
430         return false;
431 
432     // Check that the new address displacement will fit 4 bytes.
433     if (MI.getOperand(MemOpNo + X86::AddrDisp).isImm() &&
434         !isInt<32>(MI.getOperand(MemOpNo + X86::AddrDisp).getImm() +
435                    AddrDispShift))
436       return false;
437   }
438 
439   return true;
440 }
441 
442 void OptimizeLEAPass::findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs) {
443   unsigned Pos = 0;
444   for (auto &MI : MBB) {
445     // Assign the position number to the instruction. Note that we are going to
446     // move some instructions during the optimization however there will never
447     // be a need to move two instructions before any selected instruction. So to
448     // avoid multiple positions' updates during moves we just increase position
449     // counter by two leaving a free space for instructions which will be moved.
450     InstrPos[&MI] = Pos += 2;
451 
452     if (isLEA(MI))
453       LEAs[getMemOpKey(MI, 1)].push_back(const_cast<MachineInstr *>(&MI));
454   }
455 }
456 
457 // Try to find load and store instructions which recalculate addresses already
458 // calculated by some LEA and replace their memory operands with its def
459 // register.
460 bool OptimizeLEAPass::removeRedundantAddrCalc(MemOpMap &LEAs) {
461   bool Changed = false;
462 
463   assert(!LEAs.empty());
464   MachineBasicBlock *MBB = (*LEAs.begin()->second.begin())->getParent();
465 
466   // Process all instructions in basic block.
467   for (auto I = MBB->begin(), E = MBB->end(); I != E;) {
468     MachineInstr &MI = *I++;
469 
470     // Instruction must be load or store.
471     if (!MI.mayLoadOrStore())
472       continue;
473 
474     // Get the number of the first memory operand.
475     const MCInstrDesc &Desc = MI.getDesc();
476     int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags);
477 
478     // If instruction has no memory operand - skip it.
479     if (MemOpNo < 0)
480       continue;
481 
482     MemOpNo += X86II::getOperandBias(Desc);
483 
484     // Get the best LEA instruction to replace address calculation.
485     MachineInstr *DefMI;
486     int64_t AddrDispShift;
487     int Dist;
488     if (!chooseBestLEA(LEAs[getMemOpKey(MI, MemOpNo)], MI, DefMI, AddrDispShift,
489                        Dist))
490       continue;
491 
492     // If LEA occurs before current instruction, we can freely replace
493     // the instruction. If LEA occurs after, we can lift LEA above the
494     // instruction and this way to be able to replace it. Since LEA and the
495     // instruction have similar memory operands (thus, the same def
496     // instructions for these operands), we can always do that, without
497     // worries of using registers before their defs.
498     if (Dist < 0) {
499       DefMI->removeFromParent();
500       MBB->insert(MachineBasicBlock::iterator(&MI), DefMI);
501       InstrPos[DefMI] = InstrPos[&MI] - 1;
502 
503       // Make sure the instructions' position numbers are sane.
504       assert(((InstrPos[DefMI] == 1 &&
505                MachineBasicBlock::iterator(DefMI) == MBB->begin()) ||
506               InstrPos[DefMI] >
507                   InstrPos[&*std::prev(MachineBasicBlock::iterator(DefMI))]) &&
508              "Instruction positioning is broken");
509     }
510 
511     // Since we can possibly extend register lifetime, clear kill flags.
512     MRI->clearKillFlags(DefMI->getOperand(0).getReg());
513 
514     ++NumSubstLEAs;
515     DEBUG(dbgs() << "OptimizeLEAs: Candidate to replace: "; MI.dump(););
516 
517     // Change instruction operands.
518     MI.getOperand(MemOpNo + X86::AddrBaseReg)
519         .ChangeToRegister(DefMI->getOperand(0).getReg(), false);
520     MI.getOperand(MemOpNo + X86::AddrScaleAmt).ChangeToImmediate(1);
521     MI.getOperand(MemOpNo + X86::AddrIndexReg)
522         .ChangeToRegister(X86::NoRegister, false);
523     MI.getOperand(MemOpNo + X86::AddrDisp).ChangeToImmediate(AddrDispShift);
524     MI.getOperand(MemOpNo + X86::AddrSegmentReg)
525         .ChangeToRegister(X86::NoRegister, false);
526 
527     DEBUG(dbgs() << "OptimizeLEAs: Replaced by: "; MI.dump(););
528 
529     Changed = true;
530   }
531 
532   return Changed;
533 }
534 
535 // Try to find similar LEAs in the list and replace one with another.
536 bool OptimizeLEAPass::removeRedundantLEAs(MemOpMap &LEAs) {
537   bool Changed = false;
538 
539   // Loop over all entries in the table.
540   for (auto &E : LEAs) {
541     auto &List = E.second;
542 
543     // Loop over all LEA pairs.
544     auto I1 = List.begin();
545     while (I1 != List.end()) {
546       MachineInstr &First = **I1;
547       auto I2 = std::next(I1);
548       while (I2 != List.end()) {
549         MachineInstr &Last = **I2;
550         int64_t AddrDispShift;
551 
552         // LEAs should be in occurence order in the list, so we can freely
553         // replace later LEAs with earlier ones.
554         assert(calcInstrDist(First, Last) > 0 &&
555                "LEAs must be in occurence order in the list");
556 
557         // Check that the Last LEA instruction can be replaced by the First.
558         if (!isReplaceable(First, Last, AddrDispShift)) {
559           ++I2;
560           continue;
561         }
562 
563         // Loop over all uses of the Last LEA and update their operands. Note
564         // that the correctness of this has already been checked in the
565         // isReplaceable function.
566         for (auto UI = MRI->use_begin(Last.getOperand(0).getReg()),
567                   UE = MRI->use_end();
568              UI != UE;) {
569           MachineOperand &MO = *UI++;
570           MachineInstr &MI = *MO.getParent();
571 
572           // Get the number of the first memory operand.
573           const MCInstrDesc &Desc = MI.getDesc();
574           int MemOpNo =
575               X86II::getMemoryOperandNo(Desc.TSFlags) +
576               X86II::getOperandBias(Desc);
577 
578           // Update address base.
579           MO.setReg(First.getOperand(0).getReg());
580 
581           // Update address disp.
582           MachineOperand &Op = MI.getOperand(MemOpNo + X86::AddrDisp);
583           if (Op.isImm())
584             Op.setImm(Op.getImm() + AddrDispShift);
585           else if (!Op.isJTI())
586             Op.setOffset(Op.getOffset() + AddrDispShift);
587         }
588 
589         // Since we can possibly extend register lifetime, clear kill flags.
590         MRI->clearKillFlags(First.getOperand(0).getReg());
591 
592         ++NumRedundantLEAs;
593         DEBUG(dbgs() << "OptimizeLEAs: Remove redundant LEA: "; Last.dump(););
594 
595         // By this moment, all of the Last LEA's uses must be replaced. So we
596         // can freely remove it.
597         assert(MRI->use_empty(Last.getOperand(0).getReg()) &&
598                "The LEA's def register must have no uses");
599         Last.eraseFromParent();
600 
601         // Erase removed LEA from the list.
602         I2 = List.erase(I2);
603 
604         Changed = true;
605       }
606       ++I1;
607     }
608   }
609 
610   return Changed;
611 }
612 
613 bool OptimizeLEAPass::runOnMachineFunction(MachineFunction &MF) {
614   bool Changed = false;
615 
616   if (DisableX86LEAOpt || skipFunction(*MF.getFunction()))
617     return false;
618 
619   MRI = &MF.getRegInfo();
620   TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
621   TRI = MF.getSubtarget<X86Subtarget>().getRegisterInfo();
622 
623   // Process all basic blocks.
624   for (auto &MBB : MF) {
625     MemOpMap LEAs;
626     InstrPos.clear();
627 
628     // Find all LEA instructions in basic block.
629     findLEAs(MBB, LEAs);
630 
631     // If current basic block has no LEAs, move on to the next one.
632     if (LEAs.empty())
633       continue;
634 
635     // Remove redundant LEA instructions.
636     Changed |= removeRedundantLEAs(LEAs);
637 
638     // Remove redundant address calculations. Do it only for -Os/-Oz since only
639     // a code size gain is expected from this part of the pass.
640     if (MF.getFunction()->optForSize())
641       Changed |= removeRedundantAddrCalc(LEAs);
642   }
643 
644   return Changed;
645 }
646