1 //===-- PPCInstrInfo.cpp - PowerPC Instruction Information ----------------===// 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 file contains the PowerPC implementation of the TargetInstrInfo class. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "PPCInstrInfo.h" 14 #include "MCTargetDesc/PPCPredicates.h" 15 #include "PPC.h" 16 #include "PPCHazardRecognizers.h" 17 #include "PPCInstrBuilder.h" 18 #include "PPCMachineFunctionInfo.h" 19 #include "PPCTargetMachine.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/CodeGen/LiveIntervals.h" 23 #include "llvm/CodeGen/MachineFrameInfo.h" 24 #include "llvm/CodeGen/MachineFunctionPass.h" 25 #include "llvm/CodeGen/MachineInstrBuilder.h" 26 #include "llvm/CodeGen/MachineMemOperand.h" 27 #include "llvm/CodeGen/MachineRegisterInfo.h" 28 #include "llvm/CodeGen/PseudoSourceValue.h" 29 #include "llvm/CodeGen/ScheduleDAG.h" 30 #include "llvm/CodeGen/SlotIndexes.h" 31 #include "llvm/CodeGen/StackMaps.h" 32 #include "llvm/MC/MCAsmInfo.h" 33 #include "llvm/MC/MCInst.h" 34 #include "llvm/Support/CommandLine.h" 35 #include "llvm/Support/Debug.h" 36 #include "llvm/Support/ErrorHandling.h" 37 #include "llvm/Support/TargetRegistry.h" 38 #include "llvm/Support/raw_ostream.h" 39 40 using namespace llvm; 41 42 #define DEBUG_TYPE "ppc-instr-info" 43 44 #define GET_INSTRMAP_INFO 45 #define GET_INSTRINFO_CTOR_DTOR 46 #include "PPCGenInstrInfo.inc" 47 48 STATISTIC(NumStoreSPILLVSRRCAsVec, 49 "Number of spillvsrrc spilled to stack as vec"); 50 STATISTIC(NumStoreSPILLVSRRCAsGpr, 51 "Number of spillvsrrc spilled to stack as gpr"); 52 STATISTIC(NumGPRtoVSRSpill, "Number of gpr spills to spillvsrrc"); 53 STATISTIC(CmpIselsConverted, 54 "Number of ISELs that depend on comparison of constants converted"); 55 STATISTIC(MissedConvertibleImmediateInstrs, 56 "Number of compare-immediate instructions fed by constants"); 57 STATISTIC(NumRcRotatesConvertedToRcAnd, 58 "Number of record-form rotates converted to record-form andi"); 59 60 static cl:: 61 opt<bool> DisableCTRLoopAnal("disable-ppc-ctrloop-analysis", cl::Hidden, 62 cl::desc("Disable analysis for CTR loops")); 63 64 static cl::opt<bool> DisableCmpOpt("disable-ppc-cmp-opt", 65 cl::desc("Disable compare instruction optimization"), cl::Hidden); 66 67 static cl::opt<bool> VSXSelfCopyCrash("crash-on-ppc-vsx-self-copy", 68 cl::desc("Causes the backend to crash instead of generating a nop VSX copy"), 69 cl::Hidden); 70 71 static cl::opt<bool> 72 UseOldLatencyCalc("ppc-old-latency-calc", cl::Hidden, 73 cl::desc("Use the old (incorrect) instruction latency calculation")); 74 75 // Index into the OpcodesForSpill array. 76 enum SpillOpcodeKey { 77 SOK_Int4Spill, 78 SOK_Int8Spill, 79 SOK_Float8Spill, 80 SOK_Float4Spill, 81 SOK_CRSpill, 82 SOK_CRBitSpill, 83 SOK_VRVectorSpill, 84 SOK_VSXVectorSpill, 85 SOK_VectorFloat8Spill, 86 SOK_VectorFloat4Spill, 87 SOK_VRSaveSpill, 88 SOK_QuadFloat8Spill, 89 SOK_QuadFloat4Spill, 90 SOK_QuadBitSpill, 91 SOK_SpillToVSR, 92 SOK_SPESpill, 93 SOK_LastOpcodeSpill // This must be last on the enum. 94 }; 95 96 // Pin the vtable to this file. 97 void PPCInstrInfo::anchor() {} 98 99 PPCInstrInfo::PPCInstrInfo(PPCSubtarget &STI) 100 : PPCGenInstrInfo(PPC::ADJCALLSTACKDOWN, PPC::ADJCALLSTACKUP, 101 /* CatchRetOpcode */ -1, 102 STI.isPPC64() ? PPC::BLR8 : PPC::BLR), 103 Subtarget(STI), RI(STI.getTargetMachine()) {} 104 105 /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for 106 /// this target when scheduling the DAG. 107 ScheduleHazardRecognizer * 108 PPCInstrInfo::CreateTargetHazardRecognizer(const TargetSubtargetInfo *STI, 109 const ScheduleDAG *DAG) const { 110 unsigned Directive = 111 static_cast<const PPCSubtarget *>(STI)->getCPUDirective(); 112 if (Directive == PPC::DIR_440 || Directive == PPC::DIR_A2 || 113 Directive == PPC::DIR_E500mc || Directive == PPC::DIR_E5500) { 114 const InstrItineraryData *II = 115 static_cast<const PPCSubtarget *>(STI)->getInstrItineraryData(); 116 return new ScoreboardHazardRecognizer(II, DAG); 117 } 118 119 return TargetInstrInfo::CreateTargetHazardRecognizer(STI, DAG); 120 } 121 122 /// CreateTargetPostRAHazardRecognizer - Return the postRA hazard recognizer 123 /// to use for this target when scheduling the DAG. 124 ScheduleHazardRecognizer * 125 PPCInstrInfo::CreateTargetPostRAHazardRecognizer(const InstrItineraryData *II, 126 const ScheduleDAG *DAG) const { 127 unsigned Directive = 128 DAG->MF.getSubtarget<PPCSubtarget>().getCPUDirective(); 129 130 // FIXME: Leaving this as-is until we have POWER9 scheduling info 131 if (Directive == PPC::DIR_PWR7 || Directive == PPC::DIR_PWR8) 132 return new PPCDispatchGroupSBHazardRecognizer(II, DAG); 133 134 // Most subtargets use a PPC970 recognizer. 135 if (Directive != PPC::DIR_440 && Directive != PPC::DIR_A2 && 136 Directive != PPC::DIR_E500mc && Directive != PPC::DIR_E5500) { 137 assert(DAG->TII && "No InstrInfo?"); 138 139 return new PPCHazardRecognizer970(*DAG); 140 } 141 142 return new ScoreboardHazardRecognizer(II, DAG); 143 } 144 145 unsigned PPCInstrInfo::getInstrLatency(const InstrItineraryData *ItinData, 146 const MachineInstr &MI, 147 unsigned *PredCost) const { 148 if (!ItinData || UseOldLatencyCalc) 149 return PPCGenInstrInfo::getInstrLatency(ItinData, MI, PredCost); 150 151 // The default implementation of getInstrLatency calls getStageLatency, but 152 // getStageLatency does not do the right thing for us. While we have 153 // itinerary, most cores are fully pipelined, and so the itineraries only 154 // express the first part of the pipeline, not every stage. Instead, we need 155 // to use the listed output operand cycle number (using operand 0 here, which 156 // is an output). 157 158 unsigned Latency = 1; 159 unsigned DefClass = MI.getDesc().getSchedClass(); 160 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 161 const MachineOperand &MO = MI.getOperand(i); 162 if (!MO.isReg() || !MO.isDef() || MO.isImplicit()) 163 continue; 164 165 int Cycle = ItinData->getOperandCycle(DefClass, i); 166 if (Cycle < 0) 167 continue; 168 169 Latency = std::max(Latency, (unsigned) Cycle); 170 } 171 172 return Latency; 173 } 174 175 int PPCInstrInfo::getOperandLatency(const InstrItineraryData *ItinData, 176 const MachineInstr &DefMI, unsigned DefIdx, 177 const MachineInstr &UseMI, 178 unsigned UseIdx) const { 179 int Latency = PPCGenInstrInfo::getOperandLatency(ItinData, DefMI, DefIdx, 180 UseMI, UseIdx); 181 182 if (!DefMI.getParent()) 183 return Latency; 184 185 const MachineOperand &DefMO = DefMI.getOperand(DefIdx); 186 Register Reg = DefMO.getReg(); 187 188 bool IsRegCR; 189 if (Register::isVirtualRegister(Reg)) { 190 const MachineRegisterInfo *MRI = 191 &DefMI.getParent()->getParent()->getRegInfo(); 192 IsRegCR = MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRRCRegClass) || 193 MRI->getRegClass(Reg)->hasSuperClassEq(&PPC::CRBITRCRegClass); 194 } else { 195 IsRegCR = PPC::CRRCRegClass.contains(Reg) || 196 PPC::CRBITRCRegClass.contains(Reg); 197 } 198 199 if (UseMI.isBranch() && IsRegCR) { 200 if (Latency < 0) 201 Latency = getInstrLatency(ItinData, DefMI); 202 203 // On some cores, there is an additional delay between writing to a condition 204 // register, and using it from a branch. 205 unsigned Directive = Subtarget.getCPUDirective(); 206 switch (Directive) { 207 default: break; 208 case PPC::DIR_7400: 209 case PPC::DIR_750: 210 case PPC::DIR_970: 211 case PPC::DIR_E5500: 212 case PPC::DIR_PWR4: 213 case PPC::DIR_PWR5: 214 case PPC::DIR_PWR5X: 215 case PPC::DIR_PWR6: 216 case PPC::DIR_PWR6X: 217 case PPC::DIR_PWR7: 218 case PPC::DIR_PWR8: 219 // FIXME: Is this needed for POWER9? 220 Latency += 2; 221 break; 222 } 223 } 224 225 return Latency; 226 } 227 228 /// This is an architecture-specific helper function of reassociateOps. 229 /// Set special operand attributes for new instructions after reassociation. 230 void PPCInstrInfo::setSpecialOperandAttr(MachineInstr &OldMI1, 231 MachineInstr &OldMI2, 232 MachineInstr &NewMI1, 233 MachineInstr &NewMI2) const { 234 // Propagate FP flags from the original instructions. 235 // But clear poison-generating flags because those may not be valid now. 236 uint16_t IntersectedFlags = OldMI1.getFlags() & OldMI2.getFlags(); 237 NewMI1.setFlags(IntersectedFlags); 238 NewMI1.clearFlag(MachineInstr::MIFlag::NoSWrap); 239 NewMI1.clearFlag(MachineInstr::MIFlag::NoUWrap); 240 NewMI1.clearFlag(MachineInstr::MIFlag::IsExact); 241 242 NewMI2.setFlags(IntersectedFlags); 243 NewMI2.clearFlag(MachineInstr::MIFlag::NoSWrap); 244 NewMI2.clearFlag(MachineInstr::MIFlag::NoUWrap); 245 NewMI2.clearFlag(MachineInstr::MIFlag::IsExact); 246 } 247 248 // This function does not list all associative and commutative operations, but 249 // only those worth feeding through the machine combiner in an attempt to 250 // reduce the critical path. Mostly, this means floating-point operations, 251 // because they have high latencies (compared to other operations, such and 252 // and/or, which are also associative and commutative, but have low latencies). 253 bool PPCInstrInfo::isAssociativeAndCommutative(const MachineInstr &Inst) const { 254 switch (Inst.getOpcode()) { 255 // FP Add: 256 case PPC::FADD: 257 case PPC::FADDS: 258 // FP Multiply: 259 case PPC::FMUL: 260 case PPC::FMULS: 261 // Altivec Add: 262 case PPC::VADDFP: 263 // VSX Add: 264 case PPC::XSADDDP: 265 case PPC::XVADDDP: 266 case PPC::XVADDSP: 267 case PPC::XSADDSP: 268 // VSX Multiply: 269 case PPC::XSMULDP: 270 case PPC::XVMULDP: 271 case PPC::XVMULSP: 272 case PPC::XSMULSP: 273 // QPX Add: 274 case PPC::QVFADD: 275 case PPC::QVFADDS: 276 case PPC::QVFADDSs: 277 // QPX Multiply: 278 case PPC::QVFMUL: 279 case PPC::QVFMULS: 280 case PPC::QVFMULSs: 281 return Inst.getFlag(MachineInstr::MIFlag::FmReassoc) && 282 Inst.getFlag(MachineInstr::MIFlag::FmNsz); 283 default: 284 return false; 285 } 286 } 287 288 bool PPCInstrInfo::getMachineCombinerPatterns( 289 MachineInstr &Root, 290 SmallVectorImpl<MachineCombinerPattern> &Patterns) const { 291 // Using the machine combiner in this way is potentially expensive, so 292 // restrict to when aggressive optimizations are desired. 293 if (Subtarget.getTargetMachine().getOptLevel() != CodeGenOpt::Aggressive) 294 return false; 295 296 return TargetInstrInfo::getMachineCombinerPatterns(Root, Patterns); 297 } 298 299 // Detect 32 -> 64-bit extensions where we may reuse the low sub-register. 300 bool PPCInstrInfo::isCoalescableExtInstr(const MachineInstr &MI, 301 Register &SrcReg, Register &DstReg, 302 unsigned &SubIdx) const { 303 switch (MI.getOpcode()) { 304 default: return false; 305 case PPC::EXTSW: 306 case PPC::EXTSW_32: 307 case PPC::EXTSW_32_64: 308 SrcReg = MI.getOperand(1).getReg(); 309 DstReg = MI.getOperand(0).getReg(); 310 SubIdx = PPC::sub_32; 311 return true; 312 } 313 } 314 315 unsigned PPCInstrInfo::isLoadFromStackSlot(const MachineInstr &MI, 316 int &FrameIndex) const { 317 unsigned Opcode = MI.getOpcode(); 318 const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray(); 319 const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill; 320 321 if (End != std::find(OpcodesForSpill, End, Opcode)) { 322 // Check for the operands added by addFrameReference (the immediate is the 323 // offset which defaults to 0). 324 if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() && 325 MI.getOperand(2).isFI()) { 326 FrameIndex = MI.getOperand(2).getIndex(); 327 return MI.getOperand(0).getReg(); 328 } 329 } 330 return 0; 331 } 332 333 // For opcodes with the ReMaterializable flag set, this function is called to 334 // verify the instruction is really rematable. 335 bool PPCInstrInfo::isReallyTriviallyReMaterializable(const MachineInstr &MI, 336 AliasAnalysis *AA) const { 337 switch (MI.getOpcode()) { 338 default: 339 // This function should only be called for opcodes with the ReMaterializable 340 // flag set. 341 llvm_unreachable("Unknown rematerializable operation!"); 342 break; 343 case PPC::LI: 344 case PPC::LI8: 345 case PPC::LIS: 346 case PPC::LIS8: 347 case PPC::QVGPCI: 348 case PPC::ADDIStocHA: 349 case PPC::ADDIStocHA8: 350 case PPC::ADDItocL: 351 case PPC::LOAD_STACK_GUARD: 352 case PPC::XXLXORz: 353 case PPC::XXLXORspz: 354 case PPC::XXLXORdpz: 355 case PPC::XXLEQVOnes: 356 case PPC::V_SET0B: 357 case PPC::V_SET0H: 358 case PPC::V_SET0: 359 case PPC::V_SETALLONESB: 360 case PPC::V_SETALLONESH: 361 case PPC::V_SETALLONES: 362 case PPC::CRSET: 363 case PPC::CRUNSET: 364 return true; 365 } 366 return false; 367 } 368 369 unsigned PPCInstrInfo::isStoreToStackSlot(const MachineInstr &MI, 370 int &FrameIndex) const { 371 unsigned Opcode = MI.getOpcode(); 372 const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray(); 373 const unsigned *End = OpcodesForSpill + SOK_LastOpcodeSpill; 374 375 if (End != std::find(OpcodesForSpill, End, Opcode)) { 376 if (MI.getOperand(1).isImm() && !MI.getOperand(1).getImm() && 377 MI.getOperand(2).isFI()) { 378 FrameIndex = MI.getOperand(2).getIndex(); 379 return MI.getOperand(0).getReg(); 380 } 381 } 382 return 0; 383 } 384 385 MachineInstr *PPCInstrInfo::commuteInstructionImpl(MachineInstr &MI, bool NewMI, 386 unsigned OpIdx1, 387 unsigned OpIdx2) const { 388 MachineFunction &MF = *MI.getParent()->getParent(); 389 390 // Normal instructions can be commuted the obvious way. 391 if (MI.getOpcode() != PPC::RLWIMI && MI.getOpcode() != PPC::RLWIMI_rec) 392 return TargetInstrInfo::commuteInstructionImpl(MI, NewMI, OpIdx1, OpIdx2); 393 // Note that RLWIMI can be commuted as a 32-bit instruction, but not as a 394 // 64-bit instruction (so we don't handle PPC::RLWIMI8 here), because 395 // changing the relative order of the mask operands might change what happens 396 // to the high-bits of the mask (and, thus, the result). 397 398 // Cannot commute if it has a non-zero rotate count. 399 if (MI.getOperand(3).getImm() != 0) 400 return nullptr; 401 402 // If we have a zero rotate count, we have: 403 // M = mask(MB,ME) 404 // Op0 = (Op1 & ~M) | (Op2 & M) 405 // Change this to: 406 // M = mask((ME+1)&31, (MB-1)&31) 407 // Op0 = (Op2 & ~M) | (Op1 & M) 408 409 // Swap op1/op2 410 assert(((OpIdx1 == 1 && OpIdx2 == 2) || (OpIdx1 == 2 && OpIdx2 == 1)) && 411 "Only the operands 1 and 2 can be swapped in RLSIMI/RLWIMI_rec."); 412 Register Reg0 = MI.getOperand(0).getReg(); 413 Register Reg1 = MI.getOperand(1).getReg(); 414 Register Reg2 = MI.getOperand(2).getReg(); 415 unsigned SubReg1 = MI.getOperand(1).getSubReg(); 416 unsigned SubReg2 = MI.getOperand(2).getSubReg(); 417 bool Reg1IsKill = MI.getOperand(1).isKill(); 418 bool Reg2IsKill = MI.getOperand(2).isKill(); 419 bool ChangeReg0 = false; 420 // If machine instrs are no longer in two-address forms, update 421 // destination register as well. 422 if (Reg0 == Reg1) { 423 // Must be two address instruction! 424 assert(MI.getDesc().getOperandConstraint(0, MCOI::TIED_TO) && 425 "Expecting a two-address instruction!"); 426 assert(MI.getOperand(0).getSubReg() == SubReg1 && "Tied subreg mismatch"); 427 Reg2IsKill = false; 428 ChangeReg0 = true; 429 } 430 431 // Masks. 432 unsigned MB = MI.getOperand(4).getImm(); 433 unsigned ME = MI.getOperand(5).getImm(); 434 435 // We can't commute a trivial mask (there is no way to represent an all-zero 436 // mask). 437 if (MB == 0 && ME == 31) 438 return nullptr; 439 440 if (NewMI) { 441 // Create a new instruction. 442 Register Reg0 = ChangeReg0 ? Reg2 : MI.getOperand(0).getReg(); 443 bool Reg0IsDead = MI.getOperand(0).isDead(); 444 return BuildMI(MF, MI.getDebugLoc(), MI.getDesc()) 445 .addReg(Reg0, RegState::Define | getDeadRegState(Reg0IsDead)) 446 .addReg(Reg2, getKillRegState(Reg2IsKill)) 447 .addReg(Reg1, getKillRegState(Reg1IsKill)) 448 .addImm((ME + 1) & 31) 449 .addImm((MB - 1) & 31); 450 } 451 452 if (ChangeReg0) { 453 MI.getOperand(0).setReg(Reg2); 454 MI.getOperand(0).setSubReg(SubReg2); 455 } 456 MI.getOperand(2).setReg(Reg1); 457 MI.getOperand(1).setReg(Reg2); 458 MI.getOperand(2).setSubReg(SubReg1); 459 MI.getOperand(1).setSubReg(SubReg2); 460 MI.getOperand(2).setIsKill(Reg1IsKill); 461 MI.getOperand(1).setIsKill(Reg2IsKill); 462 463 // Swap the mask around. 464 MI.getOperand(4).setImm((ME + 1) & 31); 465 MI.getOperand(5).setImm((MB - 1) & 31); 466 return &MI; 467 } 468 469 bool PPCInstrInfo::findCommutedOpIndices(const MachineInstr &MI, 470 unsigned &SrcOpIdx1, 471 unsigned &SrcOpIdx2) const { 472 // For VSX A-Type FMA instructions, it is the first two operands that can be 473 // commuted, however, because the non-encoded tied input operand is listed 474 // first, the operands to swap are actually the second and third. 475 476 int AltOpc = PPC::getAltVSXFMAOpcode(MI.getOpcode()); 477 if (AltOpc == -1) 478 return TargetInstrInfo::findCommutedOpIndices(MI, SrcOpIdx1, SrcOpIdx2); 479 480 // The commutable operand indices are 2 and 3. Return them in SrcOpIdx1 481 // and SrcOpIdx2. 482 return fixCommutedOpIndices(SrcOpIdx1, SrcOpIdx2, 2, 3); 483 } 484 485 void PPCInstrInfo::insertNoop(MachineBasicBlock &MBB, 486 MachineBasicBlock::iterator MI) const { 487 // This function is used for scheduling, and the nop wanted here is the type 488 // that terminates dispatch groups on the POWER cores. 489 unsigned Directive = Subtarget.getCPUDirective(); 490 unsigned Opcode; 491 switch (Directive) { 492 default: Opcode = PPC::NOP; break; 493 case PPC::DIR_PWR6: Opcode = PPC::NOP_GT_PWR6; break; 494 case PPC::DIR_PWR7: Opcode = PPC::NOP_GT_PWR7; break; 495 case PPC::DIR_PWR8: Opcode = PPC::NOP_GT_PWR7; break; /* FIXME: Update when P8 InstrScheduling model is ready */ 496 // FIXME: Update when POWER9 scheduling model is ready. 497 case PPC::DIR_PWR9: Opcode = PPC::NOP_GT_PWR7; break; 498 } 499 500 DebugLoc DL; 501 BuildMI(MBB, MI, DL, get(Opcode)); 502 } 503 504 /// Return the noop instruction to use for a noop. 505 void PPCInstrInfo::getNoop(MCInst &NopInst) const { 506 NopInst.setOpcode(PPC::NOP); 507 } 508 509 // Branch analysis. 510 // Note: If the condition register is set to CTR or CTR8 then this is a 511 // BDNZ (imm == 1) or BDZ (imm == 0) branch. 512 bool PPCInstrInfo::analyzeBranch(MachineBasicBlock &MBB, 513 MachineBasicBlock *&TBB, 514 MachineBasicBlock *&FBB, 515 SmallVectorImpl<MachineOperand> &Cond, 516 bool AllowModify) const { 517 bool isPPC64 = Subtarget.isPPC64(); 518 519 // If the block has no terminators, it just falls into the block after it. 520 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); 521 if (I == MBB.end()) 522 return false; 523 524 if (!isUnpredicatedTerminator(*I)) 525 return false; 526 527 if (AllowModify) { 528 // If the BB ends with an unconditional branch to the fallthrough BB, 529 // we eliminate the branch instruction. 530 if (I->getOpcode() == PPC::B && 531 MBB.isLayoutSuccessor(I->getOperand(0).getMBB())) { 532 I->eraseFromParent(); 533 534 // We update iterator after deleting the last branch. 535 I = MBB.getLastNonDebugInstr(); 536 if (I == MBB.end() || !isUnpredicatedTerminator(*I)) 537 return false; 538 } 539 } 540 541 // Get the last instruction in the block. 542 MachineInstr &LastInst = *I; 543 544 // If there is only one terminator instruction, process it. 545 if (I == MBB.begin() || !isUnpredicatedTerminator(*--I)) { 546 if (LastInst.getOpcode() == PPC::B) { 547 if (!LastInst.getOperand(0).isMBB()) 548 return true; 549 TBB = LastInst.getOperand(0).getMBB(); 550 return false; 551 } else if (LastInst.getOpcode() == PPC::BCC) { 552 if (!LastInst.getOperand(2).isMBB()) 553 return true; 554 // Block ends with fall-through condbranch. 555 TBB = LastInst.getOperand(2).getMBB(); 556 Cond.push_back(LastInst.getOperand(0)); 557 Cond.push_back(LastInst.getOperand(1)); 558 return false; 559 } else if (LastInst.getOpcode() == PPC::BC) { 560 if (!LastInst.getOperand(1).isMBB()) 561 return true; 562 // Block ends with fall-through condbranch. 563 TBB = LastInst.getOperand(1).getMBB(); 564 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 565 Cond.push_back(LastInst.getOperand(0)); 566 return false; 567 } else if (LastInst.getOpcode() == PPC::BCn) { 568 if (!LastInst.getOperand(1).isMBB()) 569 return true; 570 // Block ends with fall-through condbranch. 571 TBB = LastInst.getOperand(1).getMBB(); 572 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET)); 573 Cond.push_back(LastInst.getOperand(0)); 574 return false; 575 } else if (LastInst.getOpcode() == PPC::BDNZ8 || 576 LastInst.getOpcode() == PPC::BDNZ) { 577 if (!LastInst.getOperand(0).isMBB()) 578 return true; 579 if (DisableCTRLoopAnal) 580 return true; 581 TBB = LastInst.getOperand(0).getMBB(); 582 Cond.push_back(MachineOperand::CreateImm(1)); 583 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR, 584 true)); 585 return false; 586 } else if (LastInst.getOpcode() == PPC::BDZ8 || 587 LastInst.getOpcode() == PPC::BDZ) { 588 if (!LastInst.getOperand(0).isMBB()) 589 return true; 590 if (DisableCTRLoopAnal) 591 return true; 592 TBB = LastInst.getOperand(0).getMBB(); 593 Cond.push_back(MachineOperand::CreateImm(0)); 594 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR, 595 true)); 596 return false; 597 } 598 599 // Otherwise, don't know what this is. 600 return true; 601 } 602 603 // Get the instruction before it if it's a terminator. 604 MachineInstr &SecondLastInst = *I; 605 606 // If there are three terminators, we don't know what sort of block this is. 607 if (I != MBB.begin() && isUnpredicatedTerminator(*--I)) 608 return true; 609 610 // If the block ends with PPC::B and PPC:BCC, handle it. 611 if (SecondLastInst.getOpcode() == PPC::BCC && 612 LastInst.getOpcode() == PPC::B) { 613 if (!SecondLastInst.getOperand(2).isMBB() || 614 !LastInst.getOperand(0).isMBB()) 615 return true; 616 TBB = SecondLastInst.getOperand(2).getMBB(); 617 Cond.push_back(SecondLastInst.getOperand(0)); 618 Cond.push_back(SecondLastInst.getOperand(1)); 619 FBB = LastInst.getOperand(0).getMBB(); 620 return false; 621 } else if (SecondLastInst.getOpcode() == PPC::BC && 622 LastInst.getOpcode() == PPC::B) { 623 if (!SecondLastInst.getOperand(1).isMBB() || 624 !LastInst.getOperand(0).isMBB()) 625 return true; 626 TBB = SecondLastInst.getOperand(1).getMBB(); 627 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_SET)); 628 Cond.push_back(SecondLastInst.getOperand(0)); 629 FBB = LastInst.getOperand(0).getMBB(); 630 return false; 631 } else if (SecondLastInst.getOpcode() == PPC::BCn && 632 LastInst.getOpcode() == PPC::B) { 633 if (!SecondLastInst.getOperand(1).isMBB() || 634 !LastInst.getOperand(0).isMBB()) 635 return true; 636 TBB = SecondLastInst.getOperand(1).getMBB(); 637 Cond.push_back(MachineOperand::CreateImm(PPC::PRED_BIT_UNSET)); 638 Cond.push_back(SecondLastInst.getOperand(0)); 639 FBB = LastInst.getOperand(0).getMBB(); 640 return false; 641 } else if ((SecondLastInst.getOpcode() == PPC::BDNZ8 || 642 SecondLastInst.getOpcode() == PPC::BDNZ) && 643 LastInst.getOpcode() == PPC::B) { 644 if (!SecondLastInst.getOperand(0).isMBB() || 645 !LastInst.getOperand(0).isMBB()) 646 return true; 647 if (DisableCTRLoopAnal) 648 return true; 649 TBB = SecondLastInst.getOperand(0).getMBB(); 650 Cond.push_back(MachineOperand::CreateImm(1)); 651 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR, 652 true)); 653 FBB = LastInst.getOperand(0).getMBB(); 654 return false; 655 } else if ((SecondLastInst.getOpcode() == PPC::BDZ8 || 656 SecondLastInst.getOpcode() == PPC::BDZ) && 657 LastInst.getOpcode() == PPC::B) { 658 if (!SecondLastInst.getOperand(0).isMBB() || 659 !LastInst.getOperand(0).isMBB()) 660 return true; 661 if (DisableCTRLoopAnal) 662 return true; 663 TBB = SecondLastInst.getOperand(0).getMBB(); 664 Cond.push_back(MachineOperand::CreateImm(0)); 665 Cond.push_back(MachineOperand::CreateReg(isPPC64 ? PPC::CTR8 : PPC::CTR, 666 true)); 667 FBB = LastInst.getOperand(0).getMBB(); 668 return false; 669 } 670 671 // If the block ends with two PPC:Bs, handle it. The second one is not 672 // executed, so remove it. 673 if (SecondLastInst.getOpcode() == PPC::B && LastInst.getOpcode() == PPC::B) { 674 if (!SecondLastInst.getOperand(0).isMBB()) 675 return true; 676 TBB = SecondLastInst.getOperand(0).getMBB(); 677 I = LastInst; 678 if (AllowModify) 679 I->eraseFromParent(); 680 return false; 681 } 682 683 // Otherwise, can't handle this. 684 return true; 685 } 686 687 unsigned PPCInstrInfo::removeBranch(MachineBasicBlock &MBB, 688 int *BytesRemoved) const { 689 assert(!BytesRemoved && "code size not handled"); 690 691 MachineBasicBlock::iterator I = MBB.getLastNonDebugInstr(); 692 if (I == MBB.end()) 693 return 0; 694 695 if (I->getOpcode() != PPC::B && I->getOpcode() != PPC::BCC && 696 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn && 697 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ && 698 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ) 699 return 0; 700 701 // Remove the branch. 702 I->eraseFromParent(); 703 704 I = MBB.end(); 705 706 if (I == MBB.begin()) return 1; 707 --I; 708 if (I->getOpcode() != PPC::BCC && 709 I->getOpcode() != PPC::BC && I->getOpcode() != PPC::BCn && 710 I->getOpcode() != PPC::BDNZ8 && I->getOpcode() != PPC::BDNZ && 711 I->getOpcode() != PPC::BDZ8 && I->getOpcode() != PPC::BDZ) 712 return 1; 713 714 // Remove the branch. 715 I->eraseFromParent(); 716 return 2; 717 } 718 719 unsigned PPCInstrInfo::insertBranch(MachineBasicBlock &MBB, 720 MachineBasicBlock *TBB, 721 MachineBasicBlock *FBB, 722 ArrayRef<MachineOperand> Cond, 723 const DebugLoc &DL, 724 int *BytesAdded) const { 725 // Shouldn't be a fall through. 726 assert(TBB && "insertBranch must not be told to insert a fallthrough"); 727 assert((Cond.size() == 2 || Cond.size() == 0) && 728 "PPC branch conditions have two components!"); 729 assert(!BytesAdded && "code size not handled"); 730 731 bool isPPC64 = Subtarget.isPPC64(); 732 733 // One-way branch. 734 if (!FBB) { 735 if (Cond.empty()) // Unconditional branch 736 BuildMI(&MBB, DL, get(PPC::B)).addMBB(TBB); 737 else if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8) 738 BuildMI(&MBB, DL, get(Cond[0].getImm() ? 739 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) : 740 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB); 741 else if (Cond[0].getImm() == PPC::PRED_BIT_SET) 742 BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB); 743 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET) 744 BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB); 745 else // Conditional branch 746 BuildMI(&MBB, DL, get(PPC::BCC)) 747 .addImm(Cond[0].getImm()) 748 .add(Cond[1]) 749 .addMBB(TBB); 750 return 1; 751 } 752 753 // Two-way Conditional Branch. 754 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8) 755 BuildMI(&MBB, DL, get(Cond[0].getImm() ? 756 (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) : 757 (isPPC64 ? PPC::BDZ8 : PPC::BDZ))).addMBB(TBB); 758 else if (Cond[0].getImm() == PPC::PRED_BIT_SET) 759 BuildMI(&MBB, DL, get(PPC::BC)).add(Cond[1]).addMBB(TBB); 760 else if (Cond[0].getImm() == PPC::PRED_BIT_UNSET) 761 BuildMI(&MBB, DL, get(PPC::BCn)).add(Cond[1]).addMBB(TBB); 762 else 763 BuildMI(&MBB, DL, get(PPC::BCC)) 764 .addImm(Cond[0].getImm()) 765 .add(Cond[1]) 766 .addMBB(TBB); 767 BuildMI(&MBB, DL, get(PPC::B)).addMBB(FBB); 768 return 2; 769 } 770 771 // Select analysis. 772 bool PPCInstrInfo::canInsertSelect(const MachineBasicBlock &MBB, 773 ArrayRef<MachineOperand> Cond, 774 Register DstReg, Register TrueReg, 775 Register FalseReg, int &CondCycles, 776 int &TrueCycles, int &FalseCycles) const { 777 if (Cond.size() != 2) 778 return false; 779 780 // If this is really a bdnz-like condition, then it cannot be turned into a 781 // select. 782 if (Cond[1].getReg() == PPC::CTR || Cond[1].getReg() == PPC::CTR8) 783 return false; 784 785 // Check register classes. 786 const MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); 787 const TargetRegisterClass *RC = 788 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg)); 789 if (!RC) 790 return false; 791 792 // isel is for regular integer GPRs only. 793 if (!PPC::GPRCRegClass.hasSubClassEq(RC) && 794 !PPC::GPRC_NOR0RegClass.hasSubClassEq(RC) && 795 !PPC::G8RCRegClass.hasSubClassEq(RC) && 796 !PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) 797 return false; 798 799 // FIXME: These numbers are for the A2, how well they work for other cores is 800 // an open question. On the A2, the isel instruction has a 2-cycle latency 801 // but single-cycle throughput. These numbers are used in combination with 802 // the MispredictPenalty setting from the active SchedMachineModel. 803 CondCycles = 1; 804 TrueCycles = 1; 805 FalseCycles = 1; 806 807 return true; 808 } 809 810 void PPCInstrInfo::insertSelect(MachineBasicBlock &MBB, 811 MachineBasicBlock::iterator MI, 812 const DebugLoc &dl, Register DestReg, 813 ArrayRef<MachineOperand> Cond, Register TrueReg, 814 Register FalseReg) const { 815 assert(Cond.size() == 2 && 816 "PPC branch conditions have two components!"); 817 818 // Get the register classes. 819 MachineRegisterInfo &MRI = MBB.getParent()->getRegInfo(); 820 const TargetRegisterClass *RC = 821 RI.getCommonSubClass(MRI.getRegClass(TrueReg), MRI.getRegClass(FalseReg)); 822 assert(RC && "TrueReg and FalseReg must have overlapping register classes"); 823 824 bool Is64Bit = PPC::G8RCRegClass.hasSubClassEq(RC) || 825 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC); 826 assert((Is64Bit || 827 PPC::GPRCRegClass.hasSubClassEq(RC) || 828 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) && 829 "isel is for regular integer GPRs only"); 830 831 unsigned OpCode = Is64Bit ? PPC::ISEL8 : PPC::ISEL; 832 auto SelectPred = static_cast<PPC::Predicate>(Cond[0].getImm()); 833 834 unsigned SubIdx = 0; 835 bool SwapOps = false; 836 switch (SelectPred) { 837 case PPC::PRED_EQ: 838 case PPC::PRED_EQ_MINUS: 839 case PPC::PRED_EQ_PLUS: 840 SubIdx = PPC::sub_eq; SwapOps = false; break; 841 case PPC::PRED_NE: 842 case PPC::PRED_NE_MINUS: 843 case PPC::PRED_NE_PLUS: 844 SubIdx = PPC::sub_eq; SwapOps = true; break; 845 case PPC::PRED_LT: 846 case PPC::PRED_LT_MINUS: 847 case PPC::PRED_LT_PLUS: 848 SubIdx = PPC::sub_lt; SwapOps = false; break; 849 case PPC::PRED_GE: 850 case PPC::PRED_GE_MINUS: 851 case PPC::PRED_GE_PLUS: 852 SubIdx = PPC::sub_lt; SwapOps = true; break; 853 case PPC::PRED_GT: 854 case PPC::PRED_GT_MINUS: 855 case PPC::PRED_GT_PLUS: 856 SubIdx = PPC::sub_gt; SwapOps = false; break; 857 case PPC::PRED_LE: 858 case PPC::PRED_LE_MINUS: 859 case PPC::PRED_LE_PLUS: 860 SubIdx = PPC::sub_gt; SwapOps = true; break; 861 case PPC::PRED_UN: 862 case PPC::PRED_UN_MINUS: 863 case PPC::PRED_UN_PLUS: 864 SubIdx = PPC::sub_un; SwapOps = false; break; 865 case PPC::PRED_NU: 866 case PPC::PRED_NU_MINUS: 867 case PPC::PRED_NU_PLUS: 868 SubIdx = PPC::sub_un; SwapOps = true; break; 869 case PPC::PRED_BIT_SET: SubIdx = 0; SwapOps = false; break; 870 case PPC::PRED_BIT_UNSET: SubIdx = 0; SwapOps = true; break; 871 } 872 873 Register FirstReg = SwapOps ? FalseReg : TrueReg, 874 SecondReg = SwapOps ? TrueReg : FalseReg; 875 876 // The first input register of isel cannot be r0. If it is a member 877 // of a register class that can be r0, then copy it first (the 878 // register allocator should eliminate the copy). 879 if (MRI.getRegClass(FirstReg)->contains(PPC::R0) || 880 MRI.getRegClass(FirstReg)->contains(PPC::X0)) { 881 const TargetRegisterClass *FirstRC = 882 MRI.getRegClass(FirstReg)->contains(PPC::X0) ? 883 &PPC::G8RC_NOX0RegClass : &PPC::GPRC_NOR0RegClass; 884 Register OldFirstReg = FirstReg; 885 FirstReg = MRI.createVirtualRegister(FirstRC); 886 BuildMI(MBB, MI, dl, get(TargetOpcode::COPY), FirstReg) 887 .addReg(OldFirstReg); 888 } 889 890 BuildMI(MBB, MI, dl, get(OpCode), DestReg) 891 .addReg(FirstReg).addReg(SecondReg) 892 .addReg(Cond[1].getReg(), 0, SubIdx); 893 } 894 895 static unsigned getCRBitValue(unsigned CRBit) { 896 unsigned Ret = 4; 897 if (CRBit == PPC::CR0LT || CRBit == PPC::CR1LT || 898 CRBit == PPC::CR2LT || CRBit == PPC::CR3LT || 899 CRBit == PPC::CR4LT || CRBit == PPC::CR5LT || 900 CRBit == PPC::CR6LT || CRBit == PPC::CR7LT) 901 Ret = 3; 902 if (CRBit == PPC::CR0GT || CRBit == PPC::CR1GT || 903 CRBit == PPC::CR2GT || CRBit == PPC::CR3GT || 904 CRBit == PPC::CR4GT || CRBit == PPC::CR5GT || 905 CRBit == PPC::CR6GT || CRBit == PPC::CR7GT) 906 Ret = 2; 907 if (CRBit == PPC::CR0EQ || CRBit == PPC::CR1EQ || 908 CRBit == PPC::CR2EQ || CRBit == PPC::CR3EQ || 909 CRBit == PPC::CR4EQ || CRBit == PPC::CR5EQ || 910 CRBit == PPC::CR6EQ || CRBit == PPC::CR7EQ) 911 Ret = 1; 912 if (CRBit == PPC::CR0UN || CRBit == PPC::CR1UN || 913 CRBit == PPC::CR2UN || CRBit == PPC::CR3UN || 914 CRBit == PPC::CR4UN || CRBit == PPC::CR5UN || 915 CRBit == PPC::CR6UN || CRBit == PPC::CR7UN) 916 Ret = 0; 917 918 assert(Ret != 4 && "Invalid CR bit register"); 919 return Ret; 920 } 921 922 void PPCInstrInfo::copyPhysReg(MachineBasicBlock &MBB, 923 MachineBasicBlock::iterator I, 924 const DebugLoc &DL, MCRegister DestReg, 925 MCRegister SrcReg, bool KillSrc) const { 926 // We can end up with self copies and similar things as a result of VSX copy 927 // legalization. Promote them here. 928 const TargetRegisterInfo *TRI = &getRegisterInfo(); 929 if (PPC::F8RCRegClass.contains(DestReg) && 930 PPC::VSRCRegClass.contains(SrcReg)) { 931 MCRegister SuperReg = 932 TRI->getMatchingSuperReg(DestReg, PPC::sub_64, &PPC::VSRCRegClass); 933 934 if (VSXSelfCopyCrash && SrcReg == SuperReg) 935 llvm_unreachable("nop VSX copy"); 936 937 DestReg = SuperReg; 938 } else if (PPC::F8RCRegClass.contains(SrcReg) && 939 PPC::VSRCRegClass.contains(DestReg)) { 940 MCRegister SuperReg = 941 TRI->getMatchingSuperReg(SrcReg, PPC::sub_64, &PPC::VSRCRegClass); 942 943 if (VSXSelfCopyCrash && DestReg == SuperReg) 944 llvm_unreachable("nop VSX copy"); 945 946 SrcReg = SuperReg; 947 } 948 949 // Different class register copy 950 if (PPC::CRBITRCRegClass.contains(SrcReg) && 951 PPC::GPRCRegClass.contains(DestReg)) { 952 MCRegister CRReg = getCRFromCRBit(SrcReg); 953 BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(CRReg); 954 getKillRegState(KillSrc); 955 // Rotate the CR bit in the CR fields to be the least significant bit and 956 // then mask with 0x1 (MB = ME = 31). 957 BuildMI(MBB, I, DL, get(PPC::RLWINM), DestReg) 958 .addReg(DestReg, RegState::Kill) 959 .addImm(TRI->getEncodingValue(CRReg) * 4 + (4 - getCRBitValue(SrcReg))) 960 .addImm(31) 961 .addImm(31); 962 return; 963 } else if (PPC::CRRCRegClass.contains(SrcReg) && 964 PPC::G8RCRegClass.contains(DestReg)) { 965 BuildMI(MBB, I, DL, get(PPC::MFOCRF8), DestReg).addReg(SrcReg); 966 getKillRegState(KillSrc); 967 return; 968 } else if (PPC::CRRCRegClass.contains(SrcReg) && 969 PPC::GPRCRegClass.contains(DestReg)) { 970 BuildMI(MBB, I, DL, get(PPC::MFOCRF), DestReg).addReg(SrcReg); 971 getKillRegState(KillSrc); 972 return; 973 } else if (PPC::G8RCRegClass.contains(SrcReg) && 974 PPC::VSFRCRegClass.contains(DestReg)) { 975 assert(Subtarget.hasDirectMove() && 976 "Subtarget doesn't support directmove, don't know how to copy."); 977 BuildMI(MBB, I, DL, get(PPC::MTVSRD), DestReg).addReg(SrcReg); 978 NumGPRtoVSRSpill++; 979 getKillRegState(KillSrc); 980 return; 981 } else if (PPC::VSFRCRegClass.contains(SrcReg) && 982 PPC::G8RCRegClass.contains(DestReg)) { 983 assert(Subtarget.hasDirectMove() && 984 "Subtarget doesn't support directmove, don't know how to copy."); 985 BuildMI(MBB, I, DL, get(PPC::MFVSRD), DestReg).addReg(SrcReg); 986 getKillRegState(KillSrc); 987 return; 988 } else if (PPC::SPERCRegClass.contains(SrcReg) && 989 PPC::GPRCRegClass.contains(DestReg)) { 990 BuildMI(MBB, I, DL, get(PPC::EFSCFD), DestReg).addReg(SrcReg); 991 getKillRegState(KillSrc); 992 return; 993 } else if (PPC::GPRCRegClass.contains(SrcReg) && 994 PPC::SPERCRegClass.contains(DestReg)) { 995 BuildMI(MBB, I, DL, get(PPC::EFDCFS), DestReg).addReg(SrcReg); 996 getKillRegState(KillSrc); 997 return; 998 } 999 1000 unsigned Opc; 1001 if (PPC::GPRCRegClass.contains(DestReg, SrcReg)) 1002 Opc = PPC::OR; 1003 else if (PPC::G8RCRegClass.contains(DestReg, SrcReg)) 1004 Opc = PPC::OR8; 1005 else if (PPC::F4RCRegClass.contains(DestReg, SrcReg)) 1006 Opc = PPC::FMR; 1007 else if (PPC::CRRCRegClass.contains(DestReg, SrcReg)) 1008 Opc = PPC::MCRF; 1009 else if (PPC::VRRCRegClass.contains(DestReg, SrcReg)) 1010 Opc = PPC::VOR; 1011 else if (PPC::VSRCRegClass.contains(DestReg, SrcReg)) 1012 // There are two different ways this can be done: 1013 // 1. xxlor : This has lower latency (on the P7), 2 cycles, but can only 1014 // issue in VSU pipeline 0. 1015 // 2. xmovdp/xmovsp: This has higher latency (on the P7), 6 cycles, but 1016 // can go to either pipeline. 1017 // We'll always use xxlor here, because in practically all cases where 1018 // copies are generated, they are close enough to some use that the 1019 // lower-latency form is preferable. 1020 Opc = PPC::XXLOR; 1021 else if (PPC::VSFRCRegClass.contains(DestReg, SrcReg) || 1022 PPC::VSSRCRegClass.contains(DestReg, SrcReg)) 1023 Opc = (Subtarget.hasP9Vector()) ? PPC::XSCPSGNDP : PPC::XXLORf; 1024 else if (PPC::QFRCRegClass.contains(DestReg, SrcReg)) 1025 Opc = PPC::QVFMR; 1026 else if (PPC::QSRCRegClass.contains(DestReg, SrcReg)) 1027 Opc = PPC::QVFMRs; 1028 else if (PPC::QBRCRegClass.contains(DestReg, SrcReg)) 1029 Opc = PPC::QVFMRb; 1030 else if (PPC::CRBITRCRegClass.contains(DestReg, SrcReg)) 1031 Opc = PPC::CROR; 1032 else if (PPC::SPERCRegClass.contains(DestReg, SrcReg)) 1033 Opc = PPC::EVOR; 1034 else 1035 llvm_unreachable("Impossible reg-to-reg copy"); 1036 1037 const MCInstrDesc &MCID = get(Opc); 1038 if (MCID.getNumOperands() == 3) 1039 BuildMI(MBB, I, DL, MCID, DestReg) 1040 .addReg(SrcReg).addReg(SrcReg, getKillRegState(KillSrc)); 1041 else 1042 BuildMI(MBB, I, DL, MCID, DestReg).addReg(SrcReg, getKillRegState(KillSrc)); 1043 } 1044 1045 unsigned PPCInstrInfo::getStoreOpcodeForSpill(unsigned Reg, 1046 const TargetRegisterClass *RC) 1047 const { 1048 const unsigned *OpcodesForSpill = getStoreOpcodesForSpillArray(); 1049 int OpcodeIndex = 0; 1050 1051 if (RC != nullptr) { 1052 if (PPC::GPRCRegClass.hasSubClassEq(RC) || 1053 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) { 1054 OpcodeIndex = SOK_Int4Spill; 1055 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) || 1056 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) { 1057 OpcodeIndex = SOK_Int8Spill; 1058 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) { 1059 OpcodeIndex = SOK_Float8Spill; 1060 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) { 1061 OpcodeIndex = SOK_Float4Spill; 1062 } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) { 1063 OpcodeIndex = SOK_SPESpill; 1064 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) { 1065 OpcodeIndex = SOK_CRSpill; 1066 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) { 1067 OpcodeIndex = SOK_CRBitSpill; 1068 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) { 1069 OpcodeIndex = SOK_VRVectorSpill; 1070 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) { 1071 OpcodeIndex = SOK_VSXVectorSpill; 1072 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) { 1073 OpcodeIndex = SOK_VectorFloat8Spill; 1074 } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) { 1075 OpcodeIndex = SOK_VectorFloat4Spill; 1076 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) { 1077 OpcodeIndex = SOK_VRSaveSpill; 1078 } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) { 1079 OpcodeIndex = SOK_QuadFloat8Spill; 1080 } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) { 1081 OpcodeIndex = SOK_QuadFloat4Spill; 1082 } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) { 1083 OpcodeIndex = SOK_QuadBitSpill; 1084 } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) { 1085 OpcodeIndex = SOK_SpillToVSR; 1086 } else { 1087 llvm_unreachable("Unknown regclass!"); 1088 } 1089 } else { 1090 if (PPC::GPRCRegClass.contains(Reg) || 1091 PPC::GPRC_NOR0RegClass.contains(Reg)) { 1092 OpcodeIndex = SOK_Int4Spill; 1093 } else if (PPC::G8RCRegClass.contains(Reg) || 1094 PPC::G8RC_NOX0RegClass.contains(Reg)) { 1095 OpcodeIndex = SOK_Int8Spill; 1096 } else if (PPC::F8RCRegClass.contains(Reg)) { 1097 OpcodeIndex = SOK_Float8Spill; 1098 } else if (PPC::F4RCRegClass.contains(Reg)) { 1099 OpcodeIndex = SOK_Float4Spill; 1100 } else if (PPC::SPERCRegClass.contains(Reg)) { 1101 OpcodeIndex = SOK_SPESpill; 1102 } else if (PPC::CRRCRegClass.contains(Reg)) { 1103 OpcodeIndex = SOK_CRSpill; 1104 } else if (PPC::CRBITRCRegClass.contains(Reg)) { 1105 OpcodeIndex = SOK_CRBitSpill; 1106 } else if (PPC::VRRCRegClass.contains(Reg)) { 1107 OpcodeIndex = SOK_VRVectorSpill; 1108 } else if (PPC::VSRCRegClass.contains(Reg)) { 1109 OpcodeIndex = SOK_VSXVectorSpill; 1110 } else if (PPC::VSFRCRegClass.contains(Reg)) { 1111 OpcodeIndex = SOK_VectorFloat8Spill; 1112 } else if (PPC::VSSRCRegClass.contains(Reg)) { 1113 OpcodeIndex = SOK_VectorFloat4Spill; 1114 } else if (PPC::VRSAVERCRegClass.contains(Reg)) { 1115 OpcodeIndex = SOK_VRSaveSpill; 1116 } else if (PPC::QFRCRegClass.contains(Reg)) { 1117 OpcodeIndex = SOK_QuadFloat8Spill; 1118 } else if (PPC::QSRCRegClass.contains(Reg)) { 1119 OpcodeIndex = SOK_QuadFloat4Spill; 1120 } else if (PPC::QBRCRegClass.contains(Reg)) { 1121 OpcodeIndex = SOK_QuadBitSpill; 1122 } else if (PPC::SPILLTOVSRRCRegClass.contains(Reg)) { 1123 OpcodeIndex = SOK_SpillToVSR; 1124 } else { 1125 llvm_unreachable("Unknown regclass!"); 1126 } 1127 } 1128 return OpcodesForSpill[OpcodeIndex]; 1129 } 1130 1131 unsigned 1132 PPCInstrInfo::getLoadOpcodeForSpill(unsigned Reg, 1133 const TargetRegisterClass *RC) const { 1134 const unsigned *OpcodesForSpill = getLoadOpcodesForSpillArray(); 1135 int OpcodeIndex = 0; 1136 1137 if (RC != nullptr) { 1138 if (PPC::GPRCRegClass.hasSubClassEq(RC) || 1139 PPC::GPRC_NOR0RegClass.hasSubClassEq(RC)) { 1140 OpcodeIndex = SOK_Int4Spill; 1141 } else if (PPC::G8RCRegClass.hasSubClassEq(RC) || 1142 PPC::G8RC_NOX0RegClass.hasSubClassEq(RC)) { 1143 OpcodeIndex = SOK_Int8Spill; 1144 } else if (PPC::F8RCRegClass.hasSubClassEq(RC)) { 1145 OpcodeIndex = SOK_Float8Spill; 1146 } else if (PPC::F4RCRegClass.hasSubClassEq(RC)) { 1147 OpcodeIndex = SOK_Float4Spill; 1148 } else if (PPC::SPERCRegClass.hasSubClassEq(RC)) { 1149 OpcodeIndex = SOK_SPESpill; 1150 } else if (PPC::CRRCRegClass.hasSubClassEq(RC)) { 1151 OpcodeIndex = SOK_CRSpill; 1152 } else if (PPC::CRBITRCRegClass.hasSubClassEq(RC)) { 1153 OpcodeIndex = SOK_CRBitSpill; 1154 } else if (PPC::VRRCRegClass.hasSubClassEq(RC)) { 1155 OpcodeIndex = SOK_VRVectorSpill; 1156 } else if (PPC::VSRCRegClass.hasSubClassEq(RC)) { 1157 OpcodeIndex = SOK_VSXVectorSpill; 1158 } else if (PPC::VSFRCRegClass.hasSubClassEq(RC)) { 1159 OpcodeIndex = SOK_VectorFloat8Spill; 1160 } else if (PPC::VSSRCRegClass.hasSubClassEq(RC)) { 1161 OpcodeIndex = SOK_VectorFloat4Spill; 1162 } else if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) { 1163 OpcodeIndex = SOK_VRSaveSpill; 1164 } else if (PPC::QFRCRegClass.hasSubClassEq(RC)) { 1165 OpcodeIndex = SOK_QuadFloat8Spill; 1166 } else if (PPC::QSRCRegClass.hasSubClassEq(RC)) { 1167 OpcodeIndex = SOK_QuadFloat4Spill; 1168 } else if (PPC::QBRCRegClass.hasSubClassEq(RC)) { 1169 OpcodeIndex = SOK_QuadBitSpill; 1170 } else if (PPC::SPILLTOVSRRCRegClass.hasSubClassEq(RC)) { 1171 OpcodeIndex = SOK_SpillToVSR; 1172 } else { 1173 llvm_unreachable("Unknown regclass!"); 1174 } 1175 } else { 1176 if (PPC::GPRCRegClass.contains(Reg) || 1177 PPC::GPRC_NOR0RegClass.contains(Reg)) { 1178 OpcodeIndex = SOK_Int4Spill; 1179 } else if (PPC::G8RCRegClass.contains(Reg) || 1180 PPC::G8RC_NOX0RegClass.contains(Reg)) { 1181 OpcodeIndex = SOK_Int8Spill; 1182 } else if (PPC::F8RCRegClass.contains(Reg)) { 1183 OpcodeIndex = SOK_Float8Spill; 1184 } else if (PPC::F4RCRegClass.contains(Reg)) { 1185 OpcodeIndex = SOK_Float4Spill; 1186 } else if (PPC::SPERCRegClass.contains(Reg)) { 1187 OpcodeIndex = SOK_SPESpill; 1188 } else if (PPC::CRRCRegClass.contains(Reg)) { 1189 OpcodeIndex = SOK_CRSpill; 1190 } else if (PPC::CRBITRCRegClass.contains(Reg)) { 1191 OpcodeIndex = SOK_CRBitSpill; 1192 } else if (PPC::VRRCRegClass.contains(Reg)) { 1193 OpcodeIndex = SOK_VRVectorSpill; 1194 } else if (PPC::VSRCRegClass.contains(Reg)) { 1195 OpcodeIndex = SOK_VSXVectorSpill; 1196 } else if (PPC::VSFRCRegClass.contains(Reg)) { 1197 OpcodeIndex = SOK_VectorFloat8Spill; 1198 } else if (PPC::VSSRCRegClass.contains(Reg)) { 1199 OpcodeIndex = SOK_VectorFloat4Spill; 1200 } else if (PPC::VRSAVERCRegClass.contains(Reg)) { 1201 OpcodeIndex = SOK_VRSaveSpill; 1202 } else if (PPC::QFRCRegClass.contains(Reg)) { 1203 OpcodeIndex = SOK_QuadFloat8Spill; 1204 } else if (PPC::QSRCRegClass.contains(Reg)) { 1205 OpcodeIndex = SOK_QuadFloat4Spill; 1206 } else if (PPC::QBRCRegClass.contains(Reg)) { 1207 OpcodeIndex = SOK_QuadBitSpill; 1208 } else if (PPC::SPILLTOVSRRCRegClass.contains(Reg)) { 1209 OpcodeIndex = SOK_SpillToVSR; 1210 } else { 1211 llvm_unreachable("Unknown regclass!"); 1212 } 1213 } 1214 return OpcodesForSpill[OpcodeIndex]; 1215 } 1216 1217 void PPCInstrInfo::StoreRegToStackSlot( 1218 MachineFunction &MF, unsigned SrcReg, bool isKill, int FrameIdx, 1219 const TargetRegisterClass *RC, 1220 SmallVectorImpl<MachineInstr *> &NewMIs) const { 1221 unsigned Opcode = getStoreOpcodeForSpill(PPC::NoRegister, RC); 1222 DebugLoc DL; 1223 1224 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1225 FuncInfo->setHasSpills(); 1226 1227 NewMIs.push_back(addFrameReference( 1228 BuildMI(MF, DL, get(Opcode)).addReg(SrcReg, getKillRegState(isKill)), 1229 FrameIdx)); 1230 1231 if (PPC::CRRCRegClass.hasSubClassEq(RC) || 1232 PPC::CRBITRCRegClass.hasSubClassEq(RC)) 1233 FuncInfo->setSpillsCR(); 1234 1235 if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) 1236 FuncInfo->setSpillsVRSAVE(); 1237 1238 if (isXFormMemOp(Opcode)) 1239 FuncInfo->setHasNonRISpills(); 1240 } 1241 1242 void PPCInstrInfo::storeRegToStackSlotNoUpd( 1243 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned SrcReg, 1244 bool isKill, int FrameIdx, const TargetRegisterClass *RC, 1245 const TargetRegisterInfo *TRI) const { 1246 MachineFunction &MF = *MBB.getParent(); 1247 SmallVector<MachineInstr *, 4> NewMIs; 1248 1249 StoreRegToStackSlot(MF, SrcReg, isKill, FrameIdx, RC, NewMIs); 1250 1251 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i) 1252 MBB.insert(MI, NewMIs[i]); 1253 1254 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1255 MachineMemOperand *MMO = MF.getMachineMemOperand( 1256 MachinePointerInfo::getFixedStack(MF, FrameIdx), 1257 MachineMemOperand::MOStore, MFI.getObjectSize(FrameIdx), 1258 MFI.getObjectAlign(FrameIdx)); 1259 NewMIs.back()->addMemOperand(MF, MMO); 1260 } 1261 1262 void PPCInstrInfo::storeRegToStackSlot(MachineBasicBlock &MBB, 1263 MachineBasicBlock::iterator MI, 1264 Register SrcReg, bool isKill, 1265 int FrameIdx, 1266 const TargetRegisterClass *RC, 1267 const TargetRegisterInfo *TRI) const { 1268 // We need to avoid a situation in which the value from a VRRC register is 1269 // spilled using an Altivec instruction and reloaded into a VSRC register 1270 // using a VSX instruction. The issue with this is that the VSX 1271 // load/store instructions swap the doublewords in the vector and the Altivec 1272 // ones don't. The register classes on the spill/reload may be different if 1273 // the register is defined using an Altivec instruction and is then used by a 1274 // VSX instruction. 1275 RC = updatedRC(RC); 1276 storeRegToStackSlotNoUpd(MBB, MI, SrcReg, isKill, FrameIdx, RC, TRI); 1277 } 1278 1279 void PPCInstrInfo::LoadRegFromStackSlot(MachineFunction &MF, const DebugLoc &DL, 1280 unsigned DestReg, int FrameIdx, 1281 const TargetRegisterClass *RC, 1282 SmallVectorImpl<MachineInstr *> &NewMIs) 1283 const { 1284 unsigned Opcode = getLoadOpcodeForSpill(PPC::NoRegister, RC); 1285 NewMIs.push_back(addFrameReference(BuildMI(MF, DL, get(Opcode), DestReg), 1286 FrameIdx)); 1287 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1288 1289 if (PPC::CRRCRegClass.hasSubClassEq(RC) || 1290 PPC::CRBITRCRegClass.hasSubClassEq(RC)) 1291 FuncInfo->setSpillsCR(); 1292 1293 if (PPC::VRSAVERCRegClass.hasSubClassEq(RC)) 1294 FuncInfo->setSpillsVRSAVE(); 1295 1296 if (isXFormMemOp(Opcode)) 1297 FuncInfo->setHasNonRISpills(); 1298 } 1299 1300 void PPCInstrInfo::loadRegFromStackSlotNoUpd( 1301 MachineBasicBlock &MBB, MachineBasicBlock::iterator MI, unsigned DestReg, 1302 int FrameIdx, const TargetRegisterClass *RC, 1303 const TargetRegisterInfo *TRI) const { 1304 MachineFunction &MF = *MBB.getParent(); 1305 SmallVector<MachineInstr*, 4> NewMIs; 1306 DebugLoc DL; 1307 if (MI != MBB.end()) DL = MI->getDebugLoc(); 1308 1309 PPCFunctionInfo *FuncInfo = MF.getInfo<PPCFunctionInfo>(); 1310 FuncInfo->setHasSpills(); 1311 1312 LoadRegFromStackSlot(MF, DL, DestReg, FrameIdx, RC, NewMIs); 1313 1314 for (unsigned i = 0, e = NewMIs.size(); i != e; ++i) 1315 MBB.insert(MI, NewMIs[i]); 1316 1317 const MachineFrameInfo &MFI = MF.getFrameInfo(); 1318 MachineMemOperand *MMO = MF.getMachineMemOperand( 1319 MachinePointerInfo::getFixedStack(MF, FrameIdx), 1320 MachineMemOperand::MOLoad, MFI.getObjectSize(FrameIdx), 1321 MFI.getObjectAlign(FrameIdx)); 1322 NewMIs.back()->addMemOperand(MF, MMO); 1323 } 1324 1325 void PPCInstrInfo::loadRegFromStackSlot(MachineBasicBlock &MBB, 1326 MachineBasicBlock::iterator MI, 1327 Register DestReg, int FrameIdx, 1328 const TargetRegisterClass *RC, 1329 const TargetRegisterInfo *TRI) const { 1330 // We need to avoid a situation in which the value from a VRRC register is 1331 // spilled using an Altivec instruction and reloaded into a VSRC register 1332 // using a VSX instruction. The issue with this is that the VSX 1333 // load/store instructions swap the doublewords in the vector and the Altivec 1334 // ones don't. The register classes on the spill/reload may be different if 1335 // the register is defined using an Altivec instruction and is then used by a 1336 // VSX instruction. 1337 RC = updatedRC(RC); 1338 1339 loadRegFromStackSlotNoUpd(MBB, MI, DestReg, FrameIdx, RC, TRI); 1340 } 1341 1342 bool PPCInstrInfo:: 1343 reverseBranchCondition(SmallVectorImpl<MachineOperand> &Cond) const { 1344 assert(Cond.size() == 2 && "Invalid PPC branch opcode!"); 1345 if (Cond[1].getReg() == PPC::CTR8 || Cond[1].getReg() == PPC::CTR) 1346 Cond[0].setImm(Cond[0].getImm() == 0 ? 1 : 0); 1347 else 1348 // Leave the CR# the same, but invert the condition. 1349 Cond[0].setImm(PPC::InvertPredicate((PPC::Predicate)Cond[0].getImm())); 1350 return false; 1351 } 1352 1353 // For some instructions, it is legal to fold ZERO into the RA register field. 1354 // This function performs that fold by replacing the operand with PPC::ZERO, 1355 // it does not consider whether the load immediate zero is no longer in use. 1356 bool PPCInstrInfo::onlyFoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, 1357 Register Reg) const { 1358 // A zero immediate should always be loaded with a single li. 1359 unsigned DefOpc = DefMI.getOpcode(); 1360 if (DefOpc != PPC::LI && DefOpc != PPC::LI8) 1361 return false; 1362 if (!DefMI.getOperand(1).isImm()) 1363 return false; 1364 if (DefMI.getOperand(1).getImm() != 0) 1365 return false; 1366 1367 // Note that we cannot here invert the arguments of an isel in order to fold 1368 // a ZERO into what is presented as the second argument. All we have here 1369 // is the condition bit, and that might come from a CR-logical bit operation. 1370 1371 const MCInstrDesc &UseMCID = UseMI.getDesc(); 1372 1373 // Only fold into real machine instructions. 1374 if (UseMCID.isPseudo()) 1375 return false; 1376 1377 // We need to find which of the User's operands is to be folded, that will be 1378 // the operand that matches the given register ID. 1379 unsigned UseIdx; 1380 for (UseIdx = 0; UseIdx < UseMI.getNumOperands(); ++UseIdx) 1381 if (UseMI.getOperand(UseIdx).isReg() && 1382 UseMI.getOperand(UseIdx).getReg() == Reg) 1383 break; 1384 1385 assert(UseIdx < UseMI.getNumOperands() && "Cannot find Reg in UseMI"); 1386 assert(UseIdx < UseMCID.getNumOperands() && "No operand description for Reg"); 1387 1388 const MCOperandInfo *UseInfo = &UseMCID.OpInfo[UseIdx]; 1389 1390 // We can fold the zero if this register requires a GPRC_NOR0/G8RC_NOX0 1391 // register (which might also be specified as a pointer class kind). 1392 if (UseInfo->isLookupPtrRegClass()) { 1393 if (UseInfo->RegClass /* Kind */ != 1) 1394 return false; 1395 } else { 1396 if (UseInfo->RegClass != PPC::GPRC_NOR0RegClassID && 1397 UseInfo->RegClass != PPC::G8RC_NOX0RegClassID) 1398 return false; 1399 } 1400 1401 // Make sure this is not tied to an output register (or otherwise 1402 // constrained). This is true for ST?UX registers, for example, which 1403 // are tied to their output registers. 1404 if (UseInfo->Constraints != 0) 1405 return false; 1406 1407 MCRegister ZeroReg; 1408 if (UseInfo->isLookupPtrRegClass()) { 1409 bool isPPC64 = Subtarget.isPPC64(); 1410 ZeroReg = isPPC64 ? PPC::ZERO8 : PPC::ZERO; 1411 } else { 1412 ZeroReg = UseInfo->RegClass == PPC::G8RC_NOX0RegClassID ? 1413 PPC::ZERO8 : PPC::ZERO; 1414 } 1415 1416 UseMI.getOperand(UseIdx).setReg(ZeroReg); 1417 return true; 1418 } 1419 1420 // Folds zero into instructions which have a load immediate zero as an operand 1421 // but also recognize zero as immediate zero. If the definition of the load 1422 // has no more users it is deleted. 1423 bool PPCInstrInfo::FoldImmediate(MachineInstr &UseMI, MachineInstr &DefMI, 1424 Register Reg, MachineRegisterInfo *MRI) const { 1425 bool Changed = onlyFoldImmediate(UseMI, DefMI, Reg); 1426 if (MRI->use_nodbg_empty(Reg)) 1427 DefMI.eraseFromParent(); 1428 return Changed; 1429 } 1430 1431 static bool MBBDefinesCTR(MachineBasicBlock &MBB) { 1432 for (MachineBasicBlock::iterator I = MBB.begin(), IE = MBB.end(); 1433 I != IE; ++I) 1434 if (I->definesRegister(PPC::CTR) || I->definesRegister(PPC::CTR8)) 1435 return true; 1436 return false; 1437 } 1438 1439 // We should make sure that, if we're going to predicate both sides of a 1440 // condition (a diamond), that both sides don't define the counter register. We 1441 // can predicate counter-decrement-based branches, but while that predicates 1442 // the branching, it does not predicate the counter decrement. If we tried to 1443 // merge the triangle into one predicated block, we'd decrement the counter 1444 // twice. 1445 bool PPCInstrInfo::isProfitableToIfCvt(MachineBasicBlock &TMBB, 1446 unsigned NumT, unsigned ExtraT, 1447 MachineBasicBlock &FMBB, 1448 unsigned NumF, unsigned ExtraF, 1449 BranchProbability Probability) const { 1450 return !(MBBDefinesCTR(TMBB) && MBBDefinesCTR(FMBB)); 1451 } 1452 1453 1454 bool PPCInstrInfo::isPredicated(const MachineInstr &MI) const { 1455 // The predicated branches are identified by their type, not really by the 1456 // explicit presence of a predicate. Furthermore, some of them can be 1457 // predicated more than once. Because if conversion won't try to predicate 1458 // any instruction which already claims to be predicated (by returning true 1459 // here), always return false. In doing so, we let isPredicable() be the 1460 // final word on whether not the instruction can be (further) predicated. 1461 1462 return false; 1463 } 1464 1465 bool PPCInstrInfo::PredicateInstruction(MachineInstr &MI, 1466 ArrayRef<MachineOperand> Pred) const { 1467 unsigned OpC = MI.getOpcode(); 1468 if (OpC == PPC::BLR || OpC == PPC::BLR8) { 1469 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) { 1470 bool isPPC64 = Subtarget.isPPC64(); 1471 MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZLR8 : PPC::BDNZLR) 1472 : (isPPC64 ? PPC::BDZLR8 : PPC::BDZLR))); 1473 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) { 1474 MI.setDesc(get(PPC::BCLR)); 1475 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]); 1476 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) { 1477 MI.setDesc(get(PPC::BCLRn)); 1478 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]); 1479 } else { 1480 MI.setDesc(get(PPC::BCCLR)); 1481 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1482 .addImm(Pred[0].getImm()) 1483 .add(Pred[1]); 1484 } 1485 1486 return true; 1487 } else if (OpC == PPC::B) { 1488 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) { 1489 bool isPPC64 = Subtarget.isPPC64(); 1490 MI.setDesc(get(Pred[0].getImm() ? (isPPC64 ? PPC::BDNZ8 : PPC::BDNZ) 1491 : (isPPC64 ? PPC::BDZ8 : PPC::BDZ))); 1492 } else if (Pred[0].getImm() == PPC::PRED_BIT_SET) { 1493 MachineBasicBlock *MBB = MI.getOperand(0).getMBB(); 1494 MI.RemoveOperand(0); 1495 1496 MI.setDesc(get(PPC::BC)); 1497 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1498 .add(Pred[1]) 1499 .addMBB(MBB); 1500 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) { 1501 MachineBasicBlock *MBB = MI.getOperand(0).getMBB(); 1502 MI.RemoveOperand(0); 1503 1504 MI.setDesc(get(PPC::BCn)); 1505 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1506 .add(Pred[1]) 1507 .addMBB(MBB); 1508 } else { 1509 MachineBasicBlock *MBB = MI.getOperand(0).getMBB(); 1510 MI.RemoveOperand(0); 1511 1512 MI.setDesc(get(PPC::BCC)); 1513 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1514 .addImm(Pred[0].getImm()) 1515 .add(Pred[1]) 1516 .addMBB(MBB); 1517 } 1518 1519 return true; 1520 } else if (OpC == PPC::BCTR || OpC == PPC::BCTR8 || OpC == PPC::BCTRL || 1521 OpC == PPC::BCTRL8) { 1522 if (Pred[1].getReg() == PPC::CTR8 || Pred[1].getReg() == PPC::CTR) 1523 llvm_unreachable("Cannot predicate bctr[l] on the ctr register"); 1524 1525 bool setLR = OpC == PPC::BCTRL || OpC == PPC::BCTRL8; 1526 bool isPPC64 = Subtarget.isPPC64(); 1527 1528 if (Pred[0].getImm() == PPC::PRED_BIT_SET) { 1529 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8 : PPC::BCCTR8) 1530 : (setLR ? PPC::BCCTRL : PPC::BCCTR))); 1531 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]); 1532 return true; 1533 } else if (Pred[0].getImm() == PPC::PRED_BIT_UNSET) { 1534 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCTRL8n : PPC::BCCTR8n) 1535 : (setLR ? PPC::BCCTRLn : PPC::BCCTRn))); 1536 MachineInstrBuilder(*MI.getParent()->getParent(), MI).add(Pred[1]); 1537 return true; 1538 } 1539 1540 MI.setDesc(get(isPPC64 ? (setLR ? PPC::BCCCTRL8 : PPC::BCCCTR8) 1541 : (setLR ? PPC::BCCCTRL : PPC::BCCCTR))); 1542 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 1543 .addImm(Pred[0].getImm()) 1544 .add(Pred[1]); 1545 return true; 1546 } 1547 1548 return false; 1549 } 1550 1551 bool PPCInstrInfo::SubsumesPredicate(ArrayRef<MachineOperand> Pred1, 1552 ArrayRef<MachineOperand> Pred2) const { 1553 assert(Pred1.size() == 2 && "Invalid PPC first predicate"); 1554 assert(Pred2.size() == 2 && "Invalid PPC second predicate"); 1555 1556 if (Pred1[1].getReg() == PPC::CTR8 || Pred1[1].getReg() == PPC::CTR) 1557 return false; 1558 if (Pred2[1].getReg() == PPC::CTR8 || Pred2[1].getReg() == PPC::CTR) 1559 return false; 1560 1561 // P1 can only subsume P2 if they test the same condition register. 1562 if (Pred1[1].getReg() != Pred2[1].getReg()) 1563 return false; 1564 1565 PPC::Predicate P1 = (PPC::Predicate) Pred1[0].getImm(); 1566 PPC::Predicate P2 = (PPC::Predicate) Pred2[0].getImm(); 1567 1568 if (P1 == P2) 1569 return true; 1570 1571 // Does P1 subsume P2, e.g. GE subsumes GT. 1572 if (P1 == PPC::PRED_LE && 1573 (P2 == PPC::PRED_LT || P2 == PPC::PRED_EQ)) 1574 return true; 1575 if (P1 == PPC::PRED_GE && 1576 (P2 == PPC::PRED_GT || P2 == PPC::PRED_EQ)) 1577 return true; 1578 1579 return false; 1580 } 1581 1582 bool PPCInstrInfo::DefinesPredicate(MachineInstr &MI, 1583 std::vector<MachineOperand> &Pred) const { 1584 // Note: At the present time, the contents of Pred from this function is 1585 // unused by IfConversion. This implementation follows ARM by pushing the 1586 // CR-defining operand. Because the 'DZ' and 'DNZ' count as types of 1587 // predicate, instructions defining CTR or CTR8 are also included as 1588 // predicate-defining instructions. 1589 1590 const TargetRegisterClass *RCs[] = 1591 { &PPC::CRRCRegClass, &PPC::CRBITRCRegClass, 1592 &PPC::CTRRCRegClass, &PPC::CTRRC8RegClass }; 1593 1594 bool Found = false; 1595 for (unsigned i = 0, e = MI.getNumOperands(); i != e; ++i) { 1596 const MachineOperand &MO = MI.getOperand(i); 1597 for (unsigned c = 0; c < array_lengthof(RCs) && !Found; ++c) { 1598 const TargetRegisterClass *RC = RCs[c]; 1599 if (MO.isReg()) { 1600 if (MO.isDef() && RC->contains(MO.getReg())) { 1601 Pred.push_back(MO); 1602 Found = true; 1603 } 1604 } else if (MO.isRegMask()) { 1605 for (TargetRegisterClass::iterator I = RC->begin(), 1606 IE = RC->end(); I != IE; ++I) 1607 if (MO.clobbersPhysReg(*I)) { 1608 Pred.push_back(MO); 1609 Found = true; 1610 } 1611 } 1612 } 1613 } 1614 1615 return Found; 1616 } 1617 1618 bool PPCInstrInfo::analyzeCompare(const MachineInstr &MI, Register &SrcReg, 1619 Register &SrcReg2, int &Mask, 1620 int &Value) const { 1621 unsigned Opc = MI.getOpcode(); 1622 1623 switch (Opc) { 1624 default: return false; 1625 case PPC::CMPWI: 1626 case PPC::CMPLWI: 1627 case PPC::CMPDI: 1628 case PPC::CMPLDI: 1629 SrcReg = MI.getOperand(1).getReg(); 1630 SrcReg2 = 0; 1631 Value = MI.getOperand(2).getImm(); 1632 Mask = 0xFFFF; 1633 return true; 1634 case PPC::CMPW: 1635 case PPC::CMPLW: 1636 case PPC::CMPD: 1637 case PPC::CMPLD: 1638 case PPC::FCMPUS: 1639 case PPC::FCMPUD: 1640 SrcReg = MI.getOperand(1).getReg(); 1641 SrcReg2 = MI.getOperand(2).getReg(); 1642 Value = 0; 1643 Mask = 0; 1644 return true; 1645 } 1646 } 1647 1648 bool PPCInstrInfo::optimizeCompareInstr(MachineInstr &CmpInstr, Register SrcReg, 1649 Register SrcReg2, int Mask, int Value, 1650 const MachineRegisterInfo *MRI) const { 1651 if (DisableCmpOpt) 1652 return false; 1653 1654 int OpC = CmpInstr.getOpcode(); 1655 Register CRReg = CmpInstr.getOperand(0).getReg(); 1656 1657 // FP record forms set CR1 based on the exception status bits, not a 1658 // comparison with zero. 1659 if (OpC == PPC::FCMPUS || OpC == PPC::FCMPUD) 1660 return false; 1661 1662 const TargetRegisterInfo *TRI = &getRegisterInfo(); 1663 // The record forms set the condition register based on a signed comparison 1664 // with zero (so says the ISA manual). This is not as straightforward as it 1665 // seems, however, because this is always a 64-bit comparison on PPC64, even 1666 // for instructions that are 32-bit in nature (like slw for example). 1667 // So, on PPC32, for unsigned comparisons, we can use the record forms only 1668 // for equality checks (as those don't depend on the sign). On PPC64, 1669 // we are restricted to equality for unsigned 64-bit comparisons and for 1670 // signed 32-bit comparisons the applicability is more restricted. 1671 bool isPPC64 = Subtarget.isPPC64(); 1672 bool is32BitSignedCompare = OpC == PPC::CMPWI || OpC == PPC::CMPW; 1673 bool is32BitUnsignedCompare = OpC == PPC::CMPLWI || OpC == PPC::CMPLW; 1674 bool is64BitUnsignedCompare = OpC == PPC::CMPLDI || OpC == PPC::CMPLD; 1675 1676 // Look through copies unless that gets us to a physical register. 1677 Register ActualSrc = TRI->lookThruCopyLike(SrcReg, MRI); 1678 if (ActualSrc.isVirtual()) 1679 SrcReg = ActualSrc; 1680 1681 // Get the unique definition of SrcReg. 1682 MachineInstr *MI = MRI->getUniqueVRegDef(SrcReg); 1683 if (!MI) return false; 1684 1685 bool equalityOnly = false; 1686 bool noSub = false; 1687 if (isPPC64) { 1688 if (is32BitSignedCompare) { 1689 // We can perform this optimization only if MI is sign-extending. 1690 if (isSignExtended(*MI)) 1691 noSub = true; 1692 else 1693 return false; 1694 } else if (is32BitUnsignedCompare) { 1695 // We can perform this optimization, equality only, if MI is 1696 // zero-extending. 1697 if (isZeroExtended(*MI)) { 1698 noSub = true; 1699 equalityOnly = true; 1700 } else 1701 return false; 1702 } else 1703 equalityOnly = is64BitUnsignedCompare; 1704 } else 1705 equalityOnly = is32BitUnsignedCompare; 1706 1707 if (equalityOnly) { 1708 // We need to check the uses of the condition register in order to reject 1709 // non-equality comparisons. 1710 for (MachineRegisterInfo::use_instr_iterator 1711 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end(); 1712 I != IE; ++I) { 1713 MachineInstr *UseMI = &*I; 1714 if (UseMI->getOpcode() == PPC::BCC) { 1715 PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm(); 1716 unsigned PredCond = PPC::getPredicateCondition(Pred); 1717 // We ignore hint bits when checking for non-equality comparisons. 1718 if (PredCond != PPC::PRED_EQ && PredCond != PPC::PRED_NE) 1719 return false; 1720 } else if (UseMI->getOpcode() == PPC::ISEL || 1721 UseMI->getOpcode() == PPC::ISEL8) { 1722 unsigned SubIdx = UseMI->getOperand(3).getSubReg(); 1723 if (SubIdx != PPC::sub_eq) 1724 return false; 1725 } else 1726 return false; 1727 } 1728 } 1729 1730 MachineBasicBlock::iterator I = CmpInstr; 1731 1732 // Scan forward to find the first use of the compare. 1733 for (MachineBasicBlock::iterator EL = CmpInstr.getParent()->end(); I != EL; 1734 ++I) { 1735 bool FoundUse = false; 1736 for (MachineRegisterInfo::use_instr_iterator 1737 J = MRI->use_instr_begin(CRReg), JE = MRI->use_instr_end(); 1738 J != JE; ++J) 1739 if (&*J == &*I) { 1740 FoundUse = true; 1741 break; 1742 } 1743 1744 if (FoundUse) 1745 break; 1746 } 1747 1748 SmallVector<std::pair<MachineOperand*, PPC::Predicate>, 4> PredsToUpdate; 1749 SmallVector<std::pair<MachineOperand*, unsigned>, 4> SubRegsToUpdate; 1750 1751 // There are two possible candidates which can be changed to set CR[01]. 1752 // One is MI, the other is a SUB instruction. 1753 // For CMPrr(r1,r2), we are looking for SUB(r1,r2) or SUB(r2,r1). 1754 MachineInstr *Sub = nullptr; 1755 if (SrcReg2 != 0) 1756 // MI is not a candidate for CMPrr. 1757 MI = nullptr; 1758 // FIXME: Conservatively refuse to convert an instruction which isn't in the 1759 // same BB as the comparison. This is to allow the check below to avoid calls 1760 // (and other explicit clobbers); instead we should really check for these 1761 // more explicitly (in at least a few predecessors). 1762 else if (MI->getParent() != CmpInstr.getParent()) 1763 return false; 1764 else if (Value != 0) { 1765 // The record-form instructions set CR bit based on signed comparison 1766 // against 0. We try to convert a compare against 1 or -1 into a compare 1767 // against 0 to exploit record-form instructions. For example, we change 1768 // the condition "greater than -1" into "greater than or equal to 0" 1769 // and "less than 1" into "less than or equal to 0". 1770 1771 // Since we optimize comparison based on a specific branch condition, 1772 // we don't optimize if condition code is used by more than once. 1773 if (equalityOnly || !MRI->hasOneUse(CRReg)) 1774 return false; 1775 1776 MachineInstr *UseMI = &*MRI->use_instr_begin(CRReg); 1777 if (UseMI->getOpcode() != PPC::BCC) 1778 return false; 1779 1780 PPC::Predicate Pred = (PPC::Predicate)UseMI->getOperand(0).getImm(); 1781 unsigned PredCond = PPC::getPredicateCondition(Pred); 1782 unsigned PredHint = PPC::getPredicateHint(Pred); 1783 int16_t Immed = (int16_t)Value; 1784 1785 // When modifying the condition in the predicate, we propagate hint bits 1786 // from the original predicate to the new one. 1787 if (Immed == -1 && PredCond == PPC::PRED_GT) 1788 // We convert "greater than -1" into "greater than or equal to 0", 1789 // since we are assuming signed comparison by !equalityOnly 1790 Pred = PPC::getPredicate(PPC::PRED_GE, PredHint); 1791 else if (Immed == -1 && PredCond == PPC::PRED_LE) 1792 // We convert "less than or equal to -1" into "less than 0". 1793 Pred = PPC::getPredicate(PPC::PRED_LT, PredHint); 1794 else if (Immed == 1 && PredCond == PPC::PRED_LT) 1795 // We convert "less than 1" into "less than or equal to 0". 1796 Pred = PPC::getPredicate(PPC::PRED_LE, PredHint); 1797 else if (Immed == 1 && PredCond == PPC::PRED_GE) 1798 // We convert "greater than or equal to 1" into "greater than 0". 1799 Pred = PPC::getPredicate(PPC::PRED_GT, PredHint); 1800 else 1801 return false; 1802 1803 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)), Pred)); 1804 } 1805 1806 // Search for Sub. 1807 --I; 1808 1809 // Get ready to iterate backward from CmpInstr. 1810 MachineBasicBlock::iterator E = MI, B = CmpInstr.getParent()->begin(); 1811 1812 for (; I != E && !noSub; --I) { 1813 const MachineInstr &Instr = *I; 1814 unsigned IOpC = Instr.getOpcode(); 1815 1816 if (&*I != &CmpInstr && (Instr.modifiesRegister(PPC::CR0, TRI) || 1817 Instr.readsRegister(PPC::CR0, TRI))) 1818 // This instruction modifies or uses the record condition register after 1819 // the one we want to change. While we could do this transformation, it 1820 // would likely not be profitable. This transformation removes one 1821 // instruction, and so even forcing RA to generate one move probably 1822 // makes it unprofitable. 1823 return false; 1824 1825 // Check whether CmpInstr can be made redundant by the current instruction. 1826 if ((OpC == PPC::CMPW || OpC == PPC::CMPLW || 1827 OpC == PPC::CMPD || OpC == PPC::CMPLD) && 1828 (IOpC == PPC::SUBF || IOpC == PPC::SUBF8) && 1829 ((Instr.getOperand(1).getReg() == SrcReg && 1830 Instr.getOperand(2).getReg() == SrcReg2) || 1831 (Instr.getOperand(1).getReg() == SrcReg2 && 1832 Instr.getOperand(2).getReg() == SrcReg))) { 1833 Sub = &*I; 1834 break; 1835 } 1836 1837 if (I == B) 1838 // The 'and' is below the comparison instruction. 1839 return false; 1840 } 1841 1842 // Return false if no candidates exist. 1843 if (!MI && !Sub) 1844 return false; 1845 1846 // The single candidate is called MI. 1847 if (!MI) MI = Sub; 1848 1849 int NewOpC = -1; 1850 int MIOpC = MI->getOpcode(); 1851 if (MIOpC == PPC::ANDI_rec || MIOpC == PPC::ANDI8_rec || 1852 MIOpC == PPC::ANDIS_rec || MIOpC == PPC::ANDIS8_rec) 1853 NewOpC = MIOpC; 1854 else { 1855 NewOpC = PPC::getRecordFormOpcode(MIOpC); 1856 if (NewOpC == -1 && PPC::getNonRecordFormOpcode(MIOpC) != -1) 1857 NewOpC = MIOpC; 1858 } 1859 1860 // FIXME: On the non-embedded POWER architectures, only some of the record 1861 // forms are fast, and we should use only the fast ones. 1862 1863 // The defining instruction has a record form (or is already a record 1864 // form). It is possible, however, that we'll need to reverse the condition 1865 // code of the users. 1866 if (NewOpC == -1) 1867 return false; 1868 1869 // If we have SUB(r1, r2) and CMP(r2, r1), the condition code based on CMP 1870 // needs to be updated to be based on SUB. Push the condition code 1871 // operands to OperandsToUpdate. If it is safe to remove CmpInstr, the 1872 // condition code of these operands will be modified. 1873 // Here, Value == 0 means we haven't converted comparison against 1 or -1 to 1874 // comparison against 0, which may modify predicate. 1875 bool ShouldSwap = false; 1876 if (Sub && Value == 0) { 1877 ShouldSwap = SrcReg2 != 0 && Sub->getOperand(1).getReg() == SrcReg2 && 1878 Sub->getOperand(2).getReg() == SrcReg; 1879 1880 // The operands to subf are the opposite of sub, so only in the fixed-point 1881 // case, invert the order. 1882 ShouldSwap = !ShouldSwap; 1883 } 1884 1885 if (ShouldSwap) 1886 for (MachineRegisterInfo::use_instr_iterator 1887 I = MRI->use_instr_begin(CRReg), IE = MRI->use_instr_end(); 1888 I != IE; ++I) { 1889 MachineInstr *UseMI = &*I; 1890 if (UseMI->getOpcode() == PPC::BCC) { 1891 PPC::Predicate Pred = (PPC::Predicate) UseMI->getOperand(0).getImm(); 1892 unsigned PredCond = PPC::getPredicateCondition(Pred); 1893 assert((!equalityOnly || 1894 PredCond == PPC::PRED_EQ || PredCond == PPC::PRED_NE) && 1895 "Invalid predicate for equality-only optimization"); 1896 (void)PredCond; // To suppress warning in release build. 1897 PredsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(0)), 1898 PPC::getSwappedPredicate(Pred))); 1899 } else if (UseMI->getOpcode() == PPC::ISEL || 1900 UseMI->getOpcode() == PPC::ISEL8) { 1901 unsigned NewSubReg = UseMI->getOperand(3).getSubReg(); 1902 assert((!equalityOnly || NewSubReg == PPC::sub_eq) && 1903 "Invalid CR bit for equality-only optimization"); 1904 1905 if (NewSubReg == PPC::sub_lt) 1906 NewSubReg = PPC::sub_gt; 1907 else if (NewSubReg == PPC::sub_gt) 1908 NewSubReg = PPC::sub_lt; 1909 1910 SubRegsToUpdate.push_back(std::make_pair(&(UseMI->getOperand(3)), 1911 NewSubReg)); 1912 } else // We need to abort on a user we don't understand. 1913 return false; 1914 } 1915 assert(!(Value != 0 && ShouldSwap) && 1916 "Non-zero immediate support and ShouldSwap" 1917 "may conflict in updating predicate"); 1918 1919 // Create a new virtual register to hold the value of the CR set by the 1920 // record-form instruction. If the instruction was not previously in 1921 // record form, then set the kill flag on the CR. 1922 CmpInstr.eraseFromParent(); 1923 1924 MachineBasicBlock::iterator MII = MI; 1925 BuildMI(*MI->getParent(), std::next(MII), MI->getDebugLoc(), 1926 get(TargetOpcode::COPY), CRReg) 1927 .addReg(PPC::CR0, MIOpC != NewOpC ? RegState::Kill : 0); 1928 1929 // Even if CR0 register were dead before, it is alive now since the 1930 // instruction we just built uses it. 1931 MI->clearRegisterDeads(PPC::CR0); 1932 1933 if (MIOpC != NewOpC) { 1934 // We need to be careful here: we're replacing one instruction with 1935 // another, and we need to make sure that we get all of the right 1936 // implicit uses and defs. On the other hand, the caller may be holding 1937 // an iterator to this instruction, and so we can't delete it (this is 1938 // specifically the case if this is the instruction directly after the 1939 // compare). 1940 1941 // Rotates are expensive instructions. If we're emitting a record-form 1942 // rotate that can just be an andi/andis, we should just emit that. 1943 if (MIOpC == PPC::RLWINM || MIOpC == PPC::RLWINM8) { 1944 Register GPRRes = MI->getOperand(0).getReg(); 1945 int64_t SH = MI->getOperand(2).getImm(); 1946 int64_t MB = MI->getOperand(3).getImm(); 1947 int64_t ME = MI->getOperand(4).getImm(); 1948 // We can only do this if both the start and end of the mask are in the 1949 // same halfword. 1950 bool MBInLoHWord = MB >= 16; 1951 bool MEInLoHWord = ME >= 16; 1952 uint64_t Mask = ~0LLU; 1953 1954 if (MB <= ME && MBInLoHWord == MEInLoHWord && SH == 0) { 1955 Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1); 1956 // The mask value needs to shift right 16 if we're emitting andis. 1957 Mask >>= MBInLoHWord ? 0 : 16; 1958 NewOpC = MIOpC == PPC::RLWINM 1959 ? (MBInLoHWord ? PPC::ANDI_rec : PPC::ANDIS_rec) 1960 : (MBInLoHWord ? PPC::ANDI8_rec : PPC::ANDIS8_rec); 1961 } else if (MRI->use_empty(GPRRes) && (ME == 31) && 1962 (ME - MB + 1 == SH) && (MB >= 16)) { 1963 // If we are rotating by the exact number of bits as are in the mask 1964 // and the mask is in the least significant bits of the register, 1965 // that's just an andis. (as long as the GPR result has no uses). 1966 Mask = ((1LLU << 32) - 1) & ~((1LLU << (32 - SH)) - 1); 1967 Mask >>= 16; 1968 NewOpC = MIOpC == PPC::RLWINM ? PPC::ANDIS_rec : PPC::ANDIS8_rec; 1969 } 1970 // If we've set the mask, we can transform. 1971 if (Mask != ~0LLU) { 1972 MI->RemoveOperand(4); 1973 MI->RemoveOperand(3); 1974 MI->getOperand(2).setImm(Mask); 1975 NumRcRotatesConvertedToRcAnd++; 1976 } 1977 } else if (MIOpC == PPC::RLDICL && MI->getOperand(2).getImm() == 0) { 1978 int64_t MB = MI->getOperand(3).getImm(); 1979 if (MB >= 48) { 1980 uint64_t Mask = (1LLU << (63 - MB + 1)) - 1; 1981 NewOpC = PPC::ANDI8_rec; 1982 MI->RemoveOperand(3); 1983 MI->getOperand(2).setImm(Mask); 1984 NumRcRotatesConvertedToRcAnd++; 1985 } 1986 } 1987 1988 const MCInstrDesc &NewDesc = get(NewOpC); 1989 MI->setDesc(NewDesc); 1990 1991 if (NewDesc.ImplicitDefs) 1992 for (const MCPhysReg *ImpDefs = NewDesc.getImplicitDefs(); 1993 *ImpDefs; ++ImpDefs) 1994 if (!MI->definesRegister(*ImpDefs)) 1995 MI->addOperand(*MI->getParent()->getParent(), 1996 MachineOperand::CreateReg(*ImpDefs, true, true)); 1997 if (NewDesc.ImplicitUses) 1998 for (const MCPhysReg *ImpUses = NewDesc.getImplicitUses(); 1999 *ImpUses; ++ImpUses) 2000 if (!MI->readsRegister(*ImpUses)) 2001 MI->addOperand(*MI->getParent()->getParent(), 2002 MachineOperand::CreateReg(*ImpUses, false, true)); 2003 } 2004 assert(MI->definesRegister(PPC::CR0) && 2005 "Record-form instruction does not define cr0?"); 2006 2007 // Modify the condition code of operands in OperandsToUpdate. 2008 // Since we have SUB(r1, r2) and CMP(r2, r1), the condition code needs to 2009 // be changed from r2 > r1 to r1 < r2, from r2 < r1 to r1 > r2, etc. 2010 for (unsigned i = 0, e = PredsToUpdate.size(); i < e; i++) 2011 PredsToUpdate[i].first->setImm(PredsToUpdate[i].second); 2012 2013 for (unsigned i = 0, e = SubRegsToUpdate.size(); i < e; i++) 2014 SubRegsToUpdate[i].first->setSubReg(SubRegsToUpdate[i].second); 2015 2016 return true; 2017 } 2018 2019 /// GetInstSize - Return the number of bytes of code the specified 2020 /// instruction may be. This returns the maximum number of bytes. 2021 /// 2022 unsigned PPCInstrInfo::getInstSizeInBytes(const MachineInstr &MI) const { 2023 unsigned Opcode = MI.getOpcode(); 2024 2025 if (Opcode == PPC::INLINEASM || Opcode == PPC::INLINEASM_BR) { 2026 const MachineFunction *MF = MI.getParent()->getParent(); 2027 const char *AsmStr = MI.getOperand(0).getSymbolName(); 2028 return getInlineAsmLength(AsmStr, *MF->getTarget().getMCAsmInfo()); 2029 } else if (Opcode == TargetOpcode::STACKMAP) { 2030 StackMapOpers Opers(&MI); 2031 return Opers.getNumPatchBytes(); 2032 } else if (Opcode == TargetOpcode::PATCHPOINT) { 2033 PatchPointOpers Opers(&MI); 2034 return Opers.getNumPatchBytes(); 2035 } else { 2036 return get(Opcode).getSize(); 2037 } 2038 } 2039 2040 std::pair<unsigned, unsigned> 2041 PPCInstrInfo::decomposeMachineOperandsTargetFlags(unsigned TF) const { 2042 const unsigned Mask = PPCII::MO_ACCESS_MASK; 2043 return std::make_pair(TF & Mask, TF & ~Mask); 2044 } 2045 2046 ArrayRef<std::pair<unsigned, const char *>> 2047 PPCInstrInfo::getSerializableDirectMachineOperandTargetFlags() const { 2048 using namespace PPCII; 2049 static const std::pair<unsigned, const char *> TargetFlags[] = { 2050 {MO_LO, "ppc-lo"}, 2051 {MO_HA, "ppc-ha"}, 2052 {MO_TPREL_LO, "ppc-tprel-lo"}, 2053 {MO_TPREL_HA, "ppc-tprel-ha"}, 2054 {MO_DTPREL_LO, "ppc-dtprel-lo"}, 2055 {MO_TLSLD_LO, "ppc-tlsld-lo"}, 2056 {MO_TOC_LO, "ppc-toc-lo"}, 2057 {MO_TLS, "ppc-tls"}}; 2058 return makeArrayRef(TargetFlags); 2059 } 2060 2061 ArrayRef<std::pair<unsigned, const char *>> 2062 PPCInstrInfo::getSerializableBitmaskMachineOperandTargetFlags() const { 2063 using namespace PPCII; 2064 static const std::pair<unsigned, const char *> TargetFlags[] = { 2065 {MO_PLT, "ppc-plt"}, 2066 {MO_PIC_FLAG, "ppc-pic"}, 2067 {MO_PCREL_FLAG, "ppc-pcrel"}, 2068 {MO_GOT_FLAG, "ppc-got"}}; 2069 return makeArrayRef(TargetFlags); 2070 } 2071 2072 // Expand VSX Memory Pseudo instruction to either a VSX or a FP instruction. 2073 // The VSX versions have the advantage of a full 64-register target whereas 2074 // the FP ones have the advantage of lower latency and higher throughput. So 2075 // what we are after is using the faster instructions in low register pressure 2076 // situations and using the larger register file in high register pressure 2077 // situations. 2078 bool PPCInstrInfo::expandVSXMemPseudo(MachineInstr &MI) const { 2079 unsigned UpperOpcode, LowerOpcode; 2080 switch (MI.getOpcode()) { 2081 case PPC::DFLOADf32: 2082 UpperOpcode = PPC::LXSSP; 2083 LowerOpcode = PPC::LFS; 2084 break; 2085 case PPC::DFLOADf64: 2086 UpperOpcode = PPC::LXSD; 2087 LowerOpcode = PPC::LFD; 2088 break; 2089 case PPC::DFSTOREf32: 2090 UpperOpcode = PPC::STXSSP; 2091 LowerOpcode = PPC::STFS; 2092 break; 2093 case PPC::DFSTOREf64: 2094 UpperOpcode = PPC::STXSD; 2095 LowerOpcode = PPC::STFD; 2096 break; 2097 case PPC::XFLOADf32: 2098 UpperOpcode = PPC::LXSSPX; 2099 LowerOpcode = PPC::LFSX; 2100 break; 2101 case PPC::XFLOADf64: 2102 UpperOpcode = PPC::LXSDX; 2103 LowerOpcode = PPC::LFDX; 2104 break; 2105 case PPC::XFSTOREf32: 2106 UpperOpcode = PPC::STXSSPX; 2107 LowerOpcode = PPC::STFSX; 2108 break; 2109 case PPC::XFSTOREf64: 2110 UpperOpcode = PPC::STXSDX; 2111 LowerOpcode = PPC::STFDX; 2112 break; 2113 case PPC::LIWAX: 2114 UpperOpcode = PPC::LXSIWAX; 2115 LowerOpcode = PPC::LFIWAX; 2116 break; 2117 case PPC::LIWZX: 2118 UpperOpcode = PPC::LXSIWZX; 2119 LowerOpcode = PPC::LFIWZX; 2120 break; 2121 case PPC::STIWX: 2122 UpperOpcode = PPC::STXSIWX; 2123 LowerOpcode = PPC::STFIWX; 2124 break; 2125 default: 2126 llvm_unreachable("Unknown Operation!"); 2127 } 2128 2129 Register TargetReg = MI.getOperand(0).getReg(); 2130 unsigned Opcode; 2131 if ((TargetReg >= PPC::F0 && TargetReg <= PPC::F31) || 2132 (TargetReg >= PPC::VSL0 && TargetReg <= PPC::VSL31)) 2133 Opcode = LowerOpcode; 2134 else 2135 Opcode = UpperOpcode; 2136 MI.setDesc(get(Opcode)); 2137 return true; 2138 } 2139 2140 static bool isAnImmediateOperand(const MachineOperand &MO) { 2141 return MO.isCPI() || MO.isGlobal() || MO.isImm(); 2142 } 2143 2144 bool PPCInstrInfo::expandPostRAPseudo(MachineInstr &MI) const { 2145 auto &MBB = *MI.getParent(); 2146 auto DL = MI.getDebugLoc(); 2147 2148 switch (MI.getOpcode()) { 2149 case TargetOpcode::LOAD_STACK_GUARD: { 2150 assert(Subtarget.isTargetLinux() && 2151 "Only Linux target is expected to contain LOAD_STACK_GUARD"); 2152 const int64_t Offset = Subtarget.isPPC64() ? -0x7010 : -0x7008; 2153 const unsigned Reg = Subtarget.isPPC64() ? PPC::X13 : PPC::R2; 2154 MI.setDesc(get(Subtarget.isPPC64() ? PPC::LD : PPC::LWZ)); 2155 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 2156 .addImm(Offset) 2157 .addReg(Reg); 2158 return true; 2159 } 2160 case PPC::DFLOADf32: 2161 case PPC::DFLOADf64: 2162 case PPC::DFSTOREf32: 2163 case PPC::DFSTOREf64: { 2164 assert(Subtarget.hasP9Vector() && 2165 "Invalid D-Form Pseudo-ops on Pre-P9 target."); 2166 assert(MI.getOperand(2).isReg() && 2167 isAnImmediateOperand(MI.getOperand(1)) && 2168 "D-form op must have register and immediate operands"); 2169 return expandVSXMemPseudo(MI); 2170 } 2171 case PPC::XFLOADf32: 2172 case PPC::XFSTOREf32: 2173 case PPC::LIWAX: 2174 case PPC::LIWZX: 2175 case PPC::STIWX: { 2176 assert(Subtarget.hasP8Vector() && 2177 "Invalid X-Form Pseudo-ops on Pre-P8 target."); 2178 assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() && 2179 "X-form op must have register and register operands"); 2180 return expandVSXMemPseudo(MI); 2181 } 2182 case PPC::XFLOADf64: 2183 case PPC::XFSTOREf64: { 2184 assert(Subtarget.hasVSX() && 2185 "Invalid X-Form Pseudo-ops on target that has no VSX."); 2186 assert(MI.getOperand(2).isReg() && MI.getOperand(1).isReg() && 2187 "X-form op must have register and register operands"); 2188 return expandVSXMemPseudo(MI); 2189 } 2190 case PPC::SPILLTOVSR_LD: { 2191 Register TargetReg = MI.getOperand(0).getReg(); 2192 if (PPC::VSFRCRegClass.contains(TargetReg)) { 2193 MI.setDesc(get(PPC::DFLOADf64)); 2194 return expandPostRAPseudo(MI); 2195 } 2196 else 2197 MI.setDesc(get(PPC::LD)); 2198 return true; 2199 } 2200 case PPC::SPILLTOVSR_ST: { 2201 Register SrcReg = MI.getOperand(0).getReg(); 2202 if (PPC::VSFRCRegClass.contains(SrcReg)) { 2203 NumStoreSPILLVSRRCAsVec++; 2204 MI.setDesc(get(PPC::DFSTOREf64)); 2205 return expandPostRAPseudo(MI); 2206 } else { 2207 NumStoreSPILLVSRRCAsGpr++; 2208 MI.setDesc(get(PPC::STD)); 2209 } 2210 return true; 2211 } 2212 case PPC::SPILLTOVSR_LDX: { 2213 Register TargetReg = MI.getOperand(0).getReg(); 2214 if (PPC::VSFRCRegClass.contains(TargetReg)) 2215 MI.setDesc(get(PPC::LXSDX)); 2216 else 2217 MI.setDesc(get(PPC::LDX)); 2218 return true; 2219 } 2220 case PPC::SPILLTOVSR_STX: { 2221 Register SrcReg = MI.getOperand(0).getReg(); 2222 if (PPC::VSFRCRegClass.contains(SrcReg)) { 2223 NumStoreSPILLVSRRCAsVec++; 2224 MI.setDesc(get(PPC::STXSDX)); 2225 } else { 2226 NumStoreSPILLVSRRCAsGpr++; 2227 MI.setDesc(get(PPC::STDX)); 2228 } 2229 return true; 2230 } 2231 2232 case PPC::CFENCE8: { 2233 auto Val = MI.getOperand(0).getReg(); 2234 BuildMI(MBB, MI, DL, get(PPC::CMPD), PPC::CR7).addReg(Val).addReg(Val); 2235 BuildMI(MBB, MI, DL, get(PPC::CTRL_DEP)) 2236 .addImm(PPC::PRED_NE_MINUS) 2237 .addReg(PPC::CR7) 2238 .addImm(1); 2239 MI.setDesc(get(PPC::ISYNC)); 2240 MI.RemoveOperand(0); 2241 return true; 2242 } 2243 } 2244 return false; 2245 } 2246 2247 // Essentially a compile-time implementation of a compare->isel sequence. 2248 // It takes two constants to compare, along with the true/false registers 2249 // and the comparison type (as a subreg to a CR field) and returns one 2250 // of the true/false registers, depending on the comparison results. 2251 static unsigned selectReg(int64_t Imm1, int64_t Imm2, unsigned CompareOpc, 2252 unsigned TrueReg, unsigned FalseReg, 2253 unsigned CRSubReg) { 2254 // Signed comparisons. The immediates are assumed to be sign-extended. 2255 if (CompareOpc == PPC::CMPWI || CompareOpc == PPC::CMPDI) { 2256 switch (CRSubReg) { 2257 default: llvm_unreachable("Unknown integer comparison type."); 2258 case PPC::sub_lt: 2259 return Imm1 < Imm2 ? TrueReg : FalseReg; 2260 case PPC::sub_gt: 2261 return Imm1 > Imm2 ? TrueReg : FalseReg; 2262 case PPC::sub_eq: 2263 return Imm1 == Imm2 ? TrueReg : FalseReg; 2264 } 2265 } 2266 // Unsigned comparisons. 2267 else if (CompareOpc == PPC::CMPLWI || CompareOpc == PPC::CMPLDI) { 2268 switch (CRSubReg) { 2269 default: llvm_unreachable("Unknown integer comparison type."); 2270 case PPC::sub_lt: 2271 return (uint64_t)Imm1 < (uint64_t)Imm2 ? TrueReg : FalseReg; 2272 case PPC::sub_gt: 2273 return (uint64_t)Imm1 > (uint64_t)Imm2 ? TrueReg : FalseReg; 2274 case PPC::sub_eq: 2275 return Imm1 == Imm2 ? TrueReg : FalseReg; 2276 } 2277 } 2278 return PPC::NoRegister; 2279 } 2280 2281 void PPCInstrInfo::replaceInstrOperandWithImm(MachineInstr &MI, 2282 unsigned OpNo, 2283 int64_t Imm) const { 2284 assert(MI.getOperand(OpNo).isReg() && "Operand must be a REG"); 2285 // Replace the REG with the Immediate. 2286 Register InUseReg = MI.getOperand(OpNo).getReg(); 2287 MI.getOperand(OpNo).ChangeToImmediate(Imm); 2288 2289 if (MI.implicit_operands().empty()) 2290 return; 2291 2292 // We need to make sure that the MI didn't have any implicit use 2293 // of this REG any more. 2294 const TargetRegisterInfo *TRI = &getRegisterInfo(); 2295 int UseOpIdx = MI.findRegisterUseOperandIdx(InUseReg, false, TRI); 2296 if (UseOpIdx >= 0) { 2297 MachineOperand &MO = MI.getOperand(UseOpIdx); 2298 if (MO.isImplicit()) 2299 // The operands must always be in the following order: 2300 // - explicit reg defs, 2301 // - other explicit operands (reg uses, immediates, etc.), 2302 // - implicit reg defs 2303 // - implicit reg uses 2304 // Therefore, removing the implicit operand won't change the explicit 2305 // operands layout. 2306 MI.RemoveOperand(UseOpIdx); 2307 } 2308 } 2309 2310 // Replace an instruction with one that materializes a constant (and sets 2311 // CR0 if the original instruction was a record-form instruction). 2312 void PPCInstrInfo::replaceInstrWithLI(MachineInstr &MI, 2313 const LoadImmediateInfo &LII) const { 2314 // Remove existing operands. 2315 int OperandToKeep = LII.SetCR ? 1 : 0; 2316 for (int i = MI.getNumOperands() - 1; i > OperandToKeep; i--) 2317 MI.RemoveOperand(i); 2318 2319 // Replace the instruction. 2320 if (LII.SetCR) { 2321 MI.setDesc(get(LII.Is64Bit ? PPC::ANDI8_rec : PPC::ANDI_rec)); 2322 // Set the immediate. 2323 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 2324 .addImm(LII.Imm).addReg(PPC::CR0, RegState::ImplicitDefine); 2325 return; 2326 } 2327 else 2328 MI.setDesc(get(LII.Is64Bit ? PPC::LI8 : PPC::LI)); 2329 2330 // Set the immediate. 2331 MachineInstrBuilder(*MI.getParent()->getParent(), MI) 2332 .addImm(LII.Imm); 2333 } 2334 2335 MachineInstr *PPCInstrInfo::getDefMIPostRA(unsigned Reg, MachineInstr &MI, 2336 bool &SeenIntermediateUse) const { 2337 assert(!MI.getParent()->getParent()->getRegInfo().isSSA() && 2338 "Should be called after register allocation."); 2339 const TargetRegisterInfo *TRI = &getRegisterInfo(); 2340 MachineBasicBlock::reverse_iterator E = MI.getParent()->rend(), It = MI; 2341 It++; 2342 SeenIntermediateUse = false; 2343 for (; It != E; ++It) { 2344 if (It->modifiesRegister(Reg, TRI)) 2345 return &*It; 2346 if (It->readsRegister(Reg, TRI)) 2347 SeenIntermediateUse = true; 2348 } 2349 return nullptr; 2350 } 2351 2352 MachineInstr *PPCInstrInfo::getForwardingDefMI( 2353 MachineInstr &MI, 2354 unsigned &OpNoForForwarding, 2355 bool &SeenIntermediateUse) const { 2356 OpNoForForwarding = ~0U; 2357 MachineInstr *DefMI = nullptr; 2358 MachineRegisterInfo *MRI = &MI.getParent()->getParent()->getRegInfo(); 2359 const TargetRegisterInfo *TRI = &getRegisterInfo(); 2360 // If we're in SSA, get the defs through the MRI. Otherwise, only look 2361 // within the basic block to see if the register is defined using an LI/LI8. 2362 if (MRI->isSSA()) { 2363 for (int i = 1, e = MI.getNumOperands(); i < e; i++) { 2364 if (!MI.getOperand(i).isReg()) 2365 continue; 2366 Register Reg = MI.getOperand(i).getReg(); 2367 if (!Register::isVirtualRegister(Reg)) 2368 continue; 2369 unsigned TrueReg = TRI->lookThruCopyLike(Reg, MRI); 2370 if (Register::isVirtualRegister(TrueReg)) { 2371 DefMI = MRI->getVRegDef(TrueReg); 2372 if (DefMI->getOpcode() == PPC::LI || DefMI->getOpcode() == PPC::LI8) { 2373 OpNoForForwarding = i; 2374 break; 2375 } 2376 } 2377 } 2378 } else { 2379 // Looking back through the definition for each operand could be expensive, 2380 // so exit early if this isn't an instruction that either has an immediate 2381 // form or is already an immediate form that we can handle. 2382 ImmInstrInfo III; 2383 unsigned Opc = MI.getOpcode(); 2384 bool ConvertibleImmForm = 2385 Opc == PPC::CMPWI || Opc == PPC::CMPLWI || Opc == PPC::CMPDI || 2386 Opc == PPC::CMPLDI || Opc == PPC::ADDI || Opc == PPC::ADDI8 || 2387 Opc == PPC::ORI || Opc == PPC::ORI8 || Opc == PPC::XORI || 2388 Opc == PPC::XORI8 || Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec || 2389 Opc == PPC::RLDICL_32 || Opc == PPC::RLDICL_32_64 || 2390 Opc == PPC::RLWINM || Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8 || 2391 Opc == PPC::RLWINM8_rec; 2392 bool IsVFReg = (MI.getNumOperands() && MI.getOperand(0).isReg()) 2393 ? isVFRegister(MI.getOperand(0).getReg()) 2394 : false; 2395 if (!ConvertibleImmForm && !instrHasImmForm(Opc, IsVFReg, III, true)) 2396 return nullptr; 2397 2398 // Don't convert or %X, %Y, %Y since that's just a register move. 2399 if ((Opc == PPC::OR || Opc == PPC::OR8) && 2400 MI.getOperand(1).getReg() == MI.getOperand(2).getReg()) 2401 return nullptr; 2402 for (int i = 1, e = MI.getNumOperands(); i < e; i++) { 2403 MachineOperand &MO = MI.getOperand(i); 2404 SeenIntermediateUse = false; 2405 if (MO.isReg() && MO.isUse() && !MO.isImplicit()) { 2406 Register Reg = MI.getOperand(i).getReg(); 2407 // If we see another use of this reg between the def and the MI, 2408 // we want to flat it so the def isn't deleted. 2409 MachineInstr *DefMI = getDefMIPostRA(Reg, MI, SeenIntermediateUse); 2410 if (DefMI) { 2411 // Is this register defined by some form of add-immediate (including 2412 // load-immediate) within this basic block? 2413 switch (DefMI->getOpcode()) { 2414 default: 2415 break; 2416 case PPC::LI: 2417 case PPC::LI8: 2418 case PPC::ADDItocL: 2419 case PPC::ADDI: 2420 case PPC::ADDI8: 2421 OpNoForForwarding = i; 2422 return DefMI; 2423 } 2424 } 2425 } 2426 } 2427 } 2428 return OpNoForForwarding == ~0U ? nullptr : DefMI; 2429 } 2430 2431 const unsigned *PPCInstrInfo::getStoreOpcodesForSpillArray() const { 2432 static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = { 2433 // Power 8 2434 {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR, 2435 PPC::SPILL_CRBIT, PPC::STVX, PPC::STXVD2X, PPC::STXSDX, PPC::STXSSPX, 2436 PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb, 2437 PPC::SPILLTOVSR_ST, PPC::EVSTDD}, 2438 // Power 9 2439 {PPC::STW, PPC::STD, PPC::STFD, PPC::STFS, PPC::SPILL_CR, 2440 PPC::SPILL_CRBIT, PPC::STVX, PPC::STXV, PPC::DFSTOREf64, PPC::DFSTOREf32, 2441 PPC::SPILL_VRSAVE, PPC::QVSTFDX, PPC::QVSTFSXs, PPC::QVSTFDXb, 2442 PPC::SPILLTOVSR_ST}}; 2443 2444 return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0]; 2445 } 2446 2447 const unsigned *PPCInstrInfo::getLoadOpcodesForSpillArray() const { 2448 static const unsigned OpcodesForSpill[2][SOK_LastOpcodeSpill] = { 2449 // Power 8 2450 {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR, 2451 PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXVD2X, PPC::LXSDX, PPC::LXSSPX, 2452 PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb, 2453 PPC::SPILLTOVSR_LD, PPC::EVLDD}, 2454 // Power 9 2455 {PPC::LWZ, PPC::LD, PPC::LFD, PPC::LFS, PPC::RESTORE_CR, 2456 PPC::RESTORE_CRBIT, PPC::LVX, PPC::LXV, PPC::DFLOADf64, PPC::DFLOADf32, 2457 PPC::RESTORE_VRSAVE, PPC::QVLFDX, PPC::QVLFSXs, PPC::QVLFDXb, 2458 PPC::SPILLTOVSR_LD}}; 2459 2460 return OpcodesForSpill[(Subtarget.hasP9Vector()) ? 1 : 0]; 2461 } 2462 2463 void PPCInstrInfo::fixupIsDeadOrKill(MachineInstr &StartMI, MachineInstr &EndMI, 2464 unsigned RegNo) const { 2465 const MachineRegisterInfo &MRI = 2466 StartMI.getParent()->getParent()->getRegInfo(); 2467 if (MRI.isSSA()) 2468 return; 2469 2470 // Instructions between [StartMI, EndMI] should be in same basic block. 2471 assert((StartMI.getParent() == EndMI.getParent()) && 2472 "Instructions are not in same basic block"); 2473 2474 bool IsKillSet = false; 2475 2476 auto clearOperandKillInfo = [=] (MachineInstr &MI, unsigned Index) { 2477 MachineOperand &MO = MI.getOperand(Index); 2478 if (MO.isReg() && MO.isUse() && MO.isKill() && 2479 getRegisterInfo().regsOverlap(MO.getReg(), RegNo)) 2480 MO.setIsKill(false); 2481 }; 2482 2483 // Set killed flag for EndMI. 2484 // No need to do anything if EndMI defines RegNo. 2485 int UseIndex = 2486 EndMI.findRegisterUseOperandIdx(RegNo, false, &getRegisterInfo()); 2487 if (UseIndex != -1) { 2488 EndMI.getOperand(UseIndex).setIsKill(true); 2489 IsKillSet = true; 2490 // Clear killed flag for other EndMI operands related to RegNo. In some 2491 // upexpected cases, killed may be set multiple times for same register 2492 // operand in same MI. 2493 for (int i = 0, e = EndMI.getNumOperands(); i != e; ++i) 2494 if (i != UseIndex) 2495 clearOperandKillInfo(EndMI, i); 2496 } 2497 2498 // Walking the inst in reverse order (EndMI -> StartMI]. 2499 MachineBasicBlock::reverse_iterator It = EndMI; 2500 MachineBasicBlock::reverse_iterator E = EndMI.getParent()->rend(); 2501 // EndMI has been handled above, skip it here. 2502 It++; 2503 MachineOperand *MO = nullptr; 2504 for (; It != E; ++It) { 2505 // Skip insturctions which could not be a def/use of RegNo. 2506 if (It->isDebugInstr() || It->isPosition()) 2507 continue; 2508 2509 // Clear killed flag for all It operands related to RegNo. In some 2510 // upexpected cases, killed may be set multiple times for same register 2511 // operand in same MI. 2512 for (int i = 0, e = It->getNumOperands(); i != e; ++i) 2513 clearOperandKillInfo(*It, i); 2514 2515 // If killed is not set, set killed for its last use or set dead for its def 2516 // if no use found. 2517 if (!IsKillSet) { 2518 if ((MO = It->findRegisterUseOperand(RegNo, false, &getRegisterInfo()))) { 2519 // Use found, set it killed. 2520 IsKillSet = true; 2521 MO->setIsKill(true); 2522 continue; 2523 } else if ((MO = It->findRegisterDefOperand(RegNo, false, true, 2524 &getRegisterInfo()))) { 2525 // No use found, set dead for its def. 2526 assert(&*It == &StartMI && "No new def between StartMI and EndMI."); 2527 MO->setIsDead(true); 2528 break; 2529 } 2530 } 2531 2532 if ((&*It) == &StartMI) 2533 break; 2534 } 2535 // Ensure RegMo liveness is killed after EndMI. 2536 assert((IsKillSet || (MO && MO->isDead())) && 2537 "RegNo should be killed or dead"); 2538 } 2539 2540 // This opt tries to convert the following imm form to an index form to save an 2541 // add for stack variables. 2542 // Return false if no such pattern found. 2543 // 2544 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi 2545 // ADD instr: ToBeDeletedReg = ADD ToBeChangedReg(killed), ScaleReg 2546 // Imm instr: Reg = op OffsetImm, ToBeDeletedReg(killed) 2547 // 2548 // can be converted to: 2549 // 2550 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, (OffsetAddi + OffsetImm) 2551 // Index instr: Reg = opx ScaleReg, ToBeChangedReg(killed) 2552 // 2553 // In order to eliminate ADD instr, make sure that: 2554 // 1: (OffsetAddi + OffsetImm) must be int16 since this offset will be used in 2555 // new ADDI instr and ADDI can only take int16 Imm. 2556 // 2: ToBeChangedReg must be killed in ADD instr and there is no other use 2557 // between ADDI and ADD instr since its original def in ADDI will be changed 2558 // in new ADDI instr. And also there should be no new def for it between 2559 // ADD and Imm instr as ToBeChangedReg will be used in Index instr. 2560 // 3: ToBeDeletedReg must be killed in Imm instr and there is no other use 2561 // between ADD and Imm instr since ADD instr will be eliminated. 2562 // 4: ScaleReg must not be redefined between ADD and Imm instr since it will be 2563 // moved to Index instr. 2564 bool PPCInstrInfo::foldFrameOffset(MachineInstr &MI) const { 2565 MachineFunction *MF = MI.getParent()->getParent(); 2566 MachineRegisterInfo *MRI = &MF->getRegInfo(); 2567 bool PostRA = !MRI->isSSA(); 2568 // Do this opt after PEI which is after RA. The reason is stack slot expansion 2569 // in PEI may expose such opportunities since in PEI, stack slot offsets to 2570 // frame base(OffsetAddi) are determined. 2571 if (!PostRA) 2572 return false; 2573 unsigned ToBeDeletedReg = 0; 2574 int64_t OffsetImm = 0; 2575 unsigned XFormOpcode = 0; 2576 ImmInstrInfo III; 2577 2578 // Check if Imm instr meets requirement. 2579 if (!isImmInstrEligibleForFolding(MI, ToBeDeletedReg, XFormOpcode, OffsetImm, 2580 III)) 2581 return false; 2582 2583 bool OtherIntermediateUse = false; 2584 MachineInstr *ADDMI = getDefMIPostRA(ToBeDeletedReg, MI, OtherIntermediateUse); 2585 2586 // Exit if there is other use between ADD and Imm instr or no def found. 2587 if (OtherIntermediateUse || !ADDMI) 2588 return false; 2589 2590 // Check if ADD instr meets requirement. 2591 if (!isADDInstrEligibleForFolding(*ADDMI)) 2592 return false; 2593 2594 unsigned ScaleRegIdx = 0; 2595 int64_t OffsetAddi = 0; 2596 MachineInstr *ADDIMI = nullptr; 2597 2598 // Check if there is a valid ToBeChangedReg in ADDMI. 2599 // 1: It must be killed. 2600 // 2: Its definition must be a valid ADDIMI. 2601 // 3: It must satify int16 offset requirement. 2602 if (isValidToBeChangedReg(ADDMI, 1, ADDIMI, OffsetAddi, OffsetImm)) 2603 ScaleRegIdx = 2; 2604 else if (isValidToBeChangedReg(ADDMI, 2, ADDIMI, OffsetAddi, OffsetImm)) 2605 ScaleRegIdx = 1; 2606 else 2607 return false; 2608 2609 assert(ADDIMI && "There should be ADDIMI for valid ToBeChangedReg."); 2610 unsigned ToBeChangedReg = ADDIMI->getOperand(0).getReg(); 2611 unsigned ScaleReg = ADDMI->getOperand(ScaleRegIdx).getReg(); 2612 auto NewDefFor = [&](unsigned Reg, MachineBasicBlock::iterator Start, 2613 MachineBasicBlock::iterator End) { 2614 for (auto It = ++Start; It != End; It++) 2615 if (It->modifiesRegister(Reg, &getRegisterInfo())) 2616 return true; 2617 return false; 2618 }; 2619 2620 // We are trying to replace the ImmOpNo with ScaleReg. Give up if it is 2621 // treated as special zero when ScaleReg is R0/X0 register. 2622 if (III.ZeroIsSpecialOrig == III.ImmOpNo && 2623 (ScaleReg == PPC::R0 || ScaleReg == PPC::X0)) 2624 return false; 2625 2626 // Make sure no other def for ToBeChangedReg and ScaleReg between ADD Instr 2627 // and Imm Instr. 2628 if (NewDefFor(ToBeChangedReg, *ADDMI, MI) || NewDefFor(ScaleReg, *ADDMI, MI)) 2629 return false; 2630 2631 // Now start to do the transformation. 2632 LLVM_DEBUG(dbgs() << "Replace instruction: " 2633 << "\n"); 2634 LLVM_DEBUG(ADDIMI->dump()); 2635 LLVM_DEBUG(ADDMI->dump()); 2636 LLVM_DEBUG(MI.dump()); 2637 LLVM_DEBUG(dbgs() << "with: " 2638 << "\n"); 2639 2640 // Update ADDI instr. 2641 ADDIMI->getOperand(2).setImm(OffsetAddi + OffsetImm); 2642 2643 // Update Imm instr. 2644 MI.setDesc(get(XFormOpcode)); 2645 MI.getOperand(III.ImmOpNo) 2646 .ChangeToRegister(ScaleReg, false, false, 2647 ADDMI->getOperand(ScaleRegIdx).isKill()); 2648 2649 MI.getOperand(III.OpNoForForwarding) 2650 .ChangeToRegister(ToBeChangedReg, false, false, true); 2651 2652 // Eliminate ADD instr. 2653 ADDMI->eraseFromParent(); 2654 2655 LLVM_DEBUG(ADDIMI->dump()); 2656 LLVM_DEBUG(MI.dump()); 2657 2658 return true; 2659 } 2660 2661 bool PPCInstrInfo::isADDIInstrEligibleForFolding(MachineInstr &ADDIMI, 2662 int64_t &Imm) const { 2663 unsigned Opc = ADDIMI.getOpcode(); 2664 2665 // Exit if the instruction is not ADDI. 2666 if (Opc != PPC::ADDI && Opc != PPC::ADDI8) 2667 return false; 2668 2669 Imm = ADDIMI.getOperand(2).getImm(); 2670 2671 return true; 2672 } 2673 2674 bool PPCInstrInfo::isADDInstrEligibleForFolding(MachineInstr &ADDMI) const { 2675 unsigned Opc = ADDMI.getOpcode(); 2676 2677 // Exit if the instruction is not ADD. 2678 return Opc == PPC::ADD4 || Opc == PPC::ADD8; 2679 } 2680 2681 bool PPCInstrInfo::isImmInstrEligibleForFolding(MachineInstr &MI, 2682 unsigned &ToBeDeletedReg, 2683 unsigned &XFormOpcode, 2684 int64_t &OffsetImm, 2685 ImmInstrInfo &III) const { 2686 // Only handle load/store. 2687 if (!MI.mayLoadOrStore()) 2688 return false; 2689 2690 unsigned Opc = MI.getOpcode(); 2691 2692 XFormOpcode = RI.getMappedIdxOpcForImmOpc(Opc); 2693 2694 // Exit if instruction has no index form. 2695 if (XFormOpcode == PPC::INSTRUCTION_LIST_END) 2696 return false; 2697 2698 // TODO: sync the logic between instrHasImmForm() and ImmToIdxMap. 2699 if (!instrHasImmForm(XFormOpcode, isVFRegister(MI.getOperand(0).getReg()), 2700 III, true)) 2701 return false; 2702 2703 if (!III.IsSummingOperands) 2704 return false; 2705 2706 MachineOperand ImmOperand = MI.getOperand(III.ImmOpNo); 2707 MachineOperand RegOperand = MI.getOperand(III.OpNoForForwarding); 2708 // Only support imm operands, not relocation slots or others. 2709 if (!ImmOperand.isImm()) 2710 return false; 2711 2712 assert(RegOperand.isReg() && "Instruction format is not right"); 2713 2714 // There are other use for ToBeDeletedReg after Imm instr, can not delete it. 2715 if (!RegOperand.isKill()) 2716 return false; 2717 2718 ToBeDeletedReg = RegOperand.getReg(); 2719 OffsetImm = ImmOperand.getImm(); 2720 2721 return true; 2722 } 2723 2724 bool PPCInstrInfo::isValidToBeChangedReg(MachineInstr *ADDMI, unsigned Index, 2725 MachineInstr *&ADDIMI, 2726 int64_t &OffsetAddi, 2727 int64_t OffsetImm) const { 2728 assert((Index == 1 || Index == 2) && "Invalid operand index for add."); 2729 MachineOperand &MO = ADDMI->getOperand(Index); 2730 2731 if (!MO.isKill()) 2732 return false; 2733 2734 bool OtherIntermediateUse = false; 2735 2736 ADDIMI = getDefMIPostRA(MO.getReg(), *ADDMI, OtherIntermediateUse); 2737 // Currently handle only one "add + Imminstr" pair case, exit if other 2738 // intermediate use for ToBeChangedReg found. 2739 // TODO: handle the cases where there are other "add + Imminstr" pairs 2740 // with same offset in Imminstr which is like: 2741 // 2742 // ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, OffsetAddi 2743 // ADD instr1: ToBeDeletedReg1 = ADD ToBeChangedReg, ScaleReg1 2744 // Imm instr1: Reg1 = op1 OffsetImm, ToBeDeletedReg1(killed) 2745 // ADD instr2: ToBeDeletedReg2 = ADD ToBeChangedReg(killed), ScaleReg2 2746 // Imm instr2: Reg2 = op2 OffsetImm, ToBeDeletedReg2(killed) 2747 // 2748 // can be converted to: 2749 // 2750 // new ADDI instr: ToBeChangedReg = ADDI FrameBaseReg, 2751 // (OffsetAddi + OffsetImm) 2752 // Index instr1: Reg1 = opx1 ScaleReg1, ToBeChangedReg 2753 // Index instr2: Reg2 = opx2 ScaleReg2, ToBeChangedReg(killed) 2754 2755 if (OtherIntermediateUse || !ADDIMI) 2756 return false; 2757 // Check if ADDI instr meets requirement. 2758 if (!isADDIInstrEligibleForFolding(*ADDIMI, OffsetAddi)) 2759 return false; 2760 2761 if (isInt<16>(OffsetAddi + OffsetImm)) 2762 return true; 2763 return false; 2764 } 2765 2766 // If this instruction has an immediate form and one of its operands is a 2767 // result of a load-immediate or an add-immediate, convert it to 2768 // the immediate form if the constant is in range. 2769 bool PPCInstrInfo::convertToImmediateForm(MachineInstr &MI, 2770 MachineInstr **KilledDef) const { 2771 MachineFunction *MF = MI.getParent()->getParent(); 2772 MachineRegisterInfo *MRI = &MF->getRegInfo(); 2773 bool PostRA = !MRI->isSSA(); 2774 bool SeenIntermediateUse = true; 2775 unsigned ForwardingOperand = ~0U; 2776 MachineInstr *DefMI = getForwardingDefMI(MI, ForwardingOperand, 2777 SeenIntermediateUse); 2778 if (!DefMI) 2779 return false; 2780 assert(ForwardingOperand < MI.getNumOperands() && 2781 "The forwarding operand needs to be valid at this point"); 2782 bool IsForwardingOperandKilled = MI.getOperand(ForwardingOperand).isKill(); 2783 bool KillFwdDefMI = !SeenIntermediateUse && IsForwardingOperandKilled; 2784 Register ForwardingOperandReg = MI.getOperand(ForwardingOperand).getReg(); 2785 if (KilledDef && KillFwdDefMI) 2786 *KilledDef = DefMI; 2787 2788 ImmInstrInfo III; 2789 bool IsVFReg = MI.getOperand(0).isReg() 2790 ? isVFRegister(MI.getOperand(0).getReg()) 2791 : false; 2792 bool HasImmForm = instrHasImmForm(MI.getOpcode(), IsVFReg, III, PostRA); 2793 // If this is a reg+reg instruction that has a reg+imm form, 2794 // and one of the operands is produced by an add-immediate, 2795 // try to convert it. 2796 if (HasImmForm && 2797 transformToImmFormFedByAdd(MI, III, ForwardingOperand, *DefMI, 2798 KillFwdDefMI)) 2799 return true; 2800 2801 if ((DefMI->getOpcode() != PPC::LI && DefMI->getOpcode() != PPC::LI8) || 2802 !DefMI->getOperand(1).isImm()) 2803 return false; 2804 2805 int64_t Immediate = DefMI->getOperand(1).getImm(); 2806 // Sign-extend to 64-bits. 2807 int64_t SExtImm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ? 2808 (Immediate | 0xFFFFFFFFFFFF0000) : Immediate; 2809 2810 // If this is a reg+reg instruction that has a reg+imm form, 2811 // and one of the operands is produced by LI, convert it now. 2812 if (HasImmForm) 2813 return transformToImmFormFedByLI(MI, III, ForwardingOperand, *DefMI, SExtImm); 2814 2815 bool ReplaceWithLI = false; 2816 bool Is64BitLI = false; 2817 int64_t NewImm = 0; 2818 bool SetCR = false; 2819 unsigned Opc = MI.getOpcode(); 2820 switch (Opc) { 2821 default: return false; 2822 2823 // FIXME: Any branches conditional on such a comparison can be made 2824 // unconditional. At this time, this happens too infrequently to be worth 2825 // the implementation effort, but if that ever changes, we could convert 2826 // such a pattern here. 2827 case PPC::CMPWI: 2828 case PPC::CMPLWI: 2829 case PPC::CMPDI: 2830 case PPC::CMPLDI: { 2831 // Doing this post-RA would require dataflow analysis to reliably find uses 2832 // of the CR register set by the compare. 2833 // No need to fixup killed/dead flag since this transformation is only valid 2834 // before RA. 2835 if (PostRA) 2836 return false; 2837 // If a compare-immediate is fed by an immediate and is itself an input of 2838 // an ISEL (the most common case) into a COPY of the correct register. 2839 bool Changed = false; 2840 Register DefReg = MI.getOperand(0).getReg(); 2841 int64_t Comparand = MI.getOperand(2).getImm(); 2842 int64_t SExtComparand = ((uint64_t)Comparand & ~0x7FFFuLL) != 0 ? 2843 (Comparand | 0xFFFFFFFFFFFF0000) : Comparand; 2844 2845 for (auto &CompareUseMI : MRI->use_instructions(DefReg)) { 2846 unsigned UseOpc = CompareUseMI.getOpcode(); 2847 if (UseOpc != PPC::ISEL && UseOpc != PPC::ISEL8) 2848 continue; 2849 unsigned CRSubReg = CompareUseMI.getOperand(3).getSubReg(); 2850 Register TrueReg = CompareUseMI.getOperand(1).getReg(); 2851 Register FalseReg = CompareUseMI.getOperand(2).getReg(); 2852 unsigned RegToCopy = selectReg(SExtImm, SExtComparand, Opc, TrueReg, 2853 FalseReg, CRSubReg); 2854 if (RegToCopy == PPC::NoRegister) 2855 continue; 2856 // Can't use PPC::COPY to copy PPC::ZERO[8]. Convert it to LI[8] 0. 2857 if (RegToCopy == PPC::ZERO || RegToCopy == PPC::ZERO8) { 2858 CompareUseMI.setDesc(get(UseOpc == PPC::ISEL8 ? PPC::LI8 : PPC::LI)); 2859 replaceInstrOperandWithImm(CompareUseMI, 1, 0); 2860 CompareUseMI.RemoveOperand(3); 2861 CompareUseMI.RemoveOperand(2); 2862 continue; 2863 } 2864 LLVM_DEBUG( 2865 dbgs() << "Found LI -> CMPI -> ISEL, replacing with a copy.\n"); 2866 LLVM_DEBUG(DefMI->dump(); MI.dump(); CompareUseMI.dump()); 2867 LLVM_DEBUG(dbgs() << "Is converted to:\n"); 2868 // Convert to copy and remove unneeded operands. 2869 CompareUseMI.setDesc(get(PPC::COPY)); 2870 CompareUseMI.RemoveOperand(3); 2871 CompareUseMI.RemoveOperand(RegToCopy == TrueReg ? 2 : 1); 2872 CmpIselsConverted++; 2873 Changed = true; 2874 LLVM_DEBUG(CompareUseMI.dump()); 2875 } 2876 if (Changed) 2877 return true; 2878 // This may end up incremented multiple times since this function is called 2879 // during a fixed-point transformation, but it is only meant to indicate the 2880 // presence of this opportunity. 2881 MissedConvertibleImmediateInstrs++; 2882 return false; 2883 } 2884 2885 // Immediate forms - may simply be convertable to an LI. 2886 case PPC::ADDI: 2887 case PPC::ADDI8: { 2888 // Does the sum fit in a 16-bit signed field? 2889 int64_t Addend = MI.getOperand(2).getImm(); 2890 if (isInt<16>(Addend + SExtImm)) { 2891 ReplaceWithLI = true; 2892 Is64BitLI = Opc == PPC::ADDI8; 2893 NewImm = Addend + SExtImm; 2894 break; 2895 } 2896 return false; 2897 } 2898 case PPC::RLDICL: 2899 case PPC::RLDICL_rec: 2900 case PPC::RLDICL_32: 2901 case PPC::RLDICL_32_64: { 2902 // Use APInt's rotate function. 2903 int64_t SH = MI.getOperand(2).getImm(); 2904 int64_t MB = MI.getOperand(3).getImm(); 2905 APInt InVal((Opc == PPC::RLDICL || Opc == PPC::RLDICL_rec) ? 64 : 32, 2906 SExtImm, true); 2907 InVal = InVal.rotl(SH); 2908 uint64_t Mask = MB == 0 ? -1LLU : (1LLU << (63 - MB + 1)) - 1; 2909 InVal &= Mask; 2910 // Can't replace negative values with an LI as that will sign-extend 2911 // and not clear the left bits. If we're setting the CR bit, we will use 2912 // ANDI_rec which won't sign extend, so that's safe. 2913 if (isUInt<15>(InVal.getSExtValue()) || 2914 (Opc == PPC::RLDICL_rec && isUInt<16>(InVal.getSExtValue()))) { 2915 ReplaceWithLI = true; 2916 Is64BitLI = Opc != PPC::RLDICL_32; 2917 NewImm = InVal.getSExtValue(); 2918 SetCR = Opc == PPC::RLDICL_rec; 2919 break; 2920 } 2921 return false; 2922 } 2923 case PPC::RLWINM: 2924 case PPC::RLWINM8: 2925 case PPC::RLWINM_rec: 2926 case PPC::RLWINM8_rec: { 2927 int64_t SH = MI.getOperand(2).getImm(); 2928 int64_t MB = MI.getOperand(3).getImm(); 2929 int64_t ME = MI.getOperand(4).getImm(); 2930 APInt InVal(32, SExtImm, true); 2931 InVal = InVal.rotl(SH); 2932 // Set the bits ( MB + 32 ) to ( ME + 32 ). 2933 uint64_t Mask = ((1LLU << (32 - MB)) - 1) & ~((1LLU << (31 - ME)) - 1); 2934 InVal &= Mask; 2935 // Can't replace negative values with an LI as that will sign-extend 2936 // and not clear the left bits. If we're setting the CR bit, we will use 2937 // ANDI_rec which won't sign extend, so that's safe. 2938 bool ValueFits = isUInt<15>(InVal.getSExtValue()); 2939 ValueFits |= ((Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec) && 2940 isUInt<16>(InVal.getSExtValue())); 2941 if (ValueFits) { 2942 ReplaceWithLI = true; 2943 Is64BitLI = Opc == PPC::RLWINM8 || Opc == PPC::RLWINM8_rec; 2944 NewImm = InVal.getSExtValue(); 2945 SetCR = Opc == PPC::RLWINM_rec || Opc == PPC::RLWINM8_rec; 2946 break; 2947 } 2948 return false; 2949 } 2950 case PPC::ORI: 2951 case PPC::ORI8: 2952 case PPC::XORI: 2953 case PPC::XORI8: { 2954 int64_t LogicalImm = MI.getOperand(2).getImm(); 2955 int64_t Result = 0; 2956 if (Opc == PPC::ORI || Opc == PPC::ORI8) 2957 Result = LogicalImm | SExtImm; 2958 else 2959 Result = LogicalImm ^ SExtImm; 2960 if (isInt<16>(Result)) { 2961 ReplaceWithLI = true; 2962 Is64BitLI = Opc == PPC::ORI8 || Opc == PPC::XORI8; 2963 NewImm = Result; 2964 break; 2965 } 2966 return false; 2967 } 2968 } 2969 2970 if (ReplaceWithLI) { 2971 // We need to be careful with CR-setting instructions we're replacing. 2972 if (SetCR) { 2973 // We don't know anything about uses when we're out of SSA, so only 2974 // replace if the new immediate will be reproduced. 2975 bool ImmChanged = (SExtImm & NewImm) != NewImm; 2976 if (PostRA && ImmChanged) 2977 return false; 2978 2979 if (!PostRA) { 2980 // If the defining load-immediate has no other uses, we can just replace 2981 // the immediate with the new immediate. 2982 if (MRI->hasOneUse(DefMI->getOperand(0).getReg())) 2983 DefMI->getOperand(1).setImm(NewImm); 2984 2985 // If we're not using the GPR result of the CR-setting instruction, we 2986 // just need to and with zero/non-zero depending on the new immediate. 2987 else if (MRI->use_empty(MI.getOperand(0).getReg())) { 2988 if (NewImm) { 2989 assert(Immediate && "Transformation converted zero to non-zero?"); 2990 NewImm = Immediate; 2991 } 2992 } 2993 else if (ImmChanged) 2994 return false; 2995 } 2996 } 2997 2998 LLVM_DEBUG(dbgs() << "Replacing instruction:\n"); 2999 LLVM_DEBUG(MI.dump()); 3000 LLVM_DEBUG(dbgs() << "Fed by:\n"); 3001 LLVM_DEBUG(DefMI->dump()); 3002 LoadImmediateInfo LII; 3003 LII.Imm = NewImm; 3004 LII.Is64Bit = Is64BitLI; 3005 LII.SetCR = SetCR; 3006 // If we're setting the CR, the original load-immediate must be kept (as an 3007 // operand to ANDI_rec/ANDI8_rec). 3008 if (KilledDef && SetCR) 3009 *KilledDef = nullptr; 3010 replaceInstrWithLI(MI, LII); 3011 3012 // Fixup killed/dead flag after transformation. 3013 // Pattern: 3014 // ForwardingOperandReg = LI imm1 3015 // y = op2 imm2, ForwardingOperandReg(killed) 3016 if (IsForwardingOperandKilled) 3017 fixupIsDeadOrKill(*DefMI, MI, ForwardingOperandReg); 3018 3019 LLVM_DEBUG(dbgs() << "With:\n"); 3020 LLVM_DEBUG(MI.dump()); 3021 return true; 3022 } 3023 return false; 3024 } 3025 3026 bool PPCInstrInfo::instrHasImmForm(unsigned Opc, bool IsVFReg, 3027 ImmInstrInfo &III, bool PostRA) const { 3028 // The vast majority of the instructions would need their operand 2 replaced 3029 // with an immediate when switching to the reg+imm form. A marked exception 3030 // are the update form loads/stores for which a constant operand 2 would need 3031 // to turn into a displacement and move operand 1 to the operand 2 position. 3032 III.ImmOpNo = 2; 3033 III.OpNoForForwarding = 2; 3034 III.ImmWidth = 16; 3035 III.ImmMustBeMultipleOf = 1; 3036 III.TruncateImmTo = 0; 3037 III.IsSummingOperands = false; 3038 switch (Opc) { 3039 default: return false; 3040 case PPC::ADD4: 3041 case PPC::ADD8: 3042 III.SignedImm = true; 3043 III.ZeroIsSpecialOrig = 0; 3044 III.ZeroIsSpecialNew = 1; 3045 III.IsCommutative = true; 3046 III.IsSummingOperands = true; 3047 III.ImmOpcode = Opc == PPC::ADD4 ? PPC::ADDI : PPC::ADDI8; 3048 break; 3049 case PPC::ADDC: 3050 case PPC::ADDC8: 3051 III.SignedImm = true; 3052 III.ZeroIsSpecialOrig = 0; 3053 III.ZeroIsSpecialNew = 0; 3054 III.IsCommutative = true; 3055 III.IsSummingOperands = true; 3056 III.ImmOpcode = Opc == PPC::ADDC ? PPC::ADDIC : PPC::ADDIC8; 3057 break; 3058 case PPC::ADDC_rec: 3059 III.SignedImm = true; 3060 III.ZeroIsSpecialOrig = 0; 3061 III.ZeroIsSpecialNew = 0; 3062 III.IsCommutative = true; 3063 III.IsSummingOperands = true; 3064 III.ImmOpcode = PPC::ADDIC_rec; 3065 break; 3066 case PPC::SUBFC: 3067 case PPC::SUBFC8: 3068 III.SignedImm = true; 3069 III.ZeroIsSpecialOrig = 0; 3070 III.ZeroIsSpecialNew = 0; 3071 III.IsCommutative = false; 3072 III.ImmOpcode = Opc == PPC::SUBFC ? PPC::SUBFIC : PPC::SUBFIC8; 3073 break; 3074 case PPC::CMPW: 3075 case PPC::CMPD: 3076 III.SignedImm = true; 3077 III.ZeroIsSpecialOrig = 0; 3078 III.ZeroIsSpecialNew = 0; 3079 III.IsCommutative = false; 3080 III.ImmOpcode = Opc == PPC::CMPW ? PPC::CMPWI : PPC::CMPDI; 3081 break; 3082 case PPC::CMPLW: 3083 case PPC::CMPLD: 3084 III.SignedImm = false; 3085 III.ZeroIsSpecialOrig = 0; 3086 III.ZeroIsSpecialNew = 0; 3087 III.IsCommutative = false; 3088 III.ImmOpcode = Opc == PPC::CMPLW ? PPC::CMPLWI : PPC::CMPLDI; 3089 break; 3090 case PPC::AND_rec: 3091 case PPC::AND8_rec: 3092 case PPC::OR: 3093 case PPC::OR8: 3094 case PPC::XOR: 3095 case PPC::XOR8: 3096 III.SignedImm = false; 3097 III.ZeroIsSpecialOrig = 0; 3098 III.ZeroIsSpecialNew = 0; 3099 III.IsCommutative = true; 3100 switch(Opc) { 3101 default: llvm_unreachable("Unknown opcode"); 3102 case PPC::AND_rec: 3103 III.ImmOpcode = PPC::ANDI_rec; 3104 break; 3105 case PPC::AND8_rec: 3106 III.ImmOpcode = PPC::ANDI8_rec; 3107 break; 3108 case PPC::OR: III.ImmOpcode = PPC::ORI; break; 3109 case PPC::OR8: III.ImmOpcode = PPC::ORI8; break; 3110 case PPC::XOR: III.ImmOpcode = PPC::XORI; break; 3111 case PPC::XOR8: III.ImmOpcode = PPC::XORI8; break; 3112 } 3113 break; 3114 case PPC::RLWNM: 3115 case PPC::RLWNM8: 3116 case PPC::RLWNM_rec: 3117 case PPC::RLWNM8_rec: 3118 case PPC::SLW: 3119 case PPC::SLW8: 3120 case PPC::SLW_rec: 3121 case PPC::SLW8_rec: 3122 case PPC::SRW: 3123 case PPC::SRW8: 3124 case PPC::SRW_rec: 3125 case PPC::SRW8_rec: 3126 case PPC::SRAW: 3127 case PPC::SRAW_rec: 3128 III.SignedImm = false; 3129 III.ZeroIsSpecialOrig = 0; 3130 III.ZeroIsSpecialNew = 0; 3131 III.IsCommutative = false; 3132 // This isn't actually true, but the instructions ignore any of the 3133 // upper bits, so any immediate loaded with an LI is acceptable. 3134 // This does not apply to shift right algebraic because a value 3135 // out of range will produce a -1/0. 3136 III.ImmWidth = 16; 3137 if (Opc == PPC::RLWNM || Opc == PPC::RLWNM8 || Opc == PPC::RLWNM_rec || 3138 Opc == PPC::RLWNM8_rec) 3139 III.TruncateImmTo = 5; 3140 else 3141 III.TruncateImmTo = 6; 3142 switch(Opc) { 3143 default: llvm_unreachable("Unknown opcode"); 3144 case PPC::RLWNM: III.ImmOpcode = PPC::RLWINM; break; 3145 case PPC::RLWNM8: III.ImmOpcode = PPC::RLWINM8; break; 3146 case PPC::RLWNM_rec: 3147 III.ImmOpcode = PPC::RLWINM_rec; 3148 break; 3149 case PPC::RLWNM8_rec: 3150 III.ImmOpcode = PPC::RLWINM8_rec; 3151 break; 3152 case PPC::SLW: III.ImmOpcode = PPC::RLWINM; break; 3153 case PPC::SLW8: III.ImmOpcode = PPC::RLWINM8; break; 3154 case PPC::SLW_rec: 3155 III.ImmOpcode = PPC::RLWINM_rec; 3156 break; 3157 case PPC::SLW8_rec: 3158 III.ImmOpcode = PPC::RLWINM8_rec; 3159 break; 3160 case PPC::SRW: III.ImmOpcode = PPC::RLWINM; break; 3161 case PPC::SRW8: III.ImmOpcode = PPC::RLWINM8; break; 3162 case PPC::SRW_rec: 3163 III.ImmOpcode = PPC::RLWINM_rec; 3164 break; 3165 case PPC::SRW8_rec: 3166 III.ImmOpcode = PPC::RLWINM8_rec; 3167 break; 3168 case PPC::SRAW: 3169 III.ImmWidth = 5; 3170 III.TruncateImmTo = 0; 3171 III.ImmOpcode = PPC::SRAWI; 3172 break; 3173 case PPC::SRAW_rec: 3174 III.ImmWidth = 5; 3175 III.TruncateImmTo = 0; 3176 III.ImmOpcode = PPC::SRAWI_rec; 3177 break; 3178 } 3179 break; 3180 case PPC::RLDCL: 3181 case PPC::RLDCL_rec: 3182 case PPC::RLDCR: 3183 case PPC::RLDCR_rec: 3184 case PPC::SLD: 3185 case PPC::SLD_rec: 3186 case PPC::SRD: 3187 case PPC::SRD_rec: 3188 case PPC::SRAD: 3189 case PPC::SRAD_rec: 3190 III.SignedImm = false; 3191 III.ZeroIsSpecialOrig = 0; 3192 III.ZeroIsSpecialNew = 0; 3193 III.IsCommutative = false; 3194 // This isn't actually true, but the instructions ignore any of the 3195 // upper bits, so any immediate loaded with an LI is acceptable. 3196 // This does not apply to shift right algebraic because a value 3197 // out of range will produce a -1/0. 3198 III.ImmWidth = 16; 3199 if (Opc == PPC::RLDCL || Opc == PPC::RLDCL_rec || Opc == PPC::RLDCR || 3200 Opc == PPC::RLDCR_rec) 3201 III.TruncateImmTo = 6; 3202 else 3203 III.TruncateImmTo = 7; 3204 switch(Opc) { 3205 default: llvm_unreachable("Unknown opcode"); 3206 case PPC::RLDCL: III.ImmOpcode = PPC::RLDICL; break; 3207 case PPC::RLDCL_rec: 3208 III.ImmOpcode = PPC::RLDICL_rec; 3209 break; 3210 case PPC::RLDCR: III.ImmOpcode = PPC::RLDICR; break; 3211 case PPC::RLDCR_rec: 3212 III.ImmOpcode = PPC::RLDICR_rec; 3213 break; 3214 case PPC::SLD: III.ImmOpcode = PPC::RLDICR; break; 3215 case PPC::SLD_rec: 3216 III.ImmOpcode = PPC::RLDICR_rec; 3217 break; 3218 case PPC::SRD: III.ImmOpcode = PPC::RLDICL; break; 3219 case PPC::SRD_rec: 3220 III.ImmOpcode = PPC::RLDICL_rec; 3221 break; 3222 case PPC::SRAD: 3223 III.ImmWidth = 6; 3224 III.TruncateImmTo = 0; 3225 III.ImmOpcode = PPC::SRADI; 3226 break; 3227 case PPC::SRAD_rec: 3228 III.ImmWidth = 6; 3229 III.TruncateImmTo = 0; 3230 III.ImmOpcode = PPC::SRADI_rec; 3231 break; 3232 } 3233 break; 3234 // Loads and stores: 3235 case PPC::LBZX: 3236 case PPC::LBZX8: 3237 case PPC::LHZX: 3238 case PPC::LHZX8: 3239 case PPC::LHAX: 3240 case PPC::LHAX8: 3241 case PPC::LWZX: 3242 case PPC::LWZX8: 3243 case PPC::LWAX: 3244 case PPC::LDX: 3245 case PPC::LFSX: 3246 case PPC::LFDX: 3247 case PPC::STBX: 3248 case PPC::STBX8: 3249 case PPC::STHX: 3250 case PPC::STHX8: 3251 case PPC::STWX: 3252 case PPC::STWX8: 3253 case PPC::STDX: 3254 case PPC::STFSX: 3255 case PPC::STFDX: 3256 III.SignedImm = true; 3257 III.ZeroIsSpecialOrig = 1; 3258 III.ZeroIsSpecialNew = 2; 3259 III.IsCommutative = true; 3260 III.IsSummingOperands = true; 3261 III.ImmOpNo = 1; 3262 III.OpNoForForwarding = 2; 3263 switch(Opc) { 3264 default: llvm_unreachable("Unknown opcode"); 3265 case PPC::LBZX: III.ImmOpcode = PPC::LBZ; break; 3266 case PPC::LBZX8: III.ImmOpcode = PPC::LBZ8; break; 3267 case PPC::LHZX: III.ImmOpcode = PPC::LHZ; break; 3268 case PPC::LHZX8: III.ImmOpcode = PPC::LHZ8; break; 3269 case PPC::LHAX: III.ImmOpcode = PPC::LHA; break; 3270 case PPC::LHAX8: III.ImmOpcode = PPC::LHA8; break; 3271 case PPC::LWZX: III.ImmOpcode = PPC::LWZ; break; 3272 case PPC::LWZX8: III.ImmOpcode = PPC::LWZ8; break; 3273 case PPC::LWAX: 3274 III.ImmOpcode = PPC::LWA; 3275 III.ImmMustBeMultipleOf = 4; 3276 break; 3277 case PPC::LDX: III.ImmOpcode = PPC::LD; III.ImmMustBeMultipleOf = 4; break; 3278 case PPC::LFSX: III.ImmOpcode = PPC::LFS; break; 3279 case PPC::LFDX: III.ImmOpcode = PPC::LFD; break; 3280 case PPC::STBX: III.ImmOpcode = PPC::STB; break; 3281 case PPC::STBX8: III.ImmOpcode = PPC::STB8; break; 3282 case PPC::STHX: III.ImmOpcode = PPC::STH; break; 3283 case PPC::STHX8: III.ImmOpcode = PPC::STH8; break; 3284 case PPC::STWX: III.ImmOpcode = PPC::STW; break; 3285 case PPC::STWX8: III.ImmOpcode = PPC::STW8; break; 3286 case PPC::STDX: 3287 III.ImmOpcode = PPC::STD; 3288 III.ImmMustBeMultipleOf = 4; 3289 break; 3290 case PPC::STFSX: III.ImmOpcode = PPC::STFS; break; 3291 case PPC::STFDX: III.ImmOpcode = PPC::STFD; break; 3292 } 3293 break; 3294 case PPC::LBZUX: 3295 case PPC::LBZUX8: 3296 case PPC::LHZUX: 3297 case PPC::LHZUX8: 3298 case PPC::LHAUX: 3299 case PPC::LHAUX8: 3300 case PPC::LWZUX: 3301 case PPC::LWZUX8: 3302 case PPC::LDUX: 3303 case PPC::LFSUX: 3304 case PPC::LFDUX: 3305 case PPC::STBUX: 3306 case PPC::STBUX8: 3307 case PPC::STHUX: 3308 case PPC::STHUX8: 3309 case PPC::STWUX: 3310 case PPC::STWUX8: 3311 case PPC::STDUX: 3312 case PPC::STFSUX: 3313 case PPC::STFDUX: 3314 III.SignedImm = true; 3315 III.ZeroIsSpecialOrig = 2; 3316 III.ZeroIsSpecialNew = 3; 3317 III.IsCommutative = false; 3318 III.IsSummingOperands = true; 3319 III.ImmOpNo = 2; 3320 III.OpNoForForwarding = 3; 3321 switch(Opc) { 3322 default: llvm_unreachable("Unknown opcode"); 3323 case PPC::LBZUX: III.ImmOpcode = PPC::LBZU; break; 3324 case PPC::LBZUX8: III.ImmOpcode = PPC::LBZU8; break; 3325 case PPC::LHZUX: III.ImmOpcode = PPC::LHZU; break; 3326 case PPC::LHZUX8: III.ImmOpcode = PPC::LHZU8; break; 3327 case PPC::LHAUX: III.ImmOpcode = PPC::LHAU; break; 3328 case PPC::LHAUX8: III.ImmOpcode = PPC::LHAU8; break; 3329 case PPC::LWZUX: III.ImmOpcode = PPC::LWZU; break; 3330 case PPC::LWZUX8: III.ImmOpcode = PPC::LWZU8; break; 3331 case PPC::LDUX: 3332 III.ImmOpcode = PPC::LDU; 3333 III.ImmMustBeMultipleOf = 4; 3334 break; 3335 case PPC::LFSUX: III.ImmOpcode = PPC::LFSU; break; 3336 case PPC::LFDUX: III.ImmOpcode = PPC::LFDU; break; 3337 case PPC::STBUX: III.ImmOpcode = PPC::STBU; break; 3338 case PPC::STBUX8: III.ImmOpcode = PPC::STBU8; break; 3339 case PPC::STHUX: III.ImmOpcode = PPC::STHU; break; 3340 case PPC::STHUX8: III.ImmOpcode = PPC::STHU8; break; 3341 case PPC::STWUX: III.ImmOpcode = PPC::STWU; break; 3342 case PPC::STWUX8: III.ImmOpcode = PPC::STWU8; break; 3343 case PPC::STDUX: 3344 III.ImmOpcode = PPC::STDU; 3345 III.ImmMustBeMultipleOf = 4; 3346 break; 3347 case PPC::STFSUX: III.ImmOpcode = PPC::STFSU; break; 3348 case PPC::STFDUX: III.ImmOpcode = PPC::STFDU; break; 3349 } 3350 break; 3351 // Power9 and up only. For some of these, the X-Form version has access to all 3352 // 64 VSR's whereas the D-Form only has access to the VR's. We replace those 3353 // with pseudo-ops pre-ra and for post-ra, we check that the register loaded 3354 // into or stored from is one of the VR registers. 3355 case PPC::LXVX: 3356 case PPC::LXSSPX: 3357 case PPC::LXSDX: 3358 case PPC::STXVX: 3359 case PPC::STXSSPX: 3360 case PPC::STXSDX: 3361 case PPC::XFLOADf32: 3362 case PPC::XFLOADf64: 3363 case PPC::XFSTOREf32: 3364 case PPC::XFSTOREf64: 3365 if (!Subtarget.hasP9Vector()) 3366 return false; 3367 III.SignedImm = true; 3368 III.ZeroIsSpecialOrig = 1; 3369 III.ZeroIsSpecialNew = 2; 3370 III.IsCommutative = true; 3371 III.IsSummingOperands = true; 3372 III.ImmOpNo = 1; 3373 III.OpNoForForwarding = 2; 3374 III.ImmMustBeMultipleOf = 4; 3375 switch(Opc) { 3376 default: llvm_unreachable("Unknown opcode"); 3377 case PPC::LXVX: 3378 III.ImmOpcode = PPC::LXV; 3379 III.ImmMustBeMultipleOf = 16; 3380 break; 3381 case PPC::LXSSPX: 3382 if (PostRA) { 3383 if (IsVFReg) 3384 III.ImmOpcode = PPC::LXSSP; 3385 else { 3386 III.ImmOpcode = PPC::LFS; 3387 III.ImmMustBeMultipleOf = 1; 3388 } 3389 break; 3390 } 3391 LLVM_FALLTHROUGH; 3392 case PPC::XFLOADf32: 3393 III.ImmOpcode = PPC::DFLOADf32; 3394 break; 3395 case PPC::LXSDX: 3396 if (PostRA) { 3397 if (IsVFReg) 3398 III.ImmOpcode = PPC::LXSD; 3399 else { 3400 III.ImmOpcode = PPC::LFD; 3401 III.ImmMustBeMultipleOf = 1; 3402 } 3403 break; 3404 } 3405 LLVM_FALLTHROUGH; 3406 case PPC::XFLOADf64: 3407 III.ImmOpcode = PPC::DFLOADf64; 3408 break; 3409 case PPC::STXVX: 3410 III.ImmOpcode = PPC::STXV; 3411 III.ImmMustBeMultipleOf = 16; 3412 break; 3413 case PPC::STXSSPX: 3414 if (PostRA) { 3415 if (IsVFReg) 3416 III.ImmOpcode = PPC::STXSSP; 3417 else { 3418 III.ImmOpcode = PPC::STFS; 3419 III.ImmMustBeMultipleOf = 1; 3420 } 3421 break; 3422 } 3423 LLVM_FALLTHROUGH; 3424 case PPC::XFSTOREf32: 3425 III.ImmOpcode = PPC::DFSTOREf32; 3426 break; 3427 case PPC::STXSDX: 3428 if (PostRA) { 3429 if (IsVFReg) 3430 III.ImmOpcode = PPC::STXSD; 3431 else { 3432 III.ImmOpcode = PPC::STFD; 3433 III.ImmMustBeMultipleOf = 1; 3434 } 3435 break; 3436 } 3437 LLVM_FALLTHROUGH; 3438 case PPC::XFSTOREf64: 3439 III.ImmOpcode = PPC::DFSTOREf64; 3440 break; 3441 } 3442 break; 3443 } 3444 return true; 3445 } 3446 3447 // Utility function for swaping two arbitrary operands of an instruction. 3448 static void swapMIOperands(MachineInstr &MI, unsigned Op1, unsigned Op2) { 3449 assert(Op1 != Op2 && "Cannot swap operand with itself."); 3450 3451 unsigned MaxOp = std::max(Op1, Op2); 3452 unsigned MinOp = std::min(Op1, Op2); 3453 MachineOperand MOp1 = MI.getOperand(MinOp); 3454 MachineOperand MOp2 = MI.getOperand(MaxOp); 3455 MI.RemoveOperand(std::max(Op1, Op2)); 3456 MI.RemoveOperand(std::min(Op1, Op2)); 3457 3458 // If the operands we are swapping are the two at the end (the common case) 3459 // we can just remove both and add them in the opposite order. 3460 if (MaxOp - MinOp == 1 && MI.getNumOperands() == MinOp) { 3461 MI.addOperand(MOp2); 3462 MI.addOperand(MOp1); 3463 } else { 3464 // Store all operands in a temporary vector, remove them and re-add in the 3465 // right order. 3466 SmallVector<MachineOperand, 2> MOps; 3467 unsigned TotalOps = MI.getNumOperands() + 2; // We've already removed 2 ops. 3468 for (unsigned i = MI.getNumOperands() - 1; i >= MinOp; i--) { 3469 MOps.push_back(MI.getOperand(i)); 3470 MI.RemoveOperand(i); 3471 } 3472 // MOp2 needs to be added next. 3473 MI.addOperand(MOp2); 3474 // Now add the rest. 3475 for (unsigned i = MI.getNumOperands(); i < TotalOps; i++) { 3476 if (i == MaxOp) 3477 MI.addOperand(MOp1); 3478 else { 3479 MI.addOperand(MOps.back()); 3480 MOps.pop_back(); 3481 } 3482 } 3483 } 3484 } 3485 3486 // Check if the 'MI' that has the index OpNoForForwarding 3487 // meets the requirement described in the ImmInstrInfo. 3488 bool PPCInstrInfo::isUseMIElgibleForForwarding(MachineInstr &MI, 3489 const ImmInstrInfo &III, 3490 unsigned OpNoForForwarding 3491 ) const { 3492 // As the algorithm of checking for PPC::ZERO/PPC::ZERO8 3493 // would not work pre-RA, we can only do the check post RA. 3494 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 3495 if (MRI.isSSA()) 3496 return false; 3497 3498 // Cannot do the transform if MI isn't summing the operands. 3499 if (!III.IsSummingOperands) 3500 return false; 3501 3502 // The instruction we are trying to replace must have the ZeroIsSpecialOrig set. 3503 if (!III.ZeroIsSpecialOrig) 3504 return false; 3505 3506 // We cannot do the transform if the operand we are trying to replace 3507 // isn't the same as the operand the instruction allows. 3508 if (OpNoForForwarding != III.OpNoForForwarding) 3509 return false; 3510 3511 // Check if the instruction we are trying to transform really has 3512 // the special zero register as its operand. 3513 if (MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO && 3514 MI.getOperand(III.ZeroIsSpecialOrig).getReg() != PPC::ZERO8) 3515 return false; 3516 3517 // This machine instruction is convertible if it is, 3518 // 1. summing the operands. 3519 // 2. one of the operands is special zero register. 3520 // 3. the operand we are trying to replace is allowed by the MI. 3521 return true; 3522 } 3523 3524 // Check if the DefMI is the add inst and set the ImmMO and RegMO 3525 // accordingly. 3526 bool PPCInstrInfo::isDefMIElgibleForForwarding(MachineInstr &DefMI, 3527 const ImmInstrInfo &III, 3528 MachineOperand *&ImmMO, 3529 MachineOperand *&RegMO) const { 3530 unsigned Opc = DefMI.getOpcode(); 3531 if (Opc != PPC::ADDItocL && Opc != PPC::ADDI && Opc != PPC::ADDI8) 3532 return false; 3533 3534 assert(DefMI.getNumOperands() >= 3 && 3535 "Add inst must have at least three operands"); 3536 RegMO = &DefMI.getOperand(1); 3537 ImmMO = &DefMI.getOperand(2); 3538 3539 // This DefMI is elgible for forwarding if it is: 3540 // 1. add inst 3541 // 2. one of the operands is Imm/CPI/Global. 3542 return isAnImmediateOperand(*ImmMO); 3543 } 3544 3545 bool PPCInstrInfo::isRegElgibleForForwarding( 3546 const MachineOperand &RegMO, const MachineInstr &DefMI, 3547 const MachineInstr &MI, bool KillDefMI, 3548 bool &IsFwdFeederRegKilled) const { 3549 // x = addi y, imm 3550 // ... 3551 // z = lfdx 0, x -> z = lfd imm(y) 3552 // The Reg "y" can be forwarded to the MI(z) only when there is no DEF 3553 // of "y" between the DEF of "x" and "z". 3554 // The query is only valid post RA. 3555 const MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 3556 if (MRI.isSSA()) 3557 return false; 3558 3559 Register Reg = RegMO.getReg(); 3560 3561 // Walking the inst in reverse(MI-->DefMI) to get the last DEF of the Reg. 3562 MachineBasicBlock::const_reverse_iterator It = MI; 3563 MachineBasicBlock::const_reverse_iterator E = MI.getParent()->rend(); 3564 It++; 3565 for (; It != E; ++It) { 3566 if (It->modifiesRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI) 3567 return false; 3568 else if (It->killsRegister(Reg, &getRegisterInfo()) && (&*It) != &DefMI) 3569 IsFwdFeederRegKilled = true; 3570 // Made it to DefMI without encountering a clobber. 3571 if ((&*It) == &DefMI) 3572 break; 3573 } 3574 assert((&*It) == &DefMI && "DefMI is missing"); 3575 3576 // If DefMI also defines the register to be forwarded, we can only forward it 3577 // if DefMI is being erased. 3578 if (DefMI.modifiesRegister(Reg, &getRegisterInfo())) 3579 return KillDefMI; 3580 3581 return true; 3582 } 3583 3584 bool PPCInstrInfo::isImmElgibleForForwarding(const MachineOperand &ImmMO, 3585 const MachineInstr &DefMI, 3586 const ImmInstrInfo &III, 3587 int64_t &Imm) const { 3588 assert(isAnImmediateOperand(ImmMO) && "ImmMO is NOT an immediate"); 3589 if (DefMI.getOpcode() == PPC::ADDItocL) { 3590 // The operand for ADDItocL is CPI, which isn't imm at compiling time, 3591 // However, we know that, it is 16-bit width, and has the alignment of 4. 3592 // Check if the instruction met the requirement. 3593 if (III.ImmMustBeMultipleOf > 4 || 3594 III.TruncateImmTo || III.ImmWidth != 16) 3595 return false; 3596 3597 // Going from XForm to DForm loads means that the displacement needs to be 3598 // not just an immediate but also a multiple of 4, or 16 depending on the 3599 // load. A DForm load cannot be represented if it is a multiple of say 2. 3600 // XForm loads do not have this restriction. 3601 if (ImmMO.isGlobal() && 3602 ImmMO.getGlobal()->getAlignment() < III.ImmMustBeMultipleOf) 3603 return false; 3604 3605 return true; 3606 } 3607 3608 if (ImmMO.isImm()) { 3609 // It is Imm, we need to check if the Imm fit the range. 3610 int64_t Immediate = ImmMO.getImm(); 3611 // Sign-extend to 64-bits. 3612 Imm = ((uint64_t)Immediate & ~0x7FFFuLL) != 0 ? 3613 (Immediate | 0xFFFFFFFFFFFF0000) : Immediate; 3614 3615 if (Imm % III.ImmMustBeMultipleOf) 3616 return false; 3617 if (III.TruncateImmTo) 3618 Imm &= ((1 << III.TruncateImmTo) - 1); 3619 if (III.SignedImm) { 3620 APInt ActualValue(64, Imm, true); 3621 if (!ActualValue.isSignedIntN(III.ImmWidth)) 3622 return false; 3623 } else { 3624 uint64_t UnsignedMax = (1 << III.ImmWidth) - 1; 3625 if ((uint64_t)Imm > UnsignedMax) 3626 return false; 3627 } 3628 } 3629 else 3630 return false; 3631 3632 // This ImmMO is forwarded if it meets the requriement describle 3633 // in ImmInstrInfo 3634 return true; 3635 } 3636 3637 // If an X-Form instruction is fed by an add-immediate and one of its operands 3638 // is the literal zero, attempt to forward the source of the add-immediate to 3639 // the corresponding D-Form instruction with the displacement coming from 3640 // the immediate being added. 3641 bool PPCInstrInfo::transformToImmFormFedByAdd( 3642 MachineInstr &MI, const ImmInstrInfo &III, unsigned OpNoForForwarding, 3643 MachineInstr &DefMI, bool KillDefMI) const { 3644 // RegMO ImmMO 3645 // | | 3646 // x = addi reg, imm <----- DefMI 3647 // y = op 0 , x <----- MI 3648 // | 3649 // OpNoForForwarding 3650 // Check if the MI meet the requirement described in the III. 3651 if (!isUseMIElgibleForForwarding(MI, III, OpNoForForwarding)) 3652 return false; 3653 3654 // Check if the DefMI meet the requirement 3655 // described in the III. If yes, set the ImmMO and RegMO accordingly. 3656 MachineOperand *ImmMO = nullptr; 3657 MachineOperand *RegMO = nullptr; 3658 if (!isDefMIElgibleForForwarding(DefMI, III, ImmMO, RegMO)) 3659 return false; 3660 assert(ImmMO && RegMO && "Imm and Reg operand must have been set"); 3661 3662 // As we get the Imm operand now, we need to check if the ImmMO meet 3663 // the requirement described in the III. If yes set the Imm. 3664 int64_t Imm = 0; 3665 if (!isImmElgibleForForwarding(*ImmMO, DefMI, III, Imm)) 3666 return false; 3667 3668 bool IsFwdFeederRegKilled = false; 3669 // Check if the RegMO can be forwarded to MI. 3670 if (!isRegElgibleForForwarding(*RegMO, DefMI, MI, KillDefMI, 3671 IsFwdFeederRegKilled)) 3672 return false; 3673 3674 // Get killed info in case fixup needed after transformation. 3675 unsigned ForwardKilledOperandReg = ~0U; 3676 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 3677 bool PostRA = !MRI.isSSA(); 3678 if (PostRA && MI.getOperand(OpNoForForwarding).isKill()) 3679 ForwardKilledOperandReg = MI.getOperand(OpNoForForwarding).getReg(); 3680 3681 // We know that, the MI and DefMI both meet the pattern, and 3682 // the Imm also meet the requirement with the new Imm-form. 3683 // It is safe to do the transformation now. 3684 LLVM_DEBUG(dbgs() << "Replacing instruction:\n"); 3685 LLVM_DEBUG(MI.dump()); 3686 LLVM_DEBUG(dbgs() << "Fed by:\n"); 3687 LLVM_DEBUG(DefMI.dump()); 3688 3689 // Update the base reg first. 3690 MI.getOperand(III.OpNoForForwarding).ChangeToRegister(RegMO->getReg(), 3691 false, false, 3692 RegMO->isKill()); 3693 3694 // Then, update the imm. 3695 if (ImmMO->isImm()) { 3696 // If the ImmMO is Imm, change the operand that has ZERO to that Imm 3697 // directly. 3698 replaceInstrOperandWithImm(MI, III.ZeroIsSpecialOrig, Imm); 3699 } 3700 else { 3701 // Otherwise, it is Constant Pool Index(CPI) or Global, 3702 // which is relocation in fact. We need to replace the special zero 3703 // register with ImmMO. 3704 // Before that, we need to fixup the target flags for imm. 3705 // For some reason, we miss to set the flag for the ImmMO if it is CPI. 3706 if (DefMI.getOpcode() == PPC::ADDItocL) 3707 ImmMO->setTargetFlags(PPCII::MO_TOC_LO); 3708 3709 // MI didn't have the interface such as MI.setOperand(i) though 3710 // it has MI.getOperand(i). To repalce the ZERO MachineOperand with 3711 // ImmMO, we need to remove ZERO operand and all the operands behind it, 3712 // and, add the ImmMO, then, move back all the operands behind ZERO. 3713 SmallVector<MachineOperand, 2> MOps; 3714 for (unsigned i = MI.getNumOperands() - 1; i >= III.ZeroIsSpecialOrig; i--) { 3715 MOps.push_back(MI.getOperand(i)); 3716 MI.RemoveOperand(i); 3717 } 3718 3719 // Remove the last MO in the list, which is ZERO operand in fact. 3720 MOps.pop_back(); 3721 // Add the imm operand. 3722 MI.addOperand(*ImmMO); 3723 // Now add the rest back. 3724 for (auto &MO : MOps) 3725 MI.addOperand(MO); 3726 } 3727 3728 // Update the opcode. 3729 MI.setDesc(get(III.ImmOpcode)); 3730 3731 // Fix up killed/dead flag after transformation. 3732 // Pattern 1: 3733 // x = ADD KilledFwdFeederReg, imm 3734 // n = opn KilledFwdFeederReg(killed), regn 3735 // y = XOP 0, x 3736 // Pattern 2: 3737 // x = ADD reg(killed), imm 3738 // y = XOP 0, x 3739 if (IsFwdFeederRegKilled || RegMO->isKill()) 3740 fixupIsDeadOrKill(DefMI, MI, RegMO->getReg()); 3741 // Pattern 3: 3742 // ForwardKilledOperandReg = ADD reg, imm 3743 // y = XOP 0, ForwardKilledOperandReg(killed) 3744 if (ForwardKilledOperandReg != ~0U) 3745 fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg); 3746 3747 LLVM_DEBUG(dbgs() << "With:\n"); 3748 LLVM_DEBUG(MI.dump()); 3749 3750 return true; 3751 } 3752 3753 bool PPCInstrInfo::transformToImmFormFedByLI(MachineInstr &MI, 3754 const ImmInstrInfo &III, 3755 unsigned ConstantOpNo, 3756 MachineInstr &DefMI, 3757 int64_t Imm) const { 3758 MachineRegisterInfo &MRI = MI.getParent()->getParent()->getRegInfo(); 3759 bool PostRA = !MRI.isSSA(); 3760 // Exit early if we can't convert this. 3761 if ((ConstantOpNo != III.OpNoForForwarding) && !III.IsCommutative) 3762 return false; 3763 if (Imm % III.ImmMustBeMultipleOf) 3764 return false; 3765 if (III.TruncateImmTo) 3766 Imm &= ((1 << III.TruncateImmTo) - 1); 3767 if (III.SignedImm) { 3768 APInt ActualValue(64, Imm, true); 3769 if (!ActualValue.isSignedIntN(III.ImmWidth)) 3770 return false; 3771 } else { 3772 uint64_t UnsignedMax = (1 << III.ImmWidth) - 1; 3773 if ((uint64_t)Imm > UnsignedMax) 3774 return false; 3775 } 3776 3777 // If we're post-RA, the instructions don't agree on whether register zero is 3778 // special, we can transform this as long as the register operand that will 3779 // end up in the location where zero is special isn't R0. 3780 if (PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) { 3781 unsigned PosForOrigZero = III.ZeroIsSpecialOrig ? III.ZeroIsSpecialOrig : 3782 III.ZeroIsSpecialNew + 1; 3783 Register OrigZeroReg = MI.getOperand(PosForOrigZero).getReg(); 3784 Register NewZeroReg = MI.getOperand(III.ZeroIsSpecialNew).getReg(); 3785 // If R0 is in the operand where zero is special for the new instruction, 3786 // it is unsafe to transform if the constant operand isn't that operand. 3787 if ((NewZeroReg == PPC::R0 || NewZeroReg == PPC::X0) && 3788 ConstantOpNo != III.ZeroIsSpecialNew) 3789 return false; 3790 if ((OrigZeroReg == PPC::R0 || OrigZeroReg == PPC::X0) && 3791 ConstantOpNo != PosForOrigZero) 3792 return false; 3793 } 3794 3795 // Get killed info in case fixup needed after transformation. 3796 unsigned ForwardKilledOperandReg = ~0U; 3797 if (PostRA && MI.getOperand(ConstantOpNo).isKill()) 3798 ForwardKilledOperandReg = MI.getOperand(ConstantOpNo).getReg(); 3799 3800 unsigned Opc = MI.getOpcode(); 3801 bool SpecialShift32 = Opc == PPC::SLW || Opc == PPC::SLW_rec || 3802 Opc == PPC::SRW || Opc == PPC::SRW_rec || 3803 Opc == PPC::SLW8 || Opc == PPC::SLW8_rec || 3804 Opc == PPC::SRW8 || Opc == PPC::SRW8_rec; 3805 bool SpecialShift64 = Opc == PPC::SLD || Opc == PPC::SLD_rec || 3806 Opc == PPC::SRD || Opc == PPC::SRD_rec; 3807 bool SetCR = Opc == PPC::SLW_rec || Opc == PPC::SRW_rec || 3808 Opc == PPC::SLD_rec || Opc == PPC::SRD_rec; 3809 bool RightShift = Opc == PPC::SRW || Opc == PPC::SRW_rec || Opc == PPC::SRD || 3810 Opc == PPC::SRD_rec; 3811 3812 MI.setDesc(get(III.ImmOpcode)); 3813 if (ConstantOpNo == III.OpNoForForwarding) { 3814 // Converting shifts to immediate form is a bit tricky since they may do 3815 // one of three things: 3816 // 1. If the shift amount is between OpSize and 2*OpSize, the result is zero 3817 // 2. If the shift amount is zero, the result is unchanged (save for maybe 3818 // setting CR0) 3819 // 3. If the shift amount is in [1, OpSize), it's just a shift 3820 if (SpecialShift32 || SpecialShift64) { 3821 LoadImmediateInfo LII; 3822 LII.Imm = 0; 3823 LII.SetCR = SetCR; 3824 LII.Is64Bit = SpecialShift64; 3825 uint64_t ShAmt = Imm & (SpecialShift32 ? 0x1F : 0x3F); 3826 if (Imm & (SpecialShift32 ? 0x20 : 0x40)) 3827 replaceInstrWithLI(MI, LII); 3828 // Shifts by zero don't change the value. If we don't need to set CR0, 3829 // just convert this to a COPY. Can't do this post-RA since we've already 3830 // cleaned up the copies. 3831 else if (!SetCR && ShAmt == 0 && !PostRA) { 3832 MI.RemoveOperand(2); 3833 MI.setDesc(get(PPC::COPY)); 3834 } else { 3835 // The 32 bit and 64 bit instructions are quite different. 3836 if (SpecialShift32) { 3837 // Left shifts use (N, 0, 31-N). 3838 // Right shifts use (32-N, N, 31) if 0 < N < 32. 3839 // use (0, 0, 31) if N == 0. 3840 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 32 - ShAmt : ShAmt; 3841 uint64_t MB = RightShift ? ShAmt : 0; 3842 uint64_t ME = RightShift ? 31 : 31 - ShAmt; 3843 replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH); 3844 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(MB) 3845 .addImm(ME); 3846 } else { 3847 // Left shifts use (N, 63-N). 3848 // Right shifts use (64-N, N) if 0 < N < 64. 3849 // use (0, 0) if N == 0. 3850 uint64_t SH = ShAmt == 0 ? 0 : RightShift ? 64 - ShAmt : ShAmt; 3851 uint64_t ME = RightShift ? ShAmt : 63 - ShAmt; 3852 replaceInstrOperandWithImm(MI, III.OpNoForForwarding, SH); 3853 MachineInstrBuilder(*MI.getParent()->getParent(), MI).addImm(ME); 3854 } 3855 } 3856 } else 3857 replaceInstrOperandWithImm(MI, ConstantOpNo, Imm); 3858 } 3859 // Convert commutative instructions (switch the operands and convert the 3860 // desired one to an immediate. 3861 else if (III.IsCommutative) { 3862 replaceInstrOperandWithImm(MI, ConstantOpNo, Imm); 3863 swapMIOperands(MI, ConstantOpNo, III.OpNoForForwarding); 3864 } else 3865 llvm_unreachable("Should have exited early!"); 3866 3867 // For instructions for which the constant register replaces a different 3868 // operand than where the immediate goes, we need to swap them. 3869 if (III.OpNoForForwarding != III.ImmOpNo) 3870 swapMIOperands(MI, III.OpNoForForwarding, III.ImmOpNo); 3871 3872 // If the special R0/X0 register index are different for original instruction 3873 // and new instruction, we need to fix up the register class in new 3874 // instruction. 3875 if (!PostRA && III.ZeroIsSpecialOrig != III.ZeroIsSpecialNew) { 3876 if (III.ZeroIsSpecialNew) { 3877 // If operand at III.ZeroIsSpecialNew is physical reg(eg: ZERO/ZERO8), no 3878 // need to fix up register class. 3879 Register RegToModify = MI.getOperand(III.ZeroIsSpecialNew).getReg(); 3880 if (Register::isVirtualRegister(RegToModify)) { 3881 const TargetRegisterClass *NewRC = 3882 MRI.getRegClass(RegToModify)->hasSuperClassEq(&PPC::GPRCRegClass) ? 3883 &PPC::GPRC_and_GPRC_NOR0RegClass : &PPC::G8RC_and_G8RC_NOX0RegClass; 3884 MRI.setRegClass(RegToModify, NewRC); 3885 } 3886 } 3887 } 3888 3889 // Fix up killed/dead flag after transformation. 3890 // Pattern: 3891 // ForwardKilledOperandReg = LI imm 3892 // y = XOP reg, ForwardKilledOperandReg(killed) 3893 if (ForwardKilledOperandReg != ~0U) 3894 fixupIsDeadOrKill(DefMI, MI, ForwardKilledOperandReg); 3895 return true; 3896 } 3897 3898 const TargetRegisterClass * 3899 PPCInstrInfo::updatedRC(const TargetRegisterClass *RC) const { 3900 if (Subtarget.hasVSX() && RC == &PPC::VRRCRegClass) 3901 return &PPC::VSRCRegClass; 3902 return RC; 3903 } 3904 3905 int PPCInstrInfo::getRecordFormOpcode(unsigned Opcode) { 3906 return PPC::getRecordFormOpcode(Opcode); 3907 } 3908 3909 // This function returns true if the machine instruction 3910 // always outputs a value by sign-extending a 32 bit value, 3911 // i.e. 0 to 31-th bits are same as 32-th bit. 3912 static bool isSignExtendingOp(const MachineInstr &MI) { 3913 int Opcode = MI.getOpcode(); 3914 if (Opcode == PPC::LI || Opcode == PPC::LI8 || Opcode == PPC::LIS || 3915 Opcode == PPC::LIS8 || Opcode == PPC::SRAW || Opcode == PPC::SRAW_rec || 3916 Opcode == PPC::SRAWI || Opcode == PPC::SRAWI_rec || Opcode == PPC::LWA || 3917 Opcode == PPC::LWAX || Opcode == PPC::LWA_32 || Opcode == PPC::LWAX_32 || 3918 Opcode == PPC::LHA || Opcode == PPC::LHAX || Opcode == PPC::LHA8 || 3919 Opcode == PPC::LHAX8 || Opcode == PPC::LBZ || Opcode == PPC::LBZX || 3920 Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || Opcode == PPC::LBZU || 3921 Opcode == PPC::LBZUX || Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 || 3922 Opcode == PPC::LHZ || Opcode == PPC::LHZX || Opcode == PPC::LHZ8 || 3923 Opcode == PPC::LHZX8 || Opcode == PPC::LHZU || Opcode == PPC::LHZUX || 3924 Opcode == PPC::LHZU8 || Opcode == PPC::LHZUX8 || Opcode == PPC::EXTSB || 3925 Opcode == PPC::EXTSB_rec || Opcode == PPC::EXTSH || 3926 Opcode == PPC::EXTSH_rec || Opcode == PPC::EXTSB8 || 3927 Opcode == PPC::EXTSH8 || Opcode == PPC::EXTSW || 3928 Opcode == PPC::EXTSW_rec || Opcode == PPC::SETB || Opcode == PPC::SETB8 || 3929 Opcode == PPC::EXTSH8_32_64 || Opcode == PPC::EXTSW_32_64 || 3930 Opcode == PPC::EXTSB8_32_64) 3931 return true; 3932 3933 if (Opcode == PPC::RLDICL && MI.getOperand(3).getImm() >= 33) 3934 return true; 3935 3936 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec || 3937 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec) && 3938 MI.getOperand(3).getImm() > 0 && 3939 MI.getOperand(3).getImm() <= MI.getOperand(4).getImm()) 3940 return true; 3941 3942 return false; 3943 } 3944 3945 // This function returns true if the machine instruction 3946 // always outputs zeros in higher 32 bits. 3947 static bool isZeroExtendingOp(const MachineInstr &MI) { 3948 int Opcode = MI.getOpcode(); 3949 // The 16-bit immediate is sign-extended in li/lis. 3950 // If the most significant bit is zero, all higher bits are zero. 3951 if (Opcode == PPC::LI || Opcode == PPC::LI8 || 3952 Opcode == PPC::LIS || Opcode == PPC::LIS8) { 3953 int64_t Imm = MI.getOperand(1).getImm(); 3954 if (((uint64_t)Imm & ~0x7FFFuLL) == 0) 3955 return true; 3956 } 3957 3958 // We have some variations of rotate-and-mask instructions 3959 // that clear higher 32-bits. 3960 if ((Opcode == PPC::RLDICL || Opcode == PPC::RLDICL_rec || 3961 Opcode == PPC::RLDCL || Opcode == PPC::RLDCL_rec || 3962 Opcode == PPC::RLDICL_32_64) && 3963 MI.getOperand(3).getImm() >= 32) 3964 return true; 3965 3966 if ((Opcode == PPC::RLDIC || Opcode == PPC::RLDIC_rec) && 3967 MI.getOperand(3).getImm() >= 32 && 3968 MI.getOperand(3).getImm() <= 63 - MI.getOperand(2).getImm()) 3969 return true; 3970 3971 if ((Opcode == PPC::RLWINM || Opcode == PPC::RLWINM_rec || 3972 Opcode == PPC::RLWNM || Opcode == PPC::RLWNM_rec || 3973 Opcode == PPC::RLWINM8 || Opcode == PPC::RLWNM8) && 3974 MI.getOperand(3).getImm() <= MI.getOperand(4).getImm()) 3975 return true; 3976 3977 // There are other instructions that clear higher 32-bits. 3978 if (Opcode == PPC::CNTLZW || Opcode == PPC::CNTLZW_rec || 3979 Opcode == PPC::CNTTZW || Opcode == PPC::CNTTZW_rec || 3980 Opcode == PPC::CNTLZW8 || Opcode == PPC::CNTTZW8 || 3981 Opcode == PPC::CNTLZD || Opcode == PPC::CNTLZD_rec || 3982 Opcode == PPC::CNTTZD || Opcode == PPC::CNTTZD_rec || 3983 Opcode == PPC::POPCNTD || Opcode == PPC::POPCNTW || Opcode == PPC::SLW || 3984 Opcode == PPC::SLW_rec || Opcode == PPC::SRW || Opcode == PPC::SRW_rec || 3985 Opcode == PPC::SLW8 || Opcode == PPC::SRW8 || Opcode == PPC::SLWI || 3986 Opcode == PPC::SLWI_rec || Opcode == PPC::SRWI || 3987 Opcode == PPC::SRWI_rec || Opcode == PPC::LWZ || Opcode == PPC::LWZX || 3988 Opcode == PPC::LWZU || Opcode == PPC::LWZUX || Opcode == PPC::LWBRX || 3989 Opcode == PPC::LHBRX || Opcode == PPC::LHZ || Opcode == PPC::LHZX || 3990 Opcode == PPC::LHZU || Opcode == PPC::LHZUX || Opcode == PPC::LBZ || 3991 Opcode == PPC::LBZX || Opcode == PPC::LBZU || Opcode == PPC::LBZUX || 3992 Opcode == PPC::LWZ8 || Opcode == PPC::LWZX8 || Opcode == PPC::LWZU8 || 3993 Opcode == PPC::LWZUX8 || Opcode == PPC::LWBRX8 || Opcode == PPC::LHBRX8 || 3994 Opcode == PPC::LHZ8 || Opcode == PPC::LHZX8 || Opcode == PPC::LHZU8 || 3995 Opcode == PPC::LHZUX8 || Opcode == PPC::LBZ8 || Opcode == PPC::LBZX8 || 3996 Opcode == PPC::LBZU8 || Opcode == PPC::LBZUX8 || 3997 Opcode == PPC::ANDI_rec || Opcode == PPC::ANDIS_rec || 3998 Opcode == PPC::ROTRWI || Opcode == PPC::ROTRWI_rec || 3999 Opcode == PPC::EXTLWI || Opcode == PPC::EXTLWI_rec || 4000 Opcode == PPC::MFVSRWZ) 4001 return true; 4002 4003 return false; 4004 } 4005 4006 // This function returns true if the input MachineInstr is a TOC save 4007 // instruction. 4008 bool PPCInstrInfo::isTOCSaveMI(const MachineInstr &MI) const { 4009 if (!MI.getOperand(1).isImm() || !MI.getOperand(2).isReg()) 4010 return false; 4011 unsigned TOCSaveOffset = Subtarget.getFrameLowering()->getTOCSaveOffset(); 4012 unsigned StackOffset = MI.getOperand(1).getImm(); 4013 Register StackReg = MI.getOperand(2).getReg(); 4014 if (StackReg == PPC::X1 && StackOffset == TOCSaveOffset) 4015 return true; 4016 4017 return false; 4018 } 4019 4020 // We limit the max depth to track incoming values of PHIs or binary ops 4021 // (e.g. AND) to avoid excessive cost. 4022 const unsigned MAX_DEPTH = 1; 4023 4024 bool 4025 PPCInstrInfo::isSignOrZeroExtended(const MachineInstr &MI, bool SignExt, 4026 const unsigned Depth) const { 4027 const MachineFunction *MF = MI.getParent()->getParent(); 4028 const MachineRegisterInfo *MRI = &MF->getRegInfo(); 4029 4030 // If we know this instruction returns sign- or zero-extended result, 4031 // return true. 4032 if (SignExt ? isSignExtendingOp(MI): 4033 isZeroExtendingOp(MI)) 4034 return true; 4035 4036 switch (MI.getOpcode()) { 4037 case PPC::COPY: { 4038 Register SrcReg = MI.getOperand(1).getReg(); 4039 4040 // In both ELFv1 and v2 ABI, method parameters and the return value 4041 // are sign- or zero-extended. 4042 if (MF->getSubtarget<PPCSubtarget>().isSVR4ABI()) { 4043 const PPCFunctionInfo *FuncInfo = MF->getInfo<PPCFunctionInfo>(); 4044 // We check the ZExt/SExt flags for a method parameter. 4045 if (MI.getParent()->getBasicBlock() == 4046 &MF->getFunction().getEntryBlock()) { 4047 Register VReg = MI.getOperand(0).getReg(); 4048 if (MF->getRegInfo().isLiveIn(VReg)) 4049 return SignExt ? FuncInfo->isLiveInSExt(VReg) : 4050 FuncInfo->isLiveInZExt(VReg); 4051 } 4052 4053 // For a method return value, we check the ZExt/SExt flags in attribute. 4054 // We assume the following code sequence for method call. 4055 // ADJCALLSTACKDOWN 32, implicit dead %r1, implicit %r1 4056 // BL8_NOP @func,... 4057 // ADJCALLSTACKUP 32, 0, implicit dead %r1, implicit %r1 4058 // %5 = COPY %x3; G8RC:%5 4059 if (SrcReg == PPC::X3) { 4060 const MachineBasicBlock *MBB = MI.getParent(); 4061 MachineBasicBlock::const_instr_iterator II = 4062 MachineBasicBlock::const_instr_iterator(&MI); 4063 if (II != MBB->instr_begin() && 4064 (--II)->getOpcode() == PPC::ADJCALLSTACKUP) { 4065 const MachineInstr &CallMI = *(--II); 4066 if (CallMI.isCall() && CallMI.getOperand(0).isGlobal()) { 4067 const Function *CalleeFn = 4068 dyn_cast<Function>(CallMI.getOperand(0).getGlobal()); 4069 if (!CalleeFn) 4070 return false; 4071 const IntegerType *IntTy = 4072 dyn_cast<IntegerType>(CalleeFn->getReturnType()); 4073 const AttributeSet &Attrs = 4074 CalleeFn->getAttributes().getRetAttributes(); 4075 if (IntTy && IntTy->getBitWidth() <= 32) 4076 return Attrs.hasAttribute(SignExt ? Attribute::SExt : 4077 Attribute::ZExt); 4078 } 4079 } 4080 } 4081 } 4082 4083 // If this is a copy from another register, we recursively check source. 4084 if (!Register::isVirtualRegister(SrcReg)) 4085 return false; 4086 const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 4087 if (SrcMI != NULL) 4088 return isSignOrZeroExtended(*SrcMI, SignExt, Depth); 4089 4090 return false; 4091 } 4092 4093 case PPC::ANDI_rec: 4094 case PPC::ANDIS_rec: 4095 case PPC::ORI: 4096 case PPC::ORIS: 4097 case PPC::XORI: 4098 case PPC::XORIS: 4099 case PPC::ANDI8_rec: 4100 case PPC::ANDIS8_rec: 4101 case PPC::ORI8: 4102 case PPC::ORIS8: 4103 case PPC::XORI8: 4104 case PPC::XORIS8: { 4105 // logical operation with 16-bit immediate does not change the upper bits. 4106 // So, we track the operand register as we do for register copy. 4107 Register SrcReg = MI.getOperand(1).getReg(); 4108 if (!Register::isVirtualRegister(SrcReg)) 4109 return false; 4110 const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 4111 if (SrcMI != NULL) 4112 return isSignOrZeroExtended(*SrcMI, SignExt, Depth); 4113 4114 return false; 4115 } 4116 4117 // If all incoming values are sign-/zero-extended, 4118 // the output of OR, ISEL or PHI is also sign-/zero-extended. 4119 case PPC::OR: 4120 case PPC::OR8: 4121 case PPC::ISEL: 4122 case PPC::PHI: { 4123 if (Depth >= MAX_DEPTH) 4124 return false; 4125 4126 // The input registers for PHI are operand 1, 3, ... 4127 // The input registers for others are operand 1 and 2. 4128 unsigned E = 3, D = 1; 4129 if (MI.getOpcode() == PPC::PHI) { 4130 E = MI.getNumOperands(); 4131 D = 2; 4132 } 4133 4134 for (unsigned I = 1; I != E; I += D) { 4135 if (MI.getOperand(I).isReg()) { 4136 Register SrcReg = MI.getOperand(I).getReg(); 4137 if (!Register::isVirtualRegister(SrcReg)) 4138 return false; 4139 const MachineInstr *SrcMI = MRI->getVRegDef(SrcReg); 4140 if (SrcMI == NULL || !isSignOrZeroExtended(*SrcMI, SignExt, Depth+1)) 4141 return false; 4142 } 4143 else 4144 return false; 4145 } 4146 return true; 4147 } 4148 4149 // If at least one of the incoming values of an AND is zero extended 4150 // then the output is also zero-extended. If both of the incoming values 4151 // are sign-extended then the output is also sign extended. 4152 case PPC::AND: 4153 case PPC::AND8: { 4154 if (Depth >= MAX_DEPTH) 4155 return false; 4156 4157 assert(MI.getOperand(1).isReg() && MI.getOperand(2).isReg()); 4158 4159 Register SrcReg1 = MI.getOperand(1).getReg(); 4160 Register SrcReg2 = MI.getOperand(2).getReg(); 4161 4162 if (!Register::isVirtualRegister(SrcReg1) || 4163 !Register::isVirtualRegister(SrcReg2)) 4164 return false; 4165 4166 const MachineInstr *MISrc1 = MRI->getVRegDef(SrcReg1); 4167 const MachineInstr *MISrc2 = MRI->getVRegDef(SrcReg2); 4168 if (!MISrc1 || !MISrc2) 4169 return false; 4170 4171 if(SignExt) 4172 return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) && 4173 isSignOrZeroExtended(*MISrc2, SignExt, Depth+1); 4174 else 4175 return isSignOrZeroExtended(*MISrc1, SignExt, Depth+1) || 4176 isSignOrZeroExtended(*MISrc2, SignExt, Depth+1); 4177 } 4178 4179 default: 4180 break; 4181 } 4182 return false; 4183 } 4184 4185 bool PPCInstrInfo::isBDNZ(unsigned Opcode) const { 4186 return (Opcode == (Subtarget.isPPC64() ? PPC::BDNZ8 : PPC::BDNZ)); 4187 } 4188 4189 namespace { 4190 class PPCPipelinerLoopInfo : public TargetInstrInfo::PipelinerLoopInfo { 4191 MachineInstr *Loop, *EndLoop, *LoopCount; 4192 MachineFunction *MF; 4193 const TargetInstrInfo *TII; 4194 int64_t TripCount; 4195 4196 public: 4197 PPCPipelinerLoopInfo(MachineInstr *Loop, MachineInstr *EndLoop, 4198 MachineInstr *LoopCount) 4199 : Loop(Loop), EndLoop(EndLoop), LoopCount(LoopCount), 4200 MF(Loop->getParent()->getParent()), 4201 TII(MF->getSubtarget().getInstrInfo()) { 4202 // Inspect the Loop instruction up-front, as it may be deleted when we call 4203 // createTripCountGreaterCondition. 4204 if (LoopCount->getOpcode() == PPC::LI8 || LoopCount->getOpcode() == PPC::LI) 4205 TripCount = LoopCount->getOperand(1).getImm(); 4206 else 4207 TripCount = -1; 4208 } 4209 4210 bool shouldIgnoreForPipelining(const MachineInstr *MI) const override { 4211 // Only ignore the terminator. 4212 return MI == EndLoop; 4213 } 4214 4215 Optional<bool> 4216 createTripCountGreaterCondition(int TC, MachineBasicBlock &MBB, 4217 SmallVectorImpl<MachineOperand> &Cond) override { 4218 if (TripCount == -1) { 4219 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1, 4220 // so we don't need to generate any thing here. 4221 Cond.push_back(MachineOperand::CreateImm(0)); 4222 Cond.push_back(MachineOperand::CreateReg( 4223 MF->getSubtarget<PPCSubtarget>().isPPC64() ? PPC::CTR8 : PPC::CTR, 4224 true)); 4225 return {}; 4226 } 4227 4228 return TripCount > TC; 4229 } 4230 4231 void setPreheader(MachineBasicBlock *NewPreheader) override { 4232 // Do nothing. We want the LOOP setup instruction to stay in the *old* 4233 // preheader, so we can use BDZ in the prologs to adapt the loop trip count. 4234 } 4235 4236 void adjustTripCount(int TripCountAdjust) override { 4237 // If the loop trip count is a compile-time value, then just change the 4238 // value. 4239 if (LoopCount->getOpcode() == PPC::LI8 || 4240 LoopCount->getOpcode() == PPC::LI) { 4241 int64_t TripCount = LoopCount->getOperand(1).getImm() + TripCountAdjust; 4242 LoopCount->getOperand(1).setImm(TripCount); 4243 return; 4244 } 4245 4246 // Since BDZ/BDZ8 that we will insert will also decrease the ctr by 1, 4247 // so we don't need to generate any thing here. 4248 } 4249 4250 void disposed() override { 4251 Loop->eraseFromParent(); 4252 // Ensure the loop setup instruction is deleted too. 4253 LoopCount->eraseFromParent(); 4254 } 4255 }; 4256 } // namespace 4257 4258 std::unique_ptr<TargetInstrInfo::PipelinerLoopInfo> 4259 PPCInstrInfo::analyzeLoopForPipelining(MachineBasicBlock *LoopBB) const { 4260 // We really "analyze" only hardware loops right now. 4261 MachineBasicBlock::iterator I = LoopBB->getFirstTerminator(); 4262 MachineBasicBlock *Preheader = *LoopBB->pred_begin(); 4263 if (Preheader == LoopBB) 4264 Preheader = *std::next(LoopBB->pred_begin()); 4265 MachineFunction *MF = Preheader->getParent(); 4266 4267 if (I != LoopBB->end() && isBDNZ(I->getOpcode())) { 4268 SmallPtrSet<MachineBasicBlock *, 8> Visited; 4269 if (MachineInstr *LoopInst = findLoopInstr(*Preheader, Visited)) { 4270 Register LoopCountReg = LoopInst->getOperand(0).getReg(); 4271 MachineRegisterInfo &MRI = MF->getRegInfo(); 4272 MachineInstr *LoopCount = MRI.getUniqueVRegDef(LoopCountReg); 4273 return std::make_unique<PPCPipelinerLoopInfo>(LoopInst, &*I, LoopCount); 4274 } 4275 } 4276 return nullptr; 4277 } 4278 4279 MachineInstr *PPCInstrInfo::findLoopInstr( 4280 MachineBasicBlock &PreHeader, 4281 SmallPtrSet<MachineBasicBlock *, 8> &Visited) const { 4282 4283 unsigned LOOPi = (Subtarget.isPPC64() ? PPC::MTCTR8loop : PPC::MTCTRloop); 4284 4285 // The loop set-up instruction should be in preheader 4286 for (auto &I : PreHeader.instrs()) 4287 if (I.getOpcode() == LOOPi) 4288 return &I; 4289 return nullptr; 4290 } 4291 4292 // Return true if get the base operand, byte offset of an instruction and the 4293 // memory width. Width is the size of memory that is being loaded/stored. 4294 bool PPCInstrInfo::getMemOperandWithOffsetWidth( 4295 const MachineInstr &LdSt, const MachineOperand *&BaseReg, int64_t &Offset, 4296 unsigned &Width, const TargetRegisterInfo *TRI) const { 4297 if (!LdSt.mayLoadOrStore()) 4298 return false; 4299 4300 // Handle only loads/stores with base register followed by immediate offset. 4301 if (LdSt.getNumExplicitOperands() != 3) 4302 return false; 4303 if (!LdSt.getOperand(1).isImm() || !LdSt.getOperand(2).isReg()) 4304 return false; 4305 4306 if (!LdSt.hasOneMemOperand()) 4307 return false; 4308 4309 Width = (*LdSt.memoperands_begin())->getSize(); 4310 Offset = LdSt.getOperand(1).getImm(); 4311 BaseReg = &LdSt.getOperand(2); 4312 return true; 4313 } 4314 4315 bool PPCInstrInfo::areMemAccessesTriviallyDisjoint( 4316 const MachineInstr &MIa, const MachineInstr &MIb) const { 4317 assert(MIa.mayLoadOrStore() && "MIa must be a load or store."); 4318 assert(MIb.mayLoadOrStore() && "MIb must be a load or store."); 4319 4320 if (MIa.hasUnmodeledSideEffects() || MIb.hasUnmodeledSideEffects() || 4321 MIa.hasOrderedMemoryRef() || MIb.hasOrderedMemoryRef()) 4322 return false; 4323 4324 // Retrieve the base register, offset from the base register and width. Width 4325 // is the size of memory that is being loaded/stored (e.g. 1, 2, 4). If 4326 // base registers are identical, and the offset of a lower memory access + 4327 // the width doesn't overlap the offset of a higher memory access, 4328 // then the memory accesses are different. 4329 const TargetRegisterInfo *TRI = &getRegisterInfo(); 4330 const MachineOperand *BaseOpA = nullptr, *BaseOpB = nullptr; 4331 int64_t OffsetA = 0, OffsetB = 0; 4332 unsigned int WidthA = 0, WidthB = 0; 4333 if (getMemOperandWithOffsetWidth(MIa, BaseOpA, OffsetA, WidthA, TRI) && 4334 getMemOperandWithOffsetWidth(MIb, BaseOpB, OffsetB, WidthB, TRI)) { 4335 if (BaseOpA->isIdenticalTo(*BaseOpB)) { 4336 int LowOffset = std::min(OffsetA, OffsetB); 4337 int HighOffset = std::max(OffsetA, OffsetB); 4338 int LowWidth = (LowOffset == OffsetA) ? WidthA : WidthB; 4339 if (LowOffset + LowWidth <= HighOffset) 4340 return true; 4341 } 4342 } 4343 return false; 4344 } 4345