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