1 //===-------------- PPCMIPeephole.cpp - MI Peephole Cleanups -------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===---------------------------------------------------------------------===// 8 // 9 // This pass performs peephole optimizations to clean up ugly code 10 // sequences at the MachineInstruction layer. It runs at the end of 11 // the SSA phases, following VSX swap removal. A pass of dead code 12 // elimination follows this one for quick clean-up of any dead 13 // instructions introduced here. Although we could do this as callbacks 14 // from the generic peephole pass, this would have a couple of bad 15 // effects: it might remove optimization opportunities for VSX swap 16 // removal, and it would miss cleanups made possible following VSX 17 // swap removal. 18 // 19 // NOTE: We run the verifier after this pass in Asserts/Debug builds so it 20 // is important to keep the code valid after transformations. 21 // Common causes of errors stem from violating the contract specified 22 // by kill flags. Whenever a transformation changes the live range of 23 // a register, that register should be added to the work list using 24 // addRegToUpdate(RegsToUpdate, <Reg>). Furthermore, if a transformation 25 // is changing the definition of a register (i.e. removing the single 26 // definition of the original vreg), it needs to provide a dummy 27 // definition of that register using addDummyDef(<MBB>, <Reg>). 28 //===---------------------------------------------------------------------===// 29 30 #include "MCTargetDesc/PPCMCTargetDesc.h" 31 #include "MCTargetDesc/PPCPredicates.h" 32 #include "PPC.h" 33 #include "PPCInstrBuilder.h" 34 #include "PPCInstrInfo.h" 35 #include "PPCMachineFunctionInfo.h" 36 #include "PPCTargetMachine.h" 37 #include "llvm/ADT/Statistic.h" 38 #include "llvm/CodeGen/LiveVariables.h" 39 #include "llvm/CodeGen/MachineBlockFrequencyInfo.h" 40 #include "llvm/CodeGen/MachineDominators.h" 41 #include "llvm/CodeGen/MachineFrameInfo.h" 42 #include "llvm/CodeGen/MachineFunctionPass.h" 43 #include "llvm/CodeGen/MachineInstrBuilder.h" 44 #include "llvm/CodeGen/MachinePostDominators.h" 45 #include "llvm/CodeGen/MachineRegisterInfo.h" 46 #include "llvm/InitializePasses.h" 47 #include "llvm/Support/Debug.h" 48 #include "llvm/Support/DebugCounter.h" 49 50 using namespace llvm; 51 52 #define DEBUG_TYPE "ppc-mi-peepholes" 53 54 STATISTIC(RemoveTOCSave, "Number of TOC saves removed"); 55 STATISTIC(MultiTOCSaves, 56 "Number of functions with multiple TOC saves that must be kept"); 57 STATISTIC(NumTOCSavesInPrologue, "Number of TOC saves placed in the prologue"); 58 STATISTIC(NumEliminatedSExt, "Number of eliminated sign-extensions"); 59 STATISTIC(NumEliminatedZExt, "Number of eliminated zero-extensions"); 60 STATISTIC(NumOptADDLIs, "Number of optimized ADD instruction fed by LI"); 61 STATISTIC(NumConvertedToImmediateForm, 62 "Number of instructions converted to their immediate form"); 63 STATISTIC(NumFunctionsEnteredInMIPeephole, 64 "Number of functions entered in PPC MI Peepholes"); 65 STATISTIC(NumFixedPointIterations, 66 "Number of fixed-point iterations converting reg-reg instructions " 67 "to reg-imm ones"); 68 STATISTIC(NumRotatesCollapsed, 69 "Number of pairs of rotate left, clear left/right collapsed"); 70 STATISTIC(NumEXTSWAndSLDICombined, 71 "Number of pairs of EXTSW and SLDI combined as EXTSWSLI"); 72 STATISTIC(NumLoadImmZeroFoldedAndRemoved, 73 "Number of LI(8) reg, 0 that are folded to r0 and removed"); 74 75 static cl::opt<bool> 76 FixedPointRegToImm("ppc-reg-to-imm-fixed-point", cl::Hidden, cl::init(true), 77 cl::desc("Iterate to a fixed point when attempting to " 78 "convert reg-reg instructions to reg-imm")); 79 80 static cl::opt<bool> 81 ConvertRegReg("ppc-convert-rr-to-ri", cl::Hidden, cl::init(true), 82 cl::desc("Convert eligible reg+reg instructions to reg+imm")); 83 84 static cl::opt<bool> 85 EnableSExtElimination("ppc-eliminate-signext", 86 cl::desc("enable elimination of sign-extensions"), 87 cl::init(true), cl::Hidden); 88 89 static cl::opt<bool> 90 EnableZExtElimination("ppc-eliminate-zeroext", 91 cl::desc("enable elimination of zero-extensions"), 92 cl::init(true), cl::Hidden); 93 94 static cl::opt<bool> 95 EnableTrapOptimization("ppc-opt-conditional-trap", 96 cl::desc("enable optimization of conditional traps"), 97 cl::init(false), cl::Hidden); 98 99 DEBUG_COUNTER( 100 PeepholeXToICounter, "ppc-xtoi-peephole", 101 "Controls whether PPC reg+reg to reg+imm peephole is performed on a MI"); 102 103 DEBUG_COUNTER(PeepholePerOpCounter, "ppc-per-op-peephole", 104 "Controls whether PPC per opcode peephole is performed on a MI"); 105 106 namespace { 107 108 struct PPCMIPeephole : public MachineFunctionPass { 109 110 static char ID; 111 const PPCInstrInfo *TII; 112 MachineFunction *MF; 113 MachineRegisterInfo *MRI; 114 LiveVariables *LV; 115 116 PPCMIPeephole() : MachineFunctionPass(ID) { 117 initializePPCMIPeepholePass(*PassRegistry::getPassRegistry()); 118 } 119 120 private: 121 MachineDominatorTree *MDT; 122 MachinePostDominatorTree *MPDT; 123 MachineBlockFrequencyInfo *MBFI; 124 BlockFrequency EntryFreq; 125 SmallSet<Register, 16> RegsToUpdate; 126 127 // Initialize class variables. 128 void initialize(MachineFunction &MFParm); 129 130 // Perform peepholes. 131 bool simplifyCode(); 132 133 // Perform peepholes. 134 bool eliminateRedundantCompare(); 135 bool eliminateRedundantTOCSaves(std::map<MachineInstr *, bool> &TOCSaves); 136 bool combineSEXTAndSHL(MachineInstr &MI, MachineInstr *&ToErase); 137 bool emitRLDICWhenLoweringJumpTables(MachineInstr &MI, 138 MachineInstr *&ToErase); 139 void UpdateTOCSaves(std::map<MachineInstr *, bool> &TOCSaves, 140 MachineInstr *MI); 141 142 // A number of transformations will eliminate the definition of a register 143 // as all of its uses will be removed. However, this leaves a register 144 // without a definition for LiveVariables. Such transformations should 145 // use this function to provide a dummy definition of the register that 146 // will simply be removed by DCE. 147 void addDummyDef(MachineBasicBlock &MBB, MachineInstr *At, Register Reg) { 148 BuildMI(MBB, At, At->getDebugLoc(), TII->get(PPC::IMPLICIT_DEF), Reg); 149 } 150 void addRegToUpdateWithLine(Register Reg, int Line); 151 void convertUnprimedAccPHIs(const PPCInstrInfo *TII, MachineRegisterInfo *MRI, 152 SmallVectorImpl<MachineInstr *> &PHIs, 153 Register Dst); 154 155 public: 156 157 void getAnalysisUsage(AnalysisUsage &AU) const override { 158 AU.addRequired<LiveVariablesWrapperPass>(); 159 AU.addRequired<MachineDominatorTreeWrapperPass>(); 160 AU.addRequired<MachinePostDominatorTreeWrapperPass>(); 161 AU.addRequired<MachineBlockFrequencyInfoWrapperPass>(); 162 AU.addPreserved<LiveVariablesWrapperPass>(); 163 AU.addPreserved<MachineDominatorTreeWrapperPass>(); 164 AU.addPreserved<MachinePostDominatorTreeWrapperPass>(); 165 AU.addPreserved<MachineBlockFrequencyInfoWrapperPass>(); 166 MachineFunctionPass::getAnalysisUsage(AU); 167 } 168 169 // Main entry point for this pass. 170 bool runOnMachineFunction(MachineFunction &MF) override { 171 initialize(MF); 172 // At this point, TOC pointer should not be used in a function that uses 173 // PC-Relative addressing. 174 assert((MF.getRegInfo().use_empty(PPC::X2) || 175 !MF.getSubtarget<PPCSubtarget>().isUsingPCRelativeCalls()) && 176 "TOC pointer used in a function using PC-Relative addressing!"); 177 if (skipFunction(MF.getFunction())) 178 return false; 179 bool Changed = simplifyCode(); 180 #ifndef NDEBUG 181 if (Changed) 182 MF.verify(this, "Error in PowerPC MI Peephole optimization, compile with " 183 "-mllvm -disable-ppc-peephole"); 184 #endif 185 return Changed; 186 } 187 }; 188 189 #define addRegToUpdate(R) addRegToUpdateWithLine(R, __LINE__) 190 void PPCMIPeephole::addRegToUpdateWithLine(Register Reg, int Line) { 191 if (!Register::isVirtualRegister(Reg)) 192 return; 193 if (RegsToUpdate.insert(Reg).second) 194 LLVM_DEBUG(dbgs() << "Adding register: " << Register::virtReg2Index(Reg) 195 << " on line " << Line 196 << " for re-computation of kill flags\n"); 197 } 198 199 // Initialize class variables. 200 void PPCMIPeephole::initialize(MachineFunction &MFParm) { 201 MF = &MFParm; 202 MRI = &MF->getRegInfo(); 203 MDT = &getAnalysis<MachineDominatorTreeWrapperPass>().getDomTree(); 204 MPDT = &getAnalysis<MachinePostDominatorTreeWrapperPass>().getPostDomTree(); 205 MBFI = &getAnalysis<MachineBlockFrequencyInfoWrapperPass>().getMBFI(); 206 LV = &getAnalysis<LiveVariablesWrapperPass>().getLV(); 207 EntryFreq = MBFI->getEntryFreq(); 208 TII = MF->getSubtarget<PPCSubtarget>().getInstrInfo(); 209 RegsToUpdate.clear(); 210 LLVM_DEBUG(dbgs() << "*** PowerPC MI peephole pass ***\n\n"); 211 LLVM_DEBUG(MF->dump()); 212 } 213 214 static MachineInstr *getVRegDefOrNull(MachineOperand *Op, 215 MachineRegisterInfo *MRI) { 216 assert(Op && "Invalid Operand!"); 217 if (!Op->isReg()) 218 return nullptr; 219 220 Register Reg = Op->getReg(); 221 if (!Reg.isVirtual()) 222 return nullptr; 223 224 return MRI->getVRegDef(Reg); 225 } 226 227 // This function returns number of known zero bits in output of MI 228 // starting from the most significant bit. 229 static unsigned getKnownLeadingZeroCount(const unsigned Reg, 230 const PPCInstrInfo *TII, 231 const MachineRegisterInfo *MRI) { 232 MachineInstr *MI = MRI->getVRegDef(Reg); 233 unsigned Opcode = MI->getOpcode(); 234 if (Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec || 235 Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec) 236 return MI->getOperand(3).getImm(); 237 238 if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) && 239 MI->getOperand(3).getImm() <= 63 - MI->getOperand(2).getImm()) 240 return MI->getOperand(3).getImm(); 241 242 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec || 243 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec || 244 Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) && 245 MI->getOperand(3).getImm() <= MI->getOperand(4).getImm()) 246 return 32 + MI->getOperand(3).getImm(); 247 248 if (Opcode == PPC::ANDI_rec) { 249 uint16_t Imm = MI->getOperand(2).getImm(); 250 return 48 + llvm::countl_zero(Imm); 251 } 252 253 if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec || 254 Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec || 255 Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8) 256 // The result ranges from 0 to 32. 257 return 58; 258 259 if (Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec || 260 Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec) 261 // The result ranges from 0 to 64. 262 return 57; 263 264 if (Opcode == PPC::LHZ || Opcode == PPC::LHZX || 265 Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 || 266 Opcode == PPC::LHZU || Opcode == PPC::LHZUX || 267 Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8) 268 return 48; 269 270 if (Opcode == PPC::LBZ || Opcode == PPC::LBZX || 271 Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || 272 Opcode == PPC::LBZU || Opcode == PPC::LBZUX || 273 Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8) 274 return 56; 275 276 if (Opcode == PPC::AND || Opcode == PPC::AND8 || Opcode == PPC::AND_rec || 277 Opcode == PPC::AND8_rec) 278 return std::max( 279 getKnownLeadingZeroCount(MI->getOperand(1).getReg(), TII, MRI), 280 getKnownLeadingZeroCount(MI->getOperand(2).getReg(), TII, MRI)); 281 282 if (Opcode == PPC::OR || Opcode == PPC::OR8 || Opcode == PPC::XOR || 283 Opcode == PPC::XOR8 || Opcode == PPC::OR_rec || 284 Opcode == PPC::OR8_rec || Opcode == PPC::XOR_rec || 285 Opcode == PPC::XOR8_rec) 286 return std::min( 287 getKnownLeadingZeroCount(MI->getOperand(1).getReg(), TII, MRI), 288 getKnownLeadingZeroCount(MI->getOperand(2).getReg(), TII, MRI)); 289 290 if (TII->isZeroExtended(Reg, MRI)) 291 return 32; 292 293 return 0; 294 } 295 296 // This function maintains a map for the pairs <TOC Save Instr, Keep> 297 // Each time a new TOC save is encountered, it checks if any of the existing 298 // ones are dominated by the new one. If so, it marks the existing one as 299 // redundant by setting it's entry in the map as false. It then adds the new 300 // instruction to the map with either true or false depending on if any 301 // existing instructions dominated the new one. 302 void PPCMIPeephole::UpdateTOCSaves( 303 std::map<MachineInstr *, bool> &TOCSaves, MachineInstr *MI) { 304 assert(TII->isTOCSaveMI(*MI) && "Expecting a TOC save instruction here"); 305 // FIXME: Saving TOC in prologue hasn't been implemented well in AIX ABI part, 306 // here only support it under ELFv2. 307 if (MF->getSubtarget<PPCSubtarget>().isELFv2ABI()) { 308 PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>(); 309 310 MachineBasicBlock *Entry = &MF->front(); 311 BlockFrequency CurrBlockFreq = MBFI->getBlockFreq(MI->getParent()); 312 313 // If the block in which the TOC save resides is in a block that 314 // post-dominates Entry, or a block that is hotter than entry (keep in mind 315 // that early MachineLICM has already run so the TOC save won't be hoisted) 316 // we can just do the save in the prologue. 317 if (CurrBlockFreq > EntryFreq || MPDT->dominates(MI->getParent(), Entry)) 318 FI->setMustSaveTOC(true); 319 320 // If we are saving the TOC in the prologue, all the TOC saves can be 321 // removed from the code. 322 if (FI->mustSaveTOC()) { 323 for (auto &TOCSave : TOCSaves) 324 TOCSave.second = false; 325 // Add new instruction to map. 326 TOCSaves[MI] = false; 327 return; 328 } 329 } 330 331 bool Keep = true; 332 for (auto &I : TOCSaves) { 333 MachineInstr *CurrInst = I.first; 334 // If new instruction dominates an existing one, mark existing one as 335 // redundant. 336 if (I.second && MDT->dominates(MI, CurrInst)) 337 I.second = false; 338 // Check if the new instruction is redundant. 339 if (MDT->dominates(CurrInst, MI)) { 340 Keep = false; 341 break; 342 } 343 } 344 // Add new instruction to map. 345 TOCSaves[MI] = Keep; 346 } 347 348 // This function returns a list of all PHI nodes in the tree starting from 349 // the RootPHI node. We perform a BFS traversal to get an ordered list of nodes. 350 // The list initially only contains the root PHI. When we visit a PHI node, we 351 // add it to the list. We continue to look for other PHI node operands while 352 // there are nodes to visit in the list. The function returns false if the 353 // optimization cannot be applied on this tree. 354 static bool collectUnprimedAccPHIs(MachineRegisterInfo *MRI, 355 MachineInstr *RootPHI, 356 SmallVectorImpl<MachineInstr *> &PHIs) { 357 PHIs.push_back(RootPHI); 358 unsigned VisitedIndex = 0; 359 while (VisitedIndex < PHIs.size()) { 360 MachineInstr *VisitedPHI = PHIs[VisitedIndex]; 361 for (unsigned PHIOp = 1, NumOps = VisitedPHI->getNumOperands(); 362 PHIOp != NumOps; PHIOp += 2) { 363 Register RegOp = VisitedPHI->getOperand(PHIOp).getReg(); 364 if (!RegOp.isVirtual()) 365 return false; 366 MachineInstr *Instr = MRI->getVRegDef(RegOp); 367 // While collecting the PHI nodes, we check if they can be converted (i.e. 368 // all the operands are either copies, implicit defs or PHI nodes). 369 unsigned Opcode = Instr->getOpcode(); 370 if (Opcode == PPC::COPY) { 371 Register Reg = Instr->getOperand(1).getReg(); 372 if (!Reg.isVirtual() || MRI->getRegClass(Reg) != &PPC::ACCRCRegClass) 373 return false; 374 } else if (Opcode != PPC::IMPLICIT_DEF && Opcode != PPC::PHI) 375 return false; 376 // If we detect a cycle in the PHI nodes, we exit. It would be 377 // possible to change cycles as well, but that would add a lot 378 // of complexity for a case that is unlikely to occur with MMA 379 // code. 380 if (Opcode != PPC::PHI) 381 continue; 382 if (llvm::is_contained(PHIs, Instr)) 383 return false; 384 PHIs.push_back(Instr); 385 } 386 VisitedIndex++; 387 } 388 return true; 389 } 390 391 // This function changes the unprimed accumulator PHI nodes in the PHIs list to 392 // primed accumulator PHI nodes. The list is traversed in reverse order to 393 // change all the PHI operands of a PHI node before changing the node itself. 394 // We keep a map to associate each changed PHI node to its non-changed form. 395 void PPCMIPeephole::convertUnprimedAccPHIs( 396 const PPCInstrInfo *TII, MachineRegisterInfo *MRI, 397 SmallVectorImpl<MachineInstr *> &PHIs, Register Dst) { 398 DenseMap<MachineInstr *, MachineInstr *> ChangedPHIMap; 399 for (MachineInstr *PHI : llvm::reverse(PHIs)) { 400 SmallVector<std::pair<MachineOperand, MachineOperand>, 4> PHIOps; 401 // We check if the current PHI node can be changed by looking at its 402 // operands. If all the operands are either copies from primed 403 // accumulators, implicit definitions or other unprimed accumulator 404 // PHI nodes, we change it. 405 for (unsigned PHIOp = 1, NumOps = PHI->getNumOperands(); PHIOp != NumOps; 406 PHIOp += 2) { 407 Register RegOp = PHI->getOperand(PHIOp).getReg(); 408 MachineInstr *PHIInput = MRI->getVRegDef(RegOp); 409 unsigned Opcode = PHIInput->getOpcode(); 410 assert((Opcode == PPC::COPY || Opcode == PPC::IMPLICIT_DEF || 411 Opcode == PPC::PHI) && 412 "Unexpected instruction"); 413 if (Opcode == PPC::COPY) { 414 assert(MRI->getRegClass(PHIInput->getOperand(1).getReg()) == 415 &PPC::ACCRCRegClass && 416 "Unexpected register class"); 417 PHIOps.push_back({PHIInput->getOperand(1), PHI->getOperand(PHIOp + 1)}); 418 } else if (Opcode == PPC::IMPLICIT_DEF) { 419 Register AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass); 420 BuildMI(*PHIInput->getParent(), PHIInput, PHIInput->getDebugLoc(), 421 TII->get(PPC::IMPLICIT_DEF), AccReg); 422 PHIOps.push_back({MachineOperand::CreateReg(AccReg, false), 423 PHI->getOperand(PHIOp + 1)}); 424 } else if (Opcode == PPC::PHI) { 425 // We found a PHI operand. At this point we know this operand 426 // has already been changed so we get its associated changed form 427 // from the map. 428 assert(ChangedPHIMap.count(PHIInput) == 1 && 429 "This PHI node should have already been changed."); 430 MachineInstr *PrimedAccPHI = ChangedPHIMap.lookup(PHIInput); 431 PHIOps.push_back({MachineOperand::CreateReg( 432 PrimedAccPHI->getOperand(0).getReg(), false), 433 PHI->getOperand(PHIOp + 1)}); 434 } 435 } 436 Register AccReg = Dst; 437 // If the PHI node we are changing is the root node, the register it defines 438 // will be the destination register of the original copy (of the PHI def). 439 // For all other PHI's in the list, we need to create another primed 440 // accumulator virtual register as the PHI will no longer define the 441 // unprimed accumulator. 442 if (PHI != PHIs[0]) 443 AccReg = MRI->createVirtualRegister(&PPC::ACCRCRegClass); 444 MachineInstrBuilder NewPHI = BuildMI( 445 *PHI->getParent(), PHI, PHI->getDebugLoc(), TII->get(PPC::PHI), AccReg); 446 for (auto RegMBB : PHIOps) { 447 NewPHI.add(RegMBB.first).add(RegMBB.second); 448 if (MRI->isSSA()) 449 addRegToUpdate(RegMBB.first.getReg()); 450 } 451 // The liveness of old PHI and new PHI have to be updated. 452 addRegToUpdate(PHI->getOperand(0).getReg()); 453 addRegToUpdate(AccReg); 454 ChangedPHIMap[PHI] = NewPHI.getInstr(); 455 LLVM_DEBUG(dbgs() << "Converting PHI: "); 456 LLVM_DEBUG(PHI->dump()); 457 LLVM_DEBUG(dbgs() << "To: "); 458 LLVM_DEBUG(NewPHI.getInstr()->dump()); 459 } 460 } 461 462 // Perform peephole optimizations. 463 bool PPCMIPeephole::simplifyCode() { 464 bool Simplified = false; 465 bool TrapOpt = false; 466 MachineInstr* ToErase = nullptr; 467 std::map<MachineInstr *, bool> TOCSaves; 468 const TargetRegisterInfo *TRI = &TII->getRegisterInfo(); 469 NumFunctionsEnteredInMIPeephole++; 470 if (ConvertRegReg) { 471 // Fixed-point conversion of reg/reg instructions fed by load-immediate 472 // into reg/imm instructions. FIXME: This is expensive, control it with 473 // an option. 474 bool SomethingChanged = false; 475 do { 476 NumFixedPointIterations++; 477 SomethingChanged = false; 478 for (MachineBasicBlock &MBB : *MF) { 479 for (MachineInstr &MI : MBB) { 480 if (MI.isDebugInstr()) 481 continue; 482 483 if (!DebugCounter::shouldExecute(PeepholeXToICounter)) 484 continue; 485 486 SmallSet<Register, 4> RRToRIRegsToUpdate; 487 if (!TII->convertToImmediateForm(MI, RRToRIRegsToUpdate)) 488 continue; 489 for (Register R : RRToRIRegsToUpdate) 490 addRegToUpdate(R); 491 // The updated instruction may now have new register operands. 492 // Conservatively add them to recompute the flags as well. 493 for (const MachineOperand &MO : MI.operands()) 494 if (MO.isReg()) 495 addRegToUpdate(MO.getReg()); 496 // We don't erase anything in case the def has other uses. Let DCE 497 // remove it if it can be removed. 498 LLVM_DEBUG(dbgs() << "Converted instruction to imm form: "); 499 LLVM_DEBUG(MI.dump()); 500 NumConvertedToImmediateForm++; 501 SomethingChanged = true; 502 Simplified = true; 503 continue; 504 } 505 } 506 } while (SomethingChanged && FixedPointRegToImm); 507 } 508 509 // Since we are deleting this instruction, we need to run LiveVariables 510 // on any of its definitions that are marked as needing an update since 511 // we can't run LiveVariables on a deleted register. This only needs 512 // to be done for defs since uses will have their own defining 513 // instructions so we won't be running LiveVariables on a deleted reg. 514 auto recomputeLVForDyingInstr = [&]() { 515 if (RegsToUpdate.empty()) 516 return; 517 for (MachineOperand &MO : ToErase->operands()) { 518 if (!MO.isReg() || !MO.isDef() || !RegsToUpdate.count(MO.getReg())) 519 continue; 520 Register RegToUpdate = MO.getReg(); 521 RegsToUpdate.erase(RegToUpdate); 522 // If some transformation has introduced an additional definition of 523 // this register (breaking SSA), we can safely convert this def to 524 // a def of an invalid register as the instruction is going away. 525 if (!MRI->getUniqueVRegDef(RegToUpdate)) 526 MO.setReg(PPC::NoRegister); 527 LV->recomputeForSingleDefVirtReg(RegToUpdate); 528 } 529 }; 530 531 for (MachineBasicBlock &MBB : *MF) { 532 for (MachineInstr &MI : MBB) { 533 534 // If the previous instruction was marked for elimination, 535 // remove it now. 536 if (ToErase) { 537 LLVM_DEBUG(dbgs() << "Deleting instruction: "); 538 LLVM_DEBUG(ToErase->dump()); 539 recomputeLVForDyingInstr(); 540 ToErase->eraseFromParent(); 541 ToErase = nullptr; 542 } 543 // If a conditional trap instruction got optimized to an 544 // unconditional trap, eliminate all the instructions after 545 // the trap. 546 if (EnableTrapOptimization && TrapOpt) { 547 ToErase = &MI; 548 continue; 549 } 550 551 // Ignore debug instructions. 552 if (MI.isDebugInstr()) 553 continue; 554 555 if (!DebugCounter::shouldExecute(PeepholePerOpCounter)) 556 continue; 557 558 // Per-opcode peepholes. 559 switch (MI.getOpcode()) { 560 561 default: 562 break; 563 case PPC::COPY: { 564 Register Src = MI.getOperand(1).getReg(); 565 Register Dst = MI.getOperand(0).getReg(); 566 if (!Src.isVirtual() || !Dst.isVirtual()) 567 break; 568 if (MRI->getRegClass(Src) != &PPC::UACCRCRegClass || 569 MRI->getRegClass(Dst) != &PPC::ACCRCRegClass) 570 break; 571 572 // We are copying an unprimed accumulator to a primed accumulator. 573 // If the input to the copy is a PHI that is fed only by (i) copies in 574 // the other direction (ii) implicitly defined unprimed accumulators or 575 // (iii) other PHI nodes satisfying (i) and (ii), we can change 576 // the PHI to a PHI on primed accumulators (as long as we also change 577 // its operands). To detect and change such copies, we first get a list 578 // of all the PHI nodes starting from the root PHI node in BFS order. 579 // We then visit all these PHI nodes to check if they can be changed to 580 // primed accumulator PHI nodes and if so, we change them. 581 MachineInstr *RootPHI = MRI->getVRegDef(Src); 582 if (RootPHI->getOpcode() != PPC::PHI) 583 break; 584 585 SmallVector<MachineInstr *, 4> PHIs; 586 if (!collectUnprimedAccPHIs(MRI, RootPHI, PHIs)) 587 break; 588 589 convertUnprimedAccPHIs(TII, MRI, PHIs, Dst); 590 591 ToErase = &MI; 592 break; 593 } 594 case PPC::LI: 595 case PPC::LI8: { 596 // If we are materializing a zero, look for any use operands for which 597 // zero means immediate zero. All such operands can be replaced with 598 // PPC::ZERO. 599 if (!MI.getOperand(1).isImm() || MI.getOperand(1).getImm() != 0) 600 break; 601 Register MIDestReg = MI.getOperand(0).getReg(); 602 bool Folded = false; 603 for (MachineInstr& UseMI : MRI->use_instructions(MIDestReg)) 604 Folded |= TII->onlyFoldImmediate(UseMI, MI, MIDestReg); 605 if (MRI->use_nodbg_empty(MIDestReg)) { 606 ++NumLoadImmZeroFoldedAndRemoved; 607 ToErase = &MI; 608 } 609 if (Folded) 610 addRegToUpdate(MIDestReg); 611 Simplified |= Folded; 612 break; 613 } 614 case PPC::STW: 615 case PPC::STD: { 616 MachineFrameInfo &MFI = MF->getFrameInfo(); 617 if (MFI.hasVarSizedObjects() || 618 (!MF->getSubtarget<PPCSubtarget>().isELFv2ABI() && 619 !MF->getSubtarget<PPCSubtarget>().isAIXABI())) 620 break; 621 // When encountering a TOC save instruction, call UpdateTOCSaves 622 // to add it to the TOCSaves map and mark any existing TOC saves 623 // it dominates as redundant. 624 if (TII->isTOCSaveMI(MI)) 625 UpdateTOCSaves(TOCSaves, &MI); 626 break; 627 } 628 case PPC::XXPERMDI: { 629 // Perform simplifications of 2x64 vector swaps and splats. 630 // A swap is identified by an immediate value of 2, and a splat 631 // is identified by an immediate value of 0 or 3. 632 int Immed = MI.getOperand(3).getImm(); 633 634 if (Immed == 1) 635 break; 636 637 // For each of these simplifications, we need the two source 638 // regs to match. Unfortunately, MachineCSE ignores COPY and 639 // SUBREG_TO_REG, so for example we can see 640 // XXPERMDI t, SUBREG_TO_REG(s), SUBREG_TO_REG(s), immed. 641 // We have to look through chains of COPY and SUBREG_TO_REG 642 // to find the real source values for comparison. 643 Register TrueReg1 = 644 TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI); 645 Register TrueReg2 = 646 TRI->lookThruCopyLike(MI.getOperand(2).getReg(), MRI); 647 648 if (!(TrueReg1 == TrueReg2 && TrueReg1.isVirtual())) 649 break; 650 651 MachineInstr *DefMI = MRI->getVRegDef(TrueReg1); 652 653 if (!DefMI) 654 break; 655 656 unsigned DefOpc = DefMI->getOpcode(); 657 658 // If this is a splat fed by a splatting load, the splat is 659 // redundant. Replace with a copy. This doesn't happen directly due 660 // to code in PPCDAGToDAGISel.cpp, but it can happen when converting 661 // a load of a double to a vector of 64-bit integers. 662 auto isConversionOfLoadAndSplat = [=]() -> bool { 663 if (DefOpc != PPC::XVCVDPSXDS && DefOpc != PPC::XVCVDPUXDS) 664 return false; 665 Register FeedReg1 = 666 TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI); 667 if (FeedReg1.isVirtual()) { 668 MachineInstr *LoadMI = MRI->getVRegDef(FeedReg1); 669 if (LoadMI && LoadMI->getOpcode() == PPC::LXVDSX) 670 return true; 671 } 672 return false; 673 }; 674 if ((Immed == 0 || Immed == 3) && 675 (DefOpc == PPC::LXVDSX || isConversionOfLoadAndSplat())) { 676 LLVM_DEBUG(dbgs() << "Optimizing load-and-splat/splat " 677 "to load-and-splat/copy: "); 678 LLVM_DEBUG(MI.dump()); 679 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 680 MI.getOperand(0).getReg()) 681 .add(MI.getOperand(1)); 682 addRegToUpdate(MI.getOperand(1).getReg()); 683 ToErase = &MI; 684 Simplified = true; 685 } 686 687 // If this is a splat or a swap fed by another splat, we 688 // can replace it with a copy. 689 if (DefOpc == PPC::XXPERMDI) { 690 Register DefReg1 = DefMI->getOperand(1).getReg(); 691 Register DefReg2 = DefMI->getOperand(2).getReg(); 692 unsigned DefImmed = DefMI->getOperand(3).getImm(); 693 694 // If the two inputs are not the same register, check to see if 695 // they originate from the same virtual register after only 696 // copy-like instructions. 697 if (DefReg1 != DefReg2) { 698 Register FeedReg1 = TRI->lookThruCopyLike(DefReg1, MRI); 699 Register FeedReg2 = TRI->lookThruCopyLike(DefReg2, MRI); 700 701 if (!(FeedReg1 == FeedReg2 && FeedReg1.isVirtual())) 702 break; 703 } 704 705 if (DefImmed == 0 || DefImmed == 3) { 706 LLVM_DEBUG(dbgs() << "Optimizing splat/swap or splat/splat " 707 "to splat/copy: "); 708 LLVM_DEBUG(MI.dump()); 709 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 710 MI.getOperand(0).getReg()) 711 .add(MI.getOperand(1)); 712 addRegToUpdate(MI.getOperand(1).getReg()); 713 ToErase = &MI; 714 Simplified = true; 715 } 716 717 // If this is a splat fed by a swap, we can simplify modify 718 // the splat to splat the other value from the swap's input 719 // parameter. 720 else if ((Immed == 0 || Immed == 3) && DefImmed == 2) { 721 LLVM_DEBUG(dbgs() << "Optimizing swap/splat => splat: "); 722 LLVM_DEBUG(MI.dump()); 723 addRegToUpdate(MI.getOperand(1).getReg()); 724 addRegToUpdate(MI.getOperand(2).getReg()); 725 MI.getOperand(1).setReg(DefReg1); 726 MI.getOperand(2).setReg(DefReg2); 727 MI.getOperand(3).setImm(3 - Immed); 728 addRegToUpdate(DefReg1); 729 addRegToUpdate(DefReg2); 730 Simplified = true; 731 } 732 733 // If this is a swap fed by a swap, we can replace it 734 // with a copy from the first swap's input. 735 else if (Immed == 2 && DefImmed == 2) { 736 LLVM_DEBUG(dbgs() << "Optimizing swap/swap => copy: "); 737 LLVM_DEBUG(MI.dump()); 738 addRegToUpdate(MI.getOperand(1).getReg()); 739 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 740 MI.getOperand(0).getReg()) 741 .add(DefMI->getOperand(1)); 742 addRegToUpdate(DefMI->getOperand(0).getReg()); 743 addRegToUpdate(DefMI->getOperand(1).getReg()); 744 ToErase = &MI; 745 Simplified = true; 746 } 747 } else if ((Immed == 0 || Immed == 3 || Immed == 2) && 748 DefOpc == PPC::XXPERMDIs && 749 (DefMI->getOperand(2).getImm() == 0 || 750 DefMI->getOperand(2).getImm() == 3)) { 751 ToErase = &MI; 752 Simplified = true; 753 // Swap of a splat, convert to copy. 754 if (Immed == 2) { 755 LLVM_DEBUG(dbgs() << "Optimizing swap(splat) => copy(splat): "); 756 LLVM_DEBUG(MI.dump()); 757 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 758 MI.getOperand(0).getReg()) 759 .add(MI.getOperand(1)); 760 addRegToUpdate(MI.getOperand(1).getReg()); 761 break; 762 } 763 // Splat fed by another splat - switch the output of the first 764 // and remove the second. 765 DefMI->getOperand(0).setReg(MI.getOperand(0).getReg()); 766 LLVM_DEBUG(dbgs() << "Removing redundant splat: "); 767 LLVM_DEBUG(MI.dump()); 768 } else if (Immed == 2 && 769 (DefOpc == PPC::VSPLTB || DefOpc == PPC::VSPLTH || 770 DefOpc == PPC::VSPLTW || DefOpc == PPC::XXSPLTW || 771 DefOpc == PPC::VSPLTISB || DefOpc == PPC::VSPLTISH || 772 DefOpc == PPC::VSPLTISW)) { 773 // Swap of various vector splats, convert to copy. 774 ToErase = &MI; 775 Simplified = true; 776 LLVM_DEBUG(dbgs() << "Optimizing swap(vsplt(is)?[b|h|w]|xxspltw) => " 777 "copy(vsplt(is)?[b|h|w]|xxspltw): "); 778 LLVM_DEBUG(MI.dump()); 779 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 780 MI.getOperand(0).getReg()) 781 .add(MI.getOperand(1)); 782 addRegToUpdate(MI.getOperand(1).getReg()); 783 } else if ((Immed == 0 || Immed == 3 || Immed == 2) && 784 TII->isLoadFromConstantPool(DefMI)) { 785 const Constant *C = TII->getConstantFromConstantPool(DefMI); 786 if (C && C->getType()->isVectorTy() && C->getSplatValue()) { 787 ToErase = &MI; 788 Simplified = true; 789 LLVM_DEBUG(dbgs() 790 << "Optimizing swap(splat pattern from constant-pool) " 791 "=> copy(splat pattern from constant-pool): "); 792 LLVM_DEBUG(MI.dump()); 793 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 794 MI.getOperand(0).getReg()) 795 .add(MI.getOperand(1)); 796 addRegToUpdate(MI.getOperand(1).getReg()); 797 } 798 } 799 break; 800 } 801 case PPC::VSPLTB: 802 case PPC::VSPLTH: 803 case PPC::XXSPLTW: { 804 unsigned MyOpcode = MI.getOpcode(); 805 unsigned OpNo = MyOpcode == PPC::XXSPLTW ? 1 : 2; 806 Register TrueReg = 807 TRI->lookThruCopyLike(MI.getOperand(OpNo).getReg(), MRI); 808 if (!TrueReg.isVirtual()) 809 break; 810 MachineInstr *DefMI = MRI->getVRegDef(TrueReg); 811 if (!DefMI) 812 break; 813 unsigned DefOpcode = DefMI->getOpcode(); 814 auto isConvertOfSplat = [=]() -> bool { 815 if (DefOpcode != PPC::XVCVSPSXWS && DefOpcode != PPC::XVCVSPUXWS) 816 return false; 817 Register ConvReg = DefMI->getOperand(1).getReg(); 818 if (!ConvReg.isVirtual()) 819 return false; 820 MachineInstr *Splt = MRI->getVRegDef(ConvReg); 821 return Splt && (Splt->getOpcode() == PPC::LXVWSX || 822 Splt->getOpcode() == PPC::XXSPLTW); 823 }; 824 bool AlreadySplat = (MyOpcode == DefOpcode) || 825 (MyOpcode == PPC::VSPLTB && DefOpcode == PPC::VSPLTBs) || 826 (MyOpcode == PPC::VSPLTH && DefOpcode == PPC::VSPLTHs) || 827 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::XXSPLTWs) || 828 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::LXVWSX) || 829 (MyOpcode == PPC::XXSPLTW && DefOpcode == PPC::MTVSRWS)|| 830 (MyOpcode == PPC::XXSPLTW && isConvertOfSplat()); 831 // If the instruction[s] that feed this splat have already splat 832 // the value, this splat is redundant. 833 if (AlreadySplat) { 834 LLVM_DEBUG(dbgs() << "Changing redundant splat to a copy: "); 835 LLVM_DEBUG(MI.dump()); 836 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 837 MI.getOperand(0).getReg()) 838 .add(MI.getOperand(OpNo)); 839 addRegToUpdate(MI.getOperand(OpNo).getReg()); 840 ToErase = &MI; 841 Simplified = true; 842 } 843 // Splat fed by a shift. Usually when we align value to splat into 844 // vector element zero. 845 if (DefOpcode == PPC::XXSLDWI) { 846 Register ShiftRes = DefMI->getOperand(0).getReg(); 847 Register ShiftOp1 = DefMI->getOperand(1).getReg(); 848 Register ShiftOp2 = DefMI->getOperand(2).getReg(); 849 unsigned ShiftImm = DefMI->getOperand(3).getImm(); 850 unsigned SplatImm = 851 MI.getOperand(MyOpcode == PPC::XXSPLTW ? 2 : 1).getImm(); 852 if (ShiftOp1 == ShiftOp2) { 853 unsigned NewElem = (SplatImm + ShiftImm) & 0x3; 854 if (MRI->hasOneNonDBGUse(ShiftRes)) { 855 LLVM_DEBUG(dbgs() << "Removing redundant shift: "); 856 LLVM_DEBUG(DefMI->dump()); 857 ToErase = DefMI; 858 } 859 Simplified = true; 860 LLVM_DEBUG(dbgs() << "Changing splat immediate from " << SplatImm 861 << " to " << NewElem << " in instruction: "); 862 LLVM_DEBUG(MI.dump()); 863 addRegToUpdate(MI.getOperand(OpNo).getReg()); 864 addRegToUpdate(ShiftOp1); 865 MI.getOperand(OpNo).setReg(ShiftOp1); 866 MI.getOperand(2).setImm(NewElem); 867 } 868 } 869 break; 870 } 871 case PPC::XVCVDPSP: { 872 // If this is a DP->SP conversion fed by an FRSP, the FRSP is redundant. 873 Register TrueReg = 874 TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI); 875 if (!TrueReg.isVirtual()) 876 break; 877 MachineInstr *DefMI = MRI->getVRegDef(TrueReg); 878 879 // This can occur when building a vector of single precision or integer 880 // values. 881 if (DefMI && DefMI->getOpcode() == PPC::XXPERMDI) { 882 Register DefsReg1 = 883 TRI->lookThruCopyLike(DefMI->getOperand(1).getReg(), MRI); 884 Register DefsReg2 = 885 TRI->lookThruCopyLike(DefMI->getOperand(2).getReg(), MRI); 886 if (!DefsReg1.isVirtual() || !DefsReg2.isVirtual()) 887 break; 888 MachineInstr *P1 = MRI->getVRegDef(DefsReg1); 889 MachineInstr *P2 = MRI->getVRegDef(DefsReg2); 890 891 if (!P1 || !P2) 892 break; 893 894 // Remove the passed FRSP/XSRSP instruction if it only feeds this MI 895 // and set any uses of that FRSP/XSRSP (in this MI) to the source of 896 // the FRSP/XSRSP. 897 auto removeFRSPIfPossible = [&](MachineInstr *RoundInstr) { 898 unsigned Opc = RoundInstr->getOpcode(); 899 if ((Opc == PPC::FRSP || Opc == PPC::XSRSP) && 900 MRI->hasOneNonDBGUse(RoundInstr->getOperand(0).getReg())) { 901 Simplified = true; 902 Register ConvReg1 = RoundInstr->getOperand(1).getReg(); 903 Register FRSPDefines = RoundInstr->getOperand(0).getReg(); 904 MachineInstr &Use = *(MRI->use_instr_nodbg_begin(FRSPDefines)); 905 for (int i = 0, e = Use.getNumOperands(); i < e; ++i) 906 if (Use.getOperand(i).isReg() && 907 Use.getOperand(i).getReg() == FRSPDefines) 908 Use.getOperand(i).setReg(ConvReg1); 909 LLVM_DEBUG(dbgs() << "Removing redundant FRSP/XSRSP:\n"); 910 LLVM_DEBUG(RoundInstr->dump()); 911 LLVM_DEBUG(dbgs() << "As it feeds instruction:\n"); 912 LLVM_DEBUG(MI.dump()); 913 LLVM_DEBUG(dbgs() << "Through instruction:\n"); 914 LLVM_DEBUG(DefMI->dump()); 915 addRegToUpdate(ConvReg1); 916 addRegToUpdate(FRSPDefines); 917 ToErase = RoundInstr; 918 } 919 }; 920 921 // If the input to XVCVDPSP is a vector that was built (even 922 // partially) out of FRSP's, the FRSP(s) can safely be removed 923 // since this instruction performs the same operation. 924 if (P1 != P2) { 925 removeFRSPIfPossible(P1); 926 removeFRSPIfPossible(P2); 927 break; 928 } 929 removeFRSPIfPossible(P1); 930 } 931 break; 932 } 933 case PPC::EXTSH: 934 case PPC::EXTSH8: 935 case PPC::EXTSH8_32_64: { 936 if (!EnableSExtElimination) break; 937 Register NarrowReg = MI.getOperand(1).getReg(); 938 if (!NarrowReg.isVirtual()) 939 break; 940 941 MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg); 942 unsigned SrcOpcode = SrcMI->getOpcode(); 943 // If we've used a zero-extending load that we will sign-extend, 944 // just do a sign-extending load. 945 if (SrcOpcode == PPC::LHZ || SrcOpcode == PPC::LHZX) { 946 if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg())) 947 break; 948 // Determine the new opcode. We need to make sure that if the original 949 // instruction has a 64 bit opcode we keep using a 64 bit opcode. 950 // Likewise if the source is X-Form the new opcode should also be 951 // X-Form. 952 unsigned Opc = PPC::LHA; 953 bool SourceIsXForm = SrcOpcode == PPC::LHZX; 954 bool MIIs64Bit = MI.getOpcode() == PPC::EXTSH8 || 955 MI.getOpcode() == PPC::EXTSH8_32_64; 956 957 if (SourceIsXForm && MIIs64Bit) 958 Opc = PPC::LHAX8; 959 else if (SourceIsXForm && !MIIs64Bit) 960 Opc = PPC::LHAX; 961 else if (MIIs64Bit) 962 Opc = PPC::LHA8; 963 964 addRegToUpdate(NarrowReg); 965 addRegToUpdate(MI.getOperand(0).getReg()); 966 967 // We are removing a definition of NarrowReg which will cause 968 // problems in AliveBlocks. Add an implicit def that will be 969 // removed so that AliveBlocks are updated correctly. 970 addDummyDef(MBB, &MI, NarrowReg); 971 LLVM_DEBUG(dbgs() << "Zero-extending load\n"); 972 LLVM_DEBUG(SrcMI->dump()); 973 LLVM_DEBUG(dbgs() << "and sign-extension\n"); 974 LLVM_DEBUG(MI.dump()); 975 LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n"); 976 SrcMI->setDesc(TII->get(Opc)); 977 SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg()); 978 ToErase = &MI; 979 Simplified = true; 980 NumEliminatedSExt++; 981 } 982 break; 983 } 984 case PPC::EXTSW: 985 case PPC::EXTSW_32: 986 case PPC::EXTSW_32_64: { 987 if (!EnableSExtElimination) break; 988 Register NarrowReg = MI.getOperand(1).getReg(); 989 if (!NarrowReg.isVirtual()) 990 break; 991 992 MachineInstr *SrcMI = MRI->getVRegDef(NarrowReg); 993 unsigned SrcOpcode = SrcMI->getOpcode(); 994 // If we've used a zero-extending load that we will sign-extend, 995 // just do a sign-extending load. 996 if (SrcOpcode == PPC::LWZ || SrcOpcode == PPC::LWZX) { 997 if (!MRI->hasOneNonDBGUse(SrcMI->getOperand(0).getReg())) 998 break; 999 1000 // The transformation from a zero-extending load to a sign-extending 1001 // load is only legal when the displacement is a multiple of 4. 1002 // If the displacement is not at least 4 byte aligned, don't perform 1003 // the transformation. 1004 bool IsWordAligned = false; 1005 if (SrcMI->getOperand(1).isGlobal()) { 1006 const GlobalObject *GO = 1007 dyn_cast<GlobalObject>(SrcMI->getOperand(1).getGlobal()); 1008 if (GO && GO->getAlign() && *GO->getAlign() >= 4 && 1009 (SrcMI->getOperand(1).getOffset() % 4 == 0)) 1010 IsWordAligned = true; 1011 } else if (SrcMI->getOperand(1).isImm()) { 1012 int64_t Value = SrcMI->getOperand(1).getImm(); 1013 if (Value % 4 == 0) 1014 IsWordAligned = true; 1015 } 1016 1017 // Determine the new opcode. We need to make sure that if the original 1018 // instruction has a 64 bit opcode we keep using a 64 bit opcode. 1019 // Likewise if the source is X-Form the new opcode should also be 1020 // X-Form. 1021 unsigned Opc = PPC::LWA_32; 1022 bool SourceIsXForm = SrcOpcode == PPC::LWZX; 1023 bool MIIs64Bit = MI.getOpcode() == PPC::EXTSW || 1024 MI.getOpcode() == PPC::EXTSW_32_64; 1025 1026 if (SourceIsXForm && MIIs64Bit) 1027 Opc = PPC::LWAX; 1028 else if (SourceIsXForm && !MIIs64Bit) 1029 Opc = PPC::LWAX_32; 1030 else if (MIIs64Bit) 1031 Opc = PPC::LWA; 1032 1033 if (!IsWordAligned && (Opc == PPC::LWA || Opc == PPC::LWA_32)) 1034 break; 1035 1036 addRegToUpdate(NarrowReg); 1037 addRegToUpdate(MI.getOperand(0).getReg()); 1038 1039 // We are removing a definition of NarrowReg which will cause 1040 // problems in AliveBlocks. Add an implicit def that will be 1041 // removed so that AliveBlocks are updated correctly. 1042 addDummyDef(MBB, &MI, NarrowReg); 1043 LLVM_DEBUG(dbgs() << "Zero-extending load\n"); 1044 LLVM_DEBUG(SrcMI->dump()); 1045 LLVM_DEBUG(dbgs() << "and sign-extension\n"); 1046 LLVM_DEBUG(MI.dump()); 1047 LLVM_DEBUG(dbgs() << "are merged into sign-extending load\n"); 1048 SrcMI->setDesc(TII->get(Opc)); 1049 SrcMI->getOperand(0).setReg(MI.getOperand(0).getReg()); 1050 ToErase = &MI; 1051 Simplified = true; 1052 NumEliminatedSExt++; 1053 } else if (MI.getOpcode() == PPC::EXTSW_32_64 && 1054 TII->isSignExtended(NarrowReg, MRI)) { 1055 // We can eliminate EXTSW if the input is known to be already 1056 // sign-extended. However, we are not sure whether a spill will occur 1057 // during register allocation. If there is no promotion, it will use 1058 // 'stw' instead of 'std', and 'lwz' instead of 'ld' when spilling, 1059 // since the register class is 32-bits. Consequently, the high 32-bit 1060 // information will be lost. Therefore, all these instructions in the 1061 // chain used to deduce sign extension to eliminate the 'extsw' will 1062 // need to be promoted to 64-bit pseudo instructions when the 'extsw' 1063 // is eliminated. 1064 TII->promoteInstr32To64ForElimEXTSW(NarrowReg, MRI, 0, LV); 1065 1066 LLVM_DEBUG(dbgs() << "Removing redundant sign-extension\n"); 1067 Register TmpReg = 1068 MF->getRegInfo().createVirtualRegister(&PPC::G8RCRegClass); 1069 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::IMPLICIT_DEF), 1070 TmpReg); 1071 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::INSERT_SUBREG), 1072 MI.getOperand(0).getReg()) 1073 .addReg(TmpReg) 1074 .addReg(NarrowReg) 1075 .addImm(PPC::sub_32); 1076 ToErase = &MI; 1077 Simplified = true; 1078 NumEliminatedSExt++; 1079 } 1080 break; 1081 } 1082 case PPC::RLDICL: { 1083 // We can eliminate RLDICL (e.g. for zero-extension) 1084 // if all bits to clear are already zero in the input. 1085 // This code assume following code sequence for zero-extension. 1086 // %6 = COPY %5:sub_32; (optional) 1087 // %8 = IMPLICIT_DEF; 1088 // %7<def,tied1> = INSERT_SUBREG %8<tied0>, %6, sub_32; 1089 if (!EnableZExtElimination) break; 1090 1091 if (MI.getOperand(2).getImm() != 0) 1092 break; 1093 1094 Register SrcReg = MI.getOperand(1).getReg(); 1095 if (!SrcReg.isVirtual()) 1096 break; 1097 1098 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 1099 if (!(SrcMI && SrcMI->getOpcode() == PPC::INSERT_SUBREG && 1100 SrcMI->getOperand(0).isReg() && SrcMI->getOperand(1).isReg())) 1101 break; 1102 1103 MachineInstr *ImpDefMI, *SubRegMI; 1104 ImpDefMI = MRI->getVRegDef(SrcMI->getOperand(1).getReg()); 1105 SubRegMI = MRI->getVRegDef(SrcMI->getOperand(2).getReg()); 1106 if (ImpDefMI->getOpcode() != PPC::IMPLICIT_DEF) break; 1107 1108 SrcMI = SubRegMI; 1109 if (SubRegMI->getOpcode() == PPC::COPY) { 1110 Register CopyReg = SubRegMI->getOperand(1).getReg(); 1111 if (CopyReg.isVirtual()) 1112 SrcMI = MRI->getVRegDef(CopyReg); 1113 } 1114 if (!SrcMI->getOperand(0).isReg()) 1115 break; 1116 1117 unsigned KnownZeroCount = 1118 getKnownLeadingZeroCount(SrcMI->getOperand(0).getReg(), TII, MRI); 1119 if (MI.getOperand(3).getImm() <= KnownZeroCount) { 1120 LLVM_DEBUG(dbgs() << "Removing redundant zero-extension\n"); 1121 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 1122 MI.getOperand(0).getReg()) 1123 .addReg(SrcReg); 1124 addRegToUpdate(SrcReg); 1125 ToErase = &MI; 1126 Simplified = true; 1127 NumEliminatedZExt++; 1128 } 1129 break; 1130 } 1131 1132 // TODO: Any instruction that has an immediate form fed only by a PHI 1133 // whose operands are all load immediate can be folded away. We currently 1134 // do this for ADD instructions, but should expand it to arithmetic and 1135 // binary instructions with immediate forms in the future. 1136 case PPC::ADD4: 1137 case PPC::ADD8: { 1138 auto isSingleUsePHI = [&](MachineOperand *PhiOp) { 1139 assert(PhiOp && "Invalid Operand!"); 1140 MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI); 1141 1142 return DefPhiMI && (DefPhiMI->getOpcode() == PPC::PHI) && 1143 MRI->hasOneNonDBGUse(DefPhiMI->getOperand(0).getReg()); 1144 }; 1145 1146 auto dominatesAllSingleUseLIs = [&](MachineOperand *DominatorOp, 1147 MachineOperand *PhiOp) { 1148 assert(PhiOp && "Invalid Operand!"); 1149 assert(DominatorOp && "Invalid Operand!"); 1150 MachineInstr *DefPhiMI = getVRegDefOrNull(PhiOp, MRI); 1151 MachineInstr *DefDomMI = getVRegDefOrNull(DominatorOp, MRI); 1152 1153 // Note: the vregs only show up at odd indices position of PHI Node, 1154 // the even indices position save the BB info. 1155 for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) { 1156 MachineInstr *LiMI = 1157 getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI); 1158 if (!LiMI || 1159 (LiMI->getOpcode() != PPC::LI && LiMI->getOpcode() != PPC::LI8) 1160 || !MRI->hasOneNonDBGUse(LiMI->getOperand(0).getReg()) || 1161 !MDT->dominates(DefDomMI, LiMI)) 1162 return false; 1163 } 1164 1165 return true; 1166 }; 1167 1168 MachineOperand Op1 = MI.getOperand(1); 1169 MachineOperand Op2 = MI.getOperand(2); 1170 if (isSingleUsePHI(&Op2) && dominatesAllSingleUseLIs(&Op1, &Op2)) 1171 std::swap(Op1, Op2); 1172 else if (!isSingleUsePHI(&Op1) || !dominatesAllSingleUseLIs(&Op2, &Op1)) 1173 break; // We don't have an ADD fed by LI's that can be transformed 1174 1175 // Now we know that Op1 is the PHI node and Op2 is the dominator 1176 Register DominatorReg = Op2.getReg(); 1177 1178 const TargetRegisterClass *TRC = MI.getOpcode() == PPC::ADD8 1179 ? &PPC::G8RC_and_G8RC_NOX0RegClass 1180 : &PPC::GPRC_and_GPRC_NOR0RegClass; 1181 MRI->setRegClass(DominatorReg, TRC); 1182 1183 // replace LIs with ADDIs 1184 MachineInstr *DefPhiMI = getVRegDefOrNull(&Op1, MRI); 1185 for (unsigned i = 1; i < DefPhiMI->getNumOperands(); i += 2) { 1186 MachineInstr *LiMI = getVRegDefOrNull(&DefPhiMI->getOperand(i), MRI); 1187 LLVM_DEBUG(dbgs() << "Optimizing LI to ADDI: "); 1188 LLVM_DEBUG(LiMI->dump()); 1189 1190 // There could be repeated registers in the PHI, e.g: %1 = 1191 // PHI %6, <%bb.2>, %8, <%bb.3>, %8, <%bb.6>; So if we've 1192 // already replaced the def instruction, skip. 1193 if (LiMI->getOpcode() == PPC::ADDI || LiMI->getOpcode() == PPC::ADDI8) 1194 continue; 1195 1196 assert((LiMI->getOpcode() == PPC::LI || 1197 LiMI->getOpcode() == PPC::LI8) && 1198 "Invalid Opcode!"); 1199 auto LiImm = LiMI->getOperand(1).getImm(); // save the imm of LI 1200 LiMI->removeOperand(1); // remove the imm of LI 1201 LiMI->setDesc(TII->get(LiMI->getOpcode() == PPC::LI ? PPC::ADDI 1202 : PPC::ADDI8)); 1203 MachineInstrBuilder(*LiMI->getParent()->getParent(), *LiMI) 1204 .addReg(DominatorReg) 1205 .addImm(LiImm); // restore the imm of LI 1206 LLVM_DEBUG(LiMI->dump()); 1207 } 1208 1209 // Replace ADD with COPY 1210 LLVM_DEBUG(dbgs() << "Optimizing ADD to COPY: "); 1211 LLVM_DEBUG(MI.dump()); 1212 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::COPY), 1213 MI.getOperand(0).getReg()) 1214 .add(Op1); 1215 addRegToUpdate(Op1.getReg()); 1216 addRegToUpdate(Op2.getReg()); 1217 ToErase = &MI; 1218 Simplified = true; 1219 NumOptADDLIs++; 1220 break; 1221 } 1222 case PPC::RLDICR: { 1223 Simplified |= emitRLDICWhenLoweringJumpTables(MI, ToErase) || 1224 combineSEXTAndSHL(MI, ToErase); 1225 break; 1226 } 1227 case PPC::ANDI_rec: 1228 case PPC::ANDI8_rec: 1229 case PPC::ANDIS_rec: 1230 case PPC::ANDIS8_rec: { 1231 Register TrueReg = 1232 TRI->lookThruCopyLike(MI.getOperand(1).getReg(), MRI); 1233 if (!TrueReg.isVirtual() || !MRI->hasOneNonDBGUse(TrueReg)) 1234 break; 1235 1236 MachineInstr *SrcMI = MRI->getVRegDef(TrueReg); 1237 if (!SrcMI) 1238 break; 1239 1240 unsigned SrcOpCode = SrcMI->getOpcode(); 1241 if (SrcOpCode != PPC::RLDICL && SrcOpCode != PPC::RLDICR) 1242 break; 1243 1244 Register SrcReg, DstReg; 1245 SrcReg = SrcMI->getOperand(1).getReg(); 1246 DstReg = MI.getOperand(1).getReg(); 1247 const TargetRegisterClass *SrcRC = MRI->getRegClassOrNull(SrcReg); 1248 const TargetRegisterClass *DstRC = MRI->getRegClassOrNull(DstReg); 1249 if (DstRC != SrcRC) 1250 break; 1251 1252 uint64_t AndImm = MI.getOperand(2).getImm(); 1253 if (MI.getOpcode() == PPC::ANDIS_rec || 1254 MI.getOpcode() == PPC::ANDIS8_rec) 1255 AndImm <<= 16; 1256 uint64_t LZeroAndImm = llvm::countl_zero<uint64_t>(AndImm); 1257 uint64_t RZeroAndImm = llvm::countr_zero<uint64_t>(AndImm); 1258 uint64_t ImmSrc = SrcMI->getOperand(3).getImm(); 1259 1260 // We can transfer `RLDICL/RLDICR + ANDI_rec/ANDIS_rec` to `ANDI_rec 0` 1261 // if all bits to AND are already zero in the input. 1262 bool PatternResultZero = 1263 (SrcOpCode == PPC::RLDICL && (RZeroAndImm + ImmSrc > 63)) || 1264 (SrcOpCode == PPC::RLDICR && LZeroAndImm > ImmSrc); 1265 1266 // We can eliminate RLDICL/RLDICR if it's used to clear bits and all 1267 // bits cleared will be ANDed with 0 by ANDI_rec/ANDIS_rec. 1268 bool PatternRemoveRotate = 1269 SrcMI->getOperand(2).getImm() == 0 && 1270 ((SrcOpCode == PPC::RLDICL && LZeroAndImm >= ImmSrc) || 1271 (SrcOpCode == PPC::RLDICR && (RZeroAndImm + ImmSrc > 63))); 1272 1273 if (!PatternResultZero && !PatternRemoveRotate) 1274 break; 1275 1276 LLVM_DEBUG(dbgs() << "Combining pair: "); 1277 LLVM_DEBUG(SrcMI->dump()); 1278 LLVM_DEBUG(MI.dump()); 1279 if (PatternResultZero) 1280 MI.getOperand(2).setImm(0); 1281 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg()); 1282 LLVM_DEBUG(dbgs() << "To: "); 1283 LLVM_DEBUG(MI.dump()); 1284 addRegToUpdate(MI.getOperand(1).getReg()); 1285 addRegToUpdate(SrcMI->getOperand(0).getReg()); 1286 Simplified = true; 1287 break; 1288 } 1289 case PPC::RLWINM: 1290 case PPC::RLWINM_rec: 1291 case PPC::RLWINM8: 1292 case PPC::RLWINM8_rec: { 1293 // We might replace operand 1 of the instruction which will 1294 // require we recompute kill flags for it. 1295 Register OrigOp1Reg = MI.getOperand(1).isReg() 1296 ? MI.getOperand(1).getReg() 1297 : PPC::NoRegister; 1298 Simplified = TII->combineRLWINM(MI, &ToErase); 1299 if (Simplified) { 1300 addRegToUpdate(OrigOp1Reg); 1301 if (MI.getOperand(1).isReg()) 1302 addRegToUpdate(MI.getOperand(1).getReg()); 1303 if (ToErase && ToErase->getOperand(1).isReg()) 1304 for (auto UseReg : ToErase->explicit_uses()) 1305 if (UseReg.isReg()) 1306 addRegToUpdate(UseReg.getReg()); 1307 ++NumRotatesCollapsed; 1308 } 1309 break; 1310 } 1311 // We will replace TD/TW/TDI/TWI with an unconditional trap if it will 1312 // always trap, we will delete the node if it will never trap. 1313 case PPC::TDI: 1314 case PPC::TWI: 1315 case PPC::TD: 1316 case PPC::TW: { 1317 if (!EnableTrapOptimization) break; 1318 MachineInstr *LiMI1 = getVRegDefOrNull(&MI.getOperand(1), MRI); 1319 MachineInstr *LiMI2 = getVRegDefOrNull(&MI.getOperand(2), MRI); 1320 bool IsOperand2Immediate = MI.getOperand(2).isImm(); 1321 // We can only do the optimization if we can get immediates 1322 // from both operands 1323 if (!(LiMI1 && (LiMI1->getOpcode() == PPC::LI || 1324 LiMI1->getOpcode() == PPC::LI8))) 1325 break; 1326 if (!IsOperand2Immediate && 1327 !(LiMI2 && (LiMI2->getOpcode() == PPC::LI || 1328 LiMI2->getOpcode() == PPC::LI8))) 1329 break; 1330 1331 auto ImmOperand0 = MI.getOperand(0).getImm(); 1332 auto ImmOperand1 = LiMI1->getOperand(1).getImm(); 1333 auto ImmOperand2 = IsOperand2Immediate ? MI.getOperand(2).getImm() 1334 : LiMI2->getOperand(1).getImm(); 1335 1336 // We will replace the MI with an unconditional trap if it will always 1337 // trap. 1338 if ((ImmOperand0 == 31) || 1339 ((ImmOperand0 & 0x10) && 1340 ((int64_t)ImmOperand1 < (int64_t)ImmOperand2)) || 1341 ((ImmOperand0 & 0x8) && 1342 ((int64_t)ImmOperand1 > (int64_t)ImmOperand2)) || 1343 ((ImmOperand0 & 0x2) && 1344 ((uint64_t)ImmOperand1 < (uint64_t)ImmOperand2)) || 1345 ((ImmOperand0 & 0x1) && 1346 ((uint64_t)ImmOperand1 > (uint64_t)ImmOperand2)) || 1347 ((ImmOperand0 & 0x4) && (ImmOperand1 == ImmOperand2))) { 1348 BuildMI(MBB, &MI, MI.getDebugLoc(), TII->get(PPC::TRAP)); 1349 TrapOpt = true; 1350 } 1351 // We will delete the MI if it will never trap. 1352 ToErase = &MI; 1353 Simplified = true; 1354 break; 1355 } 1356 } 1357 } 1358 1359 // If the last instruction was marked for elimination, 1360 // remove it now. 1361 if (ToErase) { 1362 recomputeLVForDyingInstr(); 1363 ToErase->eraseFromParent(); 1364 ToErase = nullptr; 1365 } 1366 // Reset TrapOpt to false at the end of the basic block. 1367 if (EnableTrapOptimization) 1368 TrapOpt = false; 1369 } 1370 1371 // Eliminate all the TOC save instructions which are redundant. 1372 Simplified |= eliminateRedundantTOCSaves(TOCSaves); 1373 PPCFunctionInfo *FI = MF->getInfo<PPCFunctionInfo>(); 1374 if (FI->mustSaveTOC()) 1375 NumTOCSavesInPrologue++; 1376 1377 // We try to eliminate redundant compare instruction. 1378 Simplified |= eliminateRedundantCompare(); 1379 1380 // If we have made any modifications and added any registers to the set of 1381 // registers for which we need to update the kill flags, do so by recomputing 1382 // LiveVariables for those registers. 1383 for (Register Reg : RegsToUpdate) { 1384 if (!MRI->reg_empty(Reg)) 1385 LV->recomputeForSingleDefVirtReg(Reg); 1386 } 1387 return Simplified; 1388 } 1389 1390 // helper functions for eliminateRedundantCompare 1391 static bool isEqOrNe(MachineInstr *BI) { 1392 PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm(); 1393 unsigned PredCond = PPC::getPredicateCondition(Pred); 1394 return (PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE); 1395 } 1396 1397 static bool isSupportedCmpOp(unsigned opCode) { 1398 return (opCode == PPC::CMPLD || opCode == PPC::CMPD || 1399 opCode == PPC::CMPLW || opCode == PPC::CMPW || 1400 opCode == PPC::CMPLDI || opCode == PPC::CMPDI || 1401 opCode == PPC::CMPLWI || opCode == PPC::CMPWI); 1402 } 1403 1404 static bool is64bitCmpOp(unsigned opCode) { 1405 return (opCode == PPC::CMPLD || opCode == PPC::CMPD || 1406 opCode == PPC::CMPLDI || opCode == PPC::CMPDI); 1407 } 1408 1409 static bool isSignedCmpOp(unsigned opCode) { 1410 return (opCode == PPC::CMPD || opCode == PPC::CMPW || 1411 opCode == PPC::CMPDI || opCode == PPC::CMPWI); 1412 } 1413 1414 static unsigned getSignedCmpOpCode(unsigned opCode) { 1415 if (opCode == PPC::CMPLD) return PPC::CMPD; 1416 if (opCode == PPC::CMPLW) return PPC::CMPW; 1417 if (opCode == PPC::CMPLDI) return PPC::CMPDI; 1418 if (opCode == PPC::CMPLWI) return PPC::CMPWI; 1419 return opCode; 1420 } 1421 1422 // We can decrement immediate x in (GE x) by changing it to (GT x-1) or 1423 // (LT x) to (LE x-1) 1424 static unsigned getPredicateToDecImm(MachineInstr *BI, MachineInstr *CMPI) { 1425 uint64_t Imm = CMPI->getOperand(2).getImm(); 1426 bool SignedCmp = isSignedCmpOp(CMPI->getOpcode()); 1427 if ((!SignedCmp && Imm == 0) || (SignedCmp && Imm == 0x8000)) 1428 return 0; 1429 1430 PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm(); 1431 unsigned PredCond = PPC::getPredicateCondition(Pred); 1432 unsigned PredHint = PPC::getPredicateHint(Pred); 1433 if (PredCond == PPC::PRED_GE) 1434 return PPC::getPredicate(PPC::PRED_GT, PredHint); 1435 if (PredCond == PPC::PRED_LT) 1436 return PPC::getPredicate(PPC::PRED_LE, PredHint); 1437 1438 return 0; 1439 } 1440 1441 // We can increment immediate x in (GT x) by changing it to (GE x+1) or 1442 // (LE x) to (LT x+1) 1443 static unsigned getPredicateToIncImm(MachineInstr *BI, MachineInstr *CMPI) { 1444 uint64_t Imm = CMPI->getOperand(2).getImm(); 1445 bool SignedCmp = isSignedCmpOp(CMPI->getOpcode()); 1446 if ((!SignedCmp && Imm == 0xFFFF) || (SignedCmp && Imm == 0x7FFF)) 1447 return 0; 1448 1449 PPC::Predicate Pred = (PPC::Predicate)BI->getOperand(0).getImm(); 1450 unsigned PredCond = PPC::getPredicateCondition(Pred); 1451 unsigned PredHint = PPC::getPredicateHint(Pred); 1452 if (PredCond == PPC::PRED_GT) 1453 return PPC::getPredicate(PPC::PRED_GE, PredHint); 1454 if (PredCond == PPC::PRED_LE) 1455 return PPC::getPredicate(PPC::PRED_LT, PredHint); 1456 1457 return 0; 1458 } 1459 1460 // This takes a Phi node and returns a register value for the specified BB. 1461 static unsigned getIncomingRegForBlock(MachineInstr *Phi, 1462 MachineBasicBlock *MBB) { 1463 for (unsigned I = 2, E = Phi->getNumOperands() + 1; I != E; I += 2) { 1464 MachineOperand &MO = Phi->getOperand(I); 1465 if (MO.getMBB() == MBB) 1466 return Phi->getOperand(I-1).getReg(); 1467 } 1468 llvm_unreachable("invalid src basic block for this Phi node\n"); 1469 return 0; 1470 } 1471 1472 // This function tracks the source of the register through register copy. 1473 // If BB1 and BB2 are non-NULL, we also track PHI instruction in BB2 1474 // assuming that the control comes from BB1 into BB2. 1475 static unsigned getSrcVReg(unsigned Reg, MachineBasicBlock *BB1, 1476 MachineBasicBlock *BB2, MachineRegisterInfo *MRI) { 1477 unsigned SrcReg = Reg; 1478 while (true) { 1479 unsigned NextReg = SrcReg; 1480 MachineInstr *Inst = MRI->getVRegDef(SrcReg); 1481 if (BB1 && Inst->getOpcode() == PPC::PHI && Inst->getParent() == BB2) { 1482 NextReg = getIncomingRegForBlock(Inst, BB1); 1483 // We track through PHI only once to avoid infinite loop. 1484 BB1 = nullptr; 1485 } 1486 else if (Inst->isFullCopy()) 1487 NextReg = Inst->getOperand(1).getReg(); 1488 if (NextReg == SrcReg || !Register::isVirtualRegister(NextReg)) 1489 break; 1490 SrcReg = NextReg; 1491 } 1492 return SrcReg; 1493 } 1494 1495 static bool eligibleForCompareElimination(MachineBasicBlock &MBB, 1496 MachineBasicBlock *&PredMBB, 1497 MachineBasicBlock *&MBBtoMoveCmp, 1498 MachineRegisterInfo *MRI) { 1499 1500 auto isEligibleBB = [&](MachineBasicBlock &BB) { 1501 auto BII = BB.getFirstInstrTerminator(); 1502 // We optimize BBs ending with a conditional branch. 1503 // We check only for BCC here, not BCCLR, because BCCLR 1504 // will be formed only later in the pipeline. 1505 if (BB.succ_size() == 2 && 1506 BII != BB.instr_end() && 1507 (*BII).getOpcode() == PPC::BCC && 1508 (*BII).getOperand(1).isReg()) { 1509 // We optimize only if the condition code is used only by one BCC. 1510 Register CndReg = (*BII).getOperand(1).getReg(); 1511 if (!CndReg.isVirtual() || !MRI->hasOneNonDBGUse(CndReg)) 1512 return false; 1513 1514 MachineInstr *CMPI = MRI->getVRegDef(CndReg); 1515 // We assume compare and branch are in the same BB for ease of analysis. 1516 if (CMPI->getParent() != &BB) 1517 return false; 1518 1519 // We skip this BB if a physical register is used in comparison. 1520 for (MachineOperand &MO : CMPI->operands()) 1521 if (MO.isReg() && !MO.getReg().isVirtual()) 1522 return false; 1523 1524 return true; 1525 } 1526 return false; 1527 }; 1528 1529 // If this BB has more than one successor, we can create a new BB and 1530 // move the compare instruction in the new BB. 1531 // So far, we do not move compare instruction to a BB having multiple 1532 // successors to avoid potentially increasing code size. 1533 auto isEligibleForMoveCmp = [](MachineBasicBlock &BB) { 1534 return BB.succ_size() == 1; 1535 }; 1536 1537 if (!isEligibleBB(MBB)) 1538 return false; 1539 1540 unsigned NumPredBBs = MBB.pred_size(); 1541 if (NumPredBBs == 1) { 1542 MachineBasicBlock *TmpMBB = *MBB.pred_begin(); 1543 if (isEligibleBB(*TmpMBB)) { 1544 PredMBB = TmpMBB; 1545 MBBtoMoveCmp = nullptr; 1546 return true; 1547 } 1548 } 1549 else if (NumPredBBs == 2) { 1550 // We check for partially redundant case. 1551 // So far, we support cases with only two predecessors 1552 // to avoid increasing the number of instructions. 1553 MachineBasicBlock::pred_iterator PI = MBB.pred_begin(); 1554 MachineBasicBlock *Pred1MBB = *PI; 1555 MachineBasicBlock *Pred2MBB = *(PI+1); 1556 1557 if (isEligibleBB(*Pred1MBB) && isEligibleForMoveCmp(*Pred2MBB)) { 1558 // We assume Pred1MBB is the BB containing the compare to be merged and 1559 // Pred2MBB is the BB to which we will append a compare instruction. 1560 // Proceed as is if Pred1MBB is different from MBB. 1561 } 1562 else if (isEligibleBB(*Pred2MBB) && isEligibleForMoveCmp(*Pred1MBB)) { 1563 // We need to swap Pred1MBB and Pred2MBB to canonicalize. 1564 std::swap(Pred1MBB, Pred2MBB); 1565 } 1566 else return false; 1567 1568 if (Pred1MBB == &MBB) 1569 return false; 1570 1571 // Here, Pred2MBB is the BB to which we need to append a compare inst. 1572 // We cannot move the compare instruction if operands are not available 1573 // in Pred2MBB (i.e. defined in MBB by an instruction other than PHI). 1574 MachineInstr *BI = &*MBB.getFirstInstrTerminator(); 1575 MachineInstr *CMPI = MRI->getVRegDef(BI->getOperand(1).getReg()); 1576 for (int I = 1; I <= 2; I++) 1577 if (CMPI->getOperand(I).isReg()) { 1578 MachineInstr *Inst = MRI->getVRegDef(CMPI->getOperand(I).getReg()); 1579 if (Inst->getParent() == &MBB && Inst->getOpcode() != PPC::PHI) 1580 return false; 1581 } 1582 1583 PredMBB = Pred1MBB; 1584 MBBtoMoveCmp = Pred2MBB; 1585 return true; 1586 } 1587 1588 return false; 1589 } 1590 1591 // This function will iterate over the input map containing a pair of TOC save 1592 // instruction and a flag. The flag will be set to false if the TOC save is 1593 // proven redundant. This function will erase from the basic block all the TOC 1594 // saves marked as redundant. 1595 bool PPCMIPeephole::eliminateRedundantTOCSaves( 1596 std::map<MachineInstr *, bool> &TOCSaves) { 1597 bool Simplified = false; 1598 int NumKept = 0; 1599 for (auto TOCSave : TOCSaves) { 1600 if (!TOCSave.second) { 1601 TOCSave.first->eraseFromParent(); 1602 RemoveTOCSave++; 1603 Simplified = true; 1604 } else { 1605 NumKept++; 1606 } 1607 } 1608 1609 if (NumKept > 1) 1610 MultiTOCSaves++; 1611 1612 return Simplified; 1613 } 1614 1615 // If multiple conditional branches are executed based on the (essentially) 1616 // same comparison, we merge compare instructions into one and make multiple 1617 // conditional branches on this comparison. 1618 // For example, 1619 // if (a == 0) { ... } 1620 // else if (a < 0) { ... } 1621 // can be executed by one compare and two conditional branches instead of 1622 // two pairs of a compare and a conditional branch. 1623 // 1624 // This method merges two compare instructions in two MBBs and modifies the 1625 // compare and conditional branch instructions if needed. 1626 // For the above example, the input for this pass looks like: 1627 // cmplwi r3, 0 1628 // beq 0, .LBB0_3 1629 // cmpwi r3, -1 1630 // bgt 0, .LBB0_4 1631 // So, before merging two compares, we need to modify these instructions as 1632 // cmpwi r3, 0 ; cmplwi and cmpwi yield same result for beq 1633 // beq 0, .LBB0_3 1634 // cmpwi r3, 0 ; greather than -1 means greater or equal to 0 1635 // bge 0, .LBB0_4 1636 1637 bool PPCMIPeephole::eliminateRedundantCompare() { 1638 bool Simplified = false; 1639 1640 for (MachineBasicBlock &MBB2 : *MF) { 1641 MachineBasicBlock *MBB1 = nullptr, *MBBtoMoveCmp = nullptr; 1642 1643 // For fully redundant case, we select two basic blocks MBB1 and MBB2 1644 // as an optimization target if 1645 // - both MBBs end with a conditional branch, 1646 // - MBB1 is the only predecessor of MBB2, and 1647 // - compare does not take a physical register as a operand in both MBBs. 1648 // In this case, eligibleForCompareElimination sets MBBtoMoveCmp nullptr. 1649 // 1650 // As partially redundant case, we additionally handle if MBB2 has one 1651 // additional predecessor, which has only one successor (MBB2). 1652 // In this case, we move the compare instruction originally in MBB2 into 1653 // MBBtoMoveCmp. This partially redundant case is typically appear by 1654 // compiling a while loop; here, MBBtoMoveCmp is the loop preheader. 1655 // 1656 // Overview of CFG of related basic blocks 1657 // Fully redundant case Partially redundant case 1658 // -------- ---------------- -------- 1659 // | MBB1 | (w/ 2 succ) | MBBtoMoveCmp | | MBB1 | (w/ 2 succ) 1660 // -------- ---------------- -------- 1661 // | \ (w/ 1 succ) \ | \ 1662 // | \ \ | \ 1663 // | \ | 1664 // -------- -------- 1665 // | MBB2 | (w/ 1 pred | MBB2 | (w/ 2 pred 1666 // -------- and 2 succ) -------- and 2 succ) 1667 // | \ | \ 1668 // | \ | \ 1669 // 1670 if (!eligibleForCompareElimination(MBB2, MBB1, MBBtoMoveCmp, MRI)) 1671 continue; 1672 1673 MachineInstr *BI1 = &*MBB1->getFirstInstrTerminator(); 1674 MachineInstr *CMPI1 = MRI->getVRegDef(BI1->getOperand(1).getReg()); 1675 1676 MachineInstr *BI2 = &*MBB2.getFirstInstrTerminator(); 1677 MachineInstr *CMPI2 = MRI->getVRegDef(BI2->getOperand(1).getReg()); 1678 bool IsPartiallyRedundant = (MBBtoMoveCmp != nullptr); 1679 1680 // We cannot optimize an unsupported compare opcode or 1681 // a mix of 32-bit and 64-bit comparisons 1682 if (!isSupportedCmpOp(CMPI1->getOpcode()) || 1683 !isSupportedCmpOp(CMPI2->getOpcode()) || 1684 is64bitCmpOp(CMPI1->getOpcode()) != is64bitCmpOp(CMPI2->getOpcode())) 1685 continue; 1686 1687 unsigned NewOpCode = 0; 1688 unsigned NewPredicate1 = 0, NewPredicate2 = 0; 1689 int16_t Imm1 = 0, NewImm1 = 0, Imm2 = 0, NewImm2 = 0; 1690 bool SwapOperands = false; 1691 1692 if (CMPI1->getOpcode() != CMPI2->getOpcode()) { 1693 // Typically, unsigned comparison is used for equality check, but 1694 // we replace it with a signed comparison if the comparison 1695 // to be merged is a signed comparison. 1696 // In other cases of opcode mismatch, we cannot optimize this. 1697 1698 // We cannot change opcode when comparing against an immediate 1699 // if the most significant bit of the immediate is one 1700 // due to the difference in sign extension. 1701 auto CmpAgainstImmWithSignBit = [](MachineInstr *I) { 1702 if (!I->getOperand(2).isImm()) 1703 return false; 1704 int16_t Imm = (int16_t)I->getOperand(2).getImm(); 1705 return Imm < 0; 1706 }; 1707 1708 if (isEqOrNe(BI2) && !CmpAgainstImmWithSignBit(CMPI2) && 1709 CMPI1->getOpcode() == getSignedCmpOpCode(CMPI2->getOpcode())) 1710 NewOpCode = CMPI1->getOpcode(); 1711 else if (isEqOrNe(BI1) && !CmpAgainstImmWithSignBit(CMPI1) && 1712 getSignedCmpOpCode(CMPI1->getOpcode()) == CMPI2->getOpcode()) 1713 NewOpCode = CMPI2->getOpcode(); 1714 else continue; 1715 } 1716 1717 if (CMPI1->getOperand(2).isReg() && CMPI2->getOperand(2).isReg()) { 1718 // In case of comparisons between two registers, these two registers 1719 // must be same to merge two comparisons. 1720 unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(), 1721 nullptr, nullptr, MRI); 1722 unsigned Cmp1Operand2 = getSrcVReg(CMPI1->getOperand(2).getReg(), 1723 nullptr, nullptr, MRI); 1724 unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(), 1725 MBB1, &MBB2, MRI); 1726 unsigned Cmp2Operand2 = getSrcVReg(CMPI2->getOperand(2).getReg(), 1727 MBB1, &MBB2, MRI); 1728 1729 if (Cmp1Operand1 == Cmp2Operand1 && Cmp1Operand2 == Cmp2Operand2) { 1730 // Same pair of registers in the same order; ready to merge as is. 1731 } 1732 else if (Cmp1Operand1 == Cmp2Operand2 && Cmp1Operand2 == Cmp2Operand1) { 1733 // Same pair of registers in different order. 1734 // We reverse the predicate to merge compare instructions. 1735 PPC::Predicate Pred = (PPC::Predicate)BI2->getOperand(0).getImm(); 1736 NewPredicate2 = (unsigned)PPC::getSwappedPredicate(Pred); 1737 // In case of partial redundancy, we need to swap operands 1738 // in another compare instruction. 1739 SwapOperands = true; 1740 } 1741 else continue; 1742 } 1743 else if (CMPI1->getOperand(2).isImm() && CMPI2->getOperand(2).isImm()) { 1744 // In case of comparisons between a register and an immediate, 1745 // the operand register must be same for two compare instructions. 1746 unsigned Cmp1Operand1 = getSrcVReg(CMPI1->getOperand(1).getReg(), 1747 nullptr, nullptr, MRI); 1748 unsigned Cmp2Operand1 = getSrcVReg(CMPI2->getOperand(1).getReg(), 1749 MBB1, &MBB2, MRI); 1750 if (Cmp1Operand1 != Cmp2Operand1) 1751 continue; 1752 1753 NewImm1 = Imm1 = (int16_t)CMPI1->getOperand(2).getImm(); 1754 NewImm2 = Imm2 = (int16_t)CMPI2->getOperand(2).getImm(); 1755 1756 // If immediate are not same, we try to adjust by changing predicate; 1757 // e.g. GT imm means GE (imm+1). 1758 if (Imm1 != Imm2 && (!isEqOrNe(BI2) || !isEqOrNe(BI1))) { 1759 int Diff = Imm1 - Imm2; 1760 if (Diff < -2 || Diff > 2) 1761 continue; 1762 1763 unsigned PredToInc1 = getPredicateToIncImm(BI1, CMPI1); 1764 unsigned PredToDec1 = getPredicateToDecImm(BI1, CMPI1); 1765 unsigned PredToInc2 = getPredicateToIncImm(BI2, CMPI2); 1766 unsigned PredToDec2 = getPredicateToDecImm(BI2, CMPI2); 1767 if (Diff == 2) { 1768 if (PredToInc2 && PredToDec1) { 1769 NewPredicate2 = PredToInc2; 1770 NewPredicate1 = PredToDec1; 1771 NewImm2++; 1772 NewImm1--; 1773 } 1774 } 1775 else if (Diff == 1) { 1776 if (PredToInc2) { 1777 NewImm2++; 1778 NewPredicate2 = PredToInc2; 1779 } 1780 else if (PredToDec1) { 1781 NewImm1--; 1782 NewPredicate1 = PredToDec1; 1783 } 1784 } 1785 else if (Diff == -1) { 1786 if (PredToDec2) { 1787 NewImm2--; 1788 NewPredicate2 = PredToDec2; 1789 } 1790 else if (PredToInc1) { 1791 NewImm1++; 1792 NewPredicate1 = PredToInc1; 1793 } 1794 } 1795 else if (Diff == -2) { 1796 if (PredToDec2 && PredToInc1) { 1797 NewPredicate2 = PredToDec2; 1798 NewPredicate1 = PredToInc1; 1799 NewImm2--; 1800 NewImm1++; 1801 } 1802 } 1803 } 1804 1805 // We cannot merge two compares if the immediates are not same. 1806 if (NewImm2 != NewImm1) 1807 continue; 1808 } 1809 1810 LLVM_DEBUG(dbgs() << "Optimize two pairs of compare and branch:\n"); 1811 LLVM_DEBUG(CMPI1->dump()); 1812 LLVM_DEBUG(BI1->dump()); 1813 LLVM_DEBUG(CMPI2->dump()); 1814 LLVM_DEBUG(BI2->dump()); 1815 for (const MachineOperand &MO : CMPI1->operands()) 1816 if (MO.isReg()) 1817 addRegToUpdate(MO.getReg()); 1818 for (const MachineOperand &MO : CMPI2->operands()) 1819 if (MO.isReg()) 1820 addRegToUpdate(MO.getReg()); 1821 1822 // We adjust opcode, predicates and immediate as we determined above. 1823 if (NewOpCode != 0 && NewOpCode != CMPI1->getOpcode()) { 1824 CMPI1->setDesc(TII->get(NewOpCode)); 1825 } 1826 if (NewPredicate1) { 1827 BI1->getOperand(0).setImm(NewPredicate1); 1828 } 1829 if (NewPredicate2) { 1830 BI2->getOperand(0).setImm(NewPredicate2); 1831 } 1832 if (NewImm1 != Imm1) { 1833 CMPI1->getOperand(2).setImm(NewImm1); 1834 } 1835 1836 if (IsPartiallyRedundant) { 1837 // We touch up the compare instruction in MBB2 and move it to 1838 // a previous BB to handle partially redundant case. 1839 if (SwapOperands) { 1840 Register Op1 = CMPI2->getOperand(1).getReg(); 1841 Register Op2 = CMPI2->getOperand(2).getReg(); 1842 CMPI2->getOperand(1).setReg(Op2); 1843 CMPI2->getOperand(2).setReg(Op1); 1844 } 1845 if (NewImm2 != Imm2) 1846 CMPI2->getOperand(2).setImm(NewImm2); 1847 1848 for (int I = 1; I <= 2; I++) { 1849 if (CMPI2->getOperand(I).isReg()) { 1850 MachineInstr *Inst = MRI->getVRegDef(CMPI2->getOperand(I).getReg()); 1851 if (Inst->getParent() != &MBB2) 1852 continue; 1853 1854 assert(Inst->getOpcode() == PPC::PHI && 1855 "We cannot support if an operand comes from this BB."); 1856 unsigned SrcReg = getIncomingRegForBlock(Inst, MBBtoMoveCmp); 1857 CMPI2->getOperand(I).setReg(SrcReg); 1858 addRegToUpdate(SrcReg); 1859 } 1860 } 1861 auto I = MachineBasicBlock::iterator(MBBtoMoveCmp->getFirstTerminator()); 1862 MBBtoMoveCmp->splice(I, &MBB2, MachineBasicBlock::iterator(CMPI2)); 1863 1864 DebugLoc DL = CMPI2->getDebugLoc(); 1865 Register NewVReg = MRI->createVirtualRegister(&PPC::CRRCRegClass); 1866 BuildMI(MBB2, MBB2.begin(), DL, 1867 TII->get(PPC::PHI), NewVReg) 1868 .addReg(BI1->getOperand(1).getReg()).addMBB(MBB1) 1869 .addReg(BI2->getOperand(1).getReg()).addMBB(MBBtoMoveCmp); 1870 BI2->getOperand(1).setReg(NewVReg); 1871 addRegToUpdate(NewVReg); 1872 } 1873 else { 1874 // We finally eliminate compare instruction in MBB2. 1875 // We do not need to treat CMPI2 specially here in terms of re-computing 1876 // live variables even though it is being deleted because: 1877 // - It defines a register that has a single use (already checked in 1878 // eligibleForCompareElimination()) 1879 // - The only user (BI2) is no longer using it so the register is dead (no 1880 // def, no uses) 1881 // - We do not attempt to recompute live variables for dead registers 1882 BI2->getOperand(1).setReg(BI1->getOperand(1).getReg()); 1883 CMPI2->eraseFromParent(); 1884 } 1885 1886 LLVM_DEBUG(dbgs() << "into a compare and two branches:\n"); 1887 LLVM_DEBUG(CMPI1->dump()); 1888 LLVM_DEBUG(BI1->dump()); 1889 LLVM_DEBUG(BI2->dump()); 1890 if (IsPartiallyRedundant) { 1891 LLVM_DEBUG(dbgs() << "The following compare is moved into " 1892 << printMBBReference(*MBBtoMoveCmp) 1893 << " to handle partial redundancy.\n"); 1894 LLVM_DEBUG(CMPI2->dump()); 1895 } 1896 Simplified = true; 1897 } 1898 1899 return Simplified; 1900 } 1901 1902 // We miss the opportunity to emit an RLDIC when lowering jump tables 1903 // since ISEL sees only a single basic block. When selecting, the clear 1904 // and shift left will be in different blocks. 1905 bool PPCMIPeephole::emitRLDICWhenLoweringJumpTables(MachineInstr &MI, 1906 MachineInstr *&ToErase) { 1907 if (MI.getOpcode() != PPC::RLDICR) 1908 return false; 1909 1910 Register SrcReg = MI.getOperand(1).getReg(); 1911 if (!SrcReg.isVirtual()) 1912 return false; 1913 1914 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 1915 if (SrcMI->getOpcode() != PPC::RLDICL) 1916 return false; 1917 1918 MachineOperand MOpSHSrc = SrcMI->getOperand(2); 1919 MachineOperand MOpMBSrc = SrcMI->getOperand(3); 1920 MachineOperand MOpSHMI = MI.getOperand(2); 1921 MachineOperand MOpMEMI = MI.getOperand(3); 1922 if (!(MOpSHSrc.isImm() && MOpMBSrc.isImm() && MOpSHMI.isImm() && 1923 MOpMEMI.isImm())) 1924 return false; 1925 1926 uint64_t SHSrc = MOpSHSrc.getImm(); 1927 uint64_t MBSrc = MOpMBSrc.getImm(); 1928 uint64_t SHMI = MOpSHMI.getImm(); 1929 uint64_t MEMI = MOpMEMI.getImm(); 1930 uint64_t NewSH = SHSrc + SHMI; 1931 uint64_t NewMB = MBSrc - SHMI; 1932 if (NewMB > 63 || NewSH > 63) 1933 return false; 1934 1935 // The bits cleared with RLDICL are [0, MBSrc). 1936 // The bits cleared with RLDICR are (MEMI, 63]. 1937 // After the sequence, the bits cleared are: 1938 // [0, MBSrc-SHMI) and (MEMI, 63). 1939 // 1940 // The bits cleared with RLDIC are [0, NewMB) and (63-NewSH, 63]. 1941 if ((63 - NewSH) != MEMI) 1942 return false; 1943 1944 LLVM_DEBUG(dbgs() << "Converting pair: "); 1945 LLVM_DEBUG(SrcMI->dump()); 1946 LLVM_DEBUG(MI.dump()); 1947 1948 MI.setDesc(TII->get(PPC::RLDIC)); 1949 MI.getOperand(1).setReg(SrcMI->getOperand(1).getReg()); 1950 MI.getOperand(2).setImm(NewSH); 1951 MI.getOperand(3).setImm(NewMB); 1952 addRegToUpdate(MI.getOperand(1).getReg()); 1953 addRegToUpdate(SrcMI->getOperand(0).getReg()); 1954 1955 LLVM_DEBUG(dbgs() << "To: "); 1956 LLVM_DEBUG(MI.dump()); 1957 NumRotatesCollapsed++; 1958 // If SrcReg has no non-debug use it's safe to delete its def SrcMI. 1959 if (MRI->use_nodbg_empty(SrcReg)) { 1960 assert(!SrcMI->hasImplicitDef() && 1961 "Not expecting an implicit def with this instr."); 1962 ToErase = SrcMI; 1963 } 1964 return true; 1965 } 1966 1967 // For case in LLVM IR 1968 // entry: 1969 // %iconv = sext i32 %index to i64 1970 // br i1 undef label %true, label %false 1971 // true: 1972 // %ptr = getelementptr inbounds i32, i32* null, i64 %iconv 1973 // ... 1974 // PPCISelLowering::combineSHL fails to combine, because sext and shl are in 1975 // different BBs when conducting instruction selection. We can do a peephole 1976 // optimization to combine these two instructions into extswsli after 1977 // instruction selection. 1978 bool PPCMIPeephole::combineSEXTAndSHL(MachineInstr &MI, 1979 MachineInstr *&ToErase) { 1980 if (MI.getOpcode() != PPC::RLDICR) 1981 return false; 1982 1983 if (!MF->getSubtarget<PPCSubtarget>().isISA3_0()) 1984 return false; 1985 1986 assert(MI.getNumOperands() == 4 && "RLDICR should have 4 operands"); 1987 1988 MachineOperand MOpSHMI = MI.getOperand(2); 1989 MachineOperand MOpMEMI = MI.getOperand(3); 1990 if (!(MOpSHMI.isImm() && MOpMEMI.isImm())) 1991 return false; 1992 1993 uint64_t SHMI = MOpSHMI.getImm(); 1994 uint64_t MEMI = MOpMEMI.getImm(); 1995 if (SHMI + MEMI != 63) 1996 return false; 1997 1998 Register SrcReg = MI.getOperand(1).getReg(); 1999 if (!SrcReg.isVirtual()) 2000 return false; 2001 2002 MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 2003 if (SrcMI->getOpcode() != PPC::EXTSW && 2004 SrcMI->getOpcode() != PPC::EXTSW_32_64) 2005 return false; 2006 2007 // If the register defined by extsw has more than one use, combination is not 2008 // needed. 2009 if (!MRI->hasOneNonDBGUse(SrcReg)) 2010 return false; 2011 2012 assert(SrcMI->getNumOperands() == 2 && "EXTSW should have 2 operands"); 2013 assert(SrcMI->getOperand(1).isReg() && 2014 "EXTSW's second operand should be a register"); 2015 if (!SrcMI->getOperand(1).getReg().isVirtual()) 2016 return false; 2017 2018 LLVM_DEBUG(dbgs() << "Combining pair: "); 2019 LLVM_DEBUG(SrcMI->dump()); 2020 LLVM_DEBUG(MI.dump()); 2021 2022 MachineInstr *NewInstr = 2023 BuildMI(*MI.getParent(), &MI, MI.getDebugLoc(), 2024 SrcMI->getOpcode() == PPC::EXTSW ? TII->get(PPC::EXTSWSLI) 2025 : TII->get(PPC::EXTSWSLI_32_64), 2026 MI.getOperand(0).getReg()) 2027 .add(SrcMI->getOperand(1)) 2028 .add(MOpSHMI); 2029 (void)NewInstr; 2030 2031 LLVM_DEBUG(dbgs() << "TO: "); 2032 LLVM_DEBUG(NewInstr->dump()); 2033 ++NumEXTSWAndSLDICombined; 2034 ToErase = &MI; 2035 // SrcMI, which is extsw, is of no use now, but we don't erase it here so we 2036 // can recompute its kill flags. We run DCE immediately after this pass 2037 // to clean up dead instructions such as this. 2038 addRegToUpdate(NewInstr->getOperand(1).getReg()); 2039 addRegToUpdate(SrcMI->getOperand(0).getReg()); 2040 return true; 2041 } 2042 2043 } // end default namespace 2044 2045 INITIALIZE_PASS_BEGIN(PPCMIPeephole, DEBUG_TYPE, 2046 "PowerPC MI Peephole Optimization", false, false) 2047 INITIALIZE_PASS_DEPENDENCY(MachineBlockFrequencyInfoWrapperPass) 2048 INITIALIZE_PASS_DEPENDENCY(MachineDominatorTreeWrapperPass) 2049 INITIALIZE_PASS_DEPENDENCY(MachinePostDominatorTreeWrapperPass) 2050 INITIALIZE_PASS_DEPENDENCY(LiveVariablesWrapperPass) 2051 INITIALIZE_PASS_END(PPCMIPeephole, DEBUG_TYPE, 2052 "PowerPC MI Peephole Optimization", false, false) 2053 2054 char PPCMIPeephole::ID = 0; 2055 FunctionPass* 2056 llvm::createPPCMIPeepholePass() { return new PPCMIPeephole(); } 2057