blob: 1aee01563c4b02cfd7447eaef9b734fc0904d8e8 [file] [log] [blame]
Eugene Zelenko60433b62017-10-05 00:33:50 +00001//===- X86OptimizeLEAs.cpp - optimize usage of LEA instructions -----------===//
Alexey Bataev7cf32472015-12-04 10:53:15 +00002//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Alexey Bataev7cf32472015-12-04 10:53:15 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the pass that performs some optimizations with LEA
Andrey Turetskiy45b22a42016-05-19 10:18:29 +000010// instructions in order to improve performance and code size.
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +000011// Currently, it does two things:
12// 1) If there are two LEA instructions calculating addresses which only differ
13// by displacement inside a basic block, one of them is removed.
14// 2) Address calculations in load and store instructions are replaced by
Alexey Bataev7cf32472015-12-04 10:53:15 +000015// existing LEA def registers where possible.
16//
17//===----------------------------------------------------------------------===//
18
Eugene Zelenko60433b62017-10-05 00:33:50 +000019#include "MCTargetDesc/X86BaseInfo.h"
Alexey Bataev7cf32472015-12-04 10:53:15 +000020#include "X86.h"
21#include "X86InstrInfo.h"
22#include "X86Subtarget.h"
Eugene Zelenko60433b62017-10-05 00:33:50 +000023#include "llvm/ADT/DenseMap.h"
24#include "llvm/ADT/DenseMapInfo.h"
25#include "llvm/ADT/Hashing.h"
26#include "llvm/ADT/SmallVector.h"
Alexey Bataev7cf32472015-12-04 10:53:15 +000027#include "llvm/ADT/Statistic.h"
Eugene Zelenko60433b62017-10-05 00:33:50 +000028#include "llvm/CodeGen/MachineBasicBlock.h"
29#include "llvm/CodeGen/MachineFunction.h"
Alexey Bataev7cf32472015-12-04 10:53:15 +000030#include "llvm/CodeGen/MachineFunctionPass.h"
Eugene Zelenko60433b62017-10-05 00:33:50 +000031#include "llvm/CodeGen/MachineInstr.h"
Alexey Bataev7cf32472015-12-04 10:53:15 +000032#include "llvm/CodeGen/MachineInstrBuilder.h"
Andrey Turetskiy0babd262016-02-20 10:58:28 +000033#include "llvm/CodeGen/MachineOperand.h"
Alexey Bataev7cf32472015-12-04 10:53:15 +000034#include "llvm/CodeGen/MachineRegisterInfo.h"
David Blaikieb3bde2e2017-11-17 01:07:10 +000035#include "llvm/CodeGen/TargetOpcodes.h"
36#include "llvm/CodeGen/TargetRegisterInfo.h"
Chandler Carruth6bda14b2017-06-06 11:49:48 +000037#include "llvm/IR/DebugInfoMetadata.h"
Eugene Zelenko60433b62017-10-05 00:33:50 +000038#include "llvm/IR/DebugLoc.h"
Alexey Bataev7cf32472015-12-04 10:53:15 +000039#include "llvm/IR/Function.h"
Eugene Zelenko60433b62017-10-05 00:33:50 +000040#include "llvm/MC/MCInstrDesc.h"
41#include "llvm/Support/CommandLine.h"
Alexey Bataev7cf32472015-12-04 10:53:15 +000042#include "llvm/Support/Debug.h"
Eugene Zelenko60433b62017-10-05 00:33:50 +000043#include "llvm/Support/ErrorHandling.h"
44#include "llvm/Support/MathExtras.h"
Alexey Bataev7cf32472015-12-04 10:53:15 +000045#include "llvm/Support/raw_ostream.h"
Eugene Zelenko60433b62017-10-05 00:33:50 +000046#include <cassert>
47#include <cstdint>
48#include <iterator>
Alexey Bataev7cf32472015-12-04 10:53:15 +000049
50using namespace llvm;
51
52#define DEBUG_TYPE "x86-optimize-LEAs"
53
Andrey Turetskiy9994b882016-02-20 11:11:55 +000054static cl::opt<bool>
55 DisableX86LEAOpt("disable-x86-lea-opt", cl::Hidden,
56 cl::desc("X86: Disable LEA optimizations."),
57 cl::init(false));
Alexey Bataev7b72b652015-12-17 07:34:39 +000058
Alexey Bataev7cf32472015-12-04 10:53:15 +000059STATISTIC(NumSubstLEAs, "Number of LEA instruction substitutions");
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +000060STATISTIC(NumRedundantLEAs, "Number of redundant LEA instructions removed");
Alexey Bataev7cf32472015-12-04 10:53:15 +000061
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000062/// Returns true if two machine operands are identical and they are not
Andrey Turetskiybca0f992016-02-04 08:57:03 +000063/// physical registers.
64static inline bool isIdenticalOp(const MachineOperand &MO1,
65 const MachineOperand &MO2);
66
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000067/// Returns true if two address displacement operands are of the same
Andrey Turetskiy0babd262016-02-20 10:58:28 +000068/// type and use the same symbol/index/address regardless of the offset.
69static bool isSimilarDispOp(const MachineOperand &MO1,
70 const MachineOperand &MO2);
71
Adrian Prantl5f8f34e42018-05-01 15:54:18 +000072/// Returns true if the instruction is LEA.
Andrey Turetskiybca0f992016-02-04 08:57:03 +000073static inline bool isLEA(const MachineInstr &MI);
74
Benjamin Kramerb7d33112016-08-06 11:13:10 +000075namespace {
Eugene Zelenko60433b62017-10-05 00:33:50 +000076
Andrey Turetskiybca0f992016-02-04 08:57:03 +000077/// A key based on instruction's memory operands.
78class MemOpKey {
79public:
80 MemOpKey(const MachineOperand *Base, const MachineOperand *Scale,
81 const MachineOperand *Index, const MachineOperand *Segment,
Matt Morehouse9e658c92017-12-01 22:20:26 +000082 const MachineOperand *Disp)
83 : Disp(Disp) {
Andrey Turetskiybca0f992016-02-04 08:57:03 +000084 Operands[0] = Base;
85 Operands[1] = Scale;
86 Operands[2] = Index;
87 Operands[3] = Segment;
88 }
89
90 bool operator==(const MemOpKey &Other) const {
91 // Addresses' bases, scales, indices and segments must be identical.
92 for (int i = 0; i < 4; ++i)
93 if (!isIdenticalOp(*Operands[i], *Other.Operands[i]))
94 return false;
95
Andrey Turetskiy0babd262016-02-20 10:58:28 +000096 // Addresses' displacements don't have to be exactly the same. It only
97 // matters that they use the same symbol/index/address. Immediates' or
98 // offsets' differences will be taken care of during instruction
99 // substitution.
100 return isSimilarDispOp(*Disp, *Other.Disp);
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000101 }
102
103 // Address' base, scale, index and segment operands.
104 const MachineOperand *Operands[4];
105
106 // Address' displacement operand.
107 const MachineOperand *Disp;
108};
Eugene Zelenko60433b62017-10-05 00:33:50 +0000109
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000110} // end anonymous namespace
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000111
112/// Provide DenseMapInfo for MemOpKey.
113namespace llvm {
Eugene Zelenko60433b62017-10-05 00:33:50 +0000114
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000115template <> struct DenseMapInfo<MemOpKey> {
Eugene Zelenko60433b62017-10-05 00:33:50 +0000116 using PtrInfo = DenseMapInfo<const MachineOperand *>;
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000117
118 static inline MemOpKey getEmptyKey() {
119 return MemOpKey(PtrInfo::getEmptyKey(), PtrInfo::getEmptyKey(),
120 PtrInfo::getEmptyKey(), PtrInfo::getEmptyKey(),
121 PtrInfo::getEmptyKey());
122 }
123
124 static inline MemOpKey getTombstoneKey() {
125 return MemOpKey(PtrInfo::getTombstoneKey(), PtrInfo::getTombstoneKey(),
126 PtrInfo::getTombstoneKey(), PtrInfo::getTombstoneKey(),
127 PtrInfo::getTombstoneKey());
128 }
129
130 static unsigned getHashValue(const MemOpKey &Val) {
131 // Checking any field of MemOpKey is enough to determine if the key is
132 // empty or tombstone.
133 assert(Val.Disp != PtrInfo::getEmptyKey() && "Cannot hash the empty key");
134 assert(Val.Disp != PtrInfo::getTombstoneKey() &&
135 "Cannot hash the tombstone key");
136
Matt Morehouse9e658c92017-12-01 22:20:26 +0000137 hash_code Hash = hash_combine(*Val.Operands[0], *Val.Operands[1],
138 *Val.Operands[2], *Val.Operands[3]);
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000139
140 // If the address displacement is an immediate, it should not affect the
141 // hash so that memory operands which differ only be immediate displacement
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000142 // would have the same hash. If the address displacement is something else,
143 // we should reflect symbol/index/address in the hash.
144 switch (Val.Disp->getType()) {
145 case MachineOperand::MO_Immediate:
146 break;
147 case MachineOperand::MO_ConstantPoolIndex:
148 case MachineOperand::MO_JumpTableIndex:
149 Hash = hash_combine(Hash, Val.Disp->getIndex());
150 break;
151 case MachineOperand::MO_ExternalSymbol:
152 Hash = hash_combine(Hash, Val.Disp->getSymbolName());
153 break;
154 case MachineOperand::MO_GlobalAddress:
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000155 Hash = hash_combine(Hash, Val.Disp->getGlobal());
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000156 break;
157 case MachineOperand::MO_BlockAddress:
158 Hash = hash_combine(Hash, Val.Disp->getBlockAddress());
159 break;
160 case MachineOperand::MO_MCSymbol:
161 Hash = hash_combine(Hash, Val.Disp->getMCSymbol());
162 break;
Andrey Turetskiyb4056062016-04-26 12:18:12 +0000163 case MachineOperand::MO_MachineBasicBlock:
164 Hash = hash_combine(Hash, Val.Disp->getMBB());
165 break;
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000166 default:
167 llvm_unreachable("Invalid address displacement operand");
168 }
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000169
170 return (unsigned)Hash;
171 }
172
173 static bool isEqual(const MemOpKey &LHS, const MemOpKey &RHS) {
174 // Checking any field of MemOpKey is enough to determine if the key is
175 // empty or tombstone.
176 if (RHS.Disp == PtrInfo::getEmptyKey())
177 return LHS.Disp == PtrInfo::getEmptyKey();
178 if (RHS.Disp == PtrInfo::getTombstoneKey())
179 return LHS.Disp == PtrInfo::getTombstoneKey();
180 return LHS == RHS;
181 }
182};
Eugene Zelenko60433b62017-10-05 00:33:50 +0000183
184} // end namespace llvm
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000185
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000186/// Returns a hash table key based on memory operands of \p MI. The
Benjamin Kramerb7d33112016-08-06 11:13:10 +0000187/// number of the first memory operand of \p MI is specified through \p N.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000188static inline MemOpKey getMemOpKey(const MachineInstr &MI, unsigned N) {
189 assert((isLEA(MI) || MI.mayLoadOrStore()) &&
190 "The instruction must be a LEA, a load or a store");
191 return MemOpKey(&MI.getOperand(N + X86::AddrBaseReg),
192 &MI.getOperand(N + X86::AddrScaleAmt),
193 &MI.getOperand(N + X86::AddrIndexReg),
194 &MI.getOperand(N + X86::AddrSegmentReg),
195 &MI.getOperand(N + X86::AddrDisp));
196}
197
198static inline bool isIdenticalOp(const MachineOperand &MO1,
199 const MachineOperand &MO2) {
200 return MO1.isIdenticalTo(MO2) &&
Daniel Sanders2bea69b2019-08-01 23:27:28 +0000201 (!MO1.isReg() || !Register::isPhysicalRegister(MO1.getReg()));
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000202}
203
Justin Bogner38e52172016-02-24 07:58:02 +0000204#ifndef NDEBUG
205static bool isValidDispOp(const MachineOperand &MO) {
206 return MO.isImm() || MO.isCPI() || MO.isJTI() || MO.isSymbol() ||
Andrey Turetskiyb4056062016-04-26 12:18:12 +0000207 MO.isGlobal() || MO.isBlockAddress() || MO.isMCSymbol() || MO.isMBB();
Justin Bogner38e52172016-02-24 07:58:02 +0000208}
209#endif
210
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000211static bool isSimilarDispOp(const MachineOperand &MO1,
212 const MachineOperand &MO2) {
213 assert(isValidDispOp(MO1) && isValidDispOp(MO2) &&
214 "Address displacement operand is not valid");
215 return (MO1.isImm() && MO2.isImm()) ||
216 (MO1.isCPI() && MO2.isCPI() && MO1.getIndex() == MO2.getIndex()) ||
217 (MO1.isJTI() && MO2.isJTI() && MO1.getIndex() == MO2.getIndex()) ||
218 (MO1.isSymbol() && MO2.isSymbol() &&
219 MO1.getSymbolName() == MO2.getSymbolName()) ||
220 (MO1.isGlobal() && MO2.isGlobal() &&
221 MO1.getGlobal() == MO2.getGlobal()) ||
222 (MO1.isBlockAddress() && MO2.isBlockAddress() &&
223 MO1.getBlockAddress() == MO2.getBlockAddress()) ||
224 (MO1.isMCSymbol() && MO2.isMCSymbol() &&
Andrey Turetskiyb4056062016-04-26 12:18:12 +0000225 MO1.getMCSymbol() == MO2.getMCSymbol()) ||
226 (MO1.isMBB() && MO2.isMBB() && MO1.getMBB() == MO2.getMBB());
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000227}
228
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000229static inline bool isLEA(const MachineInstr &MI) {
230 unsigned Opcode = MI.getOpcode();
231 return Opcode == X86::LEA16r || Opcode == X86::LEA32r ||
232 Opcode == X86::LEA64r || Opcode == X86::LEA64_32r;
233}
234
Alexey Bataev7cf32472015-12-04 10:53:15 +0000235namespace {
Eugene Zelenko60433b62017-10-05 00:33:50 +0000236
Pengfei Wang7630e242019-08-22 02:29:27 +0000237class X86OptimizeLEAPass : public MachineFunctionPass {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000238public:
Pengfei Wang7630e242019-08-22 02:29:27 +0000239 X86OptimizeLEAPass() : MachineFunctionPass(ID) {}
Alexey Bataev7cf32472015-12-04 10:53:15 +0000240
Mehdi Amini117296c2016-10-01 02:56:57 +0000241 StringRef getPassName() const override { return "X86 LEA Optimize"; }
Alexey Bataev7cf32472015-12-04 10:53:15 +0000242
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000243 /// Loop over all of the basic blocks, replacing address
Alexey Bataev7cf32472015-12-04 10:53:15 +0000244 /// calculations in load and store instructions, if it's already
245 /// been calculated by LEA. Also, remove redundant LEAs.
246 bool runOnMachineFunction(MachineFunction &MF) override;
247
Pengfei Wang7630e242019-08-22 02:29:27 +0000248 static char ID;
249
Alexey Bataev7cf32472015-12-04 10:53:15 +0000250private:
Eugene Zelenko60433b62017-10-05 00:33:50 +0000251 using MemOpMap = DenseMap<MemOpKey, SmallVector<MachineInstr *, 16>>;
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000252
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000253 /// Returns a distance between two instructions inside one basic block.
Alexey Bataev7cf32472015-12-04 10:53:15 +0000254 /// Negative result means, that instructions occur in reverse order.
255 int calcInstrDist(const MachineInstr &First, const MachineInstr &Last);
256
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000257 /// Choose the best \p LEA instruction from the \p List to replace
Alexey Bataev7cf32472015-12-04 10:53:15 +0000258 /// address calculation in \p MI instruction. Return the address displacement
Simon Pilgrim9d15fb32016-11-17 19:03:05 +0000259 /// and the distance between \p MI and the chosen \p BestLEA in
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000260 /// \p AddrDispShift and \p Dist.
Alexey Bataev7cf32472015-12-04 10:53:15 +0000261 bool chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000262 const MachineInstr &MI, MachineInstr *&BestLEA,
Alexey Bataev7cf32472015-12-04 10:53:15 +0000263 int64_t &AddrDispShift, int &Dist);
264
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000265 /// Returns the difference between addresses' displacements of \p MI1
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000266 /// and \p MI2. The numbers of the first memory operands for the instructions
267 /// are specified through \p N1 and \p N2.
268 int64_t getAddrDispShift(const MachineInstr &MI1, unsigned N1,
269 const MachineInstr &MI2, unsigned N2) const;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000270
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000271 /// Returns true if the \p Last LEA instruction can be replaced by the
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000272 /// \p First. The difference between displacements of the addresses calculated
273 /// by these LEAs is returned in \p AddrDispShift. It'll be used for proper
274 /// replacement of the \p Last LEA's uses with the \p First's def register.
275 bool isReplaceable(const MachineInstr &First, const MachineInstr &Last,
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000276 int64_t &AddrDispShift) const;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000277
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000278 /// Find all LEA instructions in the basic block. Also, assign position
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000279 /// numbers to all instructions in the basic block to speed up calculation of
280 /// distance between them.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000281 void findLEAs(const MachineBasicBlock &MBB, MemOpMap &LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000282
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000283 /// Removes redundant address calculations.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000284 bool removeRedundantAddrCalc(MemOpMap &LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000285
Andrew Ng03e35b62017-04-28 08:44:30 +0000286 /// Replace debug value MI with a new debug value instruction using register
287 /// VReg with an appropriate offset and DIExpression to incorporate the
288 /// address displacement AddrDispShift. Return new debug value instruction.
289 MachineInstr *replaceDebugValue(MachineInstr &MI, unsigned VReg,
290 int64_t AddrDispShift);
291
Adrian Prantl5f8f34e42018-05-01 15:54:18 +0000292 /// Removes LEAs which calculate similar addresses.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000293 bool removeRedundantLEAs(MemOpMap &LEAs);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000294
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000295 DenseMap<const MachineInstr *, unsigned> InstrPos;
296
Alexey Bataev7cf32472015-12-04 10:53:15 +0000297 MachineRegisterInfo *MRI;
298 const X86InstrInfo *TII;
299 const X86RegisterInfo *TRI;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000300};
Eugene Zelenko60433b62017-10-05 00:33:50 +0000301
302} // end anonymous namespace
303
Pengfei Wang7630e242019-08-22 02:29:27 +0000304char X86OptimizeLEAPass::ID = 0;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000305
Pengfei Wang7630e242019-08-22 02:29:27 +0000306FunctionPass *llvm::createX86OptimizeLEAs() { return new X86OptimizeLEAPass(); }
307INITIALIZE_PASS(X86OptimizeLEAPass, DEBUG_TYPE, "X86 optimize LEA pass", false,
308 false)
Alexey Bataev7cf32472015-12-04 10:53:15 +0000309
Pengfei Wang7630e242019-08-22 02:29:27 +0000310int X86OptimizeLEAPass::calcInstrDist(const MachineInstr &First,
311 const MachineInstr &Last) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000312 // Both instructions must be in the same basic block and they must be
313 // presented in InstrPos.
314 assert(Last.getParent() == First.getParent() &&
Alexey Bataev7cf32472015-12-04 10:53:15 +0000315 "Instructions are in different basic blocks");
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000316 assert(InstrPos.find(&First) != InstrPos.end() &&
317 InstrPos.find(&Last) != InstrPos.end() &&
318 "Instructions' positions are undefined");
Alexey Bataev7cf32472015-12-04 10:53:15 +0000319
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000320 return InstrPos[&Last] - InstrPos[&First];
Alexey Bataev7cf32472015-12-04 10:53:15 +0000321}
322
323// Find the best LEA instruction in the List to replace address recalculation in
324// MI. Such LEA must meet these requirements:
325// 1) The address calculated by the LEA differs only by the displacement from
326// the address used in MI.
327// 2) The register class of the definition of the LEA is compatible with the
328// register class of the address base register of MI.
329// 3) Displacement of the new memory operand should fit in 1 byte if possible.
330// 4) The LEA should be as close to MI as possible, and prior to it if
331// possible.
Pengfei Wang7630e242019-08-22 02:29:27 +0000332bool X86OptimizeLEAPass::chooseBestLEA(
333 const SmallVectorImpl<MachineInstr *> &List, const MachineInstr &MI,
334 MachineInstr *&BestLEA, int64_t &AddrDispShift, int &Dist) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000335 const MachineFunction *MF = MI.getParent()->getParent();
336 const MCInstrDesc &Desc = MI.getDesc();
Craig Topper477649a2016-04-28 05:58:46 +0000337 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags) +
Alexey Bataev7cf32472015-12-04 10:53:15 +0000338 X86II::getOperandBias(Desc);
339
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000340 BestLEA = nullptr;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000341
342 // Loop over all LEA instructions.
343 for (auto DefMI : List) {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000344 // Get new address displacement.
345 int64_t AddrDispShiftTemp = getAddrDispShift(MI, MemOpNo, *DefMI, 1);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000346
347 // Make sure address displacement fits 4 bytes.
348 if (!isInt<32>(AddrDispShiftTemp))
349 continue;
350
351 // Check that LEA def register can be used as MI address base. Some
352 // instructions can use a limited set of registers as address base, for
353 // example MOV8mr_NOREX. We could constrain the register class of the LEA
354 // def to suit MI, however since this case is very rare and hard to
355 // reproduce in a test it's just more reliable to skip the LEA.
356 if (TII->getRegClass(Desc, MemOpNo + X86::AddrBaseReg, TRI, *MF) !=
357 MRI->getRegClass(DefMI->getOperand(0).getReg()))
358 continue;
359
360 // Choose the closest LEA instruction from the list, prior to MI if
361 // possible. Note that we took into account resulting address displacement
362 // as well. Also note that the list is sorted by the order in which the LEAs
363 // occur, so the break condition is pretty simple.
364 int DistTemp = calcInstrDist(*DefMI, MI);
365 assert(DistTemp != 0 &&
366 "The distance between two different instructions cannot be zero");
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000367 if (DistTemp > 0 || BestLEA == nullptr) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000368 // Do not update return LEA, if the current one provides a displacement
369 // which fits in 1 byte, while the new candidate does not.
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000370 if (BestLEA != nullptr && !isInt<8>(AddrDispShiftTemp) &&
Alexey Bataev7cf32472015-12-04 10:53:15 +0000371 isInt<8>(AddrDispShift))
372 continue;
373
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000374 BestLEA = DefMI;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000375 AddrDispShift = AddrDispShiftTemp;
376 Dist = DistTemp;
377 }
378
379 // FIXME: Maybe we should not always stop at the first LEA after MI.
380 if (DistTemp < 0)
381 break;
382 }
383
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000384 return BestLEA != nullptr;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000385}
386
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000387// Get the difference between the addresses' displacements of the two
388// instructions \p MI1 and \p MI2. The numbers of the first memory operands are
389// passed through \p N1 and \p N2.
Pengfei Wang7630e242019-08-22 02:29:27 +0000390int64_t X86OptimizeLEAPass::getAddrDispShift(const MachineInstr &MI1,
391 unsigned N1,
392 const MachineInstr &MI2,
393 unsigned N2) const {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000394 const MachineOperand &Op1 = MI1.getOperand(N1 + X86::AddrDisp);
395 const MachineOperand &Op2 = MI2.getOperand(N2 + X86::AddrDisp);
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000396
397 assert(isSimilarDispOp(Op1, Op2) &&
398 "Address displacement operands are not compatible");
399
400 // After the assert above we can be sure that both operands are of the same
401 // valid type and use the same symbol/index/address, thus displacement shift
402 // calculation is rather simple.
403 if (Op1.isJTI())
404 return 0;
405 return Op1.isImm() ? Op1.getImm() - Op2.getImm()
406 : Op1.getOffset() - Op2.getOffset();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000407}
408
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000409// Check that the Last LEA can be replaced by the First LEA. To be so,
410// these requirements must be met:
411// 1) Addresses calculated by LEAs differ only by displacement.
412// 2) Def registers of LEAs belong to the same class.
413// 3) All uses of the Last LEA def register are replaceable, thus the
414// register is used only as address base.
Pengfei Wang7630e242019-08-22 02:29:27 +0000415bool X86OptimizeLEAPass::isReplaceable(const MachineInstr &First,
416 const MachineInstr &Last,
417 int64_t &AddrDispShift) const {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000418 assert(isLEA(First) && isLEA(Last) &&
419 "The function works only with LEA instructions");
420
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000421 // Make sure that LEA def registers belong to the same class. There may be
422 // instructions (like MOV8mr_NOREX) which allow a limited set of registers to
423 // be used as their operands, so we must be sure that replacing one LEA
424 // with another won't lead to putting a wrong register in the instruction.
425 if (MRI->getRegClass(First.getOperand(0).getReg()) !=
426 MRI->getRegClass(Last.getOperand(0).getReg()))
427 return false;
428
Andrea Di Biagio7937be72017-03-21 11:36:21 +0000429 // Get new address displacement.
430 AddrDispShift = getAddrDispShift(Last, 1, First, 1);
431
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000432 // Loop over all uses of the Last LEA to check that its def register is
433 // used only as address base for memory accesses. If so, it can be
434 // replaced, otherwise - no.
Andrea Di Biagio7937be72017-03-21 11:36:21 +0000435 for (auto &MO : MRI->use_nodbg_operands(Last.getOperand(0).getReg())) {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000436 MachineInstr &MI = *MO.getParent();
437
438 // Get the number of the first memory operand.
439 const MCInstrDesc &Desc = MI.getDesc();
Craig Topper477649a2016-04-28 05:58:46 +0000440 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000441
442 // If the use instruction has no memory operand - the LEA is not
443 // replaceable.
444 if (MemOpNo < 0)
445 return false;
446
447 MemOpNo += X86II::getOperandBias(Desc);
448
449 // If the address base of the use instruction is not the LEA def register -
450 // the LEA is not replaceable.
451 if (!isIdenticalOp(MI.getOperand(MemOpNo + X86::AddrBaseReg), MO))
452 return false;
453
454 // If the LEA def register is used as any other operand of the use
455 // instruction - the LEA is not replaceable.
456 for (unsigned i = 0; i < MI.getNumOperands(); i++)
457 if (i != (unsigned)(MemOpNo + X86::AddrBaseReg) &&
458 isIdenticalOp(MI.getOperand(i), MO))
459 return false;
460
461 // Check that the new address displacement will fit 4 bytes.
462 if (MI.getOperand(MemOpNo + X86::AddrDisp).isImm() &&
463 !isInt<32>(MI.getOperand(MemOpNo + X86::AddrDisp).getImm() +
464 AddrDispShift))
465 return false;
466 }
467
468 return true;
469}
470
Pengfei Wang7630e242019-08-22 02:29:27 +0000471void X86OptimizeLEAPass::findLEAs(const MachineBasicBlock &MBB,
472 MemOpMap &LEAs) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000473 unsigned Pos = 0;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000474 for (auto &MI : MBB) {
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000475 // Assign the position number to the instruction. Note that we are going to
476 // move some instructions during the optimization however there will never
477 // be a need to move two instructions before any selected instruction. So to
478 // avoid multiple positions' updates during moves we just increase position
479 // counter by two leaving a free space for instructions which will be moved.
480 InstrPos[&MI] = Pos += 2;
481
Alexey Bataev7cf32472015-12-04 10:53:15 +0000482 if (isLEA(MI))
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000483 LEAs[getMemOpKey(MI, 1)].push_back(const_cast<MachineInstr *>(&MI));
Alexey Bataev7cf32472015-12-04 10:53:15 +0000484 }
485}
486
487// Try to find load and store instructions which recalculate addresses already
488// calculated by some LEA and replace their memory operands with its def
489// register.
Pengfei Wang7630e242019-08-22 02:29:27 +0000490bool X86OptimizeLEAPass::removeRedundantAddrCalc(MemOpMap &LEAs) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000491 bool Changed = false;
492
Matt Morehouse9e658c92017-12-01 22:20:26 +0000493 assert(!LEAs.empty());
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000494 MachineBasicBlock *MBB = (*LEAs.begin()->second.begin())->getParent();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000495
496 // Process all instructions in basic block.
497 for (auto I = MBB->begin(), E = MBB->end(); I != E;) {
498 MachineInstr &MI = *I++;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000499
500 // Instruction must be load or store.
501 if (!MI.mayLoadOrStore())
502 continue;
503
504 // Get the number of the first memory operand.
505 const MCInstrDesc &Desc = MI.getDesc();
Craig Topper477649a2016-04-28 05:58:46 +0000506 int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000507
508 // If instruction has no memory operand - skip it.
509 if (MemOpNo < 0)
510 continue;
511
512 MemOpNo += X86II::getOperandBias(Desc);
513
Craig Topper87f78cf2018-08-22 18:24:13 +0000514 // Do not call chooseBestLEA if there was no matching LEA
515 auto Insns = LEAs.find(getMemOpKey(MI, MemOpNo));
516 if (Insns == LEAs.end())
517 continue;
518
Alexey Bataev7cf32472015-12-04 10:53:15 +0000519 // Get the best LEA instruction to replace address calculation.
520 MachineInstr *DefMI;
521 int64_t AddrDispShift;
522 int Dist;
Craig Topper87f78cf2018-08-22 18:24:13 +0000523 if (!chooseBestLEA(Insns->second, MI, DefMI, AddrDispShift, Dist))
Alexey Bataev7cf32472015-12-04 10:53:15 +0000524 continue;
525
526 // If LEA occurs before current instruction, we can freely replace
527 // the instruction. If LEA occurs after, we can lift LEA above the
528 // instruction and this way to be able to replace it. Since LEA and the
529 // instruction have similar memory operands (thus, the same def
530 // instructions for these operands), we can always do that, without
531 // worries of using registers before their defs.
532 if (Dist < 0) {
533 DefMI->removeFromParent();
534 MBB->insert(MachineBasicBlock::iterator(&MI), DefMI);
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000535 InstrPos[DefMI] = InstrPos[&MI] - 1;
536
537 // Make sure the instructions' position numbers are sane.
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000538 assert(((InstrPos[DefMI] == 1 &&
539 MachineBasicBlock::iterator(DefMI) == MBB->begin()) ||
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000540 InstrPos[DefMI] >
Duncan P. N. Exon Smith7b4c18e2016-07-12 03:18:50 +0000541 InstrPos[&*std::prev(MachineBasicBlock::iterator(DefMI))]) &&
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000542 "Instruction positioning is broken");
Alexey Bataev7cf32472015-12-04 10:53:15 +0000543 }
544
545 // Since we can possibly extend register lifetime, clear kill flags.
546 MRI->clearKillFlags(DefMI->getOperand(0).getReg());
547
548 ++NumSubstLEAs;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000549 LLVM_DEBUG(dbgs() << "OptimizeLEAs: Candidate to replace: "; MI.dump(););
Alexey Bataev7cf32472015-12-04 10:53:15 +0000550
551 // Change instruction operands.
552 MI.getOperand(MemOpNo + X86::AddrBaseReg)
553 .ChangeToRegister(DefMI->getOperand(0).getReg(), false);
554 MI.getOperand(MemOpNo + X86::AddrScaleAmt).ChangeToImmediate(1);
555 MI.getOperand(MemOpNo + X86::AddrIndexReg)
556 .ChangeToRegister(X86::NoRegister, false);
557 MI.getOperand(MemOpNo + X86::AddrDisp).ChangeToImmediate(AddrDispShift);
558 MI.getOperand(MemOpNo + X86::AddrSegmentReg)
559 .ChangeToRegister(X86::NoRegister, false);
560
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000561 LLVM_DEBUG(dbgs() << "OptimizeLEAs: Replaced by: "; MI.dump(););
Alexey Bataev7cf32472015-12-04 10:53:15 +0000562
563 Changed = true;
564 }
565
566 return Changed;
567}
568
Pengfei Wang7630e242019-08-22 02:29:27 +0000569MachineInstr *X86OptimizeLEAPass::replaceDebugValue(MachineInstr &MI,
570 unsigned VReg,
571 int64_t AddrDispShift) {
Andrew Ng03e35b62017-04-28 08:44:30 +0000572 DIExpression *Expr = const_cast<DIExpression *>(MI.getDebugExpression());
Adrian Prantl109b2362017-04-28 17:51:05 +0000573 if (AddrDispShift != 0)
Petar Jovanovice85bbf52019-05-20 10:35:57 +0000574 Expr = DIExpression::prepend(Expr, DIExpression::StackValue, AddrDispShift);
Andrew Ng03e35b62017-04-28 08:44:30 +0000575
576 // Replace DBG_VALUE instruction with modified version.
577 MachineBasicBlock *MBB = MI.getParent();
578 DebugLoc DL = MI.getDebugLoc();
579 bool IsIndirect = MI.isIndirectDebugValue();
Andrew Ng03e35b62017-04-28 08:44:30 +0000580 const MDNode *Var = MI.getDebugVariable();
Adrian Prantl8b9bb532017-07-28 23:00:45 +0000581 if (IsIndirect)
582 assert(MI.getOperand(1).getImm() == 0 && "DBG_VALUE with nonzero offset");
Andrew Ng03e35b62017-04-28 08:44:30 +0000583 return BuildMI(*MBB, MBB->erase(&MI), DL, TII->get(TargetOpcode::DBG_VALUE),
Adrian Prantl8b9bb532017-07-28 23:00:45 +0000584 IsIndirect, VReg, Var, Expr);
Andrew Ng03e35b62017-04-28 08:44:30 +0000585}
586
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000587// Try to find similar LEAs in the list and replace one with another.
Pengfei Wang7630e242019-08-22 02:29:27 +0000588bool X86OptimizeLEAPass::removeRedundantLEAs(MemOpMap &LEAs) {
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000589 bool Changed = false;
590
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000591 // Loop over all entries in the table.
592 for (auto &E : LEAs) {
593 auto &List = E.second;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000594
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000595 // Loop over all LEA pairs.
596 auto I1 = List.begin();
597 while (I1 != List.end()) {
598 MachineInstr &First = **I1;
599 auto I2 = std::next(I1);
600 while (I2 != List.end()) {
601 MachineInstr &Last = **I2;
602 int64_t AddrDispShift;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000603
Simon Pilgrim9d15fb32016-11-17 19:03:05 +0000604 // LEAs should be in occurrence order in the list, so we can freely
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000605 // replace later LEAs with earlier ones.
606 assert(calcInstrDist(First, Last) > 0 &&
Simon Pilgrim9d15fb32016-11-17 19:03:05 +0000607 "LEAs must be in occurrence order in the list");
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000608
609 // Check that the Last LEA instruction can be replaced by the First.
610 if (!isReplaceable(First, Last, AddrDispShift)) {
611 ++I2;
612 continue;
613 }
614
615 // Loop over all uses of the Last LEA and update their operands. Note
616 // that the correctness of this has already been checked in the
617 // isReplaceable function.
Daniel Sanders0c476112019-08-15 19:22:08 +0000618 Register FirstVReg = First.getOperand(0).getReg();
619 Register LastVReg = Last.getOperand(0).getReg();
Andrew Ng03e35b62017-04-28 08:44:30 +0000620 for (auto UI = MRI->use_begin(LastVReg), UE = MRI->use_end();
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000621 UI != UE;) {
622 MachineOperand &MO = *UI++;
623 MachineInstr &MI = *MO.getParent();
624
Andrew Ng03e35b62017-04-28 08:44:30 +0000625 if (MI.isDebugValue()) {
626 // Replace DBG_VALUE instruction with modified version using the
627 // register from the replacing LEA and the address displacement
628 // between the LEA instructions.
629 replaceDebugValue(MI, FirstVReg, AddrDispShift);
630 continue;
631 }
632
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000633 // Get the number of the first memory operand.
634 const MCInstrDesc &Desc = MI.getDesc();
635 int MemOpNo =
Craig Topper477649a2016-04-28 05:58:46 +0000636 X86II::getMemoryOperandNo(Desc.TSFlags) +
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000637 X86II::getOperandBias(Desc);
638
639 // Update address base.
Andrew Ng03e35b62017-04-28 08:44:30 +0000640 MO.setReg(FirstVReg);
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000641
642 // Update address disp.
Andrey Turetskiy0babd262016-02-20 10:58:28 +0000643 MachineOperand &Op = MI.getOperand(MemOpNo + X86::AddrDisp);
644 if (Op.isImm())
645 Op.setImm(Op.getImm() + AddrDispShift);
646 else if (!Op.isJTI())
647 Op.setOffset(Op.getOffset() + AddrDispShift);
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000648 }
649
650 // Since we can possibly extend register lifetime, clear kill flags.
Andrew Ng03e35b62017-04-28 08:44:30 +0000651 MRI->clearKillFlags(FirstVReg);
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000652
653 ++NumRedundantLEAs;
Nicola Zaghend34e60c2018-05-14 12:53:11 +0000654 LLVM_DEBUG(dbgs() << "OptimizeLEAs: Remove redundant LEA: ";
655 Last.dump(););
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000656
657 // By this moment, all of the Last LEA's uses must be replaced. So we
658 // can freely remove it.
Andrea Di Biagio7937be72017-03-21 11:36:21 +0000659 assert(MRI->use_empty(LastVReg) &&
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000660 "The LEA's def register must have no uses");
661 Last.eraseFromParent();
662
663 // Erase removed LEA from the list.
664 I2 = List.erase(I2);
665
666 Changed = true;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000667 }
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000668 ++I1;
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000669 }
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000670 }
671
672 return Changed;
673}
674
Pengfei Wang7630e242019-08-22 02:29:27 +0000675bool X86OptimizeLEAPass::runOnMachineFunction(MachineFunction &MF) {
Alexey Bataev7cf32472015-12-04 10:53:15 +0000676 bool Changed = false;
Alexey Bataev7cf32472015-12-04 10:53:15 +0000677
Matthias Braunf1caa282017-12-15 22:22:58 +0000678 if (DisableX86LEAOpt || skipFunction(MF.getFunction()))
Alexey Bataev7cf32472015-12-04 10:53:15 +0000679 return false;
680
681 MRI = &MF.getRegInfo();
682 TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
683 TRI = MF.getSubtarget<X86Subtarget>().getRegisterInfo();
684
685 // Process all basic blocks.
686 for (auto &MBB : MF) {
Andrey Turetskiybca0f992016-02-04 08:57:03 +0000687 MemOpMap LEAs;
Alexey Bataev28f0c5e2016-01-11 11:52:29 +0000688 InstrPos.clear();
Alexey Bataev7cf32472015-12-04 10:53:15 +0000689
690 // Find all LEA instructions in basic block.
691 findLEAs(MBB, LEAs);
692
693 // If current basic block has no LEAs, move on to the next one.
694 if (LEAs.empty())
695 continue;
696
Andrey Turetskiy45b22a42016-05-19 10:18:29 +0000697 // Remove redundant LEA instructions.
698 Changed |= removeRedundantLEAs(LEAs);
Andrey Turetskiy1ce2c992016-01-13 11:30:44 +0000699
Andrey Turetskiy45b22a42016-05-19 10:18:29 +0000700 // Remove redundant address calculations. Do it only for -Os/-Oz since only
701 // a code size gain is expected from this part of the pass.
Evandro Menezes85bd3972019-04-04 22:40:06 +0000702 if (MF.getFunction().hasOptSize())
Andrey Turetskiy45b22a42016-05-19 10:18:29 +0000703 Changed |= removeRedundantAddrCalc(LEAs);
Alexey Bataev7cf32472015-12-04 10:53:15 +0000704 }
705
706 return Changed;
707}