blob: e1447006cd18c9d2f2c1fef29c697cecee8a5d84 [file] [log] [blame]
Alexey Bataev7cf32472015-12-04 10:53:15 +00001//===-- 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
Andrey Turetskiy45b22a42016-05-19 10:18:29 +000011// instructions in order to improve performance and code size.
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +000012// 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
Alexey Bataev7cf32472015-12-04 10:53:15 +000016// 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"
Andrey Turetskiy0babd262016-02-20 10:58:28 +000027#include "llvm/CodeGen/MachineOperand.h"
Alexey Bataev7cf32472015-12-04 10:53:15 +000028#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
35using namespace llvm;
36
37#define DEBUG_TYPE "x86-optimize-LEAs"
38
Andrey Turetskiy9994b882016-02-20 11:11:55 +000039static cl::opt<bool>
40 DisableX86LEAOpt("disable-x86-lea-opt", cl::Hidden,
41 cl::desc("X86: Disable LEA optimizations."),
42 cl::init(false));
Alexey Bataev7b72b652015-12-17 07:34:39 +000043
Alexey Bataev7cf32472015-12-04 10:53:15 +000044STATISTIC(NumSubstLEAs, "Number of LEA instruction substitutions");
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +000045STATISTIC(NumRedundantLEAs, "Number of redundant LEA instructions removed");
Alexey Bataev7cf32472015-12-04 10:53:15 +000046
Andrey Turetskiybca0f992016-02-04 08:57:03 +000047/// \brief Returns true if two machine operands are identical and they are not
48/// physical registers.
49static inline bool isIdenticalOp(const MachineOperand &MO1,
50 const MachineOperand &MO2);
51
Andrey Turetskiy0babd262016-02-20 10:58:28 +000052/// \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.
54static bool isSimilarDispOp(const MachineOperand &MO1,
55 const MachineOperand &MO2);
56
Andrey Turetskiybca0f992016-02-04 08:57:03 +000057/// \brief Returns true if the instruction is LEA.
58static inline bool isLEA(const MachineInstr &MI);
59
Benjamin Kramerb7d33112016-08-06 11:13:10 +000060namespace {
Andrey Turetskiybca0f992016-02-04 08:57:03 +000061/// A key based on instruction's memory operands.
62class MemOpKey {
63public:
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
Andrey Turetskiy0babd262016-02-20 10:58:28 +000080 // 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);
Andrey Turetskiybca0f992016-02-04 08:57:03 +000085 }
86
87 // Address' base, scale, index and segment operands.
88 const MachineOperand *Operands[4];
89
90 // Address' displacement operand.
91 const MachineOperand *Disp;
92};
Benjamin Kramerb7d33112016-08-06 11:13:10 +000093} // end anonymous namespace
Andrey Turetskiybca0f992016-02-04 08:57:03 +000094
95/// Provide DenseMapInfo for MemOpKey.
96namespace llvm {
97template <> 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
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000124 // 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:
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000137 Hash = hash_combine(Hash, Val.Disp->getGlobal());
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000138 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;
Andrey Turetskiyb4056062016-04-26 12:18:12 +0000145 case MachineOperand::MO_MachineBasicBlock:
146 Hash = hash_combine(Hash, Val.Disp->getMBB());
147 break;
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000148 default:
149 llvm_unreachable("Invalid address displacement operand");
150 }
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000151
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
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000167/// \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.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000169static 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
179static 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
Justin Bogner38e52172016-02-24 07:58:02 +0000186#ifndef NDEBUG
187static bool isValidDispOp(const MachineOperand &MO) {
188 return MO.isImm() || MO.isCPI() || MO.isJTI() || MO.isSymbol() ||
Andrey Turetskiyb4056062016-04-26 12:18:12 +0000189 MO.isGlobal() || MO.isBlockAddress() || MO.isMCSymbol() || MO.isMBB();
Justin Bogner38e52172016-02-24 07:58:02 +0000190}
191#endif
192
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000193static 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() &&
Andrey Turetskiyb4056062016-04-26 12:18:12 +0000207 MO1.getMCSymbol() == MO2.getMCSymbol()) ||
208 (MO1.isMBB() && MO2.isMBB() && MO1.getMBB() == MO2.getMBB());
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000209}
210
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000211static 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
Alexey Bataev7cf32472015-12-04 10:53:15 +0000217namespace {
218class OptimizeLEAPass : public MachineFunctionPass {
219public:
220 OptimizeLEAPass() : MachineFunctionPass(ID) {}
221
Mehdi Amini117296c2016-10-01 02:56:57 +0000222 StringRef getPassName() const override { return "X86 LEA Optimize"; }
Alexey Bataev7cf32472015-12-04 10:53:15 +0000223
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
229private:
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000230 typedef DenseMap<MemOpKey, SmallVector<MachineInstr *, 16>> MemOpMap;
231
Alexey Bataev7cf32472015-12-04 10:53:15 +0000232 /// \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
Simon Pilgrim9d15fb32016-11-17 19:03:05 +0000238 /// and the distance between \p MI and the chosen \p BestLEA in
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000239 /// \p AddrDispShift and \p Dist.
Alexey Bataev7cf32472015-12-04 10:53:15 +0000240 bool chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000241 const MachineInstr &MI, MachineInstr *&BestLEA,
Alexey Bataev7cf32472015-12-04 10:53:15 +0000242 int64_t &AddrDispShift, int &Dist);
243
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000244 /// \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;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000249
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000250 /// \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,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000255 int64_t &AddrDispShift) const;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000256
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000257 /// \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.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000260 void findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000261
262 /// \brief Removes redundant address calculations.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000263 bool removeRedundantAddrCalc(MemOpMap &LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000264
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000265 /// \brief Removes LEAs which calculate similar addresses.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000266 bool removeRedundantLEAs(MemOpMap &LEAs);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000267
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000268 DenseMap<const MachineInstr *, unsigned> InstrPos;
269
Alexey Bataev7cf32472015-12-04 10:53:15 +0000270 MachineRegisterInfo *MRI;
271 const X86InstrInfo *TII;
272 const X86RegisterInfo *TRI;
273
274 static char ID;
275};
276char OptimizeLEAPass::ID = 0;
277}
278
279FunctionPass *llvm::createX86OptimizeLEAs() { return new OptimizeLEAPass(); }
280
281int OptimizeLEAPass::calcInstrDist(const MachineInstr &First,
282 const MachineInstr &Last) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000283 // Both instructions must be in the same basic block and they must be
284 // presented in InstrPos.
285 assert(Last.getParent() == First.getParent() &&
Alexey Bataev7cf32472015-12-04 10:53:15 +0000286 "Instructions are in different basic blocks");
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000287 assert(InstrPos.find(&First) != InstrPos.end() &&
288 InstrPos.find(&Last) != InstrPos.end() &&
289 "Instructions' positions are undefined");
Alexey Bataev7cf32472015-12-04 10:53:15 +0000290
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000291 return InstrPos[&Last] - InstrPos[&First];
Alexey Bataev7cf32472015-12-04 10:53:15 +0000292}
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.
303bool OptimizeLEAPass::chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000304 const MachineInstr &MI,
305 MachineInstr *&BestLEA,
Alexey Bataev7cf32472015-12-04 10:53:15 +0000306 int64_t &AddrDispShift, int &Dist) {
307 const MachineFunction *MF = MI.getParent()->getParent();
308 const MCInstrDesc &Desc = MI.getDesc();
Craig Topper477649a2016-04-28 05:58:46 +0000309 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags) +
Alexey Bataev7cf32472015-12-04 10:53:15 +0000310 X86II::getOperandBias(Desc);
311
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000312 BestLEA = nullptr;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000313
314 // Loop over all LEA instructions.
315 for (auto DefMI : List) {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000316 // Get new address displacement.
317 int64_t AddrDispShiftTemp = getAddrDispShift(MI, MemOpNo, *DefMI, 1);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000318
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");
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000339 if (DistTemp > 0 || BestLEA == nullptr) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000340 // Do not update return LEA, if the current one provides a displacement
341 // which fits in 1 byte, while the new candidate does not.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000342 if (BestLEA != nullptr && !isInt<8>(AddrDispShiftTemp) &&
Alexey Bataev7cf32472015-12-04 10:53:15 +0000343 isInt<8>(AddrDispShift))
344 continue;
345
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000346 BestLEA = DefMI;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000347 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
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000356 return BestLEA != nullptr;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000357}
358
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000359// 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.
362int64_t OptimizeLEAPass::getAddrDispShift(const MachineInstr &MI1, unsigned N1,
363 const MachineInstr &MI2,
364 unsigned N2) const {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000365 const MachineOperand &Op1 = MI1.getOperand(N1 + X86::AddrDisp);
366 const MachineOperand &Op2 = MI2.getOperand(N2 + X86::AddrDisp);
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000367
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();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000378}
379
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000380// 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.
386bool OptimizeLEAPass::isReplaceable(const MachineInstr &First,
387 const MachineInstr &Last,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000388 int64_t &AddrDispShift) const {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000389 assert(isLEA(First) && isLEA(Last) &&
390 "The function works only with LEA instructions");
391
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000392 // Get new address displacement.
393 AddrDispShift = getAddrDispShift(Last, 1, First, 1);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000394
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();
Craig Topper477649a2016-04-28 05:58:46 +0000411 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000412
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
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000442void OptimizeLEAPass::findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000443 unsigned Pos = 0;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000444 for (auto &MI : MBB) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000445 // 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
Alexey Bataev7cf32472015-12-04 10:53:15 +0000452 if (isLEA(MI))
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000453 LEAs[getMemOpKey(MI, 1)].push_back(const_cast<MachineInstr *>(&MI));
Alexey Bataev7cf32472015-12-04 10:53:15 +0000454 }
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.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000460bool OptimizeLEAPass::removeRedundantAddrCalc(MemOpMap &LEAs) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000461 bool Changed = false;
462
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000463 assert(!LEAs.empty());
464 MachineBasicBlock *MBB = (*LEAs.begin()->second.begin())->getParent();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000465
466 // Process all instructions in basic block.
467 for (auto I = MBB->begin(), E = MBB->end(); I != E;) {
468 MachineInstr &MI = *I++;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000469
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();
Craig Topper477649a2016-04-28 05:58:46 +0000476 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000477
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;
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000488 if (!chooseBestLEA(LEAs[getMemOpKey(MI, MemOpNo)], MI, DefMI, AddrDispShift,
489 Dist))
Alexey Bataev7cf32472015-12-04 10:53:15 +0000490 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);
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000501 InstrPos[DefMI] = InstrPos[&MI] - 1;
502
503 // Make sure the instructions' position numbers are sane.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000504 assert(((InstrPos[DefMI] == 1 &&
505 MachineBasicBlock::iterator(DefMI) == MBB->begin()) ||
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000506 InstrPos[DefMI] >
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000507 InstrPos[&*std::prev(MachineBasicBlock::iterator(DefMI))]) &&
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000508 "Instruction positioning is broken");
Alexey Bataev7cf32472015-12-04 10:53:15 +0000509 }
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
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000535// Try to find similar LEAs in the list and replace one with another.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000536bool OptimizeLEAPass::removeRedundantLEAs(MemOpMap &LEAs) {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000537 bool Changed = false;
538
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000539 // Loop over all entries in the table.
540 for (auto &E : LEAs) {
541 auto &List = E.second;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000542
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000543 // 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;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000551
Simon Pilgrim9d15fb32016-11-17 19:03:05 +0000552 // LEAs should be in occurrence order in the list, so we can freely
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000553 // replace later LEAs with earlier ones.
554 assert(calcInstrDist(First, Last) > 0 &&
Simon Pilgrim9d15fb32016-11-17 19:03:05 +0000555 "LEAs must be in occurrence order in the list");
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000556
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 =
Craig Topper477649a2016-04-28 05:58:46 +0000575 X86II::getMemoryOperandNo(Desc.TSFlags) +
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000576 X86II::getOperandBias(Desc);
577
578 // Update address base.
579 MO.setReg(First.getOperand(0).getReg());
580
581 // Update address disp.
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000582 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);
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000587 }
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;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000605 }
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000606 ++I1;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000607 }
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000608 }
609
610 return Changed;
611}
612
Alexey Bataev7cf32472015-12-04 10:53:15 +0000613bool OptimizeLEAPass::runOnMachineFunction(MachineFunction &MF) {
614 bool Changed = false;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000615
Andrey Turetskiy45b22a42016-05-19 10:18:29 +0000616 if (DisableX86LEAOpt || skipFunction(*MF.getFunction()))
Alexey Bataev7cf32472015-12-04 10:53:15 +0000617 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) {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000625 MemOpMap LEAs;
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000626 InstrPos.clear();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000627
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
Andrey Turetskiy45b22a42016-05-19 10:18:29 +0000635 // Remove redundant LEA instructions.
636 Changed |= removeRedundantLEAs(LEAs);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000637
Andrey Turetskiy45b22a42016-05-19 10:18:29 +0000638 // 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);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000642 }
643
644 return Changed;
645}