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