[X86][SSE] Update the cost table for integer-integer conversions on SSE2/SSE4.1.
[oota-llvm.git] / lib / Target / X86 / X86OptimizeLEAs.cpp
1 //===-- 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.
12 // Currently, it does one thing:
13 // 1) Address calculations in load and store instructions are replaced by
14 //    existing LEA def registers where possible.
15 //
16 //===----------------------------------------------------------------------===//
17
18 #include "X86.h"
19 #include "X86InstrInfo.h"
20 #include "X86Subtarget.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/CodeGen/LiveVariables.h"
23 #include "llvm/CodeGen/MachineFunctionPass.h"
24 #include "llvm/CodeGen/MachineInstrBuilder.h"
25 #include "llvm/CodeGen/MachineRegisterInfo.h"
26 #include "llvm/CodeGen/Passes.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/raw_ostream.h"
30 #include "llvm/Target/TargetInstrInfo.h"
31
32 using namespace llvm;
33
34 #define DEBUG_TYPE "x86-optimize-LEAs"
35
36 STATISTIC(NumSubstLEAs, "Number of LEA instruction substitutions");
37
38 namespace {
39 class OptimizeLEAPass : public MachineFunctionPass {
40 public:
41   OptimizeLEAPass() : MachineFunctionPass(ID) {}
42
43   const char *getPassName() const override { return "X86 LEA Optimize"; }
44
45   /// \brief Loop over all of the basic blocks, replacing address
46   /// calculations in load and store instructions, if it's already
47   /// been calculated by LEA. Also, remove redundant LEAs.
48   bool runOnMachineFunction(MachineFunction &MF) override;
49
50 private:
51   /// \brief Returns a distance between two instructions inside one basic block.
52   /// Negative result means, that instructions occur in reverse order.
53   int calcInstrDist(const MachineInstr &First, const MachineInstr &Last);
54
55   /// \brief Choose the best \p LEA instruction from the \p List to replace
56   /// address calculation in \p MI instruction. Return the address displacement
57   /// and the distance between \p MI and the choosen \p LEA in \p AddrDispShift
58   /// and \p Dist.
59   bool chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
60                      const MachineInstr &MI, MachineInstr *&LEA,
61                      int64_t &AddrDispShift, int &Dist);
62
63   /// \brief Returns true if two machine operand are identical and they are not
64   /// physical registers.
65   bool isIdenticalOp(const MachineOperand &MO1, const MachineOperand &MO2);
66
67   /// \brief Returns true if the instruction is LEA.
68   bool isLEA(const MachineInstr &MI);
69
70   /// \brief Returns true if two instructions have memory operands that only
71   /// differ by displacement. The numbers of the first memory operands for both
72   /// instructions are specified through \p N1 and \p N2. The address
73   /// displacement is returned through AddrDispShift.
74   bool isSimilarMemOp(const MachineInstr &MI1, unsigned N1,
75                       const MachineInstr &MI2, unsigned N2,
76                       int64_t &AddrDispShift);
77
78   /// \brief Find all LEA instructions in the basic block.
79   void findLEAs(const MachineBasicBlock &MBB,
80                 SmallVectorImpl<MachineInstr *> &List);
81
82   /// \brief Removes redundant address calculations.
83   bool removeRedundantAddrCalc(const SmallVectorImpl<MachineInstr *> &List);
84
85   MachineRegisterInfo *MRI;
86   const X86InstrInfo *TII;
87   const X86RegisterInfo *TRI;
88
89   static char ID;
90 };
91 char OptimizeLEAPass::ID = 0;
92 }
93
94 FunctionPass *llvm::createX86OptimizeLEAs() { return new OptimizeLEAPass(); }
95
96 int OptimizeLEAPass::calcInstrDist(const MachineInstr &First,
97                                    const MachineInstr &Last) {
98   const MachineBasicBlock *MBB = First.getParent();
99
100   // Both instructions must be in the same basic block.
101   assert(Last.getParent() == MBB &&
102          "Instructions are in different basic blocks");
103
104   return std::distance(MBB->begin(), MachineBasicBlock::const_iterator(&Last)) -
105          std::distance(MBB->begin(), MachineBasicBlock::const_iterator(&First));
106 }
107
108 // Find the best LEA instruction in the List to replace address recalculation in
109 // MI. Such LEA must meet these requirements:
110 // 1) The address calculated by the LEA differs only by the displacement from
111 //    the address used in MI.
112 // 2) The register class of the definition of the LEA is compatible with the
113 //    register class of the address base register of MI.
114 // 3) Displacement of the new memory operand should fit in 1 byte if possible.
115 // 4) The LEA should be as close to MI as possible, and prior to it if
116 //    possible.
117 bool OptimizeLEAPass::chooseBestLEA(const SmallVectorImpl<MachineInstr *> &List,
118                                     const MachineInstr &MI, MachineInstr *&LEA,
119                                     int64_t &AddrDispShift, int &Dist) {
120   const MachineFunction *MF = MI.getParent()->getParent();
121   const MCInstrDesc &Desc = MI.getDesc();
122   int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags, MI.getOpcode()) +
123                 X86II::getOperandBias(Desc);
124
125   LEA = nullptr;
126
127   // Loop over all LEA instructions.
128   for (auto DefMI : List) {
129     int64_t AddrDispShiftTemp = 0;
130
131     // Compare instructions memory operands.
132     if (!isSimilarMemOp(MI, MemOpNo, *DefMI, 1, AddrDispShiftTemp))
133       continue;
134
135     // Make sure address displacement fits 4 bytes.
136     if (!isInt<32>(AddrDispShiftTemp))
137       continue;
138
139     // Check that LEA def register can be used as MI address base. Some
140     // instructions can use a limited set of registers as address base, for
141     // example MOV8mr_NOREX. We could constrain the register class of the LEA
142     // def to suit MI, however since this case is very rare and hard to
143     // reproduce in a test it's just more reliable to skip the LEA.
144     if (TII->getRegClass(Desc, MemOpNo + X86::AddrBaseReg, TRI, *MF) !=
145         MRI->getRegClass(DefMI->getOperand(0).getReg()))
146       continue;
147
148     // Choose the closest LEA instruction from the list, prior to MI if
149     // possible. Note that we took into account resulting address displacement
150     // as well. Also note that the list is sorted by the order in which the LEAs
151     // occur, so the break condition is pretty simple.
152     int DistTemp = calcInstrDist(*DefMI, MI);
153     assert(DistTemp != 0 &&
154            "The distance between two different instructions cannot be zero");
155     if (DistTemp > 0 || LEA == nullptr) {
156       // Do not update return LEA, if the current one provides a displacement
157       // which fits in 1 byte, while the new candidate does not.
158       if (LEA != nullptr && !isInt<8>(AddrDispShiftTemp) &&
159           isInt<8>(AddrDispShift))
160         continue;
161
162       LEA = DefMI;
163       AddrDispShift = AddrDispShiftTemp;
164       Dist = DistTemp;
165     }
166
167     // FIXME: Maybe we should not always stop at the first LEA after MI.
168     if (DistTemp < 0)
169       break;
170   }
171
172   return LEA != nullptr;
173 }
174
175 bool OptimizeLEAPass::isIdenticalOp(const MachineOperand &MO1,
176                                     const MachineOperand &MO2) {
177   return MO1.isIdenticalTo(MO2) &&
178          (!MO1.isReg() ||
179           !TargetRegisterInfo::isPhysicalRegister(MO1.getReg()));
180 }
181
182 bool OptimizeLEAPass::isLEA(const MachineInstr &MI) {
183   unsigned Opcode = MI.getOpcode();
184   return Opcode == X86::LEA16r || Opcode == X86::LEA32r ||
185          Opcode == X86::LEA64r || Opcode == X86::LEA64_32r;
186 }
187
188 // Check if MI1 and MI2 have memory operands which represent addresses that
189 // differ only by displacement.
190 bool OptimizeLEAPass::isSimilarMemOp(const MachineInstr &MI1, unsigned N1,
191                                      const MachineInstr &MI2, unsigned N2,
192                                      int64_t &AddrDispShift) {
193   // Address base, scale, index and segment operands must be identical.
194   static const int IdenticalOpNums[] = {X86::AddrBaseReg, X86::AddrScaleAmt,
195                                         X86::AddrIndexReg, X86::AddrSegmentReg};
196   for (auto &N : IdenticalOpNums)
197     if (!isIdenticalOp(MI1.getOperand(N1 + N), MI2.getOperand(N2 + N)))
198       return false;
199
200   // Address displacement operands may differ by a constant.
201   const MachineOperand *Op1 = &MI1.getOperand(N1 + X86::AddrDisp);
202   const MachineOperand *Op2 = &MI2.getOperand(N2 + X86::AddrDisp);
203   if (!isIdenticalOp(*Op1, *Op2)) {
204     if (Op1->isImm() && Op2->isImm())
205       AddrDispShift = Op1->getImm() - Op2->getImm();
206     else if (Op1->isGlobal() && Op2->isGlobal() &&
207              Op1->getGlobal() == Op2->getGlobal())
208       AddrDispShift = Op1->getOffset() - Op2->getOffset();
209     else
210       return false;
211   }
212
213   return true;
214 }
215
216 void OptimizeLEAPass::findLEAs(const MachineBasicBlock &MBB,
217                                SmallVectorImpl<MachineInstr *> &List) {
218   for (auto &MI : MBB) {
219     if (isLEA(MI))
220       List.push_back(const_cast<MachineInstr *>(&MI));
221   }
222 }
223
224 // Try to find load and store instructions which recalculate addresses already
225 // calculated by some LEA and replace their memory operands with its def
226 // register.
227 bool OptimizeLEAPass::removeRedundantAddrCalc(
228     const SmallVectorImpl<MachineInstr *> &List) {
229   bool Changed = false;
230
231   assert(List.size() > 0);
232   MachineBasicBlock *MBB = List[0]->getParent();
233
234   // Process all instructions in basic block.
235   for (auto I = MBB->begin(), E = MBB->end(); I != E;) {
236     MachineInstr &MI = *I++;
237     unsigned Opcode = MI.getOpcode();
238
239     // Instruction must be load or store.
240     if (!MI.mayLoadOrStore())
241       continue;
242
243     // Get the number of the first memory operand.
244     const MCInstrDesc &Desc = MI.getDesc();
245     int MemOpNo = X86II::getMemoryOperandNo(Desc.TSFlags, Opcode);
246
247     // If instruction has no memory operand - skip it.
248     if (MemOpNo < 0)
249       continue;
250
251     MemOpNo += X86II::getOperandBias(Desc);
252
253     // Get the best LEA instruction to replace address calculation.
254     MachineInstr *DefMI;
255     int64_t AddrDispShift;
256     int Dist;
257     if (!chooseBestLEA(List, MI, DefMI, AddrDispShift, Dist))
258       continue;
259
260     // If LEA occurs before current instruction, we can freely replace
261     // the instruction. If LEA occurs after, we can lift LEA above the
262     // instruction and this way to be able to replace it. Since LEA and the
263     // instruction have similar memory operands (thus, the same def
264     // instructions for these operands), we can always do that, without
265     // worries of using registers before their defs.
266     if (Dist < 0) {
267       DefMI->removeFromParent();
268       MBB->insert(MachineBasicBlock::iterator(&MI), DefMI);
269     }
270
271     // Since we can possibly extend register lifetime, clear kill flags.
272     MRI->clearKillFlags(DefMI->getOperand(0).getReg());
273
274     ++NumSubstLEAs;
275     DEBUG(dbgs() << "OptimizeLEAs: Candidate to replace: "; MI.dump(););
276
277     // Change instruction operands.
278     MI.getOperand(MemOpNo + X86::AddrBaseReg)
279         .ChangeToRegister(DefMI->getOperand(0).getReg(), false);
280     MI.getOperand(MemOpNo + X86::AddrScaleAmt).ChangeToImmediate(1);
281     MI.getOperand(MemOpNo + X86::AddrIndexReg)
282         .ChangeToRegister(X86::NoRegister, false);
283     MI.getOperand(MemOpNo + X86::AddrDisp).ChangeToImmediate(AddrDispShift);
284     MI.getOperand(MemOpNo + X86::AddrSegmentReg)
285         .ChangeToRegister(X86::NoRegister, false);
286
287     DEBUG(dbgs() << "OptimizeLEAs: Replaced by: "; MI.dump(););
288
289     Changed = true;
290   }
291
292   return Changed;
293 }
294
295 bool OptimizeLEAPass::runOnMachineFunction(MachineFunction &MF) {
296   bool Changed = false;
297
298   // Perform this optimization only if we care about code size.
299   if (!MF.getFunction()->optForSize())
300     return false;
301
302   MRI = &MF.getRegInfo();
303   TII = MF.getSubtarget<X86Subtarget>().getInstrInfo();
304   TRI = MF.getSubtarget<X86Subtarget>().getRegisterInfo();
305
306   // Process all basic blocks.
307   for (auto &MBB : MF) {
308     SmallVector<MachineInstr *, 16> LEAs;
309
310     // Find all LEA instructions in basic block.
311     findLEAs(MBB, LEAs);
312
313     // If current basic block has no LEAs, move on to the next one.
314     if (LEAs.empty())
315       continue;
316
317     // Remove redundant address calculations.
318     Changed |= removeRedundantAddrCalc(LEAs);
319   }
320
321   return Changed;
322 }