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 //===----------------------------------------------------------------------===// 35 36 #define DEBUG_TYPE "peephole-opt" 37 #include "llvm/CodeGen/Passes.h" 38 #include "llvm/CodeGen/MachineDominators.h" 39 #include "llvm/CodeGen/MachineInstrBuilder.h" 40 #include "llvm/CodeGen/MachineRegisterInfo.h" 41 #include "llvm/Target/TargetInstrInfo.h" 42 #include "llvm/Target/TargetRegisterInfo.h" 43 #include "llvm/Support/CommandLine.h" 44 #include "llvm/ADT/SmallPtrSet.h" 45 #include "llvm/ADT/Statistic.h" 46 using namespace llvm; 47 48 // Optimize Extensions 49 static cl::opt<bool> 50 Aggressive("aggressive-ext-opt", cl::Hidden, 51 cl::desc("Aggressive extension optimization")); 52 53 STATISTIC(NumReuse, "Number of extension results reused"); 54 STATISTIC(NumEliminated, "Number of compares eliminated"); 55 56 namespace { 57 class PeepholeOptimizer : public MachineFunctionPass { 58 const TargetMachine *TM; 59 const TargetInstrInfo *TII; 60 MachineRegisterInfo *MRI; 61 MachineDominatorTree *DT; // Machine dominator tree 62 63 public: 64 static char ID; // Pass identification 65 PeepholeOptimizer() : MachineFunctionPass(ID) {} 66 67 virtual bool runOnMachineFunction(MachineFunction &MF); 68 69 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 70 AU.setPreservesCFG(); 71 MachineFunctionPass::getAnalysisUsage(AU); 72 if (Aggressive) { 73 AU.addRequired<MachineDominatorTree>(); 74 AU.addPreserved<MachineDominatorTree>(); 75 } 76 } 77 78 private: 79 bool OptimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB); 80 bool OptimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB, 81 SmallPtrSet<MachineInstr*, 8> &LocalMIs); 82 }; 83 } 84 85 char PeepholeOptimizer::ID = 0; 86 INITIALIZE_PASS(PeepholeOptimizer, "peephole-opts", 87 "Peephole Optimizations", false, false); 88 89 FunctionPass *llvm::createPeepholeOptimizerPass() { 90 return new PeepholeOptimizer(); 91 } 92 93 /// OptimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads 94 /// a single register and writes a single register and it does not modify the 95 /// source, and if the source value is preserved as a sub-register of the 96 /// result, then replace all reachable uses of the source with the subreg of the 97 /// result. 98 /// 99 /// Do not generate an EXTRACT that is used only in a debug use, as this changes 100 /// the code. Since this code does not currently share EXTRACTs, just ignore all 101 /// debug uses. 102 bool PeepholeOptimizer:: 103 OptimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB, 104 SmallPtrSet<MachineInstr*, 8> &LocalMIs) { 105 LocalMIs.insert(MI); 106 107 unsigned SrcReg, DstReg, SubIdx; 108 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx)) 109 return false; 110 111 if (TargetRegisterInfo::isPhysicalRegister(DstReg) || 112 TargetRegisterInfo::isPhysicalRegister(SrcReg)) 113 return false; 114 115 MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(SrcReg); 116 if (++UI == MRI->use_nodbg_end()) 117 // No other uses. 118 return false; 119 120 // The source has other uses. See if we can replace the other uses with use of 121 // the result of the extension. 122 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs; 123 UI = MRI->use_nodbg_begin(DstReg); 124 for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end(); 125 UI != UE; ++UI) 126 ReachedBBs.insert(UI->getParent()); 127 128 // Uses that are in the same BB of uses of the result of the instruction. 129 SmallVector<MachineOperand*, 8> Uses; 130 131 // Uses that the result of the instruction can reach. 132 SmallVector<MachineOperand*, 8> ExtendedUses; 133 134 bool ExtendLife = true; 135 UI = MRI->use_nodbg_begin(SrcReg); 136 for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end(); 137 UI != UE; ++UI) { 138 MachineOperand &UseMO = UI.getOperand(); 139 MachineInstr *UseMI = &*UI; 140 if (UseMI == MI) 141 continue; 142 143 if (UseMI->isPHI()) { 144 ExtendLife = false; 145 continue; 146 } 147 148 // It's an error to translate this: 149 // 150 // %reg1025 = <sext> %reg1024 151 // ... 152 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4 153 // 154 // into this: 155 // 156 // %reg1025 = <sext> %reg1024 157 // ... 158 // %reg1027 = COPY %reg1025:4 159 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4 160 // 161 // The problem here is that SUBREG_TO_REG is there to assert that an 162 // implicit zext occurs. It doesn't insert a zext instruction. If we allow 163 // the COPY here, it will give us the value after the <sext>, not the 164 // original value of %reg1024 before <sext>. 165 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG) 166 continue; 167 168 MachineBasicBlock *UseMBB = UseMI->getParent(); 169 if (UseMBB == MBB) { 170 // Local uses that come after the extension. 171 if (!LocalMIs.count(UseMI)) 172 Uses.push_back(&UseMO); 173 } else if (ReachedBBs.count(UseMBB)) { 174 // Non-local uses where the result of the extension is used. Always 175 // replace these unless it's a PHI. 176 Uses.push_back(&UseMO); 177 } else if (Aggressive && DT->dominates(MBB, UseMBB)) { 178 // We may want to extend the live range of the extension result in order 179 // to replace these uses. 180 ExtendedUses.push_back(&UseMO); 181 } else { 182 // Both will be live out of the def MBB anyway. Don't extend live range of 183 // the extension result. 184 ExtendLife = false; 185 break; 186 } 187 } 188 189 if (ExtendLife && !ExtendedUses.empty()) 190 // Extend the liveness of the extension result. 191 std::copy(ExtendedUses.begin(), ExtendedUses.end(), 192 std::back_inserter(Uses)); 193 194 // Now replace all uses. 195 bool Changed = false; 196 if (!Uses.empty()) { 197 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs; 198 199 // Look for PHI uses of the extended result, we don't want to extend the 200 // liveness of a PHI input. It breaks all kinds of assumptions down 201 // stream. A PHI use is expected to be the kill of its source values. 202 UI = MRI->use_nodbg_begin(DstReg); 203 for (MachineRegisterInfo::use_nodbg_iterator 204 UE = MRI->use_nodbg_end(); UI != UE; ++UI) 205 if (UI->isPHI()) 206 PHIBBs.insert(UI->getParent()); 207 208 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg); 209 for (unsigned i = 0, e = Uses.size(); i != e; ++i) { 210 MachineOperand *UseMO = Uses[i]; 211 MachineInstr *UseMI = UseMO->getParent(); 212 MachineBasicBlock *UseMBB = UseMI->getParent(); 213 if (PHIBBs.count(UseMBB)) 214 continue; 215 216 unsigned NewVR = MRI->createVirtualRegister(RC); 217 BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(), 218 TII->get(TargetOpcode::COPY), NewVR) 219 .addReg(DstReg, 0, SubIdx); 220 221 UseMO->setReg(NewVR); 222 ++NumReuse; 223 Changed = true; 224 } 225 } 226 227 return Changed; 228 } 229 230 /// OptimizeCmpInstr - If the instruction is a compare and the previous 231 /// instruction it's comparing against all ready sets (or could be modified to 232 /// set) the same flag as the compare, then we can remove the comparison and use 233 /// the flag from the previous instruction. 234 bool PeepholeOptimizer::OptimizeCmpInstr(MachineInstr *MI, 235 MachineBasicBlock *MBB) { 236 // If this instruction is a comparison against zero and isn't comparing a 237 // physical register, we can try to optimize it. 238 unsigned SrcReg; 239 int CmpValue; 240 if (!TII->AnalyzeCompare(MI, SrcReg, CmpValue) || 241 TargetRegisterInfo::isPhysicalRegister(SrcReg) || CmpValue != 0) 242 return false; 243 244 MachineRegisterInfo::def_iterator DI = MRI->def_begin(SrcReg); 245 if (llvm::next(DI) != MRI->def_end()) 246 // Only support one definition. 247 return false; 248 249 // Attempt to convert the defining instruction to set the "zero" flag. 250 if (TII->ConvertToSetZeroFlag(&*DI, MI)) { 251 ++NumEliminated; 252 return true; 253 } 254 255 return false; 256 } 257 258 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) { 259 TM = &MF.getTarget(); 260 TII = TM->getInstrInfo(); 261 MRI = &MF.getRegInfo(); 262 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : 0; 263 264 bool Changed = false; 265 266 SmallPtrSet<MachineInstr*, 8> LocalMIs; 267 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) { 268 MachineBasicBlock *MBB = &*I; 269 LocalMIs.clear(); 270 271 for (MachineBasicBlock::iterator 272 MII = I->begin(), ME = I->end(); MII != ME; ) { 273 MachineInstr *MI = &*MII; 274 275 if (MI->getDesc().isCompare() && 276 !MI->getDesc().hasUnmodeledSideEffects()) { 277 ++MII; // The iterator may become invalid if the compare is deleted. 278 Changed |= OptimizeCmpInstr(MI, MBB); 279 } else { 280 Changed |= OptimizeExtInstr(MI, MBB, LocalMIs); 281 ++MII; 282 } 283 } 284 } 285 286 return Changed; 287 } 288