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