Add OR and XOR memory operand support.
[oota-llvm.git] / lib / Target / X86 / X86PeepholeOpt.cpp
1 //===-- PeepholeOptimizer.cpp - X86 Peephole Optimizer --------------------===//
2 // 
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file was developed by the LLVM research group and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 // 
8 //===----------------------------------------------------------------------===//
9 //
10 // This file contains a peephole optimizer for the X86.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "X86.h"
15 #include "llvm/CodeGen/MachineFunctionPass.h"
16 #include "llvm/CodeGen/MachineInstrBuilder.h"
17 #include "llvm/Target/MRegisterInfo.h"
18 #include "Support/Statistic.h"
19 #include "Support/STLExtras.h"
20
21 using namespace llvm;
22
23 namespace {
24   Statistic<> NumPHOpts("x86-peephole",
25                         "Number of peephole optimization performed");
26   struct PH : public MachineFunctionPass {
27     virtual bool runOnMachineFunction(MachineFunction &MF);
28
29     bool PeepholeOptimize(MachineBasicBlock &MBB,
30                           MachineBasicBlock::iterator &I);
31
32     virtual const char *getPassName() const { return "X86 Peephole Optimizer"; }
33   };
34 }
35
36 FunctionPass *llvm::createX86PeepholeOptimizerPass() { return new PH(); }
37
38 bool PH::runOnMachineFunction(MachineFunction &MF) {
39   bool Changed = false;
40
41   for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI != E; ++BI)
42     for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); )
43       if (PeepholeOptimize(*BI, I)) {
44         Changed = true;
45         ++NumPHOpts;
46       } else
47         ++I;
48
49   return Changed;
50 }
51
52
53 bool PH::PeepholeOptimize(MachineBasicBlock &MBB,
54                           MachineBasicBlock::iterator &I) {
55   assert(I != MBB.end());
56   MachineBasicBlock::iterator NextI = next(I);
57
58   MachineInstr *MI = I;
59   MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
60   unsigned Size = 0;
61   switch (MI->getOpcode()) {
62   case X86::MOVrr8:
63   case X86::MOVrr16:
64   case X86::MOVrr32:   // Destroy X = X copies...
65     if (MI->getOperand(0).getReg() == MI->getOperand(1).getReg()) {
66       I = MBB.erase(I);
67       return true;
68     }
69     return false;
70
71     // A large number of X86 instructions have forms which take an 8-bit
72     // immediate despite the fact that the operands are 16 or 32 bits.  Because
73     // this can save three bytes of code size (and icache space), we want to
74     // shrink them if possible.
75   case X86::IMULrri16: case X86::IMULrri32:
76     assert(MI->getNumOperands() == 3 && "These should all have 3 operands!");
77     if (MI->getOperand(2).isImmediate()) {
78       int Val = MI->getOperand(2).getImmedValue();
79       // If the value is the same when signed extended from 8 bits...
80       if (Val == (signed int)(signed char)Val) {
81         unsigned Opcode;
82         switch (MI->getOpcode()) {
83         default: assert(0 && "Unknown opcode value!");
84         case X86::IMULrri16: Opcode = X86::IMULrri16b; break;
85         case X86::IMULrri32: Opcode = X86::IMULrri32b; break;
86         }
87         unsigned R0 = MI->getOperand(0).getReg();
88         unsigned R1 = MI->getOperand(1).getReg();
89         I = MBB.insert(MBB.erase(I),
90                        BuildMI(Opcode, 2, R0).addReg(R1).addZImm((char)Val));
91         return true;
92       }
93     }
94     return false;
95
96 #if 0
97   case X86::IMULrmi16: case X86::IMULrmi32:
98     assert(MI->getNumOperands() == 6 && "These should all have 6 operands!");
99     if (MI->getOperand(5).isImmediate()) {
100       int Val = MI->getOperand(5).getImmedValue();
101       // If the value is the same when signed extended from 8 bits...
102       if (Val == (signed int)(signed char)Val) {
103         unsigned Opcode;
104         switch (MI->getOpcode()) {
105         default: assert(0 && "Unknown opcode value!");
106         case X86::IMULrmi16: Opcode = X86::IMULrmi16b; break;
107         case X86::IMULrmi32: Opcode = X86::IMULrmi32b; break;
108         }
109         unsigned R0 = MI->getOperand(0).getReg();
110         unsigned R1 = MI->getOperand(1).getReg();
111         unsigned Scale = MI->getOperand(2).getImmedValue();
112         unsigned R2 = MI->getOperand(3).getReg();
113         unsigned Offset = MI->getOperand(4).getImmedValue();
114         I = MBB.insert(MBB.erase(I),
115                        BuildMI(Opcode, 5, R0).addReg(R1).addZImm(Scale).
116                              addReg(R2).addSImm(Offset).addZImm((char)Val));
117         return true;
118       }
119     }
120     return false;
121 #endif
122
123   case X86::ADDri16:  case X86::ADDri32:
124   case X86::SUBri16:  case X86::SUBri32:
125   case X86::ANDri16:  case X86::ANDri32:
126   case X86::ORri16:   case X86::ORri32:
127   case X86::XORri16:  case X86::XORri32:
128     assert(MI->getNumOperands() == 2 && "These should all have 2 operands!");
129     if (MI->getOperand(1).isImmediate()) {
130       int Val = MI->getOperand(1).getImmedValue();
131       // If the value is the same when signed extended from 8 bits...
132       if (Val == (signed int)(signed char)Val) {
133         unsigned Opcode;
134         switch (MI->getOpcode()) {
135         default: assert(0 && "Unknown opcode value!");
136         case X86::ADDri16:  Opcode = X86::ADDri16b; break;
137         case X86::ADDri32:  Opcode = X86::ADDri32b; break;
138         case X86::SUBri16:  Opcode = X86::SUBri16b; break;
139         case X86::SUBri32:  Opcode = X86::SUBri32b; break;
140         case X86::ANDri16:  Opcode = X86::ANDri16b; break;
141         case X86::ANDri32:  Opcode = X86::ANDri32b; break;
142         case X86::ORri16:   Opcode = X86::ORri16b; break;
143         case X86::ORri32:   Opcode = X86::ORri32b; break;
144         case X86::XORri16:  Opcode = X86::XORri16b; break;
145         case X86::XORri32:  Opcode = X86::XORri32b; break;
146         }
147         unsigned R0 = MI->getOperand(0).getReg();
148         I = MBB.insert(MBB.erase(I),
149                     BuildMI(Opcode, 1, R0, MOTy::UseAndDef).addZImm((char)Val));
150         return true;
151       }
152     }
153     return false;
154
155
156   case X86::ADDmi16:  case X86::ADDmi32:
157   case X86::SUBmi16:  case X86::SUBmi32:
158   case X86::ANDmi16:  case X86::ANDmi32:
159   case X86::ORmi16:  case X86::ORmi32:
160   case X86::XORmi16:  case X86::XORmi32:
161     assert(MI->getNumOperands() == 5 && "These should all have 5 operands!");
162     if (MI->getOperand(4).isImmediate()) {
163       int Val = MI->getOperand(4).getImmedValue();
164       // If the value is the same when signed extended from 8 bits...
165       if (Val == (signed int)(signed char)Val) {
166         unsigned Opcode;
167         switch (MI->getOpcode()) {
168         default: assert(0 && "Unknown opcode value!");
169         case X86::ADDmi16:  Opcode = X86::ADDmi16b; break;
170         case X86::ADDmi32:  Opcode = X86::ADDmi32b; break;
171         case X86::SUBmi16:  Opcode = X86::SUBmi16b; break;
172         case X86::SUBmi32:  Opcode = X86::SUBmi32b; break;
173         case X86::ANDmi16:  Opcode = X86::ANDmi16b; break;
174         case X86::ANDmi32:  Opcode = X86::ANDmi32b; break;
175         case X86::ORmi16:   Opcode = X86::ORmi16b; break;
176         case X86::ORmi32:   Opcode = X86::ORmi32b; break;
177         case X86::XORmi16:  Opcode = X86::XORmi16b; break;
178         case X86::XORmi32:  Opcode = X86::XORmi32b; break;
179         }
180         unsigned R0 = MI->getOperand(0).getReg();
181         unsigned Scale = MI->getOperand(1).getImmedValue();
182         unsigned R1 = MI->getOperand(2).getReg();
183         unsigned Offset = MI->getOperand(3).getImmedValue();
184         I = MBB.insert(MBB.erase(I),
185                        BuildMI(Opcode, 5).addReg(R0).addZImm(Scale).
186                              addReg(R1).addSImm(Offset).addZImm((char)Val));
187         return true;
188       }
189     }
190     return false;
191
192 #if 0
193   case X86::MOVri32: Size++;
194   case X86::MOVri16: Size++;
195   case X86::MOVri8:
196     // FIXME: We can only do this transformation if we know that flags are not
197     // used here, because XOR clobbers the flags!
198     if (MI->getOperand(1).isImmediate()) {         // avoid mov EAX, <value>
199       int Val = MI->getOperand(1).getImmedValue();
200       if (Val == 0) {                              // mov EAX, 0 -> xor EAX, EAX
201         static const unsigned Opcode[] ={X86::XORrr8,X86::XORrr16,X86::XORrr32};
202         unsigned Reg = MI->getOperand(0).getReg();
203         I = MBB.insert(MBB.erase(I),
204                        BuildMI(Opcode[Size], 2, Reg).addReg(Reg).addReg(Reg));
205         return true;
206       } else if (Val == -1) {                     // mov EAX, -1 -> or EAX, -1
207         // TODO: 'or Reg, -1' has a smaller encoding than 'mov Reg, -1'
208       }
209     }
210     return false;
211 #endif
212   case X86::BSWAPr32:        // Change bswap EAX, bswap EAX into nothing
213     if (Next->getOpcode() == X86::BSWAPr32 &&
214         MI->getOperand(0).getReg() == Next->getOperand(0).getReg()) {
215       I = MBB.erase(MBB.erase(I));
216       return true;
217     }
218     return false;
219   default:
220     return false;
221   }
222 }
223
224 namespace {
225   class UseDefChains : public MachineFunctionPass {
226     std::vector<MachineInstr*> DefiningInst;
227   public:
228     // getDefinition - Return the machine instruction that defines the specified
229     // SSA virtual register.
230     MachineInstr *getDefinition(unsigned Reg) {
231       assert(MRegisterInfo::isVirtualRegister(Reg) &&
232              "use-def chains only exist for SSA registers!");
233       assert(Reg - MRegisterInfo::FirstVirtualRegister < DefiningInst.size() &&
234              "Unknown register number!");
235       assert(DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] &&
236              "Unknown register number!");
237       return DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister];
238     }
239
240     // setDefinition - Update the use-def chains to indicate that MI defines
241     // register Reg.
242     void setDefinition(unsigned Reg, MachineInstr *MI) {
243       if (Reg-MRegisterInfo::FirstVirtualRegister >= DefiningInst.size())
244         DefiningInst.resize(Reg-MRegisterInfo::FirstVirtualRegister+1);
245       DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] = MI;
246     }
247
248     // removeDefinition - Update the use-def chains to forget about Reg
249     // entirely.
250     void removeDefinition(unsigned Reg) {
251       assert(getDefinition(Reg));      // Check validity
252       DefiningInst[Reg-MRegisterInfo::FirstVirtualRegister] = 0;
253     }
254
255     virtual bool runOnMachineFunction(MachineFunction &MF) {
256       for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI!=E; ++BI)
257         for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); ++I) {
258           for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i) {
259             MachineOperand &MO = I->getOperand(i);
260             if (MO.isRegister() && MO.isDef() && !MO.isUse() &&
261                 MRegisterInfo::isVirtualRegister(MO.getReg()))
262               setDefinition(MO.getReg(), I);
263           }
264         }
265       return false;
266     }
267
268     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
269       AU.setPreservesAll();
270       MachineFunctionPass::getAnalysisUsage(AU);
271     }
272
273     virtual void releaseMemory() {
274       std::vector<MachineInstr*>().swap(DefiningInst);
275     }
276   };
277
278   RegisterAnalysis<UseDefChains> X("use-def-chains",
279                                 "use-def chain construction for machine code");
280 }
281
282
283 namespace {
284   Statistic<> NumSSAPHOpts("x86-ssa-peephole",
285                            "Number of SSA peephole optimization performed");
286
287   /// SSAPH - This pass is an X86-specific, SSA-based, peephole optimizer.  This
288   /// pass is really a bad idea: a better instruction selector should completely
289   /// supersume it.  However, that will take some time to develop, and the
290   /// simple things this can do are important now.
291   class SSAPH : public MachineFunctionPass {
292     UseDefChains *UDC;
293   public:
294     virtual bool runOnMachineFunction(MachineFunction &MF);
295
296     bool PeepholeOptimize(MachineBasicBlock &MBB,
297                           MachineBasicBlock::iterator &I);
298
299     virtual const char *getPassName() const {
300       return "X86 SSA-based Peephole Optimizer";
301     }
302
303     /// Propagate - Set MI[DestOpNo] = Src[SrcOpNo], optionally change the
304     /// opcode of the instruction, then return true.
305     bool Propagate(MachineInstr *MI, unsigned DestOpNo,
306                    MachineInstr *Src, unsigned SrcOpNo, unsigned NewOpcode = 0){
307       MI->getOperand(DestOpNo) = Src->getOperand(SrcOpNo);
308       if (NewOpcode) MI->setOpcode(NewOpcode);
309       return true;
310     }
311
312     /// OptimizeAddress - If we can fold the addressing arithmetic for this
313     /// memory instruction into the instruction itself, do so and return true.
314     bool OptimizeAddress(MachineInstr *MI, unsigned OpNo);
315
316     /// getDefininingInst - If the specified operand is a read of an SSA
317     /// register, return the machine instruction defining it, otherwise, return
318     /// null.
319     MachineInstr *getDefiningInst(MachineOperand &MO) {
320       if (MO.isDef() || !MO.isRegister() ||
321           !MRegisterInfo::isVirtualRegister(MO.getReg())) return 0;
322       return UDC->getDefinition(MO.getReg());
323     }
324
325     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
326       AU.addRequired<UseDefChains>();
327       AU.addPreserved<UseDefChains>();
328       MachineFunctionPass::getAnalysisUsage(AU);
329     }
330   };
331 }
332
333 FunctionPass *llvm::createX86SSAPeepholeOptimizerPass() { return new SSAPH(); }
334
335 bool SSAPH::runOnMachineFunction(MachineFunction &MF) {
336   bool Changed = false;
337   bool LocalChanged;
338
339   UDC = &getAnalysis<UseDefChains>();
340
341   do {
342     LocalChanged = false;
343
344     for (MachineFunction::iterator BI = MF.begin(), E = MF.end(); BI != E; ++BI)
345       for (MachineBasicBlock::iterator I = BI->begin(); I != BI->end(); )
346         if (PeepholeOptimize(*BI, I)) {
347           LocalChanged = true;
348           ++NumSSAPHOpts;
349         } else
350           ++I;
351     Changed |= LocalChanged;
352   } while (LocalChanged);
353
354   return Changed;
355 }
356
357 static bool isValidScaleAmount(unsigned Scale) {
358   return Scale == 1 || Scale == 2 || Scale == 4 || Scale == 8;
359 }
360
361 /// OptimizeAddress - If we can fold the addressing arithmetic for this
362 /// memory instruction into the instruction itself, do so and return true.
363 bool SSAPH::OptimizeAddress(MachineInstr *MI, unsigned OpNo) {
364   MachineOperand &BaseRegOp      = MI->getOperand(OpNo+0);
365   MachineOperand &ScaleOp        = MI->getOperand(OpNo+1);
366   MachineOperand &IndexRegOp     = MI->getOperand(OpNo+2);
367   MachineOperand &DisplacementOp = MI->getOperand(OpNo+3);
368
369   unsigned BaseReg  = BaseRegOp.hasAllocatedReg() ? BaseRegOp.getReg() : 0;
370   unsigned Scale    = ScaleOp.getImmedValue();
371   unsigned IndexReg = IndexRegOp.hasAllocatedReg() ? IndexRegOp.getReg() : 0;
372
373   bool Changed = false;
374
375   // If the base register is unset, and the index register is set with a scale
376   // of 1, move it to be the base register.
377   if (BaseRegOp.hasAllocatedReg() && BaseReg == 0 &&
378       Scale == 1 && IndexReg != 0) {
379     BaseRegOp.setReg(IndexReg);
380     IndexRegOp.setReg(0);
381     return true;
382   }
383
384   // Attempt to fold instructions used by the base register into the instruction
385   if (MachineInstr *DefInst = getDefiningInst(BaseRegOp)) {
386     switch (DefInst->getOpcode()) {
387     case X86::MOVri32:
388       // If there is no displacement set for this instruction set one now.
389       // FIXME: If we can fold two immediates together, we should do so!
390       if (DisplacementOp.isImmediate() && !DisplacementOp.getImmedValue()) {
391         if (DefInst->getOperand(1).isImmediate()) {
392           BaseRegOp.setReg(0);
393           return Propagate(MI, OpNo+3, DefInst, 1);
394         }
395       }
396       break;
397
398     case X86::ADDrr32:
399       // If the source is a register-register add, and we do not yet have an
400       // index register, fold the add into the memory address.
401       if (IndexReg == 0) {
402         BaseRegOp = DefInst->getOperand(1);
403         IndexRegOp = DefInst->getOperand(2);
404         ScaleOp.setImmedValue(1);
405         return true;
406       }
407       break;
408
409     case X86::SHLri32:
410       // If this shift could be folded into the index portion of the address if
411       // it were the index register, move it to the index register operand now,
412       // so it will be folded in below.
413       if ((Scale == 1 || (IndexReg == 0 && IndexRegOp.hasAllocatedReg())) &&
414           DefInst->getOperand(2).getImmedValue() < 4) {
415         std::swap(BaseRegOp, IndexRegOp);
416         ScaleOp.setImmedValue(1); Scale = 1;
417         std::swap(IndexReg, BaseReg);
418         Changed = true;
419         break;
420       }
421     }
422   }
423
424   // Attempt to fold instructions used by the index into the instruction
425   if (MachineInstr *DefInst = getDefiningInst(IndexRegOp)) {
426     switch (DefInst->getOpcode()) {
427     case X86::SHLri32: {
428       // Figure out what the resulting scale would be if we folded this shift.
429       unsigned ResScale = Scale * (1 << DefInst->getOperand(2).getImmedValue());
430       if (isValidScaleAmount(ResScale)) {
431         IndexRegOp = DefInst->getOperand(1);
432         ScaleOp.setImmedValue(ResScale);
433         return true;
434       }
435       break;
436     }
437     }
438   }
439
440   return Changed;
441 }
442
443 bool SSAPH::PeepholeOptimize(MachineBasicBlock &MBB,
444                              MachineBasicBlock::iterator &I) {
445     MachineBasicBlock::iterator NextI = next(I);
446
447   MachineInstr *MI = I;
448   MachineInstr *Next = (NextI != MBB.end()) ? &*NextI : (MachineInstr*)0;
449
450   bool Changed = false;
451
452   // Scan the operands of this instruction.  If any operands are
453   // register-register copies, replace the operand with the source.
454   for (unsigned i = 0, e = MI->getNumOperands(); i != e; ++i)
455     // Is this an SSA register use?
456     if (MachineInstr *DefInst = getDefiningInst(MI->getOperand(i)))
457       // If the operand is a vreg-vreg copy, it is always safe to replace the
458       // source value with the input operand.
459       if (DefInst->getOpcode() == X86::MOVrr8  ||
460           DefInst->getOpcode() == X86::MOVrr16 ||
461           DefInst->getOpcode() == X86::MOVrr32) {
462         // Don't propagate physical registers into PHI nodes...
463         if (MI->getOpcode() != X86::PHI ||
464             (DefInst->getOperand(1).isRegister() &&
465              MRegisterInfo::isVirtualRegister(DefInst->getOperand(1).getReg())))
466         Changed = Propagate(MI, i, DefInst, 1);
467       }
468   
469   
470   // Perform instruction specific optimizations.
471   switch (MI->getOpcode()) {
472
473     // Register to memory stores.  Format: <base,scale,indexreg,immdisp>, srcreg
474   case X86::MOVmr32: case X86::MOVmr16: case X86::MOVmr8:
475   case X86::MOVmi32: case X86::MOVmi16: case X86::MOVmi8:
476     // Check to see if we can fold the source instruction into this one...
477     if (MachineInstr *SrcInst = getDefiningInst(MI->getOperand(4))) {
478       switch (SrcInst->getOpcode()) {
479         // Fold the immediate value into the store, if possible.
480       case X86::MOVri8:  return Propagate(MI, 4, SrcInst, 1, X86::MOVmi8);
481       case X86::MOVri16: return Propagate(MI, 4, SrcInst, 1, X86::MOVmi16);
482       case X86::MOVri32: return Propagate(MI, 4, SrcInst, 1, X86::MOVmi32);
483       default: break;
484       }
485     }
486
487     // If we can optimize the addressing expression, do so now.
488     if (OptimizeAddress(MI, 0))
489       return true;
490     break;
491
492   case X86::MOVrm32:
493   case X86::MOVrm16:
494   case X86::MOVrm8:
495     // If we can optimize the addressing expression, do so now.
496     if (OptimizeAddress(MI, 1))
497       return true;
498     break;
499
500   default: break;
501   }
502
503   return Changed;
504 }