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