X86 Peephole: fold loads to the source register operand if possible.
[oota-llvm.git] / lib / CodeGen / PeepholeOptimizer.cpp
1 //===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
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 // Perform peephole optimizations on the machine code:
11 //
12 // - Optimize Extensions
13 //
14 //     Optimization of sign / zero extension instructions. It may be extended to
15 //     handle other instructions with similar properties.
16 //
17 //     On some targets, some instructions, e.g. X86 sign / zero extension, may
18 //     leave the source value in the lower part of the result. This optimization
19 //     will replace some uses of the pre-extension value with uses of the
20 //     sub-register of the results.
21 //
22 // - Optimize Comparisons
23 //
24 //     Optimization of comparison instructions. For instance, in this code:
25 //
26 //       sub r1, 1
27 //       cmp r1, 0
28 //       bz  L1
29 //
30 //     If the "sub" instruction all ready sets (or could be modified to set) the
31 //     same flag that the "cmp" instruction sets and that "bz" uses, then we can
32 //     eliminate the "cmp" instruction.
33 //
34 //     Another instance, in this code:
35 //
36 //       sub r1, r3 | sub r1, imm
37 //       cmp r3, r1 or cmp r1, r3 | cmp r1, imm
38 //       bge L1
39 //
40 //     If the branch instruction can use flag from "sub", then we can replace
41 //     "sub" with "subs" and eliminate the "cmp" instruction.
42 //
43 // - Optimize Bitcast pairs:
44 //
45 //     v1 = bitcast v0
46 //     v2 = bitcast v1
47 //        = v2
48 //   =>
49 //     v1 = bitcast v0
50 //        = v0
51 //
52 //===----------------------------------------------------------------------===//
53
54 #define DEBUG_TYPE "peephole-opt"
55 #include "llvm/CodeGen/Passes.h"
56 #include "llvm/CodeGen/MachineDominators.h"
57 #include "llvm/CodeGen/MachineInstrBuilder.h"
58 #include "llvm/CodeGen/MachineRegisterInfo.h"
59 #include "llvm/Target/TargetInstrInfo.h"
60 #include "llvm/Target/TargetRegisterInfo.h"
61 #include "llvm/Support/CommandLine.h"
62 #include "llvm/ADT/DenseMap.h"
63 #include "llvm/ADT/SmallPtrSet.h"
64 #include "llvm/ADT/SmallSet.h"
65 #include "llvm/ADT/Statistic.h"
66 using namespace llvm;
67
68 // Optimize Extensions
69 static cl::opt<bool>
70 Aggressive("aggressive-ext-opt", cl::Hidden,
71            cl::desc("Aggressive extension optimization"));
72
73 static cl::opt<bool>
74 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
75                 cl::desc("Disable the peephole optimizer"));
76
77 STATISTIC(NumReuse,      "Number of extension results reused");
78 STATISTIC(NumBitcasts,   "Number of bitcasts eliminated");
79 STATISTIC(NumCmps,       "Number of compares eliminated");
80 STATISTIC(NumImmFold,    "Number of move immediate folded");
81 STATISTIC(NumLoadFold,   "Number of loads folded");
82
83 namespace {
84   class PeepholeOptimizer : public MachineFunctionPass {
85     const TargetMachine   *TM;
86     const TargetInstrInfo *TII;
87     MachineRegisterInfo   *MRI;
88     MachineDominatorTree  *DT;  // Machine dominator tree
89
90   public:
91     static char ID; // Pass identification
92     PeepholeOptimizer() : MachineFunctionPass(ID) {
93       initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
94     }
95
96     virtual bool runOnMachineFunction(MachineFunction &MF);
97
98     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
99       AU.setPreservesCFG();
100       MachineFunctionPass::getAnalysisUsage(AU);
101       if (Aggressive) {
102         AU.addRequired<MachineDominatorTree>();
103         AU.addPreserved<MachineDominatorTree>();
104       }
105     }
106
107   private:
108     bool optimizeBitcastInstr(MachineInstr *MI, MachineBasicBlock *MBB);
109     bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
110     bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
111                           SmallPtrSet<MachineInstr*, 8> &LocalMIs);
112     bool isMoveImmediate(MachineInstr *MI,
113                          SmallSet<unsigned, 4> &ImmDefRegs,
114                          DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
115     bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
116                        SmallSet<unsigned, 4> &ImmDefRegs,
117                        DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
118     bool isLoadFoldable(MachineInstr *MI, unsigned &FoldAsLoadDefReg);
119   };
120 }
121
122 char PeepholeOptimizer::ID = 0;
123 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
124 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
125                 "Peephole Optimizations", false, false)
126 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
127 INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
128                 "Peephole Optimizations", false, false)
129
130 /// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
131 /// a single register and writes a single register and it does not modify the
132 /// source, and if the source value is preserved as a sub-register of the
133 /// result, then replace all reachable uses of the source with the subreg of the
134 /// result.
135 ///
136 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
137 /// the code. Since this code does not currently share EXTRACTs, just ignore all
138 /// debug uses.
139 bool PeepholeOptimizer::
140 optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
141                  SmallPtrSet<MachineInstr*, 8> &LocalMIs) {
142   unsigned SrcReg, DstReg, SubIdx;
143   if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
144     return false;
145
146   if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
147       TargetRegisterInfo::isPhysicalRegister(SrcReg))
148     return false;
149
150   if (MRI->hasOneNonDBGUse(SrcReg))
151     // No other uses.
152     return false;
153
154   // Ensure DstReg can get a register class that actually supports
155   // sub-registers. Don't change the class until we commit.
156   const TargetRegisterClass *DstRC = MRI->getRegClass(DstReg);
157   DstRC = TM->getRegisterInfo()->getSubClassWithSubReg(DstRC, SubIdx);
158   if (!DstRC)
159     return false;
160
161   // The ext instr may be operating on a sub-register of SrcReg as well.
162   // PPC::EXTSW is a 32 -> 64-bit sign extension, but it reads a 64-bit
163   // register.
164   // If UseSrcSubIdx is Set, SubIdx also applies to SrcReg, and only uses of
165   // SrcReg:SubIdx should be replaced.
166   bool UseSrcSubIdx = TM->getRegisterInfo()->
167     getSubClassWithSubReg(MRI->getRegClass(SrcReg), SubIdx) != 0;
168
169   // The source has other uses. See if we can replace the other uses with use of
170   // the result of the extension.
171   SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
172   for (MachineRegisterInfo::use_nodbg_iterator
173        UI = MRI->use_nodbg_begin(DstReg), UE = MRI->use_nodbg_end();
174        UI != UE; ++UI)
175     ReachedBBs.insert(UI->getParent());
176
177   // Uses that are in the same BB of uses of the result of the instruction.
178   SmallVector<MachineOperand*, 8> Uses;
179
180   // Uses that the result of the instruction can reach.
181   SmallVector<MachineOperand*, 8> ExtendedUses;
182
183   bool ExtendLife = true;
184   for (MachineRegisterInfo::use_nodbg_iterator
185        UI = MRI->use_nodbg_begin(SrcReg), UE = MRI->use_nodbg_end();
186        UI != UE; ++UI) {
187     MachineOperand &UseMO = UI.getOperand();
188     MachineInstr *UseMI = &*UI;
189     if (UseMI == MI)
190       continue;
191
192     if (UseMI->isPHI()) {
193       ExtendLife = false;
194       continue;
195     }
196
197     // Only accept uses of SrcReg:SubIdx.
198     if (UseSrcSubIdx && UseMO.getSubReg() != SubIdx)
199       continue;
200
201     // It's an error to translate this:
202     //
203     //    %reg1025 = <sext> %reg1024
204     //     ...
205     //    %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
206     //
207     // into this:
208     //
209     //    %reg1025 = <sext> %reg1024
210     //     ...
211     //    %reg1027 = COPY %reg1025:4
212     //    %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
213     //
214     // The problem here is that SUBREG_TO_REG is there to assert that an
215     // implicit zext occurs. It doesn't insert a zext instruction. If we allow
216     // the COPY here, it will give us the value after the <sext>, not the
217     // original value of %reg1024 before <sext>.
218     if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
219       continue;
220
221     MachineBasicBlock *UseMBB = UseMI->getParent();
222     if (UseMBB == MBB) {
223       // Local uses that come after the extension.
224       if (!LocalMIs.count(UseMI))
225         Uses.push_back(&UseMO);
226     } else if (ReachedBBs.count(UseMBB)) {
227       // Non-local uses where the result of the extension is used. Always
228       // replace these unless it's a PHI.
229       Uses.push_back(&UseMO);
230     } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
231       // We may want to extend the live range of the extension result in order
232       // to replace these uses.
233       ExtendedUses.push_back(&UseMO);
234     } else {
235       // Both will be live out of the def MBB anyway. Don't extend live range of
236       // the extension result.
237       ExtendLife = false;
238       break;
239     }
240   }
241
242   if (ExtendLife && !ExtendedUses.empty())
243     // Extend the liveness of the extension result.
244     std::copy(ExtendedUses.begin(), ExtendedUses.end(),
245               std::back_inserter(Uses));
246
247   // Now replace all uses.
248   bool Changed = false;
249   if (!Uses.empty()) {
250     SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
251
252     // Look for PHI uses of the extended result, we don't want to extend the
253     // liveness of a PHI input. It breaks all kinds of assumptions down
254     // stream. A PHI use is expected to be the kill of its source values.
255     for (MachineRegisterInfo::use_nodbg_iterator
256          UI = MRI->use_nodbg_begin(DstReg), UE = MRI->use_nodbg_end();
257          UI != UE; ++UI)
258       if (UI->isPHI())
259         PHIBBs.insert(UI->getParent());
260
261     const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
262     for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
263       MachineOperand *UseMO = Uses[i];
264       MachineInstr *UseMI = UseMO->getParent();
265       MachineBasicBlock *UseMBB = UseMI->getParent();
266       if (PHIBBs.count(UseMBB))
267         continue;
268
269       // About to add uses of DstReg, clear DstReg's kill flags.
270       if (!Changed) {
271         MRI->clearKillFlags(DstReg);
272         MRI->constrainRegClass(DstReg, DstRC);
273       }
274
275       unsigned NewVR = MRI->createVirtualRegister(RC);
276       MachineInstr *Copy = BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
277                                    TII->get(TargetOpcode::COPY), NewVR)
278         .addReg(DstReg, 0, SubIdx);
279       // SubIdx applies to both SrcReg and DstReg when UseSrcSubIdx is set.
280       if (UseSrcSubIdx) {
281         Copy->getOperand(0).setSubReg(SubIdx);
282         Copy->getOperand(0).setIsUndef();
283       }
284       UseMO->setReg(NewVR);
285       ++NumReuse;
286       Changed = true;
287     }
288   }
289
290   return Changed;
291 }
292
293 /// optimizeBitcastInstr - If the instruction is a bitcast instruction A that
294 /// cannot be optimized away during isel (e.g. ARM::VMOVSR, which bitcast
295 /// a value cross register classes), and the source is defined by another
296 /// bitcast instruction B. And if the register class of source of B matches
297 /// the register class of instruction A, then it is legal to replace all uses
298 /// of the def of A with source of B. e.g.
299 ///   %vreg0<def> = VMOVSR %vreg1
300 ///   %vreg3<def> = VMOVRS %vreg0
301 ///   Replace all uses of vreg3 with vreg1.
302
303 bool PeepholeOptimizer::optimizeBitcastInstr(MachineInstr *MI,
304                                              MachineBasicBlock *MBB) {
305   unsigned NumDefs = MI->getDesc().getNumDefs();
306   unsigned NumSrcs = MI->getDesc().getNumOperands() - NumDefs;
307   if (NumDefs != 1)
308     return false;
309
310   unsigned Def = 0;
311   unsigned Src = 0;
312   for (unsigned i = 0, e = NumDefs + NumSrcs; i != e; ++i) {
313     const MachineOperand &MO = MI->getOperand(i);
314     if (!MO.isReg())
315       continue;
316     unsigned Reg = MO.getReg();
317     if (!Reg)
318       continue;
319     if (MO.isDef())
320       Def = Reg;
321     else if (Src)
322       // Multiple sources?
323       return false;
324     else
325       Src = Reg;
326   }
327
328   assert(Def && Src && "Malformed bitcast instruction!");
329
330   MachineInstr *DefMI = MRI->getVRegDef(Src);
331   if (!DefMI || !DefMI->isBitcast())
332     return false;
333
334   unsigned SrcSrc = 0;
335   NumDefs = DefMI->getDesc().getNumDefs();
336   NumSrcs = DefMI->getDesc().getNumOperands() - NumDefs;
337   if (NumDefs != 1)
338     return false;
339   for (unsigned i = 0, e = NumDefs + NumSrcs; i != e; ++i) {
340     const MachineOperand &MO = DefMI->getOperand(i);
341     if (!MO.isReg() || MO.isDef())
342       continue;
343     unsigned Reg = MO.getReg();
344     if (!Reg)
345       continue;
346     if (!MO.isDef()) {
347       if (SrcSrc)
348         // Multiple sources?
349         return false;
350       else
351         SrcSrc = Reg;
352     }
353   }
354
355   if (MRI->getRegClass(SrcSrc) != MRI->getRegClass(Def))
356     return false;
357
358   MRI->replaceRegWith(Def, SrcSrc);
359   MRI->clearKillFlags(SrcSrc);
360   MI->eraseFromParent();
361   ++NumBitcasts;
362   return true;
363 }
364
365 /// optimizeCmpInstr - If the instruction is a compare and the previous
366 /// instruction it's comparing against all ready sets (or could be modified to
367 /// set) the same flag as the compare, then we can remove the comparison and use
368 /// the flag from the previous instruction.
369 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
370                                          MachineBasicBlock *MBB) {
371   // If this instruction is a comparison against zero and isn't comparing a
372   // physical register, we can try to optimize it.
373   unsigned SrcReg, SrcReg2;
374   int CmpMask, CmpValue;
375   if (!TII->analyzeCompare(MI, SrcReg, SrcReg2, CmpMask, CmpValue) ||
376       TargetRegisterInfo::isPhysicalRegister(SrcReg) ||
377       (SrcReg2 != 0 && TargetRegisterInfo::isPhysicalRegister(SrcReg2)))
378     return false;
379
380   // Attempt to optimize the comparison instruction.
381   if (TII->optimizeCompareInstr(MI, SrcReg, SrcReg2, CmpMask, CmpValue, MRI)) {
382     ++NumCmps;
383     return true;
384   }
385
386   return false;
387 }
388
389 /// isLoadFoldable - Check whether MI is a candidate for folding into a later
390 /// instruction. We only fold loads to virtual registers and the virtual
391 /// register defined has a single use.
392 bool PeepholeOptimizer::isLoadFoldable(MachineInstr *MI,
393                                        unsigned &FoldAsLoadDefReg) {
394   if (!MI->canFoldAsLoad() || !MI->mayLoad())
395     return false;
396   const MCInstrDesc &MCID = MI->getDesc();
397   if (MCID.getNumDefs() != 1)
398     return false;
399
400   unsigned Reg = MI->getOperand(0).getReg();
401   // To reduce compilation time, we check MRI->hasOneUse when inserting
402   // loads. It should be checked when processing uses of the load, since
403   // uses can be removed during peephole.
404   if (!MI->getOperand(0).getSubReg() &&
405       TargetRegisterInfo::isVirtualRegister(Reg) &&
406       MRI->hasOneUse(Reg)) {
407     FoldAsLoadDefReg = Reg;
408     return true;
409   }
410   return false;
411 }
412
413 bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
414                                         SmallSet<unsigned, 4> &ImmDefRegs,
415                                  DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
416   const MCInstrDesc &MCID = MI->getDesc();
417   if (!MI->isMoveImmediate())
418     return false;
419   if (MCID.getNumDefs() != 1)
420     return false;
421   unsigned Reg = MI->getOperand(0).getReg();
422   if (TargetRegisterInfo::isVirtualRegister(Reg)) {
423     ImmDefMIs.insert(std::make_pair(Reg, MI));
424     ImmDefRegs.insert(Reg);
425     return true;
426   }
427
428   return false;
429 }
430
431 /// foldImmediate - Try folding register operands that are defined by move
432 /// immediate instructions, i.e. a trivial constant folding optimization, if
433 /// and only if the def and use are in the same BB.
434 bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
435                                       SmallSet<unsigned, 4> &ImmDefRegs,
436                                  DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
437   for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
438     MachineOperand &MO = MI->getOperand(i);
439     if (!MO.isReg() || MO.isDef())
440       continue;
441     unsigned Reg = MO.getReg();
442     if (!TargetRegisterInfo::isVirtualRegister(Reg))
443       continue;
444     if (ImmDefRegs.count(Reg) == 0)
445       continue;
446     DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
447     assert(II != ImmDefMIs.end());
448     if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
449       ++NumImmFold;
450       return true;
451     }
452   }
453   return false;
454 }
455
456 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
457   if (DisablePeephole)
458     return false;
459
460   TM  = &MF.getTarget();
461   TII = TM->getInstrInfo();
462   MRI = &MF.getRegInfo();
463   DT  = Aggressive ? &getAnalysis<MachineDominatorTree>() : 0;
464
465   bool Changed = false;
466
467   SmallPtrSet<MachineInstr*, 8> LocalMIs;
468   SmallSet<unsigned, 4> ImmDefRegs;
469   DenseMap<unsigned, MachineInstr*> ImmDefMIs;
470   unsigned FoldAsLoadDefReg;
471   for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
472     MachineBasicBlock *MBB = &*I;
473
474     bool SeenMoveImm = false;
475     LocalMIs.clear();
476     ImmDefRegs.clear();
477     ImmDefMIs.clear();
478     FoldAsLoadDefReg = 0;
479
480     bool First = true;
481     MachineBasicBlock::iterator PMII;
482     for (MachineBasicBlock::iterator
483            MII = I->begin(), MIE = I->end(); MII != MIE; ) {
484       MachineInstr *MI = &*MII;
485       LocalMIs.insert(MI);
486
487       // If there exists an instruction which belongs to the following
488       // categories, we will discard the load candidate.
489       if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
490           MI->isKill() || MI->isInlineAsm() || MI->isDebugValue() ||
491           MI->hasUnmodeledSideEffects()) {
492         FoldAsLoadDefReg = 0;
493         ++MII;
494         continue;
495       }
496       if (MI->mayStore() || MI->isCall())
497         FoldAsLoadDefReg = 0;
498
499       if (MI->isBitcast()) {
500         if (optimizeBitcastInstr(MI, MBB)) {
501           // MI is deleted.
502           LocalMIs.erase(MI);
503           Changed = true;
504           MII = First ? I->begin() : llvm::next(PMII);
505           continue;
506         }
507       } else if (MI->isCompare()) {
508         if (optimizeCmpInstr(MI, MBB)) {
509           // MI is deleted.
510           LocalMIs.erase(MI);
511           Changed = true;
512           MII = First ? I->begin() : llvm::next(PMII);
513           continue;
514         }
515       }
516
517       if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
518         SeenMoveImm = true;
519       } else {
520         Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
521         if (SeenMoveImm)
522           Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);
523       }
524
525       // Check whether MI is a load candidate for folding into a later
526       // instruction. If MI is not a candidate, check whether we can fold an
527       // earlier load into MI.
528       if (!isLoadFoldable(MI, FoldAsLoadDefReg) && FoldAsLoadDefReg) {
529         // We need to fold load after optimizeCmpInstr, since optimizeCmpInstr
530         // can enable folding by converting SUB to CMP.
531         MachineInstr *DefMI = 0;
532         MachineInstr *FoldMI = TII->optimizeLoadInstr(MI, MRI,
533                                                       FoldAsLoadDefReg, DefMI);
534         if (FoldMI) {
535           // Update LocalMIs since we replaced MI with FoldMI and deleted DefMI.
536           LocalMIs.erase(MI);
537           LocalMIs.erase(DefMI);
538           LocalMIs.insert(FoldMI);
539           MI->eraseFromParent();
540           DefMI->eraseFromParent();
541           ++NumLoadFold;
542
543           // MI is replaced with FoldMI.
544           Changed = true;
545           PMII = FoldMI;
546           MII = llvm::next(PMII);
547           continue;
548         }
549       }
550       First = false;
551       PMII = MII;
552       ++MII;
553     }
554   }
555
556   return Changed;
557 }