1 //===-- PeepholeOptimizer.cpp - Peephole Optimizations --------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Perform peephole optimizations on the machine code:
12 // - Optimize Extensions
14 // Optimization of sign / zero extension instructions. It may be extended to
15 // handle other instructions with similar properties.
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.
22 // - Optimize Comparisons
24 // Optimization of comparison instructions. For instance, in this code:
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.
34 // Another instance, in this code:
36 // sub r1, r3 | sub r1, imm
37 // cmp r3, r1 or cmp r1, r3 | cmp r1, imm
40 // If the branch instruction can use flag from "sub", then we can replace
41 // "sub" with "subs" and eliminate the "cmp" instruction.
43 // - Optimize Bitcast pairs:
52 //===----------------------------------------------------------------------===//
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"
68 // Optimize Extensions
70 Aggressive("aggressive-ext-opt", cl::Hidden,
71 cl::desc("Aggressive extension optimization"));
74 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false),
75 cl::desc("Disable the peephole optimizer"));
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");
83 class PeepholeOptimizer : public MachineFunctionPass {
84 const TargetMachine *TM;
85 const TargetInstrInfo *TII;
86 MachineRegisterInfo *MRI;
87 MachineDominatorTree *DT; // Machine dominator tree
90 static char ID; // Pass identification
91 PeepholeOptimizer() : MachineFunctionPass(ID) {
92 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry());
95 virtual bool runOnMachineFunction(MachineFunction &MF);
97 virtual void getAnalysisUsage(AnalysisUsage &AU) const {
99 MachineFunctionPass::getAnalysisUsage(AU);
101 AU.addRequired<MachineDominatorTree>();
102 AU.addPreserved<MachineDominatorTree>();
107 bool optimizeBitcastInstr(MachineInstr *MI, MachineBasicBlock *MBB);
108 bool optimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB);
109 bool optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
110 SmallPtrSet<MachineInstr*, 8> &LocalMIs);
111 bool isMoveImmediate(MachineInstr *MI,
112 SmallSet<unsigned, 4> &ImmDefRegs,
113 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
114 bool foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
115 SmallSet<unsigned, 4> &ImmDefRegs,
116 DenseMap<unsigned, MachineInstr*> &ImmDefMIs);
120 char PeepholeOptimizer::ID = 0;
121 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID;
122 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts",
123 "Peephole Optimizations", false, false)
124 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree)
125 INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts",
126 "Peephole Optimizations", false, false)
128 /// optimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads
129 /// a single register and writes a single register and it does not modify the
130 /// source, and if the source value is preserved as a sub-register of the
131 /// result, then replace all reachable uses of the source with the subreg of the
134 /// Do not generate an EXTRACT that is used only in a debug use, as this changes
135 /// the code. Since this code does not currently share EXTRACTs, just ignore all
137 bool PeepholeOptimizer::
138 optimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB,
139 SmallPtrSet<MachineInstr*, 8> &LocalMIs) {
140 unsigned SrcReg, DstReg, SubIdx;
141 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx))
144 if (TargetRegisterInfo::isPhysicalRegister(DstReg) ||
145 TargetRegisterInfo::isPhysicalRegister(SrcReg))
148 MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(SrcReg);
149 if (++UI == MRI->use_nodbg_end())
153 // The source has other uses. See if we can replace the other uses with use of
154 // the result of the extension.
155 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs;
156 UI = MRI->use_nodbg_begin(DstReg);
157 for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
159 ReachedBBs.insert(UI->getParent());
161 // Uses that are in the same BB of uses of the result of the instruction.
162 SmallVector<MachineOperand*, 8> Uses;
164 // Uses that the result of the instruction can reach.
165 SmallVector<MachineOperand*, 8> ExtendedUses;
167 bool ExtendLife = true;
168 UI = MRI->use_nodbg_begin(SrcReg);
169 for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end();
171 MachineOperand &UseMO = UI.getOperand();
172 MachineInstr *UseMI = &*UI;
176 if (UseMI->isPHI()) {
181 // It's an error to translate this:
183 // %reg1025 = <sext> %reg1024
185 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4
189 // %reg1025 = <sext> %reg1024
191 // %reg1027 = COPY %reg1025:4
192 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4
194 // The problem here is that SUBREG_TO_REG is there to assert that an
195 // implicit zext occurs. It doesn't insert a zext instruction. If we allow
196 // the COPY here, it will give us the value after the <sext>, not the
197 // original value of %reg1024 before <sext>.
198 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG)
201 MachineBasicBlock *UseMBB = UseMI->getParent();
203 // Local uses that come after the extension.
204 if (!LocalMIs.count(UseMI))
205 Uses.push_back(&UseMO);
206 } else if (ReachedBBs.count(UseMBB)) {
207 // Non-local uses where the result of the extension is used. Always
208 // replace these unless it's a PHI.
209 Uses.push_back(&UseMO);
210 } else if (Aggressive && DT->dominates(MBB, UseMBB)) {
211 // We may want to extend the live range of the extension result in order
212 // to replace these uses.
213 ExtendedUses.push_back(&UseMO);
215 // Both will be live out of the def MBB anyway. Don't extend live range of
216 // the extension result.
222 if (ExtendLife && !ExtendedUses.empty())
223 // Extend the liveness of the extension result.
224 std::copy(ExtendedUses.begin(), ExtendedUses.end(),
225 std::back_inserter(Uses));
227 // Now replace all uses.
228 bool Changed = false;
230 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs;
232 // Look for PHI uses of the extended result, we don't want to extend the
233 // liveness of a PHI input. It breaks all kinds of assumptions down
234 // stream. A PHI use is expected to be the kill of its source values.
235 UI = MRI->use_nodbg_begin(DstReg);
236 for (MachineRegisterInfo::use_nodbg_iterator
237 UE = MRI->use_nodbg_end(); UI != UE; ++UI)
239 PHIBBs.insert(UI->getParent());
241 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg);
242 for (unsigned i = 0, e = Uses.size(); i != e; ++i) {
243 MachineOperand *UseMO = Uses[i];
244 MachineInstr *UseMI = UseMO->getParent();
245 MachineBasicBlock *UseMBB = UseMI->getParent();
246 if (PHIBBs.count(UseMBB))
249 // About to add uses of DstReg, clear DstReg's kill flags.
251 MRI->clearKillFlags(DstReg);
253 unsigned NewVR = MRI->createVirtualRegister(RC);
254 BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(),
255 TII->get(TargetOpcode::COPY), NewVR)
256 .addReg(DstReg, 0, SubIdx);
258 UseMO->setReg(NewVR);
267 /// optimizeBitcastInstr - If the instruction is a bitcast instruction A that
268 /// cannot be optimized away during isel (e.g. ARM::VMOVSR, which bitcast
269 /// a value cross register classes), and the source is defined by another
270 /// bitcast instruction B. And if the register class of source of B matches
271 /// the register class of instruction A, then it is legal to replace all uses
272 /// of the def of A with source of B. e.g.
273 /// %vreg0<def> = VMOVSR %vreg1
274 /// %vreg3<def> = VMOVRS %vreg0
275 /// Replace all uses of vreg3 with vreg1.
277 bool PeepholeOptimizer::optimizeBitcastInstr(MachineInstr *MI,
278 MachineBasicBlock *MBB) {
279 unsigned NumDefs = MI->getDesc().getNumDefs();
280 unsigned NumSrcs = MI->getDesc().getNumOperands() - NumDefs;
286 for (unsigned i = 0, e = NumDefs + NumSrcs; i != e; ++i) {
287 const MachineOperand &MO = MI->getOperand(i);
290 unsigned Reg = MO.getReg();
302 assert(Def && Src && "Malformed bitcast instruction!");
304 MachineInstr *DefMI = MRI->getVRegDef(Src);
305 if (!DefMI || !DefMI->isBitcast())
309 NumDefs = DefMI->getDesc().getNumDefs();
310 NumSrcs = DefMI->getDesc().getNumOperands() - NumDefs;
313 for (unsigned i = 0, e = NumDefs + NumSrcs; i != e; ++i) {
314 const MachineOperand &MO = DefMI->getOperand(i);
315 if (!MO.isReg() || MO.isDef())
317 unsigned Reg = MO.getReg();
329 if (MRI->getRegClass(SrcSrc) != MRI->getRegClass(Def))
332 MRI->replaceRegWith(Def, SrcSrc);
333 MRI->clearKillFlags(SrcSrc);
334 MI->eraseFromParent();
339 /// optimizeCmpInstr - If the instruction is a compare and the previous
340 /// instruction it's comparing against all ready sets (or could be modified to
341 /// set) the same flag as the compare, then we can remove the comparison and use
342 /// the flag from the previous instruction.
343 bool PeepholeOptimizer::optimizeCmpInstr(MachineInstr *MI,
344 MachineBasicBlock *MBB) {
345 // If this instruction is a comparison against zero and isn't comparing a
346 // physical register, we can try to optimize it.
348 int CmpMask, CmpValue;
349 if (!TII->AnalyzeCompare(MI, SrcReg, CmpMask, CmpValue) ||
350 TargetRegisterInfo::isPhysicalRegister(SrcReg))
353 // Attempt to optimize the comparison instruction.
354 if (TII->OptimizeCompareInstr(MI, SrcReg, CmpMask, CmpValue, MRI)) {
362 bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI,
363 SmallSet<unsigned, 4> &ImmDefRegs,
364 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
365 const MCInstrDesc &MCID = MI->getDesc();
366 if (!MI->isMoveImmediate())
368 if (MCID.getNumDefs() != 1)
370 unsigned Reg = MI->getOperand(0).getReg();
371 if (TargetRegisterInfo::isVirtualRegister(Reg)) {
372 ImmDefMIs.insert(std::make_pair(Reg, MI));
373 ImmDefRegs.insert(Reg);
380 /// foldImmediate - Try folding register operands that are defined by move
381 /// immediate instructions, i.e. a trivial constant folding optimization, if
382 /// and only if the def and use are in the same BB.
383 bool PeepholeOptimizer::foldImmediate(MachineInstr *MI, MachineBasicBlock *MBB,
384 SmallSet<unsigned, 4> &ImmDefRegs,
385 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) {
386 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) {
387 MachineOperand &MO = MI->getOperand(i);
388 if (!MO.isReg() || MO.isDef())
390 unsigned Reg = MO.getReg();
391 if (!TargetRegisterInfo::isVirtualRegister(Reg))
393 if (ImmDefRegs.count(Reg) == 0)
395 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg);
396 assert(II != ImmDefMIs.end());
397 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) {
405 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) {
409 TM = &MF.getTarget();
410 TII = TM->getInstrInfo();
411 MRI = &MF.getRegInfo();
412 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : 0;
414 bool Changed = false;
416 SmallPtrSet<MachineInstr*, 8> LocalMIs;
417 SmallSet<unsigned, 4> ImmDefRegs;
418 DenseMap<unsigned, MachineInstr*> ImmDefMIs;
419 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) {
420 MachineBasicBlock *MBB = &*I;
422 bool SeenMoveImm = false;
428 MachineBasicBlock::iterator PMII;
429 for (MachineBasicBlock::iterator
430 MII = I->begin(), MIE = I->end(); MII != MIE; ) {
431 MachineInstr *MI = &*MII;
434 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() ||
435 MI->isKill() || MI->isInlineAsm() || MI->isDebugValue() ||
436 MI->hasUnmodeledSideEffects()) {
441 if (MI->isBitcast()) {
442 if (optimizeBitcastInstr(MI, MBB)) {
446 MII = First ? I->begin() : llvm::next(PMII);
449 } else if (MI->isCompare()) {
450 if (optimizeCmpInstr(MI, MBB)) {
454 MII = First ? I->begin() : llvm::next(PMII);
459 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) {
462 Changed |= optimizeExtInstr(MI, MBB, LocalMIs);
464 Changed |= foldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs);