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