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