OSDN Git Service

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