blob: 5a7b562cb1da1adefacd2d519d474ca8af58b5a0 [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
11// instructions in order to improve 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 +000047class MemOpKey;
48
49/// \brief Returns a hash table key based on memory operands of \p MI. The
50/// number of the first memory operand of \p MI is specified through \p N.
51static inline MemOpKey getMemOpKey(const MachineInstr &MI, unsigned N);
52
53/// \brief Returns true if two machine operands are identical and they are not
54/// physical registers.
55static inline bool isIdenticalOp(const MachineOperand &MO1,
56 const MachineOperand &MO2);
57
Andrey Turetskiy0babd262016-02-20 10:58:28 +000058/// \brief Returns true if two address displacement operands are of the same
59/// type and use the same symbol/index/address regardless of the offset.
60static bool isSimilarDispOp(const MachineOperand &MO1,
61 const MachineOperand &MO2);
62
Andrey Turetskiybca0f992016-02-04 08:57:03 +000063/// \brief Returns true if the instruction is LEA.
64static inline bool isLEA(const MachineInstr &MI);
65
66/// A key based on instruction's memory operands.
67class MemOpKey {
68public:
69 MemOpKey(const MachineOperand *Base, const MachineOperand *Scale,
70 const MachineOperand *Index, const MachineOperand *Segment,
71 const MachineOperand *Disp)
72 : Disp(Disp) {
73 Operands[0] = Base;
74 Operands[1] = Scale;
75 Operands[2] = Index;
76 Operands[3] = Segment;
77 }
78
79 bool operator==(const MemOpKey &Other) const {
80 // Addresses' bases, scales, indices and segments must be identical.
81 for (int i = 0; i < 4; ++i)
82 if (!isIdenticalOp(*Operands[i], *Other.Operands[i]))
83 return false;
84
Andrey Turetskiy0babd262016-02-20 10:58:28 +000085 // Addresses' displacements don't have to be exactly the same. It only
86 // matters that they use the same symbol/index/address. Immediates' or
87 // offsets' differences will be taken care of during instruction
88 // substitution.
89 return isSimilarDispOp(*Disp, *Other.Disp);
Andrey Turetskiybca0f992016-02-04 08:57:03 +000090 }
91
92 // Address' base, scale, index and segment operands.
93 const MachineOperand *Operands[4];
94
95 // Address' displacement operand.
96 const MachineOperand *Disp;
97};
98
99/// Provide DenseMapInfo for MemOpKey.
100namespace llvm {
101template <> struct DenseMapInfo<MemOpKey> {
102 typedef DenseMapInfo<const MachineOperand *> PtrInfo;
103
104 static inline MemOpKey getEmptyKey() {
105 return MemOpKey(PtrInfo::getEmptyKey(), PtrInfo::getEmptyKey(),
106 PtrInfo::getEmptyKey(), PtrInfo::getEmptyKey(),
107 PtrInfo::getEmptyKey());
108 }
109
110 static inline MemOpKey getTombstoneKey() {
111 return MemOpKey(PtrInfo::getTombstoneKey(), PtrInfo::getTombstoneKey(),
112 PtrInfo::getTombstoneKey(), PtrInfo::getTombstoneKey(),
113 PtrInfo::getTombstoneKey());
114 }
115
116 static unsigned getHashValue(const MemOpKey &Val) {
117 // Checking any field of MemOpKey is enough to determine if the key is
118 // empty or tombstone.
119 assert(Val.Disp != PtrInfo::getEmptyKey() && "Cannot hash the empty key");
120 assert(Val.Disp != PtrInfo::getTombstoneKey() &&
121 "Cannot hash the tombstone key");
122
123 hash_code Hash = hash_combine(*Val.Operands[0], *Val.Operands[1],
124 *Val.Operands[2], *Val.Operands[3]);
125
126 // If the address displacement is an immediate, it should not affect the
127 // hash so that memory operands which differ only be immediate displacement
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000128 // would have the same hash. If the address displacement is something else,
129 // we should reflect symbol/index/address in the hash.
130 switch (Val.Disp->getType()) {
131 case MachineOperand::MO_Immediate:
132 break;
133 case MachineOperand::MO_ConstantPoolIndex:
134 case MachineOperand::MO_JumpTableIndex:
135 Hash = hash_combine(Hash, Val.Disp->getIndex());
136 break;
137 case MachineOperand::MO_ExternalSymbol:
138 Hash = hash_combine(Hash, Val.Disp->getSymbolName());
139 break;
140 case MachineOperand::MO_GlobalAddress:
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000141 Hash = hash_combine(Hash, Val.Disp->getGlobal());
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000142 break;
143 case MachineOperand::MO_BlockAddress:
144 Hash = hash_combine(Hash, Val.Disp->getBlockAddress());
145 break;
146 case MachineOperand::MO_MCSymbol:
147 Hash = hash_combine(Hash, Val.Disp->getMCSymbol());
148 break;
149 default:
150 llvm_unreachable("Invalid address displacement operand");
151 }
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000152
153 return (unsigned)Hash;
154 }
155
156 static bool isEqual(const MemOpKey &LHS, const MemOpKey &RHS) {
157 // Checking any field of MemOpKey is enough to determine if the key is
158 // empty or tombstone.
159 if (RHS.Disp == PtrInfo::getEmptyKey())
160 return LHS.Disp == PtrInfo::getEmptyKey();
161 if (RHS.Disp == PtrInfo::getTombstoneKey())
162 return LHS.Disp == PtrInfo::getTombstoneKey();
163 return LHS == RHS;
164 }
165};
166}
167
168static inline MemOpKey getMemOpKey(const MachineInstr &MI, unsigned N) {
169 assert((isLEA(MI) || MI.mayLoadOrStore()) &&
170 "The instruction must be a LEA, a load or a store");
171 return MemOpKey(&MI.getOperand(N + X86::AddrBaseReg),
172 &MI.getOperand(N + X86::AddrScaleAmt),
173 &MI.getOperand(N + X86::AddrIndexReg),
174 &MI.getOperand(N + X86::AddrSegmentReg),
175 &MI.getOperand(N + X86::AddrDisp));
176}
177
178static inline bool isIdenticalOp(const MachineOperand &MO1,
179 const MachineOperand &MO2) {
180 return MO1.isIdenticalTo(MO2) &&
181 (!MO1.isReg() ||
182 !TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
183}
184
Justin Bogner38e52172016-02-24 07:58:02 +0000185#ifndef NDEBUG
186static bool isValidDispOp(const MachineOperand &MO) {
187 return MO.isImm() || MO.isCPI() || MO.isJTI() || MO.isSymbol() ||
188 MO.isGlobal() || MO.isBlockAddress() || MO.isMCSymbol();
189}
190#endif
191
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000192static bool isSimilarDispOp(const MachineOperand &MO1,
193 const MachineOperand &MO2) {
194 assert(isValidDispOp(MO1) && isValidDispOp(MO2) &&
195 "Address displacement operand is not valid");
196 return (MO1.isImm() && MO2.isImm()) ||
197 (MO1.isCPI() && MO2.isCPI() && MO1.getIndex() == MO2.getIndex()) ||
198 (MO1.isJTI() && MO2.isJTI() && MO1.getIndex() == MO2.getIndex()) ||
199 (MO1.isSymbol() && MO2.isSymbol() &&
200 MO1.getSymbolName() == MO2.getSymbolName()) ||
201 (MO1.isGlobal() && MO2.isGlobal() &&
202 MO1.getGlobal() == MO2.getGlobal()) ||
203 (MO1.isBlockAddress() && MO2.isBlockAddress() &&
204 MO1.getBlockAddress() == MO2.getBlockAddress()) ||
205 (MO1.isMCSymbol() && MO2.isMCSymbol() &&
206 MO1.getMCSymbol() == MO2.getMCSymbol());
207}
208
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000209static inline bool isLEA(const MachineInstr &MI) {
210 unsigned Opcode = MI.getOpcode();
211 return Opcode == X86::LEA16r || Opcode == X86::LEA32r ||
212 Opcode == X86::LEA64r || Opcode == X86::LEA64_32r;
213}
214
Alexey Bataev7cf32472015-12-04 10:53:15 +0000215namespace {
216class OptimizeLEAPass : public MachineFunctionPass {
217public:
218 OptimizeLEAPass() : MachineFunctionPass(ID) {}
219
220 const char *getPassName() const override { return "X86 LEA Optimize"; }
221
222 /// \brief Loop over all of the basic blocks, replacing address
223 /// calculations in load and store instructions, if it's already
224 /// been calculated by LEA. Also, remove redundant LEAs.
225 bool runOnMachineFunction(MachineFunction &MF) override;
226
227private:
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000228 typedef DenseMap<MemOpKey, SmallVector<MachineInstr *, 16>> MemOpMap;
229
Alexey Bataev7cf32472015-12-04 10:53:15 +0000230 /// \brief Returns a distance between two instructions inside one basic block.
231 /// Negative result means, that instructions occur in reverse order.
232 int calcInstrDist(const MachineInstr &First, const MachineInstr &Last);
233
234 /// \brief Choose the best \p LEA instruction from the \p List to replace
235 /// address calculation in \p MI instruction. Return the address displacement
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000236 /// and the distance between \p MI and the choosen \p BestLEA in
237 /// \p AddrDispShift and \p Dist.
Alexey Bataev7cf32472015-12-04 10:53:15 +0000238 bool chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000239 const MachineInstr &MI, MachineInstr *&BestLEA,
Alexey Bataev7cf32472015-12-04 10:53:15 +0000240 int64_t &AddrDispShift, int &Dist);
241
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000242 /// \brief Returns the difference between addresses' displacements of \p MI1
243 /// and \p MI2. The numbers of the first memory operands for the instructions
244 /// are specified through \p N1 and \p N2.
245 int64_t getAddrDispShift(const MachineInstr &MI1, unsigned N1,
246 const MachineInstr &MI2, unsigned N2) const;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000247
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000248 /// \brief Returns true if the \p Last LEA instruction can be replaced by the
249 /// \p First. The difference between displacements of the addresses calculated
250 /// by these LEAs is returned in \p AddrDispShift. It'll be used for proper
251 /// replacement of the \p Last LEA's uses with the \p First's def register.
252 bool isReplaceable(const MachineInstr &First, const MachineInstr &Last,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000253 int64_t &AddrDispShift) const;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000254
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000255 /// \brief Find all LEA instructions in the basic block. Also, assign position
256 /// numbers to all instructions in the basic block to speed up calculation of
257 /// distance between them.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000258 void findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000259
260 /// \brief Removes redundant address calculations.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000261 bool removeRedundantAddrCalc(MemOpMap &LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000262
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000263 /// \brief Removes LEAs which calculate similar addresses.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000264 bool removeRedundantLEAs(MemOpMap &LEAs);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000265
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000266 DenseMap<const MachineInstr *, unsigned> InstrPos;
267
Alexey Bataev7cf32472015-12-04 10:53:15 +0000268 MachineRegisterInfo *MRI;
269 const X86InstrInfo *TII;
270 const X86RegisterInfo *TRI;
271
272 static char ID;
273};
274char OptimizeLEAPass::ID = 0;
275}
276
277FunctionPass *llvm::createX86OptimizeLEAs() { return new OptimizeLEAPass(); }
278
279int OptimizeLEAPass::calcInstrDist(const MachineInstr &First,
280 const MachineInstr &Last) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000281 // Both instructions must be in the same basic block and they must be
282 // presented in InstrPos.
283 assert(Last.getParent() == First.getParent() &&
Alexey Bataev7cf32472015-12-04 10:53:15 +0000284 "Instructions are in different basic blocks");
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000285 assert(InstrPos.find(&First) != InstrPos.end() &&
286 InstrPos.find(&Last) != InstrPos.end() &&
287 "Instructions' positions are undefined");
Alexey Bataev7cf32472015-12-04 10:53:15 +0000288
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000289 return InstrPos[&Last] - InstrPos[&First];
Alexey Bataev7cf32472015-12-04 10:53:15 +0000290}
291
292// Find the best LEA instruction in the List to replace address recalculation in
293// MI. Such LEA must meet these requirements:
294// 1) The address calculated by the LEA differs only by the displacement from
295// the address used in MI.
296// 2) The register class of the definition of the LEA is compatible with the
297// register class of the address base register of MI.
298// 3) Displacement of the new memory operand should fit in 1 byte if possible.
299// 4) The LEA should be as close to MI as possible, and prior to it if
300// possible.
301bool OptimizeLEAPass::chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000302 const MachineInstr &MI,
303 MachineInstr *&BestLEA,
Alexey Bataev7cf32472015-12-04 10:53:15 +0000304 int64_t &AddrDispShift, int &Dist) {
305 const MachineFunction *MF = MI.getParent()->getParent();
306 const MCInstrDesc &Desc = MI.getDesc();
307 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags, MI.getOpcode()) +
308 X86II::getOperandBias(Desc);
309
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000310 BestLEA = nullptr;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000311
312 // Loop over all LEA instructions.
313 for (auto DefMI : List) {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000314 // Get new address displacement.
315 int64_t AddrDispShiftTemp = getAddrDispShift(MI, MemOpNo, *DefMI, 1);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000316
317 // Make sure address displacement fits 4 bytes.
318 if (!isInt<32>(AddrDispShiftTemp))
319 continue;
320
321 // Check that LEA def register can be used as MI address base. Some
322 // instructions can use a limited set of registers as address base, for
323 // example MOV8mr_NOREX. We could constrain the register class of the LEA
324 // def to suit MI, however since this case is very rare and hard to
325 // reproduce in a test it's just more reliable to skip the LEA.
326 if (TII->getRegClass(Desc, MemOpNo + X86::AddrBaseReg, TRI, *MF) !=
327 MRI->getRegClass(DefMI->getOperand(0).getReg()))
328 continue;
329
330 // Choose the closest LEA instruction from the list, prior to MI if
331 // possible. Note that we took into account resulting address displacement
332 // as well. Also note that the list is sorted by the order in which the LEAs
333 // occur, so the break condition is pretty simple.
334 int DistTemp = calcInstrDist(*DefMI, MI);
335 assert(DistTemp != 0 &&
336 "The distance between two different instructions cannot be zero");
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000337 if (DistTemp > 0 || BestLEA == nullptr) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000338 // Do not update return LEA, if the current one provides a displacement
339 // which fits in 1 byte, while the new candidate does not.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000340 if (BestLEA != nullptr && !isInt<8>(AddrDispShiftTemp) &&
Alexey Bataev7cf32472015-12-04 10:53:15 +0000341 isInt<8>(AddrDispShift))
342 continue;
343
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000344 BestLEA = DefMI;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000345 AddrDispShift = AddrDispShiftTemp;
346 Dist = DistTemp;
347 }
348
349 // FIXME: Maybe we should not always stop at the first LEA after MI.
350 if (DistTemp < 0)
351 break;
352 }
353
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000354 return BestLEA != nullptr;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000355}
356
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000357// Get the difference between the addresses' displacements of the two
358// instructions \p MI1 and \p MI2. The numbers of the first memory operands are
359// passed through \p N1 and \p N2.
360int64_t OptimizeLEAPass::getAddrDispShift(const MachineInstr &MI1, unsigned N1,
361 const MachineInstr &MI2,
362 unsigned N2) const {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000363 const MachineOperand &Op1 = MI1.getOperand(N1 + X86::AddrDisp);
364 const MachineOperand &Op2 = MI2.getOperand(N2 + X86::AddrDisp);
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000365
366 assert(isSimilarDispOp(Op1, Op2) &&
367 "Address displacement operands are not compatible");
368
369 // After the assert above we can be sure that both operands are of the same
370 // valid type and use the same symbol/index/address, thus displacement shift
371 // calculation is rather simple.
372 if (Op1.isJTI())
373 return 0;
374 return Op1.isImm() ? Op1.getImm() - Op2.getImm()
375 : Op1.getOffset() - Op2.getOffset();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000376}
377
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000378// Check that the Last LEA can be replaced by the First LEA. To be so,
379// these requirements must be met:
380// 1) Addresses calculated by LEAs differ only by displacement.
381// 2) Def registers of LEAs belong to the same class.
382// 3) All uses of the Last LEA def register are replaceable, thus the
383// register is used only as address base.
384bool OptimizeLEAPass::isReplaceable(const MachineInstr &First,
385 const MachineInstr &Last,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000386 int64_t &AddrDispShift) const {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000387 assert(isLEA(First) && isLEA(Last) &&
388 "The function works only with LEA instructions");
389
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000390 // Get new address displacement.
391 AddrDispShift = getAddrDispShift(Last, 1, First, 1);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000392
393 // Make sure that LEA def registers belong to the same class. There may be
394 // instructions (like MOV8mr_NOREX) which allow a limited set of registers to
395 // be used as their operands, so we must be sure that replacing one LEA
396 // with another won't lead to putting a wrong register in the instruction.
397 if (MRI->getRegClass(First.getOperand(0).getReg()) !=
398 MRI->getRegClass(Last.getOperand(0).getReg()))
399 return false;
400
401 // Loop over all uses of the Last LEA to check that its def register is
402 // used only as address base for memory accesses. If so, it can be
403 // replaced, otherwise - no.
404 for (auto &MO : MRI->use_operands(Last.getOperand(0).getReg())) {
405 MachineInstr &MI = *MO.getParent();
406
407 // Get the number of the first memory operand.
408 const MCInstrDesc &Desc = MI.getDesc();
409 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags, MI.getOpcode());
410
411 // If the use instruction has no memory operand - the LEA is not
412 // replaceable.
413 if (MemOpNo < 0)
414 return false;
415
416 MemOpNo += X86II::getOperandBias(Desc);
417
418 // If the address base of the use instruction is not the LEA def register -
419 // the LEA is not replaceable.
420 if (!isIdenticalOp(MI.getOperand(MemOpNo + X86::AddrBaseReg), MO))
421 return false;
422
423 // If the LEA def register is used as any other operand of the use
424 // instruction - the LEA is not replaceable.
425 for (unsigned i = 0; i < MI.getNumOperands(); i++)
426 if (i != (unsigned)(MemOpNo + X86::AddrBaseReg) &&
427 isIdenticalOp(MI.getOperand(i), MO))
428 return false;
429
430 // Check that the new address displacement will fit 4 bytes.
431 if (MI.getOperand(MemOpNo + X86::AddrDisp).isImm() &&
432 !isInt<32>(MI.getOperand(MemOpNo + X86::AddrDisp).getImm() +
433 AddrDispShift))
434 return false;
435 }
436
437 return true;
438}
439
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000440void OptimizeLEAPass::findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000441 unsigned Pos = 0;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000442 for (auto &MI : MBB) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000443 // Assign the position number to the instruction. Note that we are going to
444 // move some instructions during the optimization however there will never
445 // be a need to move two instructions before any selected instruction. So to
446 // avoid multiple positions' updates during moves we just increase position
447 // counter by two leaving a free space for instructions which will be moved.
448 InstrPos[&MI] = Pos += 2;
449
Alexey Bataev7cf32472015-12-04 10:53:15 +0000450 if (isLEA(MI))
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000451 LEAs[getMemOpKey(MI, 1)].push_back(const_cast<MachineInstr *>(&MI));
Alexey Bataev7cf32472015-12-04 10:53:15 +0000452 }
453}
454
455// Try to find load and store instructions which recalculate addresses already
456// calculated by some LEA and replace their memory operands with its def
457// register.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000458bool OptimizeLEAPass::removeRedundantAddrCalc(MemOpMap &LEAs) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000459 bool Changed = false;
460
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000461 assert(!LEAs.empty());
462 MachineBasicBlock *MBB = (*LEAs.begin()->second.begin())->getParent();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000463
464 // Process all instructions in basic block.
465 for (auto I = MBB->begin(), E = MBB->end(); I != E;) {
466 MachineInstr &MI = *I++;
467 unsigned Opcode = MI.getOpcode();
468
469 // Instruction must be load or store.
470 if (!MI.mayLoadOrStore())
471 continue;
472
473 // Get the number of the first memory operand.
474 const MCInstrDesc &Desc = MI.getDesc();
475 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags, Opcode);
476
477 // If instruction has no memory operand - skip it.
478 if (MemOpNo < 0)
479 continue;
480
481 MemOpNo += X86II::getOperandBias(Desc);
482
483 // Get the best LEA instruction to replace address calculation.
484 MachineInstr *DefMI;
485 int64_t AddrDispShift;
486 int Dist;
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000487 if (!chooseBestLEA(LEAs[getMemOpKey(MI, MemOpNo)], MI, DefMI, AddrDispShift,
488 Dist))
Alexey Bataev7cf32472015-12-04 10:53:15 +0000489 continue;
490
491 // If LEA occurs before current instruction, we can freely replace
492 // the instruction. If LEA occurs after, we can lift LEA above the
493 // instruction and this way to be able to replace it. Since LEA and the
494 // instruction have similar memory operands (thus, the same def
495 // instructions for these operands), we can always do that, without
496 // worries of using registers before their defs.
497 if (Dist < 0) {
498 DefMI->removeFromParent();
499 MBB->insert(MachineBasicBlock::iterator(&MI), DefMI);
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000500 InstrPos[DefMI] = InstrPos[&MI] - 1;
501
502 // Make sure the instructions' position numbers are sane.
503 assert(((InstrPos[DefMI] == 1 && DefMI == MBB->begin()) ||
504 InstrPos[DefMI] >
505 InstrPos[std::prev(MachineBasicBlock::iterator(DefMI))]) &&
506 "Instruction positioning is broken");
Alexey Bataev7cf32472015-12-04 10:53:15 +0000507 }
508
509 // Since we can possibly extend register lifetime, clear kill flags.
510 MRI->clearKillFlags(DefMI->getOperand(0).getReg());
511
512 ++NumSubstLEAs;
513 DEBUG(dbgs() << "OptimizeLEAs: Candidate to replace: "; MI.dump(););
514
515 // Change instruction operands.
516 MI.getOperand(MemOpNo + X86::AddrBaseReg)
517 .ChangeToRegister(DefMI->getOperand(0).getReg(), false);
518 MI.getOperand(MemOpNo + X86::AddrScaleAmt).ChangeToImmediate(1);
519 MI.getOperand(MemOpNo + X86::AddrIndexReg)
520 .ChangeToRegister(X86::NoRegister, false);
521 MI.getOperand(MemOpNo + X86::AddrDisp).ChangeToImmediate(AddrDispShift);
522 MI.getOperand(MemOpNo + X86::AddrSegmentReg)
523 .ChangeToRegister(X86::NoRegister, false);
524
525 DEBUG(dbgs() << "OptimizeLEAs: Replaced by: "; MI.dump(););
526
527 Changed = true;
528 }
529
530 return Changed;
531}
532
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000533// Try to find similar LEAs in the list and replace one with another.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000534bool OptimizeLEAPass::removeRedundantLEAs(MemOpMap &LEAs) {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000535 bool Changed = false;
536
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000537 // Loop over all entries in the table.
538 for (auto &E : LEAs) {
539 auto &List = E.second;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000540
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000541 // Loop over all LEA pairs.
542 auto I1 = List.begin();
543 while (I1 != List.end()) {
544 MachineInstr &First = **I1;
545 auto I2 = std::next(I1);
546 while (I2 != List.end()) {
547 MachineInstr &Last = **I2;
548 int64_t AddrDispShift;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000549
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000550 // LEAs should be in occurence order in the list, so we can freely
551 // replace later LEAs with earlier ones.
552 assert(calcInstrDist(First, Last) > 0 &&
553 "LEAs must be in occurence order in the list");
554
555 // Check that the Last LEA instruction can be replaced by the First.
556 if (!isReplaceable(First, Last, AddrDispShift)) {
557 ++I2;
558 continue;
559 }
560
561 // Loop over all uses of the Last LEA and update their operands. Note
562 // that the correctness of this has already been checked in the
563 // isReplaceable function.
564 for (auto UI = MRI->use_begin(Last.getOperand(0).getReg()),
565 UE = MRI->use_end();
566 UI != UE;) {
567 MachineOperand &MO = *UI++;
568 MachineInstr &MI = *MO.getParent();
569
570 // Get the number of the first memory operand.
571 const MCInstrDesc &Desc = MI.getDesc();
572 int MemOpNo =
573 X86II::getMemoryOperandNo(Desc.TSFlags, MI.getOpcode()) +
574 X86II::getOperandBias(Desc);
575
576 // Update address base.
577 MO.setReg(First.getOperand(0).getReg());
578
579 // Update address disp.
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000580 MachineOperand &Op = MI.getOperand(MemOpNo + X86::AddrDisp);
581 if (Op.isImm())
582 Op.setImm(Op.getImm() + AddrDispShift);
583 else if (!Op.isJTI())
584 Op.setOffset(Op.getOffset() + AddrDispShift);
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000585 }
586
587 // Since we can possibly extend register lifetime, clear kill flags.
588 MRI->clearKillFlags(First.getOperand(0).getReg());
589
590 ++NumRedundantLEAs;
591 DEBUG(dbgs() << "OptimizeLEAs: Remove redundant LEA: "; Last.dump(););
592
593 // By this moment, all of the Last LEA's uses must be replaced. So we
594 // can freely remove it.
595 assert(MRI->use_empty(Last.getOperand(0).getReg()) &&
596 "The LEA's def register must have no uses");
597 Last.eraseFromParent();
598
599 // Erase removed LEA from the list.
600 I2 = List.erase(I2);
601
602 Changed = true;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000603 }
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000604 ++I1;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000605 }
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000606 }
607
608 return Changed;
609}
610
Alexey Bataev7cf32472015-12-04 10:53:15 +0000611bool OptimizeLEAPass::runOnMachineFunction(MachineFunction &MF) {
612 bool Changed = false;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000613
614 // Perform this optimization only if we care about code size.
Andrey Turetskiy9994b882016-02-20 11:11:55 +0000615 if (DisableX86LEAOpt || !MF.getFunction()->optForSize())
Alexey Bataev7cf32472015-12-04 10:53:15 +0000616 return false;
617
618 MRI = &MF.getRegInfo();
619 TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
620 TRI = MF.getSubtarget<X86Subtarget>().getRegisterInfo();
621
622 // Process all basic blocks.
623 for (auto &MBB : MF) {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000624 MemOpMap LEAs;
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000625 InstrPos.clear();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000626
627 // Find all LEA instructions in basic block.
628 findLEAs(MBB, LEAs);
629
630 // If current basic block has no LEAs, move on to the next one.
631 if (LEAs.empty())
632 continue;
633
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000634 // Remove redundant LEA instructions. The optimization may have a negative
635 // effect on performance, so do it only for -Oz.
636 if (MF.getFunction()->optForMinSize())
637 Changed |= removeRedundantLEAs(LEAs);
638
Alexey Bataev7cf32472015-12-04 10:53:15 +0000639 // Remove redundant address calculations.
640 Changed |= removeRedundantAddrCalc(LEAs);
641 }
642
643 return Changed;
644}