576f39d3c3a389977e8a5b4c120c19adb4392f94
[oota-llvm.git] / lib / Target / X86 / X86FixupLEAs.cpp
1 //===-- X86FixupLEAs.cpp - use or replace 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 which will find  instructions  which
11 // can be re-written as LEA instructions in order to reduce pipeline
12 // delays for some models of the Intel Atom family.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "X86.h"
17 #include "X86InstrInfo.h"
18 #include "X86Subtarget.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/CodeGen/LiveVariables.h"
21 #include "llvm/CodeGen/MachineFunctionPass.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/Passes.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetInstrInfo.h"
28 using namespace llvm;
29
30 #define DEBUG_TYPE "x86-fixup-LEAs"
31
32 STATISTIC(NumLEAs, "Number of LEA instructions created");
33
34 namespace {
35   class FixupLEAPass : public MachineFunctionPass {
36     enum RegUsageState { RU_NotUsed, RU_Write, RU_Read };
37     static char ID;
38     /// \brief Loop over all of the instructions in the basic block
39     /// replacing applicable instructions with LEA instructions,
40     /// where appropriate.
41     bool processBasicBlock(MachineFunction &MF, MachineFunction::iterator MFI);
42
43     const char *getPassName() const override { return "X86 Atom LEA Fixup";}
44
45     /// \brief Given a machine register, look for the instruction
46     /// which writes it in the current basic block. If found,
47     /// try to replace it with an equivalent LEA instruction.
48     /// If replacement succeeds, then also process the the newly created
49     /// instruction.
50     void  seekLEAFixup(MachineOperand& p, MachineBasicBlock::iterator& I,
51                       MachineFunction::iterator MFI);
52
53     /// \brief Given a memory access or LEA instruction
54     /// whose address mode uses a base and/or index register, look for
55     /// an opportunity to replace the instruction which sets the base or index
56     /// register with an equivalent LEA instruction.
57     void processInstruction(MachineBasicBlock::iterator& I,
58                             MachineFunction::iterator MFI);
59
60     /// \brief Given a LEA instruction which is unprofitable
61     /// on Silvermont try to replace it with an equivalent ADD instruction
62     void processInstructionForSLM(MachineBasicBlock::iterator& I,
63                                   MachineFunction::iterator MFI);
64
65     /// \brief Determine if an instruction references a machine register
66     /// and, if so, whether it reads or writes the register.
67     RegUsageState usesRegister(MachineOperand& p,
68                                MachineBasicBlock::iterator I);
69
70     /// \brief Step backwards through a basic block, looking
71     /// for an instruction which writes a register within 
72     /// a maximum of INSTR_DISTANCE_THRESHOLD instruction latency cycles.
73     MachineBasicBlock::iterator searchBackwards(MachineOperand& p,
74                                                 MachineBasicBlock::iterator& I,
75                                                 MachineFunction::iterator MFI);
76
77     /// \brief if an instruction can be converted to an 
78     /// equivalent LEA, insert the new instruction into the basic block
79     /// and return a pointer to it. Otherwise, return zero.
80     MachineInstr* postRAConvertToLEA(MachineFunction::iterator &MFI,
81                                      MachineBasicBlock::iterator &MBBI) const;
82
83   public:
84     FixupLEAPass() : MachineFunctionPass(ID) {}
85
86     /// \brief Loop over all of the basic blocks,
87     /// replacing instructions by equivalent LEA instructions
88     /// if needed and when possible.
89     bool runOnMachineFunction(MachineFunction &MF) override;
90
91   private:
92     MachineFunction *MF;
93     const TargetMachine *TM;
94     const X86InstrInfo *TII; // Machine instruction info.
95
96   };
97   char FixupLEAPass::ID = 0;
98 }
99
100 MachineInstr *
101 FixupLEAPass::postRAConvertToLEA(MachineFunction::iterator &MFI,
102                                  MachineBasicBlock::iterator &MBBI) const {
103   MachineInstr* MI = MBBI;
104   MachineInstr* NewMI;
105   switch (MI->getOpcode()) {
106   case X86::MOV32rr:
107   case X86::MOV64rr: {
108     const MachineOperand& Src = MI->getOperand(1);
109     const MachineOperand& Dest = MI->getOperand(0);
110     NewMI = BuildMI(*MF, MI->getDebugLoc(),
111       TII->get( MI->getOpcode() == X86::MOV32rr ? X86::LEA32r : X86::LEA64r))
112       .addOperand(Dest)
113       .addOperand(Src).addImm(1).addReg(0).addImm(0).addReg(0);
114     MFI->insert(MBBI, NewMI);   // Insert the new inst
115     return NewMI;
116   }
117   case X86::ADD64ri32:
118   case X86::ADD64ri8:
119   case X86::ADD64ri32_DB:
120   case X86::ADD64ri8_DB:
121   case X86::ADD32ri:
122   case X86::ADD32ri8:
123   case X86::ADD32ri_DB:
124   case X86::ADD32ri8_DB:
125   case X86::ADD16ri:
126   case X86::ADD16ri8:
127   case X86::ADD16ri_DB:
128   case X86::ADD16ri8_DB:
129     if (!MI->getOperand(2).isImm()) {
130       // convertToThreeAddress will call getImm()
131       // which requires isImm() to be true
132       return nullptr;
133     }
134     break;
135   case X86::ADD16rr:
136   case X86::ADD16rr_DB:
137     if (MI->getOperand(1).getReg() != MI->getOperand(2).getReg()) {
138       // if src1 != src2, then convertToThreeAddress will
139       // need to create a Virtual register, which we cannot do
140       // after register allocation.
141       return nullptr;
142     }
143   }
144   return TII->convertToThreeAddress(MFI, MBBI, nullptr);
145 }
146
147 FunctionPass *llvm::createX86FixupLEAs() {
148   return new FixupLEAPass();
149 }
150
151 bool FixupLEAPass::runOnMachineFunction(MachineFunction &Func) {
152   MF = &Func;
153   TM = &MF->getTarget();
154   TII = static_cast<const X86InstrInfo*>(TM->getInstrInfo());
155
156   DEBUG(dbgs() << "Start X86FixupLEAs\n";);
157   // Process all basic blocks.
158   for (MachineFunction::iterator I = Func.begin(), E = Func.end(); I != E; ++I)
159     processBasicBlock(Func, I);
160   DEBUG(dbgs() << "End X86FixupLEAs\n";);
161
162   return true;
163 }
164
165 FixupLEAPass::RegUsageState FixupLEAPass::usesRegister(MachineOperand& p,
166                                 MachineBasicBlock::iterator I) {
167   RegUsageState RegUsage = RU_NotUsed;
168   MachineInstr* MI = I;
169
170   for (unsigned int i = 0; i < MI->getNumOperands(); ++i) {
171     MachineOperand& opnd = MI->getOperand(i);
172     if (opnd.isReg() && opnd.getReg() == p.getReg()){
173       if (opnd.isDef())
174         return RU_Write;
175       RegUsage = RU_Read;
176     }
177   }
178   return RegUsage;
179 }
180
181 /// getPreviousInstr - Given a reference to an instruction in a basic
182 /// block, return a reference to the previous instruction in the block,
183 /// wrapping around to the last instruction of the block if the block
184 /// branches to itself.
185 static inline bool getPreviousInstr(MachineBasicBlock::iterator& I,
186                                     MachineFunction::iterator MFI) {
187   if (I == MFI->begin()) {
188     if (MFI->isPredecessor(MFI)) {
189       I = --MFI->end();
190       return true;
191     }
192     else
193       return false;
194   }
195   --I;
196   return true;
197 }
198
199 MachineBasicBlock::iterator FixupLEAPass::searchBackwards(MachineOperand& p,
200                                    MachineBasicBlock::iterator& I,
201                                    MachineFunction::iterator MFI) {
202   int InstrDistance = 1;
203   MachineBasicBlock::iterator CurInst;
204   static const int INSTR_DISTANCE_THRESHOLD = 5;
205
206   CurInst = I;
207   bool Found;
208   Found = getPreviousInstr(CurInst, MFI);
209   while( Found && I != CurInst) {
210     if (CurInst->isCall() || CurInst->isInlineAsm())
211       break;
212     if (InstrDistance > INSTR_DISTANCE_THRESHOLD)
213       break; // too far back to make a difference
214     if (usesRegister(p, CurInst) == RU_Write){
215       return CurInst;
216     }
217     InstrDistance += TII->getInstrLatency(TM->getInstrItineraryData(), CurInst);
218     Found = getPreviousInstr(CurInst, MFI);
219   }
220   return nullptr;
221 }
222
223 void FixupLEAPass::processInstruction(MachineBasicBlock::iterator& I,
224                                       MachineFunction::iterator MFI) {
225   // Process a load, store, or LEA instruction.
226   MachineInstr *MI = I;
227   int opcode = MI->getOpcode();
228   const MCInstrDesc& Desc = MI->getDesc();
229   int AddrOffset = X86II::getMemoryOperandNo(Desc.TSFlags, opcode);
230   if (AddrOffset >= 0) {
231     AddrOffset += X86II::getOperandBias(Desc);
232     MachineOperand& p = MI->getOperand(AddrOffset + X86::AddrBaseReg);
233     if (p.isReg() && p.getReg() != X86::ESP) {
234       seekLEAFixup(p, I, MFI);
235     }
236     MachineOperand& q = MI->getOperand(AddrOffset + X86::AddrIndexReg);
237     if (q.isReg() && q.getReg() != X86::ESP) {
238       seekLEAFixup(q, I, MFI);
239     }
240   }
241 }
242
243 void FixupLEAPass::seekLEAFixup(MachineOperand& p,
244                                 MachineBasicBlock::iterator& I,
245                                 MachineFunction::iterator MFI) {
246   MachineBasicBlock::iterator MBI = searchBackwards(p, I, MFI);
247   if (MBI) {
248     MachineInstr* NewMI = postRAConvertToLEA(MFI, MBI);
249     if (NewMI) {
250       ++NumLEAs;
251       DEBUG(dbgs() << "FixLEA: Candidate to replace:"; MBI->dump(););
252       // now to replace with an equivalent LEA...
253       DEBUG(dbgs() << "FixLEA: Replaced by: "; NewMI->dump(););
254       MFI->erase(MBI);
255       MachineBasicBlock::iterator J =
256                              static_cast<MachineBasicBlock::iterator> (NewMI);
257       processInstruction(J, MFI);
258     }
259   }
260 }
261
262 void FixupLEAPass::processInstructionForSLM(MachineBasicBlock::iterator &I,
263                                             MachineFunction::iterator MFI) {
264   MachineInstr *MI = I;
265   const int opcode = MI->getOpcode();
266   if (opcode != X86::LEA16r && opcode != X86::LEA32r && opcode != X86::LEA64r &&
267       opcode != X86::LEA64_32r)
268     return;
269   if (MI->getOperand(5).getReg() != 0 || !MI->getOperand(4).isImm() ||
270       !TII->isSafeToClobberEFLAGS(*MFI, I))
271     return;
272   const unsigned DstR = MI->getOperand(0).getReg();
273   const unsigned SrcR1 = MI->getOperand(1).getReg();
274   const unsigned SrcR2 = MI->getOperand(3).getReg();
275   if ((SrcR1 == 0 || SrcR1 != DstR) && (SrcR2 == 0 || SrcR2 != DstR))
276     return;
277   if (MI->getOperand(2).getImm() > 1)
278     return;
279   int addrr_opcode, addri_opcode;
280   switch (opcode) {
281   case X86::LEA16r:
282     addrr_opcode = X86::ADD16rr;
283     addri_opcode = X86::ADD16ri;
284     break;
285   case X86::LEA32r:
286     addrr_opcode = X86::ADD32rr;
287     addri_opcode = X86::ADD32ri;
288     break;
289   case X86::LEA64_32r:
290   case X86::LEA64r:
291     addrr_opcode = X86::ADD64rr;
292     addri_opcode = X86::ADD64ri32;
293     break;
294   default:
295     assert(false && "Unexpected LEA instruction");
296   }
297   DEBUG(dbgs() << "FixLEA: Candidate to replace:"; I->dump(););
298   DEBUG(dbgs() << "FixLEA: Replaced by: ";);
299   MachineInstr *NewMI = 0;
300   const MachineOperand &Dst = MI->getOperand(0);
301   // Make ADD instruction for two registers writing to LEA's destination
302   if (SrcR1 != 0 && SrcR2 != 0) {
303     const MachineOperand &Src1 = MI->getOperand(SrcR1 == DstR ? 1 : 3);
304     const MachineOperand &Src2 = MI->getOperand(SrcR1 == DstR ? 3 : 1);
305     NewMI = BuildMI(*MF, MI->getDebugLoc(), TII->get(addrr_opcode))
306                 .addOperand(Dst)
307                 .addOperand(Src1)
308                 .addOperand(Src2);
309     MFI->insert(I, NewMI);
310     DEBUG(NewMI->dump(););
311   }
312   // Make ADD instruction for immediate
313   if (MI->getOperand(4).getImm() != 0) {
314     const MachineOperand &SrcR = MI->getOperand(SrcR1 == DstR ? 1 : 3);
315     NewMI = BuildMI(*MF, MI->getDebugLoc(), TII->get(addri_opcode))
316                 .addOperand(Dst)
317                 .addOperand(SrcR)
318                 .addImm(MI->getOperand(4).getImm());
319     MFI->insert(I, NewMI);
320     DEBUG(NewMI->dump(););
321   }
322   if (NewMI) {
323     MFI->erase(I);
324     I = static_cast<MachineBasicBlock::iterator>(NewMI);
325   }
326 }
327
328 bool FixupLEAPass::processBasicBlock(MachineFunction &MF,
329                                      MachineFunction::iterator MFI) {
330
331   for (MachineBasicBlock::iterator I = MFI->begin(); I != MFI->end(); ++I) {
332     if (TM->getSubtarget<X86Subtarget>().isSLM())
333       processInstructionForSLM(I, MFI);
334     else
335       processInstruction(I, MFI);
336   }
337   return false;
338 }