blob: 1a3a0951a74ecbb5c9c1e765a025d06a4a581972 [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
Hans Wennborg84047892016-02-17 02:49:59 +000039static cl::opt<bool> EnableX86LEAOpt("enable-x86-lea-opt", cl::Hidden,
40 cl::desc("X86: Enable LEA optimizations."),
41 cl::init(false));
Alexey Bataev7b72b652015-12-17 07:34:39 +000042
Alexey Bataev7cf32472015-12-04 10:53:15 +000043STATISTIC(NumSubstLEAs, "Number of LEA instruction substitutions");
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +000044STATISTIC(NumRedundantLEAs, "Number of redundant LEA instructions removed");
Alexey Bataev7cf32472015-12-04 10:53:15 +000045
Andrey Turetskiybca0f992016-02-04 08:57:03 +000046class MemOpKey;
47
48/// \brief Returns a hash table key based on memory operands of \p MI. The
49/// number of the first memory operand of \p MI is specified through \p N.
50static inline MemOpKey getMemOpKey(const MachineInstr &MI, unsigned N);
51
52/// \brief Returns true if two machine operands are identical and they are not
53/// physical registers.
54static inline bool isIdenticalOp(const MachineOperand &MO1,
55 const MachineOperand &MO2);
56
Andrey Turetskiy0babd262016-02-20 10:58:28 +000057/// \brief Returns true if two address displacement operands are of the same
58/// type and use the same symbol/index/address regardless of the offset.
59static bool isSimilarDispOp(const MachineOperand &MO1,
60 const MachineOperand &MO2);
61
62/// \brief Returns true if the type of \p MO is valid for address displacement
63/// operand. According to X86DAGToDAGISel::getAddressOperands allowed types are:
64/// MO_Immediate, MO_ConstantPoolIndex, MO_JumpTableIndex, MO_ExternalSymbol,
65/// MO_GlobalAddress, MO_BlockAddress or MO_MCSymbol.
66static inline bool isValidDispOp(const MachineOperand &MO);
67
Andrey Turetskiybca0f992016-02-04 08:57:03 +000068/// \brief Returns true if the instruction is LEA.
69static inline bool isLEA(const MachineInstr &MI);
70
71/// A key based on instruction's memory operands.
72class MemOpKey {
73public:
74 MemOpKey(const MachineOperand *Base, const MachineOperand *Scale,
75 const MachineOperand *Index, const MachineOperand *Segment,
76 const MachineOperand *Disp)
77 : Disp(Disp) {
78 Operands[0] = Base;
79 Operands[1] = Scale;
80 Operands[2] = Index;
81 Operands[3] = Segment;
82 }
83
84 bool operator==(const MemOpKey &Other) const {
85 // Addresses' bases, scales, indices and segments must be identical.
86 for (int i = 0; i < 4; ++i)
87 if (!isIdenticalOp(*Operands[i], *Other.Operands[i]))
88 return false;
89
Andrey Turetskiy0babd262016-02-20 10:58:28 +000090 // Addresses' displacements don't have to be exactly the same. It only
91 // matters that they use the same symbol/index/address. Immediates' or
92 // offsets' differences will be taken care of during instruction
93 // substitution.
94 return isSimilarDispOp(*Disp, *Other.Disp);
Andrey Turetskiybca0f992016-02-04 08:57:03 +000095 }
96
97 // Address' base, scale, index and segment operands.
98 const MachineOperand *Operands[4];
99
100 // Address' displacement operand.
101 const MachineOperand *Disp;
102};
103
104/// Provide DenseMapInfo for MemOpKey.
105namespace llvm {
106template <> struct DenseMapInfo<MemOpKey> {
107 typedef DenseMapInfo<const MachineOperand *> PtrInfo;
108
109 static inline MemOpKey getEmptyKey() {
110 return MemOpKey(PtrInfo::getEmptyKey(), PtrInfo::getEmptyKey(),
111 PtrInfo::getEmptyKey(), PtrInfo::getEmptyKey(),
112 PtrInfo::getEmptyKey());
113 }
114
115 static inline MemOpKey getTombstoneKey() {
116 return MemOpKey(PtrInfo::getTombstoneKey(), PtrInfo::getTombstoneKey(),
117 PtrInfo::getTombstoneKey(), PtrInfo::getTombstoneKey(),
118 PtrInfo::getTombstoneKey());
119 }
120
121 static unsigned getHashValue(const MemOpKey &Val) {
122 // Checking any field of MemOpKey is enough to determine if the key is
123 // empty or tombstone.
124 assert(Val.Disp != PtrInfo::getEmptyKey() && "Cannot hash the empty key");
125 assert(Val.Disp != PtrInfo::getTombstoneKey() &&
126 "Cannot hash the tombstone key");
127
128 hash_code Hash = hash_combine(*Val.Operands[0], *Val.Operands[1],
129 *Val.Operands[2], *Val.Operands[3]);
130
131 // If the address displacement is an immediate, it should not affect the
132 // hash so that memory operands which differ only be immediate displacement
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000133 // would have the same hash. If the address displacement is something else,
134 // we should reflect symbol/index/address in the hash.
135 switch (Val.Disp->getType()) {
136 case MachineOperand::MO_Immediate:
137 break;
138 case MachineOperand::MO_ConstantPoolIndex:
139 case MachineOperand::MO_JumpTableIndex:
140 Hash = hash_combine(Hash, Val.Disp->getIndex());
141 break;
142 case MachineOperand::MO_ExternalSymbol:
143 Hash = hash_combine(Hash, Val.Disp->getSymbolName());
144 break;
145 case MachineOperand::MO_GlobalAddress:
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000146 Hash = hash_combine(Hash, Val.Disp->getGlobal());
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000147 break;
148 case MachineOperand::MO_BlockAddress:
149 Hash = hash_combine(Hash, Val.Disp->getBlockAddress());
150 break;
151 case MachineOperand::MO_MCSymbol:
152 Hash = hash_combine(Hash, Val.Disp->getMCSymbol());
153 break;
154 default:
155 llvm_unreachable("Invalid address displacement operand");
156 }
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000157
158 return (unsigned)Hash;
159 }
160
161 static bool isEqual(const MemOpKey &LHS, const MemOpKey &RHS) {
162 // Checking any field of MemOpKey is enough to determine if the key is
163 // empty or tombstone.
164 if (RHS.Disp == PtrInfo::getEmptyKey())
165 return LHS.Disp == PtrInfo::getEmptyKey();
166 if (RHS.Disp == PtrInfo::getTombstoneKey())
167 return LHS.Disp == PtrInfo::getTombstoneKey();
168 return LHS == RHS;
169 }
170};
171}
172
173static inline MemOpKey getMemOpKey(const MachineInstr &MI, unsigned N) {
174 assert((isLEA(MI) || MI.mayLoadOrStore()) &&
175 "The instruction must be a LEA, a load or a store");
176 return MemOpKey(&MI.getOperand(N + X86::AddrBaseReg),
177 &MI.getOperand(N + X86::AddrScaleAmt),
178 &MI.getOperand(N + X86::AddrIndexReg),
179 &MI.getOperand(N + X86::AddrSegmentReg),
180 &MI.getOperand(N + X86::AddrDisp));
181}
182
183static inline bool isIdenticalOp(const MachineOperand &MO1,
184 const MachineOperand &MO2) {
185 return MO1.isIdenticalTo(MO2) &&
186 (!MO1.isReg() ||
187 !TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
188}
189
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000190static bool isSimilarDispOp(const MachineOperand &MO1,
191 const MachineOperand &MO2) {
192 assert(isValidDispOp(MO1) && isValidDispOp(MO2) &&
193 "Address displacement operand is not valid");
194 return (MO1.isImm() && MO2.isImm()) ||
195 (MO1.isCPI() && MO2.isCPI() && MO1.getIndex() == MO2.getIndex()) ||
196 (MO1.isJTI() && MO2.isJTI() && MO1.getIndex() == MO2.getIndex()) ||
197 (MO1.isSymbol() && MO2.isSymbol() &&
198 MO1.getSymbolName() == MO2.getSymbolName()) ||
199 (MO1.isGlobal() && MO2.isGlobal() &&
200 MO1.getGlobal() == MO2.getGlobal()) ||
201 (MO1.isBlockAddress() && MO2.isBlockAddress() &&
202 MO1.getBlockAddress() == MO2.getBlockAddress()) ||
203 (MO1.isMCSymbol() && MO2.isMCSymbol() &&
204 MO1.getMCSymbol() == MO2.getMCSymbol());
205}
206
207static inline bool isValidDispOp(const MachineOperand &MO) {
208 return MO.isImm() || MO.isCPI() || MO.isJTI() || MO.isSymbol() ||
209 MO.isGlobal() || MO.isBlockAddress() || MO.isMCSymbol();
210}
211
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000212static inline bool isLEA(const MachineInstr &MI) {
213 unsigned Opcode = MI.getOpcode();
214 return Opcode == X86::LEA16r || Opcode == X86::LEA32r ||
215 Opcode == X86::LEA64r || Opcode == X86::LEA64_32r;
216}
217
Alexey Bataev7cf32472015-12-04 10:53:15 +0000218namespace {
219class OptimizeLEAPass : public MachineFunctionPass {
220public:
221 OptimizeLEAPass() : MachineFunctionPass(ID) {}
222
223 const char *getPassName() const override { return "X86 LEA Optimize"; }
224
225 /// \brief Loop over all of the basic blocks, replacing address
226 /// calculations in load and store instructions, if it's already
227 /// been calculated by LEA. Also, remove redundant LEAs.
228 bool runOnMachineFunction(MachineFunction &MF) override;
229
230private:
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000231 typedef DenseMap<MemOpKey, SmallVector<MachineInstr *, 16>> MemOpMap;
232
Alexey Bataev7cf32472015-12-04 10:53:15 +0000233 /// \brief Returns a distance between two instructions inside one basic block.
234 /// Negative result means, that instructions occur in reverse order.
235 int calcInstrDist(const MachineInstr &First, const MachineInstr &Last);
236
237 /// \brief Choose the best \p LEA instruction from the \p List to replace
238 /// address calculation in \p MI instruction. Return the address displacement
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000239 /// and the distance between \p MI and the choosen \p BestLEA in
240 /// \p AddrDispShift and \p Dist.
Alexey Bataev7cf32472015-12-04 10:53:15 +0000241 bool chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000242 const MachineInstr &MI, MachineInstr *&BestLEA,
Alexey Bataev7cf32472015-12-04 10:53:15 +0000243 int64_t &AddrDispShift, int &Dist);
244
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000245 /// \brief Returns the difference between addresses' displacements of \p MI1
246 /// and \p MI2. The numbers of the first memory operands for the instructions
247 /// are specified through \p N1 and \p N2.
248 int64_t getAddrDispShift(const MachineInstr &MI1, unsigned N1,
249 const MachineInstr &MI2, unsigned N2) const;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000250
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000251 /// \brief Returns true if the \p Last LEA instruction can be replaced by the
252 /// \p First. The difference between displacements of the addresses calculated
253 /// by these LEAs is returned in \p AddrDispShift. It'll be used for proper
254 /// replacement of the \p Last LEA's uses with the \p First's def register.
255 bool isReplaceable(const MachineInstr &First, const MachineInstr &Last,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000256 int64_t &AddrDispShift) const;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000257
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000258 /// \brief Find all LEA instructions in the basic block. Also, assign position
259 /// numbers to all instructions in the basic block to speed up calculation of
260 /// distance between them.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000261 void findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000262
263 /// \brief Removes redundant address calculations.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000264 bool removeRedundantAddrCalc(MemOpMap &LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000265
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000266 /// \brief Removes LEAs which calculate similar addresses.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000267 bool removeRedundantLEAs(MemOpMap &LEAs);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000268
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000269 DenseMap<const MachineInstr *, unsigned> InstrPos;
270
Alexey Bataev7cf32472015-12-04 10:53:15 +0000271 MachineRegisterInfo *MRI;
272 const X86InstrInfo *TII;
273 const X86RegisterInfo *TRI;
274
275 static char ID;
276};
277char OptimizeLEAPass::ID = 0;
278}
279
280FunctionPass *llvm::createX86OptimizeLEAs() { return new OptimizeLEAPass(); }
281
282int OptimizeLEAPass::calcInstrDist(const MachineInstr &First,
283 const MachineInstr &Last) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000284 // Both instructions must be in the same basic block and they must be
285 // presented in InstrPos.
286 assert(Last.getParent() == First.getParent() &&
Alexey Bataev7cf32472015-12-04 10:53:15 +0000287 "Instructions are in different basic blocks");
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000288 assert(InstrPos.find(&First) != InstrPos.end() &&
289 InstrPos.find(&Last) != InstrPos.end() &&
290 "Instructions' positions are undefined");
Alexey Bataev7cf32472015-12-04 10:53:15 +0000291
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000292 return InstrPos[&Last] - InstrPos[&First];
Alexey Bataev7cf32472015-12-04 10:53:15 +0000293}
294
295// Find the best LEA instruction in the List to replace address recalculation in
296// MI. Such LEA must meet these requirements:
297// 1) The address calculated by the LEA differs only by the displacement from
298// the address used in MI.
299// 2) The register class of the definition of the LEA is compatible with the
300// register class of the address base register of MI.
301// 3) Displacement of the new memory operand should fit in 1 byte if possible.
302// 4) The LEA should be as close to MI as possible, and prior to it if
303// possible.
304bool OptimizeLEAPass::chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000305 const MachineInstr &MI,
306 MachineInstr *&BestLEA,
Alexey Bataev7cf32472015-12-04 10:53:15 +0000307 int64_t &AddrDispShift, int &Dist) {
308 const MachineFunction *MF = MI.getParent()->getParent();
309 const MCInstrDesc &Desc = MI.getDesc();
310 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags, MI.getOpcode()) +
311 X86II::getOperandBias(Desc);
312
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000313 BestLEA = nullptr;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000314
315 // Loop over all LEA instructions.
316 for (auto DefMI : List) {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000317 // Get new address displacement.
318 int64_t AddrDispShiftTemp = getAddrDispShift(MI, MemOpNo, *DefMI, 1);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000319
320 // Make sure address displacement fits 4 bytes.
321 if (!isInt<32>(AddrDispShiftTemp))
322 continue;
323
324 // Check that LEA def register can be used as MI address base. Some
325 // instructions can use a limited set of registers as address base, for
326 // example MOV8mr_NOREX. We could constrain the register class of the LEA
327 // def to suit MI, however since this case is very rare and hard to
328 // reproduce in a test it's just more reliable to skip the LEA.
329 if (TII->getRegClass(Desc, MemOpNo + X86::AddrBaseReg, TRI, *MF) !=
330 MRI->getRegClass(DefMI->getOperand(0).getReg()))
331 continue;
332
333 // Choose the closest LEA instruction from the list, prior to MI if
334 // possible. Note that we took into account resulting address displacement
335 // as well. Also note that the list is sorted by the order in which the LEAs
336 // occur, so the break condition is pretty simple.
337 int DistTemp = calcInstrDist(*DefMI, MI);
338 assert(DistTemp != 0 &&
339 "The distance between two different instructions cannot be zero");
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000340 if (DistTemp > 0 || BestLEA == nullptr) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000341 // Do not update return LEA, if the current one provides a displacement
342 // which fits in 1 byte, while the new candidate does not.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000343 if (BestLEA != nullptr && !isInt<8>(AddrDispShiftTemp) &&
Alexey Bataev7cf32472015-12-04 10:53:15 +0000344 isInt<8>(AddrDispShift))
345 continue;
346
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000347 BestLEA = DefMI;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000348 AddrDispShift = AddrDispShiftTemp;
349 Dist = DistTemp;
350 }
351
352 // FIXME: Maybe we should not always stop at the first LEA after MI.
353 if (DistTemp < 0)
354 break;
355 }
356
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000357 return BestLEA != nullptr;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000358}
359
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000360// Get the difference between the addresses' displacements of the two
361// instructions \p MI1 and \p MI2. The numbers of the first memory operands are
362// passed through \p N1 and \p N2.
363int64_t OptimizeLEAPass::getAddrDispShift(const MachineInstr &MI1, unsigned N1,
364 const MachineInstr &MI2,
365 unsigned N2) const {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000366 const MachineOperand &Op1 = MI1.getOperand(N1 + X86::AddrDisp);
367 const MachineOperand &Op2 = MI2.getOperand(N2 + X86::AddrDisp);
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000368
369 assert(isSimilarDispOp(Op1, Op2) &&
370 "Address displacement operands are not compatible");
371
372 // After the assert above we can be sure that both operands are of the same
373 // valid type and use the same symbol/index/address, thus displacement shift
374 // calculation is rather simple.
375 if (Op1.isJTI())
376 return 0;
377 return Op1.isImm() ? Op1.getImm() - Op2.getImm()
378 : Op1.getOffset() - Op2.getOffset();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000379}
380
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000381// Check that the Last LEA can be replaced by the First LEA. To be so,
382// these requirements must be met:
383// 1) Addresses calculated by LEAs differ only by displacement.
384// 2) Def registers of LEAs belong to the same class.
385// 3) All uses of the Last LEA def register are replaceable, thus the
386// register is used only as address base.
387bool OptimizeLEAPass::isReplaceable(const MachineInstr &First,
388 const MachineInstr &Last,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000389 int64_t &AddrDispShift) const {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000390 assert(isLEA(First) && isLEA(Last) &&
391 "The function works only with LEA instructions");
392
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000393 // Get new address displacement.
394 AddrDispShift = getAddrDispShift(Last, 1, First, 1);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000395
396 // Make sure that LEA def registers belong to the same class. There may be
397 // instructions (like MOV8mr_NOREX) which allow a limited set of registers to
398 // be used as their operands, so we must be sure that replacing one LEA
399 // with another won't lead to putting a wrong register in the instruction.
400 if (MRI->getRegClass(First.getOperand(0).getReg()) !=
401 MRI->getRegClass(Last.getOperand(0).getReg()))
402 return false;
403
404 // Loop over all uses of the Last LEA to check that its def register is
405 // used only as address base for memory accesses. If so, it can be
406 // replaced, otherwise - no.
407 for (auto &MO : MRI->use_operands(Last.getOperand(0).getReg())) {
408 MachineInstr &MI = *MO.getParent();
409
410 // Get the number of the first memory operand.
411 const MCInstrDesc &Desc = MI.getDesc();
412 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags, MI.getOpcode());
413
414 // If the use instruction has no memory operand - the LEA is not
415 // replaceable.
416 if (MemOpNo < 0)
417 return false;
418
419 MemOpNo += X86II::getOperandBias(Desc);
420
421 // If the address base of the use instruction is not the LEA def register -
422 // the LEA is not replaceable.
423 if (!isIdenticalOp(MI.getOperand(MemOpNo + X86::AddrBaseReg), MO))
424 return false;
425
426 // If the LEA def register is used as any other operand of the use
427 // instruction - the LEA is not replaceable.
428 for (unsigned i = 0; i < MI.getNumOperands(); i++)
429 if (i != (unsigned)(MemOpNo + X86::AddrBaseReg) &&
430 isIdenticalOp(MI.getOperand(i), MO))
431 return false;
432
433 // Check that the new address displacement will fit 4 bytes.
434 if (MI.getOperand(MemOpNo + X86::AddrDisp).isImm() &&
435 !isInt<32>(MI.getOperand(MemOpNo + X86::AddrDisp).getImm() +
436 AddrDispShift))
437 return false;
438 }
439
440 return true;
441}
442
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000443void OptimizeLEAPass::findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000444 unsigned Pos = 0;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000445 for (auto &MI : MBB) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000446 // Assign the position number to the instruction. Note that we are going to
447 // move some instructions during the optimization however there will never
448 // be a need to move two instructions before any selected instruction. So to
449 // avoid multiple positions' updates during moves we just increase position
450 // counter by two leaving a free space for instructions which will be moved.
451 InstrPos[&MI] = Pos += 2;
452
Alexey Bataev7cf32472015-12-04 10:53:15 +0000453 if (isLEA(MI))
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000454 LEAs[getMemOpKey(MI, 1)].push_back(const_cast<MachineInstr *>(&MI));
Alexey Bataev7cf32472015-12-04 10:53:15 +0000455 }
456}
457
458// Try to find load and store instructions which recalculate addresses already
459// calculated by some LEA and replace their memory operands with its def
460// register.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000461bool OptimizeLEAPass::removeRedundantAddrCalc(MemOpMap &LEAs) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000462 bool Changed = false;
463
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000464 assert(!LEAs.empty());
465 MachineBasicBlock *MBB = (*LEAs.begin()->second.begin())->getParent();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000466
467 // Process all instructions in basic block.
468 for (auto I = MBB->begin(), E = MBB->end(); I != E;) {
469 MachineInstr &MI = *I++;
470 unsigned Opcode = MI.getOpcode();
471
472 // Instruction must be load or store.
473 if (!MI.mayLoadOrStore())
474 continue;
475
476 // Get the number of the first memory operand.
477 const MCInstrDesc &Desc = MI.getDesc();
478 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags, Opcode);
479
480 // If instruction has no memory operand - skip it.
481 if (MemOpNo < 0)
482 continue;
483
484 MemOpNo += X86II::getOperandBias(Desc);
485
486 // Get the best LEA instruction to replace address calculation.
487 MachineInstr *DefMI;
488 int64_t AddrDispShift;
489 int Dist;
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000490 if (!chooseBestLEA(LEAs[getMemOpKey(MI, MemOpNo)], MI, DefMI, AddrDispShift,
491 Dist))
Alexey Bataev7cf32472015-12-04 10:53:15 +0000492 continue;
493
494 // If LEA occurs before current instruction, we can freely replace
495 // the instruction. If LEA occurs after, we can lift LEA above the
496 // instruction and this way to be able to replace it. Since LEA and the
497 // instruction have similar memory operands (thus, the same def
498 // instructions for these operands), we can always do that, without
499 // worries of using registers before their defs.
500 if (Dist < 0) {
501 DefMI->removeFromParent();
502 MBB->insert(MachineBasicBlock::iterator(&MI), DefMI);
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000503 InstrPos[DefMI] = InstrPos[&MI] - 1;
504
505 // Make sure the instructions' position numbers are sane.
506 assert(((InstrPos[DefMI] == 1 && DefMI == MBB->begin()) ||
507 InstrPos[DefMI] >
508 InstrPos[std::prev(MachineBasicBlock::iterator(DefMI))]) &&
509 "Instruction positioning is broken");
Alexey Bataev7cf32472015-12-04 10:53:15 +0000510 }
511
512 // Since we can possibly extend register lifetime, clear kill flags.
513 MRI->clearKillFlags(DefMI->getOperand(0).getReg());
514
515 ++NumSubstLEAs;
516 DEBUG(dbgs() << "OptimizeLEAs: Candidate to replace: "; MI.dump(););
517
518 // Change instruction operands.
519 MI.getOperand(MemOpNo + X86::AddrBaseReg)
520 .ChangeToRegister(DefMI->getOperand(0).getReg(), false);
521 MI.getOperand(MemOpNo + X86::AddrScaleAmt).ChangeToImmediate(1);
522 MI.getOperand(MemOpNo + X86::AddrIndexReg)
523 .ChangeToRegister(X86::NoRegister, false);
524 MI.getOperand(MemOpNo + X86::AddrDisp).ChangeToImmediate(AddrDispShift);
525 MI.getOperand(MemOpNo + X86::AddrSegmentReg)
526 .ChangeToRegister(X86::NoRegister, false);
527
528 DEBUG(dbgs() << "OptimizeLEAs: Replaced by: "; MI.dump(););
529
530 Changed = true;
531 }
532
533 return Changed;
534}
535
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000536// Try to find similar LEAs in the list and replace one with another.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000537bool OptimizeLEAPass::removeRedundantLEAs(MemOpMap &LEAs) {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000538 bool Changed = false;
539
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000540 // Loop over all entries in the table.
541 for (auto &E : LEAs) {
542 auto &List = E.second;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000543
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000544 // Loop over all LEA pairs.
545 auto I1 = List.begin();
546 while (I1 != List.end()) {
547 MachineInstr &First = **I1;
548 auto I2 = std::next(I1);
549 while (I2 != List.end()) {
550 MachineInstr &Last = **I2;
551 int64_t AddrDispShift;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000552
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000553 // LEAs should be in occurence order in the list, so we can freely
554 // replace later LEAs with earlier ones.
555 assert(calcInstrDist(First, Last) > 0 &&
556 "LEAs must be in occurence order in the list");
557
558 // Check that the Last LEA instruction can be replaced by the First.
559 if (!isReplaceable(First, Last, AddrDispShift)) {
560 ++I2;
561 continue;
562 }
563
564 // Loop over all uses of the Last LEA and update their operands. Note
565 // that the correctness of this has already been checked in the
566 // isReplaceable function.
567 for (auto UI = MRI->use_begin(Last.getOperand(0).getReg()),
568 UE = MRI->use_end();
569 UI != UE;) {
570 MachineOperand &MO = *UI++;
571 MachineInstr &MI = *MO.getParent();
572
573 // Get the number of the first memory operand.
574 const MCInstrDesc &Desc = MI.getDesc();
575 int MemOpNo =
576 X86II::getMemoryOperandNo(Desc.TSFlags, MI.getOpcode()) +
577 X86II::getOperandBias(Desc);
578
579 // Update address base.
580 MO.setReg(First.getOperand(0).getReg());
581
582 // Update address disp.
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000583 MachineOperand &Op = MI.getOperand(MemOpNo + X86::AddrDisp);
584 if (Op.isImm())
585 Op.setImm(Op.getImm() + AddrDispShift);
586 else if (!Op.isJTI())
587 Op.setOffset(Op.getOffset() + AddrDispShift);
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000588 }
589
590 // Since we can possibly extend register lifetime, clear kill flags.
591 MRI->clearKillFlags(First.getOperand(0).getReg());
592
593 ++NumRedundantLEAs;
594 DEBUG(dbgs() << "OptimizeLEAs: Remove redundant LEA: "; Last.dump(););
595
596 // By this moment, all of the Last LEA's uses must be replaced. So we
597 // can freely remove it.
598 assert(MRI->use_empty(Last.getOperand(0).getReg()) &&
599 "The LEA's def register must have no uses");
600 Last.eraseFromParent();
601
602 // Erase removed LEA from the list.
603 I2 = List.erase(I2);
604
605 Changed = true;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000606 }
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000607 ++I1;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000608 }
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000609 }
610
611 return Changed;
612}
613
Alexey Bataev7cf32472015-12-04 10:53:15 +0000614bool OptimizeLEAPass::runOnMachineFunction(MachineFunction &MF) {
615 bool Changed = false;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000616
617 // Perform this optimization only if we care about code size.
Hans Wennborg84047892016-02-17 02:49:59 +0000618 if (!EnableX86LEAOpt || !MF.getFunction()->optForSize())
Alexey Bataev7cf32472015-12-04 10:53:15 +0000619 return false;
620
621 MRI = &MF.getRegInfo();
622 TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
623 TRI = MF.getSubtarget<X86Subtarget>().getRegisterInfo();
624
625 // Process all basic blocks.
626 for (auto &MBB : MF) {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000627 MemOpMap LEAs;
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000628 InstrPos.clear();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000629
630 // Find all LEA instructions in basic block.
631 findLEAs(MBB, LEAs);
632
633 // If current basic block has no LEAs, move on to the next one.
634 if (LEAs.empty())
635 continue;
636
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000637 // Remove redundant LEA instructions. The optimization may have a negative
638 // effect on performance, so do it only for -Oz.
639 if (MF.getFunction()->optForMinSize())
640 Changed |= removeRedundantLEAs(LEAs);
641
Alexey Bataev7cf32472015-12-04 10:53:15 +0000642 // Remove redundant address calculations.
643 Changed |= removeRedundantAddrCalc(LEAs);
644 }
645
646 return Changed;
647}