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 // - Optimize Bitcast pairs: 35 // 36 // v1 = bitcast v0 37 // v2 = bitcast v1 38 // = v2 39 // => 40 // v1 = bitcast v0 41 // = v0 42 // 43 //===----------------------------------------------------------------------===// 44 45 #define DEBUG_TYPE "peephole-opt" 46 #include "llvm/CodeGen/Passes.h" 47 #include "llvm/CodeGen/MachineDominators.h" 48 #include "llvm/CodeGen/MachineInstrBuilder.h" 49 #include "llvm/CodeGen/MachineRegisterInfo.h" 50 #include "llvm/Target/TargetInstrInfo.h" 51 #include "llvm/Target/TargetRegisterInfo.h" 52 #include "llvm/Support/CommandLine.h" 53 #include "llvm/ADT/DenseMap.h" 54 #include "llvm/ADT/SmallPtrSet.h" 55 #include "llvm/ADT/SmallSet.h" 56 #include "llvm/ADT/Statistic.h" 57 using namespace llvm; 58 59 // Optimize Extensions 60 static cl::opt<bool> 61 Aggressive("aggressive-ext-opt", cl::Hidden, 62 cl::desc("Aggressive extension optimization")); 63 64 static cl::opt<bool> 65 DisablePeephole("disable-peephole", cl::Hidden, cl::init(false), 66 cl::desc("Disable the peephole optimizer")); 67 68 STATISTIC(NumReuse, "Number of extension results reused"); 69 STATISTIC(NumBitcasts, "Number of bitcasts eliminated"); 70 STATISTIC(NumCmps, "Number of compares eliminated"); 71 STATISTIC(NumImmFold, "Number of move immediate foled"); 72 73 namespace { 74 class PeepholeOptimizer : public MachineFunctionPass { 75 const TargetMachine *TM; 76 const TargetInstrInfo *TII; 77 MachineRegisterInfo *MRI; 78 MachineDominatorTree *DT; // Machine dominator tree 79 80 public: 81 static char ID; // Pass identification 82 PeepholeOptimizer() : MachineFunctionPass(ID) { 83 initializePeepholeOptimizerPass(*PassRegistry::getPassRegistry()); 84 } 85 86 virtual bool runOnMachineFunction(MachineFunction &MF); 87 88 virtual void getAnalysisUsage(AnalysisUsage &AU) const { 89 AU.setPreservesCFG(); 90 MachineFunctionPass::getAnalysisUsage(AU); 91 if (Aggressive) { 92 AU.addRequired<MachineDominatorTree>(); 93 AU.addPreserved<MachineDominatorTree>(); 94 } 95 } 96 97 private: 98 bool OptimizeBitcastInstr(MachineInstr *MI, MachineBasicBlock *MBB); 99 bool OptimizeCmpInstr(MachineInstr *MI, MachineBasicBlock *MBB); 100 bool OptimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB, 101 SmallPtrSet<MachineInstr*, 8> &LocalMIs); 102 bool isMoveImmediate(MachineInstr *MI, 103 SmallSet<unsigned, 4> &ImmDefRegs, 104 DenseMap<unsigned, MachineInstr*> &ImmDefMIs); 105 bool FoldImmediate(MachineInstr *MI, MachineBasicBlock *MBB, 106 SmallSet<unsigned, 4> &ImmDefRegs, 107 DenseMap<unsigned, MachineInstr*> &ImmDefMIs); 108 }; 109 } 110 111 char PeepholeOptimizer::ID = 0; 112 char &llvm::PeepholeOptimizerID = PeepholeOptimizer::ID; 113 INITIALIZE_PASS_BEGIN(PeepholeOptimizer, "peephole-opts", 114 "Peephole Optimizations", false, false) 115 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTree) 116 INITIALIZE_PASS_END(PeepholeOptimizer, "peephole-opts", 117 "Peephole Optimizations", false, false) 118 119 /// OptimizeExtInstr - If instruction is a copy-like instruction, i.e. it reads 120 /// a single register and writes a single register and it does not modify the 121 /// source, and if the source value is preserved as a sub-register of the 122 /// result, then replace all reachable uses of the source with the subreg of the 123 /// result. 124 /// 125 /// Do not generate an EXTRACT that is used only in a debug use, as this changes 126 /// the code. Since this code does not currently share EXTRACTs, just ignore all 127 /// debug uses. 128 bool PeepholeOptimizer:: 129 OptimizeExtInstr(MachineInstr *MI, MachineBasicBlock *MBB, 130 SmallPtrSet<MachineInstr*, 8> &LocalMIs) { 131 unsigned SrcReg, DstReg, SubIdx; 132 if (!TII->isCoalescableExtInstr(*MI, SrcReg, DstReg, SubIdx)) 133 return false; 134 135 if (TargetRegisterInfo::isPhysicalRegister(DstReg) || 136 TargetRegisterInfo::isPhysicalRegister(SrcReg)) 137 return false; 138 139 MachineRegisterInfo::use_nodbg_iterator UI = MRI->use_nodbg_begin(SrcReg); 140 if (++UI == MRI->use_nodbg_end()) 141 // No other uses. 142 return false; 143 144 // The source has other uses. See if we can replace the other uses with use of 145 // the result of the extension. 146 SmallPtrSet<MachineBasicBlock*, 4> ReachedBBs; 147 UI = MRI->use_nodbg_begin(DstReg); 148 for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end(); 149 UI != UE; ++UI) 150 ReachedBBs.insert(UI->getParent()); 151 152 // Uses that are in the same BB of uses of the result of the instruction. 153 SmallVector<MachineOperand*, 8> Uses; 154 155 // Uses that the result of the instruction can reach. 156 SmallVector<MachineOperand*, 8> ExtendedUses; 157 158 bool ExtendLife = true; 159 UI = MRI->use_nodbg_begin(SrcReg); 160 for (MachineRegisterInfo::use_nodbg_iterator UE = MRI->use_nodbg_end(); 161 UI != UE; ++UI) { 162 MachineOperand &UseMO = UI.getOperand(); 163 MachineInstr *UseMI = &*UI; 164 if (UseMI == MI) 165 continue; 166 167 if (UseMI->isPHI()) { 168 ExtendLife = false; 169 continue; 170 } 171 172 // It's an error to translate this: 173 // 174 // %reg1025 = <sext> %reg1024 175 // ... 176 // %reg1026 = SUBREG_TO_REG 0, %reg1024, 4 177 // 178 // into this: 179 // 180 // %reg1025 = <sext> %reg1024 181 // ... 182 // %reg1027 = COPY %reg1025:4 183 // %reg1026 = SUBREG_TO_REG 0, %reg1027, 4 184 // 185 // The problem here is that SUBREG_TO_REG is there to assert that an 186 // implicit zext occurs. It doesn't insert a zext instruction. If we allow 187 // the COPY here, it will give us the value after the <sext>, not the 188 // original value of %reg1024 before <sext>. 189 if (UseMI->getOpcode() == TargetOpcode::SUBREG_TO_REG) 190 continue; 191 192 MachineBasicBlock *UseMBB = UseMI->getParent(); 193 if (UseMBB == MBB) { 194 // Local uses that come after the extension. 195 if (!LocalMIs.count(UseMI)) 196 Uses.push_back(&UseMO); 197 } else if (ReachedBBs.count(UseMBB)) { 198 // Non-local uses where the result of the extension is used. Always 199 // replace these unless it's a PHI. 200 Uses.push_back(&UseMO); 201 } else if (Aggressive && DT->dominates(MBB, UseMBB)) { 202 // We may want to extend the live range of the extension result in order 203 // to replace these uses. 204 ExtendedUses.push_back(&UseMO); 205 } else { 206 // Both will be live out of the def MBB anyway. Don't extend live range of 207 // the extension result. 208 ExtendLife = false; 209 break; 210 } 211 } 212 213 if (ExtendLife && !ExtendedUses.empty()) 214 // Extend the liveness of the extension result. 215 std::copy(ExtendedUses.begin(), ExtendedUses.end(), 216 std::back_inserter(Uses)); 217 218 // Now replace all uses. 219 bool Changed = false; 220 if (!Uses.empty()) { 221 SmallPtrSet<MachineBasicBlock*, 4> PHIBBs; 222 223 // Look for PHI uses of the extended result, we don't want to extend the 224 // liveness of a PHI input. It breaks all kinds of assumptions down 225 // stream. A PHI use is expected to be the kill of its source values. 226 UI = MRI->use_nodbg_begin(DstReg); 227 for (MachineRegisterInfo::use_nodbg_iterator 228 UE = MRI->use_nodbg_end(); UI != UE; ++UI) 229 if (UI->isPHI()) 230 PHIBBs.insert(UI->getParent()); 231 232 const TargetRegisterClass *RC = MRI->getRegClass(SrcReg); 233 for (unsigned i = 0, e = Uses.size(); i != e; ++i) { 234 MachineOperand *UseMO = Uses[i]; 235 MachineInstr *UseMI = UseMO->getParent(); 236 MachineBasicBlock *UseMBB = UseMI->getParent(); 237 if (PHIBBs.count(UseMBB)) 238 continue; 239 240 unsigned NewVR = MRI->createVirtualRegister(RC); 241 BuildMI(*UseMBB, UseMI, UseMI->getDebugLoc(), 242 TII->get(TargetOpcode::COPY), NewVR) 243 .addReg(DstReg, 0, SubIdx); 244 245 UseMO->setReg(NewVR); 246 ++NumReuse; 247 Changed = true; 248 } 249 } 250 251 return Changed; 252 } 253 254 /// OptimizeBitcastInstr - If the instruction is a bitcast instruction A that 255 /// cannot be optimized away during isel (e.g. ARM::VMOVSR, which bitcast 256 /// a value cross register classes), and the source is defined by another 257 /// bitcast instruction B. And if the register class of source of B matches 258 /// the register class of instruction A, then it is legal to replace all uses 259 /// of the def of A with source of B. e.g. 260 /// %vreg0<def> = VMOVSR %vreg1 261 /// %vreg3<def> = VMOVRS %vreg0 262 /// Replace all uses of vreg3 with vreg1. 263 264 bool PeepholeOptimizer::OptimizeBitcastInstr(MachineInstr *MI, 265 MachineBasicBlock *MBB) { 266 unsigned NumDefs = MI->getDesc().getNumDefs(); 267 unsigned NumSrcs = MI->getDesc().getNumOperands() - NumDefs; 268 if (NumDefs != 1) 269 return false; 270 271 unsigned Def = 0; 272 unsigned Src = 0; 273 for (unsigned i = 0, e = NumDefs + NumSrcs; i != e; ++i) { 274 const MachineOperand &MO = MI->getOperand(i); 275 if (!MO.isReg()) 276 continue; 277 unsigned Reg = MO.getReg(); 278 if (!Reg) 279 continue; 280 if (MO.isDef()) 281 Def = Reg; 282 else if (Src) 283 // Multiple sources? 284 return false; 285 else 286 Src = Reg; 287 } 288 289 assert(Def && Src && "Malformed bitcast instruction!"); 290 291 MachineInstr *DefMI = MRI->getVRegDef(Src); 292 if (!DefMI || !DefMI->isBitcast()) 293 return false; 294 295 unsigned SrcSrc = 0; 296 NumDefs = DefMI->getDesc().getNumDefs(); 297 NumSrcs = DefMI->getDesc().getNumOperands() - NumDefs; 298 if (NumDefs != 1) 299 return false; 300 for (unsigned i = 0, e = NumDefs + NumSrcs; i != e; ++i) { 301 const MachineOperand &MO = DefMI->getOperand(i); 302 if (!MO.isReg() || MO.isDef()) 303 continue; 304 unsigned Reg = MO.getReg(); 305 if (!Reg) 306 continue; 307 if (!MO.isDef()) { 308 if (SrcSrc) 309 // Multiple sources? 310 return false; 311 else 312 SrcSrc = Reg; 313 } 314 } 315 316 if (MRI->getRegClass(SrcSrc) != MRI->getRegClass(Def)) 317 return false; 318 319 MRI->replaceRegWith(Def, SrcSrc); 320 MRI->clearKillFlags(SrcSrc); 321 MI->eraseFromParent(); 322 ++NumBitcasts; 323 return true; 324 } 325 326 /// OptimizeCmpInstr - If the instruction is a compare and the previous 327 /// instruction it's comparing against all ready sets (or could be modified to 328 /// set) the same flag as the compare, then we can remove the comparison and use 329 /// the flag from the previous instruction. 330 bool PeepholeOptimizer::OptimizeCmpInstr(MachineInstr *MI, 331 MachineBasicBlock *MBB) { 332 // If this instruction is a comparison against zero and isn't comparing a 333 // physical register, we can try to optimize it. 334 unsigned SrcReg; 335 int CmpMask, CmpValue; 336 if (!TII->AnalyzeCompare(MI, SrcReg, CmpMask, CmpValue) || 337 TargetRegisterInfo::isPhysicalRegister(SrcReg)) 338 return false; 339 340 // Attempt to optimize the comparison instruction. 341 if (TII->OptimizeCompareInstr(MI, SrcReg, CmpMask, CmpValue, MRI)) { 342 ++NumCmps; 343 return true; 344 } 345 346 return false; 347 } 348 349 bool PeepholeOptimizer::isMoveImmediate(MachineInstr *MI, 350 SmallSet<unsigned, 4> &ImmDefRegs, 351 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) { 352 const MCInstrDesc &MCID = MI->getDesc(); 353 if (!MI->isMoveImmediate()) 354 return false; 355 if (MCID.getNumDefs() != 1) 356 return false; 357 unsigned Reg = MI->getOperand(0).getReg(); 358 if (TargetRegisterInfo::isVirtualRegister(Reg)) { 359 ImmDefMIs.insert(std::make_pair(Reg, MI)); 360 ImmDefRegs.insert(Reg); 361 return true; 362 } 363 364 return false; 365 } 366 367 /// FoldImmediate - Try folding register operands that are defined by move 368 /// immediate instructions, i.e. a trivial constant folding optimization, if 369 /// and only if the def and use are in the same BB. 370 bool PeepholeOptimizer::FoldImmediate(MachineInstr *MI, MachineBasicBlock *MBB, 371 SmallSet<unsigned, 4> &ImmDefRegs, 372 DenseMap<unsigned, MachineInstr*> &ImmDefMIs) { 373 for (unsigned i = 0, e = MI->getDesc().getNumOperands(); i != e; ++i) { 374 MachineOperand &MO = MI->getOperand(i); 375 if (!MO.isReg() || MO.isDef()) 376 continue; 377 unsigned Reg = MO.getReg(); 378 if (!TargetRegisterInfo::isVirtualRegister(Reg)) 379 continue; 380 if (ImmDefRegs.count(Reg) == 0) 381 continue; 382 DenseMap<unsigned, MachineInstr*>::iterator II = ImmDefMIs.find(Reg); 383 assert(II != ImmDefMIs.end()); 384 if (TII->FoldImmediate(MI, II->second, Reg, MRI)) { 385 ++NumImmFold; 386 return true; 387 } 388 } 389 return false; 390 } 391 392 bool PeepholeOptimizer::runOnMachineFunction(MachineFunction &MF) { 393 if (DisablePeephole) 394 return false; 395 396 TM = &MF.getTarget(); 397 TII = TM->getInstrInfo(); 398 MRI = &MF.getRegInfo(); 399 DT = Aggressive ? &getAnalysis<MachineDominatorTree>() : 0; 400 401 bool Changed = false; 402 403 SmallPtrSet<MachineInstr*, 8> LocalMIs; 404 SmallSet<unsigned, 4> ImmDefRegs; 405 DenseMap<unsigned, MachineInstr*> ImmDefMIs; 406 for (MachineFunction::iterator I = MF.begin(), E = MF.end(); I != E; ++I) { 407 MachineBasicBlock *MBB = &*I; 408 409 bool SeenMoveImm = false; 410 LocalMIs.clear(); 411 ImmDefRegs.clear(); 412 ImmDefMIs.clear(); 413 414 bool First = true; 415 MachineBasicBlock::iterator PMII; 416 for (MachineBasicBlock::iterator 417 MII = I->begin(), MIE = I->end(); MII != MIE; ) { 418 MachineInstr *MI = &*MII; 419 LocalMIs.insert(MI); 420 421 if (MI->isLabel() || MI->isPHI() || MI->isImplicitDef() || 422 MI->isKill() || MI->isInlineAsm() || MI->isDebugValue() || 423 MI->hasUnmodeledSideEffects()) { 424 ++MII; 425 continue; 426 } 427 428 if (MI->isBitcast()) { 429 if (OptimizeBitcastInstr(MI, MBB)) { 430 // MI is deleted. 431 LocalMIs.erase(MI); 432 Changed = true; 433 MII = First ? I->begin() : llvm::next(PMII); 434 continue; 435 } 436 } else if (MI->isCompare()) { 437 if (OptimizeCmpInstr(MI, MBB)) { 438 // MI is deleted. 439 LocalMIs.erase(MI); 440 Changed = true; 441 MII = First ? I->begin() : llvm::next(PMII); 442 continue; 443 } 444 } 445 446 if (isMoveImmediate(MI, ImmDefRegs, ImmDefMIs)) { 447 SeenMoveImm = true; 448 } else { 449 Changed |= OptimizeExtInstr(MI, MBB, LocalMIs); 450 if (SeenMoveImm) 451 Changed |= FoldImmediate(MI, MBB, ImmDefRegs, ImmDefMIs); 452 } 453 454 First = false; 455 PMII = MII; 456 ++MII; 457 } 458 } 459 460 return Changed; 461 } 462