1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file defines a pattern matching instruction selector for PowerPC, 11 // converting from a legalized dag to a PPC dag. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "MCTargetDesc/PPCMCTargetDesc.h" 16 #include "MCTargetDesc/PPCPredicates.h" 17 #include "PPC.h" 18 #include "PPCISelLowering.h" 19 #include "PPCMachineFunctionInfo.h" 20 #include "PPCSubtarget.h" 21 #include "PPCTargetMachine.h" 22 #include "llvm/ADT/APInt.h" 23 #include "llvm/ADT/DenseMap.h" 24 #include "llvm/ADT/STLExtras.h" 25 #include "llvm/ADT/SmallPtrSet.h" 26 #include "llvm/ADT/SmallVector.h" 27 #include "llvm/ADT/Statistic.h" 28 #include "llvm/Analysis/BranchProbabilityInfo.h" 29 #include "llvm/CodeGen/FunctionLoweringInfo.h" 30 #include "llvm/CodeGen/ISDOpcodes.h" 31 #include "llvm/CodeGen/MachineBasicBlock.h" 32 #include "llvm/CodeGen/MachineFunction.h" 33 #include "llvm/CodeGen/MachineInstrBuilder.h" 34 #include "llvm/CodeGen/MachineRegisterInfo.h" 35 #include "llvm/CodeGen/SelectionDAG.h" 36 #include "llvm/CodeGen/SelectionDAGISel.h" 37 #include "llvm/CodeGen/SelectionDAGNodes.h" 38 #include "llvm/CodeGen/TargetInstrInfo.h" 39 #include "llvm/CodeGen/TargetRegisterInfo.h" 40 #include "llvm/CodeGen/ValueTypes.h" 41 #include "llvm/IR/BasicBlock.h" 42 #include "llvm/IR/DebugLoc.h" 43 #include "llvm/IR/Function.h" 44 #include "llvm/IR/GlobalValue.h" 45 #include "llvm/IR/InlineAsm.h" 46 #include "llvm/IR/InstrTypes.h" 47 #include "llvm/IR/Module.h" 48 #include "llvm/Support/Casting.h" 49 #include "llvm/Support/CodeGen.h" 50 #include "llvm/Support/CommandLine.h" 51 #include "llvm/Support/Compiler.h" 52 #include "llvm/Support/Debug.h" 53 #include "llvm/Support/ErrorHandling.h" 54 #include "llvm/Support/KnownBits.h" 55 #include "llvm/Support/MachineValueType.h" 56 #include "llvm/Support/MathExtras.h" 57 #include "llvm/Support/raw_ostream.h" 58 #include <algorithm> 59 #include <cassert> 60 #include <cstdint> 61 #include <iterator> 62 #include <limits> 63 #include <memory> 64 #include <new> 65 #include <tuple> 66 #include <utility> 67 68 using namespace llvm; 69 70 #define DEBUG_TYPE "ppc-codegen" 71 72 STATISTIC(NumSextSetcc, 73 "Number of (sext(setcc)) nodes expanded into GPR sequence."); 74 STATISTIC(NumZextSetcc, 75 "Number of (zext(setcc)) nodes expanded into GPR sequence."); 76 STATISTIC(SignExtensionsAdded, 77 "Number of sign extensions for compare inputs added."); 78 STATISTIC(ZeroExtensionsAdded, 79 "Number of zero extensions for compare inputs added."); 80 STATISTIC(NumLogicOpsOnComparison, 81 "Number of logical ops on i1 values calculated in GPR."); 82 STATISTIC(OmittedForNonExtendUses, 83 "Number of compares not eliminated as they have non-extending uses."); 84 STATISTIC(NumP9Setb, 85 "Number of compares lowered to setb."); 86 87 // FIXME: Remove this once the bug has been fixed! 88 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug", 89 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden); 90 91 static cl::opt<bool> 92 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true), 93 cl::desc("use aggressive ppc isel for bit permutations"), 94 cl::Hidden); 95 static cl::opt<bool> BPermRewriterNoMasking( 96 "ppc-bit-perm-rewriter-stress-rotates", 97 cl::desc("stress rotate selection in aggressive ppc isel for " 98 "bit permutations"), 99 cl::Hidden); 100 101 static cl::opt<bool> EnableBranchHint( 102 "ppc-use-branch-hint", cl::init(true), 103 cl::desc("Enable static hinting of branches on ppc"), 104 cl::Hidden); 105 106 static cl::opt<bool> EnableTLSOpt( 107 "ppc-tls-opt", cl::init(true), 108 cl::desc("Enable tls optimization peephole"), 109 cl::Hidden); 110 111 enum ICmpInGPRType { ICGPR_All, ICGPR_None, ICGPR_I32, ICGPR_I64, 112 ICGPR_NonExtIn, ICGPR_Zext, ICGPR_Sext, ICGPR_ZextI32, 113 ICGPR_SextI32, ICGPR_ZextI64, ICGPR_SextI64 }; 114 115 static cl::opt<ICmpInGPRType> CmpInGPR( 116 "ppc-gpr-icmps", cl::Hidden, cl::init(ICGPR_All), 117 cl::desc("Specify the types of comparisons to emit GPR-only code for."), 118 cl::values(clEnumValN(ICGPR_None, "none", "Do not modify integer comparisons."), 119 clEnumValN(ICGPR_All, "all", "All possible int comparisons in GPRs."), 120 clEnumValN(ICGPR_I32, "i32", "Only i32 comparisons in GPRs."), 121 clEnumValN(ICGPR_I64, "i64", "Only i64 comparisons in GPRs."), 122 clEnumValN(ICGPR_NonExtIn, "nonextin", 123 "Only comparisons where inputs don't need [sz]ext."), 124 clEnumValN(ICGPR_Zext, "zext", "Only comparisons with zext result."), 125 clEnumValN(ICGPR_ZextI32, "zexti32", 126 "Only i32 comparisons with zext result."), 127 clEnumValN(ICGPR_ZextI64, "zexti64", 128 "Only i64 comparisons with zext result."), 129 clEnumValN(ICGPR_Sext, "sext", "Only comparisons with sext result."), 130 clEnumValN(ICGPR_SextI32, "sexti32", 131 "Only i32 comparisons with sext result."), 132 clEnumValN(ICGPR_SextI64, "sexti64", 133 "Only i64 comparisons with sext result."))); 134 namespace { 135 136 //===--------------------------------------------------------------------===// 137 /// PPCDAGToDAGISel - PPC specific code to select PPC machine 138 /// instructions for SelectionDAG operations. 139 /// 140 class PPCDAGToDAGISel : public SelectionDAGISel { 141 const PPCTargetMachine &TM; 142 const PPCSubtarget *PPCSubTarget; 143 const PPCTargetLowering *PPCLowering; 144 unsigned GlobalBaseReg; 145 146 public: 147 explicit PPCDAGToDAGISel(PPCTargetMachine &tm, CodeGenOpt::Level OptLevel) 148 : SelectionDAGISel(tm, OptLevel), TM(tm) {} 149 150 bool runOnMachineFunction(MachineFunction &MF) override { 151 // Make sure we re-emit a set of the global base reg if necessary 152 GlobalBaseReg = 0; 153 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>(); 154 PPCLowering = PPCSubTarget->getTargetLowering(); 155 SelectionDAGISel::runOnMachineFunction(MF); 156 157 if (!PPCSubTarget->isSVR4ABI()) 158 InsertVRSaveCode(MF); 159 160 return true; 161 } 162 163 void PreprocessISelDAG() override; 164 void PostprocessISelDAG() override; 165 166 /// getI16Imm - Return a target constant with the specified value, of type 167 /// i16. 168 inline SDValue getI16Imm(unsigned Imm, const SDLoc &dl) { 169 return CurDAG->getTargetConstant(Imm, dl, MVT::i16); 170 } 171 172 /// getI32Imm - Return a target constant with the specified value, of type 173 /// i32. 174 inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) { 175 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 176 } 177 178 /// getI64Imm - Return a target constant with the specified value, of type 179 /// i64. 180 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) { 181 return CurDAG->getTargetConstant(Imm, dl, MVT::i64); 182 } 183 184 /// getSmallIPtrImm - Return a target constant of pointer type. 185 inline SDValue getSmallIPtrImm(unsigned Imm, const SDLoc &dl) { 186 return CurDAG->getTargetConstant( 187 Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout())); 188 } 189 190 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a 191 /// rotate and mask opcode and mask operation. 192 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask, 193 unsigned &SH, unsigned &MB, unsigned &ME); 194 195 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC 196 /// base register. Return the virtual register that holds this value. 197 SDNode *getGlobalBaseReg(); 198 199 void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0); 200 201 // Select - Convert the specified operand from a target-independent to a 202 // target-specific node if it hasn't already been changed. 203 void Select(SDNode *N) override; 204 205 bool tryBitfieldInsert(SDNode *N); 206 bool tryBitPermutation(SDNode *N); 207 bool tryIntCompareInGPR(SDNode *N); 208 209 // tryTLSXFormLoad - Convert an ISD::LOAD fed by a PPCISD::ADD_TLS into 210 // an X-Form load instruction with the offset being a relocation coming from 211 // the PPCISD::ADD_TLS. 212 bool tryTLSXFormLoad(LoadSDNode *N); 213 // tryTLSXFormStore - Convert an ISD::STORE fed by a PPCISD::ADD_TLS into 214 // an X-Form store instruction with the offset being a relocation coming from 215 // the PPCISD::ADD_TLS. 216 bool tryTLSXFormStore(StoreSDNode *N); 217 /// SelectCC - Select a comparison of the specified values with the 218 /// specified condition code, returning the CR# of the expression. 219 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, 220 const SDLoc &dl); 221 222 /// SelectAddrImm - Returns true if the address N can be represented by 223 /// a base register plus a signed 16-bit displacement [r+imm]. 224 bool SelectAddrImm(SDValue N, SDValue &Disp, 225 SDValue &Base) { 226 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 0); 227 } 228 229 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc 230 /// immediate field. Note that the operand at this point is already the 231 /// result of a prior SelectAddressRegImm call. 232 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const { 233 if (N.getOpcode() == ISD::TargetConstant || 234 N.getOpcode() == ISD::TargetGlobalAddress) { 235 Out = N; 236 return true; 237 } 238 239 return false; 240 } 241 242 /// SelectAddrIdx - Given the specified addressed, check to see if it can be 243 /// represented as an indexed [r+r] operation. Returns false if it can 244 /// be represented by [r+imm], which are preferred. 245 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) { 246 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG); 247 } 248 249 /// SelectAddrIdxOnly - Given the specified addressed, force it to be 250 /// represented as an indexed [r+r] operation. 251 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) { 252 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG); 253 } 254 255 /// SelectAddrImmX4 - Returns true if the address N can be represented by 256 /// a base register plus a signed 16-bit displacement that is a multiple of 4. 257 /// Suitable for use by STD and friends. 258 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) { 259 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 4); 260 } 261 262 bool SelectAddrImmX16(SDValue N, SDValue &Disp, SDValue &Base) { 263 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, 16); 264 } 265 266 // Select an address into a single register. 267 bool SelectAddr(SDValue N, SDValue &Base) { 268 Base = N; 269 return true; 270 } 271 272 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for 273 /// inline asm expressions. It is always correct to compute the value into 274 /// a register. The case of adding a (possibly relocatable) constant to a 275 /// register can be improved, but it is wrong to substitute Reg+Reg for 276 /// Reg in an asm, because the load or store opcode would have to change. 277 bool SelectInlineAsmMemoryOperand(const SDValue &Op, 278 unsigned ConstraintID, 279 std::vector<SDValue> &OutOps) override { 280 switch(ConstraintID) { 281 default: 282 errs() << "ConstraintID: " << ConstraintID << "\n"; 283 llvm_unreachable("Unexpected asm memory constraint"); 284 case InlineAsm::Constraint_es: 285 case InlineAsm::Constraint_i: 286 case InlineAsm::Constraint_m: 287 case InlineAsm::Constraint_o: 288 case InlineAsm::Constraint_Q: 289 case InlineAsm::Constraint_Z: 290 case InlineAsm::Constraint_Zy: 291 // We need to make sure that this one operand does not end up in r0 292 // (because we might end up lowering this as 0(%op)). 293 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo(); 294 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1); 295 SDLoc dl(Op); 296 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32); 297 SDValue NewOp = 298 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 299 dl, Op.getValueType(), 300 Op, RC), 0); 301 302 OutOps.push_back(NewOp); 303 return false; 304 } 305 return true; 306 } 307 308 void InsertVRSaveCode(MachineFunction &MF); 309 310 StringRef getPassName() const override { 311 return "PowerPC DAG->DAG Pattern Instruction Selection"; 312 } 313 314 // Include the pieces autogenerated from the target description. 315 #include "PPCGenDAGISel.inc" 316 317 private: 318 bool trySETCC(SDNode *N); 319 320 void PeepholePPC64(); 321 void PeepholePPC64ZExt(); 322 void PeepholeCROps(); 323 324 SDValue combineToCMPB(SDNode *N); 325 void foldBoolExts(SDValue &Res, SDNode *&N); 326 327 bool AllUsersSelectZero(SDNode *N); 328 void SwapAllSelectUsers(SDNode *N); 329 330 bool isOffsetMultipleOf(SDNode *N, unsigned Val) const; 331 void transferMemOperands(SDNode *N, SDNode *Result); 332 }; 333 334 } // end anonymous namespace 335 336 /// InsertVRSaveCode - Once the entire function has been instruction selected, 337 /// all virtual registers are created and all machine instructions are built, 338 /// check to see if we need to save/restore VRSAVE. If so, do it. 339 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) { 340 // Check to see if this function uses vector registers, which means we have to 341 // save and restore the VRSAVE register and update it with the regs we use. 342 // 343 // In this case, there will be virtual registers of vector type created 344 // by the scheduler. Detect them now. 345 bool HasVectorVReg = false; 346 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) { 347 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 348 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) { 349 HasVectorVReg = true; 350 break; 351 } 352 } 353 if (!HasVectorVReg) return; // nothing to do. 354 355 // If we have a vector register, we want to emit code into the entry and exit 356 // blocks to save and restore the VRSAVE register. We do this here (instead 357 // of marking all vector instructions as clobbering VRSAVE) for two reasons: 358 // 359 // 1. This (trivially) reduces the load on the register allocator, by not 360 // having to represent the live range of the VRSAVE register. 361 // 2. This (more significantly) allows us to create a temporary virtual 362 // register to hold the saved VRSAVE value, allowing this temporary to be 363 // register allocated, instead of forcing it to be spilled to the stack. 364 365 // Create two vregs - one to hold the VRSAVE register that is live-in to the 366 // function and one for the value after having bits or'd into it. 367 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass); 368 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass); 369 370 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo(); 371 MachineBasicBlock &EntryBB = *Fn.begin(); 372 DebugLoc dl; 373 // Emit the following code into the entry block: 374 // InVRSAVE = MFVRSAVE 375 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE 376 // MTVRSAVE UpdatedVRSAVE 377 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point 378 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE); 379 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE), 380 UpdatedVRSAVE).addReg(InVRSAVE); 381 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE); 382 383 // Find all return blocks, outputting a restore in each epilog. 384 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) { 385 if (BB->isReturnBlock()) { 386 IP = BB->end(); --IP; 387 388 // Skip over all terminator instructions, which are part of the return 389 // sequence. 390 MachineBasicBlock::iterator I2 = IP; 391 while (I2 != BB->begin() && (--I2)->isTerminator()) 392 IP = I2; 393 394 // Emit: MTVRSAVE InVRSave 395 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE); 396 } 397 } 398 } 399 400 /// getGlobalBaseReg - Output the instructions required to put the 401 /// base address to use for accessing globals into a register. 402 /// 403 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() { 404 if (!GlobalBaseReg) { 405 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo(); 406 // Insert the set of GlobalBaseReg into the first MBB of the function 407 MachineBasicBlock &FirstMBB = MF->front(); 408 MachineBasicBlock::iterator MBBI = FirstMBB.begin(); 409 const Module *M = MF->getFunction().getParent(); 410 DebugLoc dl; 411 412 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) { 413 if (PPCSubTarget->isTargetELF()) { 414 GlobalBaseReg = PPC::R30; 415 if (M->getPICLevel() == PICLevel::SmallPIC) { 416 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR)); 417 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 418 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true); 419 } else { 420 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR)); 421 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 422 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass); 423 BuildMI(FirstMBB, MBBI, dl, 424 TII.get(PPC::UpdateGBR), GlobalBaseReg) 425 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg); 426 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true); 427 } 428 } else { 429 GlobalBaseReg = 430 RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass); 431 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR)); 432 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 433 } 434 } else { 435 // We must ensure that this sequence is dominated by the prologue. 436 // FIXME: This is a bit of a big hammer since we don't get the benefits 437 // of shrink-wrapping whenever we emit this instruction. Considering 438 // this is used in any function where we emit a jump table, this may be 439 // a significant limitation. We should consider inserting this in the 440 // block where it is used and then commoning this sequence up if it 441 // appears in multiple places. 442 // Note: on ISA 3.0 cores, we can use lnia (addpcis) instead of 443 // MovePCtoLR8. 444 MF->getInfo<PPCFunctionInfo>()->setShrinkWrapDisabled(true); 445 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass); 446 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8)); 447 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg); 448 } 449 } 450 return CurDAG->getRegister(GlobalBaseReg, 451 PPCLowering->getPointerTy(CurDAG->getDataLayout())) 452 .getNode(); 453 } 454 455 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant 456 /// operand. If so Imm will receive the 32-bit value. 457 static bool isInt32Immediate(SDNode *N, unsigned &Imm) { 458 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) { 459 Imm = cast<ConstantSDNode>(N)->getZExtValue(); 460 return true; 461 } 462 return false; 463 } 464 465 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant 466 /// operand. If so Imm will receive the 64-bit value. 467 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) { 468 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) { 469 Imm = cast<ConstantSDNode>(N)->getZExtValue(); 470 return true; 471 } 472 return false; 473 } 474 475 // isInt32Immediate - This method tests to see if a constant operand. 476 // If so Imm will receive the 32 bit value. 477 static bool isInt32Immediate(SDValue N, unsigned &Imm) { 478 return isInt32Immediate(N.getNode(), Imm); 479 } 480 481 /// isInt64Immediate - This method tests to see if the value is a 64-bit 482 /// constant operand. If so Imm will receive the 64-bit value. 483 static bool isInt64Immediate(SDValue N, uint64_t &Imm) { 484 return isInt64Immediate(N.getNode(), Imm); 485 } 486 487 static unsigned getBranchHint(unsigned PCC, FunctionLoweringInfo *FuncInfo, 488 const SDValue &DestMBB) { 489 assert(isa<BasicBlockSDNode>(DestMBB)); 490 491 if (!FuncInfo->BPI) return PPC::BR_NO_HINT; 492 493 const BasicBlock *BB = FuncInfo->MBB->getBasicBlock(); 494 const Instruction *BBTerm = BB->getTerminator(); 495 496 if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT; 497 498 const BasicBlock *TBB = BBTerm->getSuccessor(0); 499 const BasicBlock *FBB = BBTerm->getSuccessor(1); 500 501 auto TProb = FuncInfo->BPI->getEdgeProbability(BB, TBB); 502 auto FProb = FuncInfo->BPI->getEdgeProbability(BB, FBB); 503 504 // We only want to handle cases which are easy to predict at static time, e.g. 505 // C++ throw statement, that is very likely not taken, or calling never 506 // returned function, e.g. stdlib exit(). So we set Threshold to filter 507 // unwanted cases. 508 // 509 // Below is LLVM branch weight table, we only want to handle case 1, 2 510 // 511 // Case Taken:Nontaken Example 512 // 1. Unreachable 1048575:1 C++ throw, stdlib exit(), 513 // 2. Invoke-terminating 1:1048575 514 // 3. Coldblock 4:64 __builtin_expect 515 // 4. Loop Branch 124:4 For loop 516 // 5. PH/ZH/FPH 20:12 517 const uint32_t Threshold = 10000; 518 519 if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb)) 520 return PPC::BR_NO_HINT; 521 522 LLVM_DEBUG(dbgs() << "Use branch hint for '" << FuncInfo->Fn->getName() 523 << "::" << BB->getName() << "'\n" 524 << " -> " << TBB->getName() << ": " << TProb << "\n" 525 << " -> " << FBB->getName() << ": " << FProb << "\n"); 526 527 const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB); 528 529 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities, 530 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock 531 if (BBDN->getBasicBlock()->getBasicBlock() != TBB) 532 std::swap(TProb, FProb); 533 534 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT; 535 } 536 537 // isOpcWithIntImmediate - This method tests to see if the node is a specific 538 // opcode and that it has a immediate integer right operand. 539 // If so Imm will receive the 32 bit value. 540 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) { 541 return N->getOpcode() == Opc 542 && isInt32Immediate(N->getOperand(1).getNode(), Imm); 543 } 544 545 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) { 546 SDLoc dl(SN); 547 int FI = cast<FrameIndexSDNode>(N)->getIndex(); 548 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0)); 549 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8; 550 if (SN->hasOneUse()) 551 CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI, 552 getSmallIPtrImm(Offset, dl)); 553 else 554 ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI, 555 getSmallIPtrImm(Offset, dl))); 556 } 557 558 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask, 559 bool isShiftMask, unsigned &SH, 560 unsigned &MB, unsigned &ME) { 561 // Don't even go down this path for i64, since different logic will be 562 // necessary for rldicl/rldicr/rldimi. 563 if (N->getValueType(0) != MVT::i32) 564 return false; 565 566 unsigned Shift = 32; 567 unsigned Indeterminant = ~0; // bit mask marking indeterminant results 568 unsigned Opcode = N->getOpcode(); 569 if (N->getNumOperands() != 2 || 570 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31)) 571 return false; 572 573 if (Opcode == ISD::SHL) { 574 // apply shift left to mask if it comes first 575 if (isShiftMask) Mask = Mask << Shift; 576 // determine which bits are made indeterminant by shift 577 Indeterminant = ~(0xFFFFFFFFu << Shift); 578 } else if (Opcode == ISD::SRL) { 579 // apply shift right to mask if it comes first 580 if (isShiftMask) Mask = Mask >> Shift; 581 // determine which bits are made indeterminant by shift 582 Indeterminant = ~(0xFFFFFFFFu >> Shift); 583 // adjust for the left rotate 584 Shift = 32 - Shift; 585 } else if (Opcode == ISD::ROTL) { 586 Indeterminant = 0; 587 } else { 588 return false; 589 } 590 591 // if the mask doesn't intersect any Indeterminant bits 592 if (Mask && !(Mask & Indeterminant)) { 593 SH = Shift & 31; 594 // make sure the mask is still a mask (wrap arounds may not be) 595 return isRunOfOnes(Mask, MB, ME); 596 } 597 return false; 598 } 599 600 bool PPCDAGToDAGISel::tryTLSXFormStore(StoreSDNode *ST) { 601 SDValue Base = ST->getBasePtr(); 602 if (Base.getOpcode() != PPCISD::ADD_TLS) 603 return false; 604 SDValue Offset = ST->getOffset(); 605 if (!Offset.isUndef()) 606 return false; 607 608 SDLoc dl(ST); 609 EVT MemVT = ST->getMemoryVT(); 610 EVT RegVT = ST->getValue().getValueType(); 611 612 unsigned Opcode; 613 switch (MemVT.getSimpleVT().SimpleTy) { 614 default: 615 return false; 616 case MVT::i8: { 617 Opcode = (RegVT == MVT::i32) ? PPC::STBXTLS_32 : PPC::STBXTLS; 618 break; 619 } 620 case MVT::i16: { 621 Opcode = (RegVT == MVT::i32) ? PPC::STHXTLS_32 : PPC::STHXTLS; 622 break; 623 } 624 case MVT::i32: { 625 Opcode = (RegVT == MVT::i32) ? PPC::STWXTLS_32 : PPC::STWXTLS; 626 break; 627 } 628 case MVT::i64: { 629 Opcode = PPC::STDXTLS; 630 break; 631 } 632 } 633 SDValue Chain = ST->getChain(); 634 SDVTList VTs = ST->getVTList(); 635 SDValue Ops[] = {ST->getValue(), Base.getOperand(0), Base.getOperand(1), 636 Chain}; 637 SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops); 638 transferMemOperands(ST, MN); 639 ReplaceNode(ST, MN); 640 return true; 641 } 642 643 bool PPCDAGToDAGISel::tryTLSXFormLoad(LoadSDNode *LD) { 644 SDValue Base = LD->getBasePtr(); 645 if (Base.getOpcode() != PPCISD::ADD_TLS) 646 return false; 647 SDValue Offset = LD->getOffset(); 648 if (!Offset.isUndef()) 649 return false; 650 651 SDLoc dl(LD); 652 EVT MemVT = LD->getMemoryVT(); 653 EVT RegVT = LD->getValueType(0); 654 unsigned Opcode; 655 switch (MemVT.getSimpleVT().SimpleTy) { 656 default: 657 return false; 658 case MVT::i8: { 659 Opcode = (RegVT == MVT::i32) ? PPC::LBZXTLS_32 : PPC::LBZXTLS; 660 break; 661 } 662 case MVT::i16: { 663 Opcode = (RegVT == MVT::i32) ? PPC::LHZXTLS_32 : PPC::LHZXTLS; 664 break; 665 } 666 case MVT::i32: { 667 Opcode = (RegVT == MVT::i32) ? PPC::LWZXTLS_32 : PPC::LWZXTLS; 668 break; 669 } 670 case MVT::i64: { 671 Opcode = PPC::LDXTLS; 672 break; 673 } 674 } 675 SDValue Chain = LD->getChain(); 676 SDVTList VTs = LD->getVTList(); 677 SDValue Ops[] = {Base.getOperand(0), Base.getOperand(1), Chain}; 678 SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops); 679 transferMemOperands(LD, MN); 680 ReplaceNode(LD, MN); 681 return true; 682 } 683 684 /// Turn an or of two masked values into the rotate left word immediate then 685 /// mask insert (rlwimi) instruction. 686 bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) { 687 SDValue Op0 = N->getOperand(0); 688 SDValue Op1 = N->getOperand(1); 689 SDLoc dl(N); 690 691 KnownBits LKnown, RKnown; 692 CurDAG->computeKnownBits(Op0, LKnown); 693 CurDAG->computeKnownBits(Op1, RKnown); 694 695 unsigned TargetMask = LKnown.Zero.getZExtValue(); 696 unsigned InsertMask = RKnown.Zero.getZExtValue(); 697 698 if ((TargetMask | InsertMask) == 0xFFFFFFFF) { 699 unsigned Op0Opc = Op0.getOpcode(); 700 unsigned Op1Opc = Op1.getOpcode(); 701 unsigned Value, SH = 0; 702 TargetMask = ~TargetMask; 703 InsertMask = ~InsertMask; 704 705 // If the LHS has a foldable shift and the RHS does not, then swap it to the 706 // RHS so that we can fold the shift into the insert. 707 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) { 708 if (Op0.getOperand(0).getOpcode() == ISD::SHL || 709 Op0.getOperand(0).getOpcode() == ISD::SRL) { 710 if (Op1.getOperand(0).getOpcode() != ISD::SHL && 711 Op1.getOperand(0).getOpcode() != ISD::SRL) { 712 std::swap(Op0, Op1); 713 std::swap(Op0Opc, Op1Opc); 714 std::swap(TargetMask, InsertMask); 715 } 716 } 717 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) { 718 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL && 719 Op1.getOperand(0).getOpcode() != ISD::SRL) { 720 std::swap(Op0, Op1); 721 std::swap(Op0Opc, Op1Opc); 722 std::swap(TargetMask, InsertMask); 723 } 724 } 725 726 unsigned MB, ME; 727 if (isRunOfOnes(InsertMask, MB, ME)) { 728 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) && 729 isInt32Immediate(Op1.getOperand(1), Value)) { 730 Op1 = Op1.getOperand(0); 731 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value; 732 } 733 if (Op1Opc == ISD::AND) { 734 // The AND mask might not be a constant, and we need to make sure that 735 // if we're going to fold the masking with the insert, all bits not 736 // know to be zero in the mask are known to be one. 737 KnownBits MKnown; 738 CurDAG->computeKnownBits(Op1.getOperand(1), MKnown); 739 bool CanFoldMask = InsertMask == MKnown.One.getZExtValue(); 740 741 unsigned SHOpc = Op1.getOperand(0).getOpcode(); 742 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask && 743 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) { 744 // Note that Value must be in range here (less than 32) because 745 // otherwise there would not be any bits set in InsertMask. 746 Op1 = Op1.getOperand(0).getOperand(0); 747 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value; 748 } 749 } 750 751 SH &= 31; 752 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl), 753 getI32Imm(ME, dl) }; 754 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops)); 755 return true; 756 } 757 } 758 return false; 759 } 760 761 // Predict the number of instructions that would be generated by calling 762 // selectI64Imm(N). 763 static unsigned selectI64ImmInstrCountDirect(int64_t Imm) { 764 // Assume no remaining bits. 765 unsigned Remainder = 0; 766 // Assume no shift required. 767 unsigned Shift = 0; 768 769 // If it can't be represented as a 32 bit value. 770 if (!isInt<32>(Imm)) { 771 Shift = countTrailingZeros<uint64_t>(Imm); 772 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift; 773 774 // If the shifted value fits 32 bits. 775 if (isInt<32>(ImmSh)) { 776 // Go with the shifted value. 777 Imm = ImmSh; 778 } else { 779 // Still stuck with a 64 bit value. 780 Remainder = Imm; 781 Shift = 32; 782 Imm >>= 32; 783 } 784 } 785 786 // Intermediate operand. 787 unsigned Result = 0; 788 789 // Handle first 32 bits. 790 unsigned Lo = Imm & 0xFFFF; 791 792 // Simple value. 793 if (isInt<16>(Imm)) { 794 // Just the Lo bits. 795 ++Result; 796 } else if (Lo) { 797 // Handle the Hi bits and Lo bits. 798 Result += 2; 799 } else { 800 // Just the Hi bits. 801 ++Result; 802 } 803 804 // If no shift, we're done. 805 if (!Shift) return Result; 806 807 // If Hi word == Lo word, 808 // we can use rldimi to insert the Lo word into Hi word. 809 if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) { 810 ++Result; 811 return Result; 812 } 813 814 // Shift for next step if the upper 32-bits were not zero. 815 if (Imm) 816 ++Result; 817 818 // Add in the last bits as required. 819 if ((Remainder >> 16) & 0xFFFF) 820 ++Result; 821 if (Remainder & 0xFFFF) 822 ++Result; 823 824 return Result; 825 } 826 827 static uint64_t Rot64(uint64_t Imm, unsigned R) { 828 return (Imm << R) | (Imm >> (64 - R)); 829 } 830 831 static unsigned selectI64ImmInstrCount(int64_t Imm) { 832 unsigned Count = selectI64ImmInstrCountDirect(Imm); 833 834 // If the instruction count is 1 or 2, we do not need further analysis 835 // since rotate + load constant requires at least 2 instructions. 836 if (Count <= 2) 837 return Count; 838 839 for (unsigned r = 1; r < 63; ++r) { 840 uint64_t RImm = Rot64(Imm, r); 841 unsigned RCount = selectI64ImmInstrCountDirect(RImm) + 1; 842 Count = std::min(Count, RCount); 843 844 // See comments in selectI64Imm for an explanation of the logic below. 845 unsigned LS = findLastSet(RImm); 846 if (LS != r-1) 847 continue; 848 849 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1)); 850 uint64_t RImmWithOnes = RImm | OnesMask; 851 852 RCount = selectI64ImmInstrCountDirect(RImmWithOnes) + 1; 853 Count = std::min(Count, RCount); 854 } 855 856 return Count; 857 } 858 859 // Select a 64-bit constant. For cost-modeling purposes, selectI64ImmInstrCount 860 // (above) needs to be kept in sync with this function. 861 static SDNode *selectI64ImmDirect(SelectionDAG *CurDAG, const SDLoc &dl, 862 int64_t Imm) { 863 // Assume no remaining bits. 864 unsigned Remainder = 0; 865 // Assume no shift required. 866 unsigned Shift = 0; 867 868 // If it can't be represented as a 32 bit value. 869 if (!isInt<32>(Imm)) { 870 Shift = countTrailingZeros<uint64_t>(Imm); 871 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift; 872 873 // If the shifted value fits 32 bits. 874 if (isInt<32>(ImmSh)) { 875 // Go with the shifted value. 876 Imm = ImmSh; 877 } else { 878 // Still stuck with a 64 bit value. 879 Remainder = Imm; 880 Shift = 32; 881 Imm >>= 32; 882 } 883 } 884 885 // Intermediate operand. 886 SDNode *Result; 887 888 // Handle first 32 bits. 889 unsigned Lo = Imm & 0xFFFF; 890 unsigned Hi = (Imm >> 16) & 0xFFFF; 891 892 auto getI32Imm = [CurDAG, dl](unsigned Imm) { 893 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 894 }; 895 896 // Simple value. 897 if (isInt<16>(Imm)) { 898 uint64_t SextImm = SignExtend64(Lo, 16); 899 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64); 900 // Just the Lo bits. 901 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm); 902 } else if (Lo) { 903 // Handle the Hi bits. 904 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8; 905 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi)); 906 // And Lo bits. 907 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, 908 SDValue(Result, 0), getI32Imm(Lo)); 909 } else { 910 // Just the Hi bits. 911 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi)); 912 } 913 914 // If no shift, we're done. 915 if (!Shift) return Result; 916 917 // If Hi word == Lo word, 918 // we can use rldimi to insert the Lo word into Hi word. 919 if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) { 920 SDValue Ops[] = 921 { SDValue(Result, 0), SDValue(Result, 0), getI32Imm(Shift), getI32Imm(0)}; 922 return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops); 923 } 924 925 // Shift for next step if the upper 32-bits were not zero. 926 if (Imm) { 927 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, 928 SDValue(Result, 0), 929 getI32Imm(Shift), 930 getI32Imm(63 - Shift)); 931 } 932 933 // Add in the last bits as required. 934 if ((Hi = (Remainder >> 16) & 0xFFFF)) { 935 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64, 936 SDValue(Result, 0), getI32Imm(Hi)); 937 } 938 if ((Lo = Remainder & 0xFFFF)) { 939 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, 940 SDValue(Result, 0), getI32Imm(Lo)); 941 } 942 943 return Result; 944 } 945 946 static SDNode *selectI64Imm(SelectionDAG *CurDAG, const SDLoc &dl, 947 int64_t Imm) { 948 unsigned Count = selectI64ImmInstrCountDirect(Imm); 949 950 // If the instruction count is 1 or 2, we do not need further analysis 951 // since rotate + load constant requires at least 2 instructions. 952 if (Count <= 2) 953 return selectI64ImmDirect(CurDAG, dl, Imm); 954 955 unsigned RMin = 0; 956 957 int64_t MatImm; 958 unsigned MaskEnd; 959 960 for (unsigned r = 1; r < 63; ++r) { 961 uint64_t RImm = Rot64(Imm, r); 962 unsigned RCount = selectI64ImmInstrCountDirect(RImm) + 1; 963 if (RCount < Count) { 964 Count = RCount; 965 RMin = r; 966 MatImm = RImm; 967 MaskEnd = 63; 968 } 969 970 // If the immediate to generate has many trailing zeros, it might be 971 // worthwhile to generate a rotated value with too many leading ones 972 // (because that's free with li/lis's sign-extension semantics), and then 973 // mask them off after rotation. 974 975 unsigned LS = findLastSet(RImm); 976 // We're adding (63-LS) higher-order ones, and we expect to mask them off 977 // after performing the inverse rotation by (64-r). So we need that: 978 // 63-LS == 64-r => LS == r-1 979 if (LS != r-1) 980 continue; 981 982 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1)); 983 uint64_t RImmWithOnes = RImm | OnesMask; 984 985 RCount = selectI64ImmInstrCountDirect(RImmWithOnes) + 1; 986 if (RCount < Count) { 987 Count = RCount; 988 RMin = r; 989 MatImm = RImmWithOnes; 990 MaskEnd = LS; 991 } 992 } 993 994 if (!RMin) 995 return selectI64ImmDirect(CurDAG, dl, Imm); 996 997 auto getI32Imm = [CurDAG, dl](unsigned Imm) { 998 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 999 }; 1000 1001 SDValue Val = SDValue(selectI64ImmDirect(CurDAG, dl, MatImm), 0); 1002 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val, 1003 getI32Imm(64 - RMin), getI32Imm(MaskEnd)); 1004 } 1005 1006 static unsigned allUsesTruncate(SelectionDAG *CurDAG, SDNode *N) { 1007 unsigned MaxTruncation = 0; 1008 // Cannot use range-based for loop here as we need the actual use (i.e. we 1009 // need the operand number corresponding to the use). A range-based for 1010 // will unbox the use and provide an SDNode*. 1011 for (SDNode::use_iterator Use = N->use_begin(), UseEnd = N->use_end(); 1012 Use != UseEnd; ++Use) { 1013 unsigned Opc = 1014 Use->isMachineOpcode() ? Use->getMachineOpcode() : Use->getOpcode(); 1015 switch (Opc) { 1016 default: return 0; 1017 case ISD::TRUNCATE: 1018 if (Use->isMachineOpcode()) 1019 return 0; 1020 MaxTruncation = 1021 std::max(MaxTruncation, Use->getValueType(0).getSizeInBits()); 1022 continue; 1023 case ISD::STORE: { 1024 if (Use->isMachineOpcode()) 1025 return 0; 1026 StoreSDNode *STN = cast<StoreSDNode>(*Use); 1027 unsigned MemVTSize = STN->getMemoryVT().getSizeInBits(); 1028 if (MemVTSize == 64 || Use.getOperandNo() != 0) 1029 return 0; 1030 MaxTruncation = std::max(MaxTruncation, MemVTSize); 1031 continue; 1032 } 1033 case PPC::STW8: 1034 case PPC::STWX8: 1035 case PPC::STWU8: 1036 case PPC::STWUX8: 1037 if (Use.getOperandNo() != 0) 1038 return 0; 1039 MaxTruncation = std::max(MaxTruncation, 32u); 1040 continue; 1041 case PPC::STH8: 1042 case PPC::STHX8: 1043 case PPC::STHU8: 1044 case PPC::STHUX8: 1045 if (Use.getOperandNo() != 0) 1046 return 0; 1047 MaxTruncation = std::max(MaxTruncation, 16u); 1048 continue; 1049 case PPC::STB8: 1050 case PPC::STBX8: 1051 case PPC::STBU8: 1052 case PPC::STBUX8: 1053 if (Use.getOperandNo() != 0) 1054 return 0; 1055 MaxTruncation = std::max(MaxTruncation, 8u); 1056 continue; 1057 } 1058 } 1059 return MaxTruncation; 1060 } 1061 1062 // Select a 64-bit constant. 1063 static SDNode *selectI64Imm(SelectionDAG *CurDAG, SDNode *N) { 1064 SDLoc dl(N); 1065 1066 // Get 64 bit value. 1067 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue(); 1068 if (unsigned MinSize = allUsesTruncate(CurDAG, N)) { 1069 uint64_t SextImm = SignExtend64(Imm, MinSize); 1070 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64); 1071 if (isInt<16>(SextImm)) 1072 return CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm); 1073 } 1074 return selectI64Imm(CurDAG, dl, Imm); 1075 } 1076 1077 namespace { 1078 1079 class BitPermutationSelector { 1080 struct ValueBit { 1081 SDValue V; 1082 1083 // The bit number in the value, using a convention where bit 0 is the 1084 // lowest-order bit. 1085 unsigned Idx; 1086 1087 // ConstZero means a bit we need to mask off. 1088 // Variable is a bit comes from an input variable. 1089 // VariableKnownToBeZero is also a bit comes from an input variable, 1090 // but it is known to be already zero. So we do not need to mask them. 1091 enum Kind { 1092 ConstZero, 1093 Variable, 1094 VariableKnownToBeZero 1095 } K; 1096 1097 ValueBit(SDValue V, unsigned I, Kind K = Variable) 1098 : V(V), Idx(I), K(K) {} 1099 ValueBit(Kind K = Variable) 1100 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {} 1101 1102 bool isZero() const { 1103 return K == ConstZero || K == VariableKnownToBeZero; 1104 } 1105 1106 bool hasValue() const { 1107 return K == Variable || K == VariableKnownToBeZero; 1108 } 1109 1110 SDValue getValue() const { 1111 assert(hasValue() && "Cannot get the value of a constant bit"); 1112 return V; 1113 } 1114 1115 unsigned getValueBitIndex() const { 1116 assert(hasValue() && "Cannot get the value bit index of a constant bit"); 1117 return Idx; 1118 } 1119 }; 1120 1121 // A bit group has the same underlying value and the same rotate factor. 1122 struct BitGroup { 1123 SDValue V; 1124 unsigned RLAmt; 1125 unsigned StartIdx, EndIdx; 1126 1127 // This rotation amount assumes that the lower 32 bits of the quantity are 1128 // replicated in the high 32 bits by the rotation operator (which is done 1129 // by rlwinm and friends in 64-bit mode). 1130 bool Repl32; 1131 // Did converting to Repl32 == true change the rotation factor? If it did, 1132 // it decreased it by 32. 1133 bool Repl32CR; 1134 // Was this group coalesced after setting Repl32 to true? 1135 bool Repl32Coalesced; 1136 1137 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E) 1138 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false), 1139 Repl32Coalesced(false) { 1140 LLVM_DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R 1141 << " [" << S << ", " << E << "]\n"); 1142 } 1143 }; 1144 1145 // Information on each (Value, RLAmt) pair (like the number of groups 1146 // associated with each) used to choose the lowering method. 1147 struct ValueRotInfo { 1148 SDValue V; 1149 unsigned RLAmt = std::numeric_limits<unsigned>::max(); 1150 unsigned NumGroups = 0; 1151 unsigned FirstGroupStartIdx = std::numeric_limits<unsigned>::max(); 1152 bool Repl32 = false; 1153 1154 ValueRotInfo() = default; 1155 1156 // For sorting (in reverse order) by NumGroups, and then by 1157 // FirstGroupStartIdx. 1158 bool operator < (const ValueRotInfo &Other) const { 1159 // We need to sort so that the non-Repl32 come first because, when we're 1160 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit 1161 // masking operation. 1162 if (Repl32 < Other.Repl32) 1163 return true; 1164 else if (Repl32 > Other.Repl32) 1165 return false; 1166 else if (NumGroups > Other.NumGroups) 1167 return true; 1168 else if (NumGroups < Other.NumGroups) 1169 return false; 1170 else if (RLAmt == 0 && Other.RLAmt != 0) 1171 return true; 1172 else if (RLAmt != 0 && Other.RLAmt == 0) 1173 return false; 1174 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx) 1175 return true; 1176 return false; 1177 } 1178 }; 1179 1180 using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>; 1181 using ValueBitsMemoizer = 1182 DenseMap<SDValue, std::unique_ptr<ValueBitsMemoizedValue>>; 1183 ValueBitsMemoizer Memoizer; 1184 1185 // Return a pair of bool and a SmallVector pointer to a memoization entry. 1186 // The bool is true if something interesting was deduced, otherwise if we're 1187 // providing only a generic representation of V (or something else likewise 1188 // uninteresting for instruction selection) through the SmallVector. 1189 std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V, 1190 unsigned NumBits) { 1191 auto &ValueEntry = Memoizer[V]; 1192 if (ValueEntry) 1193 return std::make_pair(ValueEntry->first, &ValueEntry->second); 1194 ValueEntry.reset(new ValueBitsMemoizedValue()); 1195 bool &Interesting = ValueEntry->first; 1196 SmallVector<ValueBit, 64> &Bits = ValueEntry->second; 1197 Bits.resize(NumBits); 1198 1199 switch (V.getOpcode()) { 1200 default: break; 1201 case ISD::ROTL: 1202 if (isa<ConstantSDNode>(V.getOperand(1))) { 1203 unsigned RotAmt = V.getConstantOperandVal(1); 1204 1205 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second; 1206 1207 for (unsigned i = 0; i < NumBits; ++i) 1208 Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt]; 1209 1210 return std::make_pair(Interesting = true, &Bits); 1211 } 1212 break; 1213 case ISD::SHL: 1214 if (isa<ConstantSDNode>(V.getOperand(1))) { 1215 unsigned ShiftAmt = V.getConstantOperandVal(1); 1216 1217 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second; 1218 1219 for (unsigned i = ShiftAmt; i < NumBits; ++i) 1220 Bits[i] = LHSBits[i - ShiftAmt]; 1221 1222 for (unsigned i = 0; i < ShiftAmt; ++i) 1223 Bits[i] = ValueBit(ValueBit::ConstZero); 1224 1225 return std::make_pair(Interesting = true, &Bits); 1226 } 1227 break; 1228 case ISD::SRL: 1229 if (isa<ConstantSDNode>(V.getOperand(1))) { 1230 unsigned ShiftAmt = V.getConstantOperandVal(1); 1231 1232 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second; 1233 1234 for (unsigned i = 0; i < NumBits - ShiftAmt; ++i) 1235 Bits[i] = LHSBits[i + ShiftAmt]; 1236 1237 for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i) 1238 Bits[i] = ValueBit(ValueBit::ConstZero); 1239 1240 return std::make_pair(Interesting = true, &Bits); 1241 } 1242 break; 1243 case ISD::AND: 1244 if (isa<ConstantSDNode>(V.getOperand(1))) { 1245 uint64_t Mask = V.getConstantOperandVal(1); 1246 1247 const SmallVector<ValueBit, 64> *LHSBits; 1248 // Mark this as interesting, only if the LHS was also interesting. This 1249 // prevents the overall procedure from matching a single immediate 'and' 1250 // (which is non-optimal because such an and might be folded with other 1251 // things if we don't select it here). 1252 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits); 1253 1254 for (unsigned i = 0; i < NumBits; ++i) 1255 if (((Mask >> i) & 1) == 1) 1256 Bits[i] = (*LHSBits)[i]; 1257 else { 1258 // AND instruction masks this bit. If the input is already zero, 1259 // we have nothing to do here. Otherwise, make the bit ConstZero. 1260 if ((*LHSBits)[i].isZero()) 1261 Bits[i] = (*LHSBits)[i]; 1262 else 1263 Bits[i] = ValueBit(ValueBit::ConstZero); 1264 } 1265 1266 return std::make_pair(Interesting, &Bits); 1267 } 1268 break; 1269 case ISD::OR: { 1270 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second; 1271 const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second; 1272 1273 bool AllDisjoint = true; 1274 SDValue LastVal = SDValue(); 1275 unsigned LastIdx = 0; 1276 for (unsigned i = 0; i < NumBits; ++i) { 1277 if (LHSBits[i].isZero() && RHSBits[i].isZero()) { 1278 // If both inputs are known to be zero and one is ConstZero and 1279 // another is VariableKnownToBeZero, we can select whichever 1280 // we like. To minimize the number of bit groups, we select 1281 // VariableKnownToBeZero if this bit is the next bit of the same 1282 // input variable from the previous bit. Otherwise, we select 1283 // ConstZero. 1284 if (LHSBits[i].hasValue() && LHSBits[i].getValue() == LastVal && 1285 LHSBits[i].getValueBitIndex() == LastIdx + 1) 1286 Bits[i] = LHSBits[i]; 1287 else if (RHSBits[i].hasValue() && RHSBits[i].getValue() == LastVal && 1288 RHSBits[i].getValueBitIndex() == LastIdx + 1) 1289 Bits[i] = RHSBits[i]; 1290 else 1291 Bits[i] = ValueBit(ValueBit::ConstZero); 1292 } 1293 else if (LHSBits[i].isZero()) 1294 Bits[i] = RHSBits[i]; 1295 else if (RHSBits[i].isZero()) 1296 Bits[i] = LHSBits[i]; 1297 else { 1298 AllDisjoint = false; 1299 break; 1300 } 1301 // We remember the value and bit index of this bit. 1302 if (Bits[i].hasValue()) { 1303 LastVal = Bits[i].getValue(); 1304 LastIdx = Bits[i].getValueBitIndex(); 1305 } 1306 else { 1307 if (LastVal) LastVal = SDValue(); 1308 LastIdx = 0; 1309 } 1310 } 1311 1312 if (!AllDisjoint) 1313 break; 1314 1315 return std::make_pair(Interesting = true, &Bits); 1316 } 1317 case ISD::ZERO_EXTEND: { 1318 // We support only the case with zero extension from i32 to i64 so far. 1319 if (V.getValueType() != MVT::i64 || 1320 V.getOperand(0).getValueType() != MVT::i32) 1321 break; 1322 1323 const SmallVector<ValueBit, 64> *LHSBits; 1324 const unsigned NumOperandBits = 32; 1325 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), 1326 NumOperandBits); 1327 1328 for (unsigned i = 0; i < NumOperandBits; ++i) 1329 Bits[i] = (*LHSBits)[i]; 1330 1331 for (unsigned i = NumOperandBits; i < NumBits; ++i) 1332 Bits[i] = ValueBit(ValueBit::ConstZero); 1333 1334 return std::make_pair(Interesting, &Bits); 1335 } 1336 case ISD::AssertZext: { 1337 // For AssertZext, we look through the operand and 1338 // mark the bits known to be zero. 1339 const SmallVector<ValueBit, 64> *LHSBits; 1340 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), 1341 NumBits); 1342 1343 EVT FromType = cast<VTSDNode>(V.getOperand(1))->getVT(); 1344 const unsigned NumValidBits = FromType.getSizeInBits(); 1345 for (unsigned i = 0; i < NumValidBits; ++i) 1346 Bits[i] = (*LHSBits)[i]; 1347 1348 // These bits are known to be zero. 1349 for (unsigned i = NumValidBits; i < NumBits; ++i) 1350 Bits[i] = ValueBit((*LHSBits)[i].getValue(), 1351 (*LHSBits)[i].getValueBitIndex(), 1352 ValueBit::VariableKnownToBeZero); 1353 1354 return std::make_pair(Interesting, &Bits); 1355 } 1356 case ISD::LOAD: 1357 LoadSDNode *LD = cast<LoadSDNode>(V); 1358 if (ISD::isZEXTLoad(V.getNode()) && V.getResNo() == 0) { 1359 EVT VT = LD->getMemoryVT(); 1360 const unsigned NumValidBits = VT.getSizeInBits(); 1361 1362 for (unsigned i = 0; i < NumValidBits; ++i) 1363 Bits[i] = ValueBit(V, i); 1364 1365 // These bits are known to be zero. 1366 for (unsigned i = NumValidBits; i < NumBits; ++i) 1367 Bits[i] = ValueBit(V, i, ValueBit::VariableKnownToBeZero); 1368 1369 // Zero-extending load itself cannot be optimized. So, it is not 1370 // interesting by itself though it gives useful information. 1371 return std::make_pair(Interesting = false, &Bits); 1372 } 1373 break; 1374 } 1375 1376 for (unsigned i = 0; i < NumBits; ++i) 1377 Bits[i] = ValueBit(V, i); 1378 1379 return std::make_pair(Interesting = false, &Bits); 1380 } 1381 1382 // For each value (except the constant ones), compute the left-rotate amount 1383 // to get it from its original to final position. 1384 void computeRotationAmounts() { 1385 NeedMask = false; 1386 RLAmt.resize(Bits.size()); 1387 for (unsigned i = 0; i < Bits.size(); ++i) 1388 if (Bits[i].hasValue()) { 1389 unsigned VBI = Bits[i].getValueBitIndex(); 1390 if (i >= VBI) 1391 RLAmt[i] = i - VBI; 1392 else 1393 RLAmt[i] = Bits.size() - (VBI - i); 1394 } else if (Bits[i].isZero()) { 1395 NeedMask = true; 1396 RLAmt[i] = UINT32_MAX; 1397 } else { 1398 llvm_unreachable("Unknown value bit type"); 1399 } 1400 } 1401 1402 // Collect groups of consecutive bits with the same underlying value and 1403 // rotation factor. If we're doing late masking, we ignore zeros, otherwise 1404 // they break up groups. 1405 void collectBitGroups(bool LateMask) { 1406 BitGroups.clear(); 1407 1408 unsigned LastRLAmt = RLAmt[0]; 1409 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue(); 1410 unsigned LastGroupStartIdx = 0; 1411 bool IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue(); 1412 for (unsigned i = 1; i < Bits.size(); ++i) { 1413 unsigned ThisRLAmt = RLAmt[i]; 1414 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue(); 1415 if (LateMask && !ThisValue) { 1416 ThisValue = LastValue; 1417 ThisRLAmt = LastRLAmt; 1418 // If we're doing late masking, then the first bit group always starts 1419 // at zero (even if the first bits were zero). 1420 if (BitGroups.empty()) 1421 LastGroupStartIdx = 0; 1422 } 1423 1424 // If this bit is known to be zero and the current group is a bit group 1425 // of zeros, we do not need to terminate the current bit group even the 1426 // Value or RLAmt does not match here. Instead, we terminate this group 1427 // when the first non-zero bit appears later. 1428 if (IsGroupOfZeros && Bits[i].isZero()) 1429 continue; 1430 1431 // If this bit has the same underlying value and the same rotate factor as 1432 // the last one, then they're part of the same group. 1433 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue) 1434 // We cannot continue the current group if this bits is not known to 1435 // be zero in a bit group of zeros. 1436 if (!(IsGroupOfZeros && ThisValue && !Bits[i].isZero())) 1437 continue; 1438 1439 if (LastValue.getNode()) 1440 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx, 1441 i-1)); 1442 LastRLAmt = ThisRLAmt; 1443 LastValue = ThisValue; 1444 LastGroupStartIdx = i; 1445 IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue(); 1446 } 1447 if (LastValue.getNode()) 1448 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx, 1449 Bits.size()-1)); 1450 1451 if (BitGroups.empty()) 1452 return; 1453 1454 // We might be able to combine the first and last groups. 1455 if (BitGroups.size() > 1) { 1456 // If the first and last groups are the same, then remove the first group 1457 // in favor of the last group, making the ending index of the last group 1458 // equal to the ending index of the to-be-removed first group. 1459 if (BitGroups[0].StartIdx == 0 && 1460 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 && 1461 BitGroups[0].V == BitGroups[BitGroups.size()-1].V && 1462 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) { 1463 LLVM_DEBUG(dbgs() << "\tcombining final bit group with initial one\n"); 1464 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx; 1465 BitGroups.erase(BitGroups.begin()); 1466 } 1467 } 1468 } 1469 1470 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups 1471 // associated with each. If the number of groups are same, we prefer a group 1472 // which does not require rotate, i.e. RLAmt is 0, to avoid the first rotate 1473 // instruction. If there is a degeneracy, pick the one that occurs 1474 // first (in the final value). 1475 void collectValueRotInfo() { 1476 ValueRots.clear(); 1477 1478 for (auto &BG : BitGroups) { 1479 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0); 1480 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)]; 1481 VRI.V = BG.V; 1482 VRI.RLAmt = BG.RLAmt; 1483 VRI.Repl32 = BG.Repl32; 1484 VRI.NumGroups += 1; 1485 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx); 1486 } 1487 1488 // Now that we've collected the various ValueRotInfo instances, we need to 1489 // sort them. 1490 ValueRotsVec.clear(); 1491 for (auto &I : ValueRots) { 1492 ValueRotsVec.push_back(I.second); 1493 } 1494 llvm::sort(ValueRotsVec); 1495 } 1496 1497 // In 64-bit mode, rlwinm and friends have a rotation operator that 1498 // replicates the low-order 32 bits into the high-order 32-bits. The mask 1499 // indices of these instructions can only be in the lower 32 bits, so they 1500 // can only represent some 64-bit bit groups. However, when they can be used, 1501 // the 32-bit replication can be used to represent, as a single bit group, 1502 // otherwise separate bit groups. We'll convert to replicated-32-bit bit 1503 // groups when possible. Returns true if any of the bit groups were 1504 // converted. 1505 void assignRepl32BitGroups() { 1506 // If we have bits like this: 1507 // 1508 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 1509 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24 1510 // Groups: | RLAmt = 8 | RLAmt = 40 | 1511 // 1512 // But, making use of a 32-bit operation that replicates the low-order 32 1513 // bits into the high-order 32 bits, this can be one bit group with a RLAmt 1514 // of 8. 1515 1516 auto IsAllLow32 = [this](BitGroup & BG) { 1517 if (BG.StartIdx <= BG.EndIdx) { 1518 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) { 1519 if (!Bits[i].hasValue()) 1520 continue; 1521 if (Bits[i].getValueBitIndex() >= 32) 1522 return false; 1523 } 1524 } else { 1525 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) { 1526 if (!Bits[i].hasValue()) 1527 continue; 1528 if (Bits[i].getValueBitIndex() >= 32) 1529 return false; 1530 } 1531 for (unsigned i = 0; i <= BG.EndIdx; ++i) { 1532 if (!Bits[i].hasValue()) 1533 continue; 1534 if (Bits[i].getValueBitIndex() >= 32) 1535 return false; 1536 } 1537 } 1538 1539 return true; 1540 }; 1541 1542 for (auto &BG : BitGroups) { 1543 // If this bit group has RLAmt of 0 and will not be merged with 1544 // another bit group, we don't benefit from Repl32. We don't mark 1545 // such group to give more freedom for later instruction selection. 1546 if (BG.RLAmt == 0) { 1547 auto PotentiallyMerged = [this](BitGroup & BG) { 1548 for (auto &BG2 : BitGroups) 1549 if (&BG != &BG2 && BG.V == BG2.V && 1550 (BG2.RLAmt == 0 || BG2.RLAmt == 32)) 1551 return true; 1552 return false; 1553 }; 1554 if (!PotentiallyMerged(BG)) 1555 continue; 1556 } 1557 if (BG.StartIdx < 32 && BG.EndIdx < 32) { 1558 if (IsAllLow32(BG)) { 1559 if (BG.RLAmt >= 32) { 1560 BG.RLAmt -= 32; 1561 BG.Repl32CR = true; 1562 } 1563 1564 BG.Repl32 = true; 1565 1566 LLVM_DEBUG(dbgs() << "\t32-bit replicated bit group for " 1567 << BG.V.getNode() << " RLAmt = " << BG.RLAmt << " [" 1568 << BG.StartIdx << ", " << BG.EndIdx << "]\n"); 1569 } 1570 } 1571 } 1572 1573 // Now walk through the bit groups, consolidating where possible. 1574 for (auto I = BitGroups.begin(); I != BitGroups.end();) { 1575 // We might want to remove this bit group by merging it with the previous 1576 // group (which might be the ending group). 1577 auto IP = (I == BitGroups.begin()) ? 1578 std::prev(BitGroups.end()) : std::prev(I); 1579 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt && 1580 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) { 1581 1582 LLVM_DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " 1583 << I->V.getNode() << " RLAmt = " << I->RLAmt << " [" 1584 << I->StartIdx << ", " << I->EndIdx 1585 << "] with group with range [" << IP->StartIdx << ", " 1586 << IP->EndIdx << "]\n"); 1587 1588 IP->EndIdx = I->EndIdx; 1589 IP->Repl32CR = IP->Repl32CR || I->Repl32CR; 1590 IP->Repl32Coalesced = true; 1591 I = BitGroups.erase(I); 1592 continue; 1593 } else { 1594 // There is a special case worth handling: If there is a single group 1595 // covering the entire upper 32 bits, and it can be merged with both 1596 // the next and previous groups (which might be the same group), then 1597 // do so. If it is the same group (so there will be only one group in 1598 // total), then we need to reverse the order of the range so that it 1599 // covers the entire 64 bits. 1600 if (I->StartIdx == 32 && I->EndIdx == 63) { 1601 assert(std::next(I) == BitGroups.end() && 1602 "bit group ends at index 63 but there is another?"); 1603 auto IN = BitGroups.begin(); 1604 1605 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V && 1606 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt && 1607 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP && 1608 IsAllLow32(*I)) { 1609 1610 LLVM_DEBUG(dbgs() << "\tcombining bit group for " << I->V.getNode() 1611 << " RLAmt = " << I->RLAmt << " [" << I->StartIdx 1612 << ", " << I->EndIdx 1613 << "] with 32-bit replicated groups with ranges [" 1614 << IP->StartIdx << ", " << IP->EndIdx << "] and [" 1615 << IN->StartIdx << ", " << IN->EndIdx << "]\n"); 1616 1617 if (IP == IN) { 1618 // There is only one other group; change it to cover the whole 1619 // range (backward, so that it can still be Repl32 but cover the 1620 // whole 64-bit range). 1621 IP->StartIdx = 31; 1622 IP->EndIdx = 30; 1623 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32; 1624 IP->Repl32Coalesced = true; 1625 I = BitGroups.erase(I); 1626 } else { 1627 // There are two separate groups, one before this group and one 1628 // after us (at the beginning). We're going to remove this group, 1629 // but also the group at the very beginning. 1630 IP->EndIdx = IN->EndIdx; 1631 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32; 1632 IP->Repl32Coalesced = true; 1633 I = BitGroups.erase(I); 1634 BitGroups.erase(BitGroups.begin()); 1635 } 1636 1637 // This must be the last group in the vector (and we might have 1638 // just invalidated the iterator above), so break here. 1639 break; 1640 } 1641 } 1642 } 1643 1644 ++I; 1645 } 1646 } 1647 1648 SDValue getI32Imm(unsigned Imm, const SDLoc &dl) { 1649 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 1650 } 1651 1652 uint64_t getZerosMask() { 1653 uint64_t Mask = 0; 1654 for (unsigned i = 0; i < Bits.size(); ++i) { 1655 if (Bits[i].hasValue()) 1656 continue; 1657 Mask |= (UINT64_C(1) << i); 1658 } 1659 1660 return ~Mask; 1661 } 1662 1663 // This method extends an input value to 64 bit if input is 32-bit integer. 1664 // While selecting instructions in BitPermutationSelector in 64-bit mode, 1665 // an input value can be a 32-bit integer if a ZERO_EXTEND node is included. 1666 // In such case, we extend it to 64 bit to be consistent with other values. 1667 SDValue ExtendToInt64(SDValue V, const SDLoc &dl) { 1668 if (V.getValueSizeInBits() == 64) 1669 return V; 1670 1671 assert(V.getValueSizeInBits() == 32); 1672 SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32); 1673 SDValue ImDef = SDValue(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, 1674 MVT::i64), 0); 1675 SDValue ExtVal = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, 1676 MVT::i64, ImDef, V, 1677 SubRegIdx), 0); 1678 return ExtVal; 1679 } 1680 1681 // Depending on the number of groups for a particular value, it might be 1682 // better to rotate, mask explicitly (using andi/andis), and then or the 1683 // result. Select this part of the result first. 1684 void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) { 1685 if (BPermRewriterNoMasking) 1686 return; 1687 1688 for (ValueRotInfo &VRI : ValueRotsVec) { 1689 unsigned Mask = 0; 1690 for (unsigned i = 0; i < Bits.size(); ++i) { 1691 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V) 1692 continue; 1693 if (RLAmt[i] != VRI.RLAmt) 1694 continue; 1695 Mask |= (1u << i); 1696 } 1697 1698 // Compute the masks for andi/andis that would be necessary. 1699 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16; 1700 assert((ANDIMask != 0 || ANDISMask != 0) && 1701 "No set bits in mask for value bit groups"); 1702 bool NeedsRotate = VRI.RLAmt != 0; 1703 1704 // We're trying to minimize the number of instructions. If we have one 1705 // group, using one of andi/andis can break even. If we have three 1706 // groups, we can use both andi and andis and break even (to use both 1707 // andi and andis we also need to or the results together). We need four 1708 // groups if we also need to rotate. To use andi/andis we need to do more 1709 // than break even because rotate-and-mask instructions tend to be easier 1710 // to schedule. 1711 1712 // FIXME: We've biased here against using andi/andis, which is right for 1713 // POWER cores, but not optimal everywhere. For example, on the A2, 1714 // andi/andis have single-cycle latency whereas the rotate-and-mask 1715 // instructions take two cycles, and it would be better to bias toward 1716 // andi/andis in break-even cases. 1717 1718 unsigned NumAndInsts = (unsigned) NeedsRotate + 1719 (unsigned) (ANDIMask != 0) + 1720 (unsigned) (ANDISMask != 0) + 1721 (unsigned) (ANDIMask != 0 && ANDISMask != 0) + 1722 (unsigned) (bool) Res; 1723 1724 LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() 1725 << " RL: " << VRI.RLAmt << ":" 1726 << "\n\t\t\tisel using masking: " << NumAndInsts 1727 << " using rotates: " << VRI.NumGroups << "\n"); 1728 1729 if (NumAndInsts >= VRI.NumGroups) 1730 continue; 1731 1732 LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n"); 1733 1734 if (InstCnt) *InstCnt += NumAndInsts; 1735 1736 SDValue VRot; 1737 if (VRI.RLAmt) { 1738 SDValue Ops[] = 1739 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl), 1740 getI32Imm(31, dl) }; 1741 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, 1742 Ops), 0); 1743 } else { 1744 VRot = VRI.V; 1745 } 1746 1747 SDValue ANDIVal, ANDISVal; 1748 if (ANDIMask != 0) 1749 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32, 1750 VRot, getI32Imm(ANDIMask, dl)), 0); 1751 if (ANDISMask != 0) 1752 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32, 1753 VRot, getI32Imm(ANDISMask, dl)), 0); 1754 1755 SDValue TotalVal; 1756 if (!ANDIVal) 1757 TotalVal = ANDISVal; 1758 else if (!ANDISVal) 1759 TotalVal = ANDIVal; 1760 else 1761 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1762 ANDIVal, ANDISVal), 0); 1763 1764 if (!Res) 1765 Res = TotalVal; 1766 else 1767 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1768 Res, TotalVal), 0); 1769 1770 // Now, remove all groups with this underlying value and rotation 1771 // factor. 1772 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 1773 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt; 1774 }); 1775 } 1776 } 1777 1778 // Instruction selection for the 32-bit case. 1779 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) { 1780 SDLoc dl(N); 1781 SDValue Res; 1782 1783 if (InstCnt) *InstCnt = 0; 1784 1785 // Take care of cases that should use andi/andis first. 1786 SelectAndParts32(dl, Res, InstCnt); 1787 1788 // If we've not yet selected a 'starting' instruction, and we have no zeros 1789 // to fill in, select the (Value, RLAmt) with the highest priority (largest 1790 // number of groups), and start with this rotated value. 1791 if ((!NeedMask || LateMask) && !Res) { 1792 ValueRotInfo &VRI = ValueRotsVec[0]; 1793 if (VRI.RLAmt) { 1794 if (InstCnt) *InstCnt += 1; 1795 SDValue Ops[] = 1796 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl), 1797 getI32Imm(31, dl) }; 1798 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 1799 0); 1800 } else { 1801 Res = VRI.V; 1802 } 1803 1804 // Now, remove all groups with this underlying value and rotation factor. 1805 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 1806 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt; 1807 }); 1808 } 1809 1810 if (InstCnt) *InstCnt += BitGroups.size(); 1811 1812 // Insert the other groups (one at a time). 1813 for (auto &BG : BitGroups) { 1814 if (!Res) { 1815 SDValue Ops[] = 1816 { BG.V, getI32Imm(BG.RLAmt, dl), 1817 getI32Imm(Bits.size() - BG.EndIdx - 1, dl), 1818 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) }; 1819 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 1820 } else { 1821 SDValue Ops[] = 1822 { Res, BG.V, getI32Imm(BG.RLAmt, dl), 1823 getI32Imm(Bits.size() - BG.EndIdx - 1, dl), 1824 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) }; 1825 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0); 1826 } 1827 } 1828 1829 if (LateMask) { 1830 unsigned Mask = (unsigned) getZerosMask(); 1831 1832 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16; 1833 assert((ANDIMask != 0 || ANDISMask != 0) && 1834 "No set bits in zeros mask?"); 1835 1836 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) + 1837 (unsigned) (ANDISMask != 0) + 1838 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 1839 1840 SDValue ANDIVal, ANDISVal; 1841 if (ANDIMask != 0) 1842 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32, 1843 Res, getI32Imm(ANDIMask, dl)), 0); 1844 if (ANDISMask != 0) 1845 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32, 1846 Res, getI32Imm(ANDISMask, dl)), 0); 1847 1848 if (!ANDIVal) 1849 Res = ANDISVal; 1850 else if (!ANDISVal) 1851 Res = ANDIVal; 1852 else 1853 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1854 ANDIVal, ANDISVal), 0); 1855 } 1856 1857 return Res.getNode(); 1858 } 1859 1860 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32, 1861 unsigned MaskStart, unsigned MaskEnd, 1862 bool IsIns) { 1863 // In the notation used by the instructions, 'start' and 'end' are reversed 1864 // because bits are counted from high to low order. 1865 unsigned InstMaskStart = 64 - MaskEnd - 1, 1866 InstMaskEnd = 64 - MaskStart - 1; 1867 1868 if (Repl32) 1869 return 1; 1870 1871 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) || 1872 InstMaskEnd == 63 - RLAmt) 1873 return 1; 1874 1875 return 2; 1876 } 1877 1878 // For 64-bit values, not all combinations of rotates and masks are 1879 // available. Produce one if it is available. 1880 SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt, 1881 bool Repl32, unsigned MaskStart, unsigned MaskEnd, 1882 unsigned *InstCnt = nullptr) { 1883 // In the notation used by the instructions, 'start' and 'end' are reversed 1884 // because bits are counted from high to low order. 1885 unsigned InstMaskStart = 64 - MaskEnd - 1, 1886 InstMaskEnd = 64 - MaskStart - 1; 1887 1888 if (InstCnt) *InstCnt += 1; 1889 1890 if (Repl32) { 1891 // This rotation amount assumes that the lower 32 bits of the quantity 1892 // are replicated in the high 32 bits by the rotation operator (which is 1893 // done by rlwinm and friends). 1894 assert(InstMaskStart >= 32 && "Mask cannot start out of range"); 1895 assert(InstMaskEnd >= 32 && "Mask cannot end out of range"); 1896 SDValue Ops[] = 1897 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 1898 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) }; 1899 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64, 1900 Ops), 0); 1901 } 1902 1903 if (InstMaskEnd == 63) { 1904 SDValue Ops[] = 1905 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 1906 getI32Imm(InstMaskStart, dl) }; 1907 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0); 1908 } 1909 1910 if (InstMaskStart == 0) { 1911 SDValue Ops[] = 1912 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 1913 getI32Imm(InstMaskEnd, dl) }; 1914 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0); 1915 } 1916 1917 if (InstMaskEnd == 63 - RLAmt) { 1918 SDValue Ops[] = 1919 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 1920 getI32Imm(InstMaskStart, dl) }; 1921 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0); 1922 } 1923 1924 // We cannot do this with a single instruction, so we'll use two. The 1925 // problem is that we're not free to choose both a rotation amount and mask 1926 // start and end independently. We can choose an arbitrary mask start and 1927 // end, but then the rotation amount is fixed. Rotation, however, can be 1928 // inverted, and so by applying an "inverse" rotation first, we can get the 1929 // desired result. 1930 if (InstCnt) *InstCnt += 1; 1931 1932 // The rotation mask for the second instruction must be MaskStart. 1933 unsigned RLAmt2 = MaskStart; 1934 // The first instruction must rotate V so that the overall rotation amount 1935 // is RLAmt. 1936 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64; 1937 if (RLAmt1) 1938 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63); 1939 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd); 1940 } 1941 1942 // For 64-bit values, not all combinations of rotates and masks are 1943 // available. Produce a rotate-mask-and-insert if one is available. 1944 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl, 1945 unsigned RLAmt, bool Repl32, unsigned MaskStart, 1946 unsigned MaskEnd, unsigned *InstCnt = nullptr) { 1947 // In the notation used by the instructions, 'start' and 'end' are reversed 1948 // because bits are counted from high to low order. 1949 unsigned InstMaskStart = 64 - MaskEnd - 1, 1950 InstMaskEnd = 64 - MaskStart - 1; 1951 1952 if (InstCnt) *InstCnt += 1; 1953 1954 if (Repl32) { 1955 // This rotation amount assumes that the lower 32 bits of the quantity 1956 // are replicated in the high 32 bits by the rotation operator (which is 1957 // done by rlwinm and friends). 1958 assert(InstMaskStart >= 32 && "Mask cannot start out of range"); 1959 assert(InstMaskEnd >= 32 && "Mask cannot end out of range"); 1960 SDValue Ops[] = 1961 { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 1962 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) }; 1963 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64, 1964 Ops), 0); 1965 } 1966 1967 if (InstMaskEnd == 63 - RLAmt) { 1968 SDValue Ops[] = 1969 { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl), 1970 getI32Imm(InstMaskStart, dl) }; 1971 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0); 1972 } 1973 1974 // We cannot do this with a single instruction, so we'll use two. The 1975 // problem is that we're not free to choose both a rotation amount and mask 1976 // start and end independently. We can choose an arbitrary mask start and 1977 // end, but then the rotation amount is fixed. Rotation, however, can be 1978 // inverted, and so by applying an "inverse" rotation first, we can get the 1979 // desired result. 1980 if (InstCnt) *InstCnt += 1; 1981 1982 // The rotation mask for the second instruction must be MaskStart. 1983 unsigned RLAmt2 = MaskStart; 1984 // The first instruction must rotate V so that the overall rotation amount 1985 // is RLAmt. 1986 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64; 1987 if (RLAmt1) 1988 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63); 1989 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd); 1990 } 1991 1992 void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) { 1993 if (BPermRewriterNoMasking) 1994 return; 1995 1996 // The idea here is the same as in the 32-bit version, but with additional 1997 // complications from the fact that Repl32 might be true. Because we 1998 // aggressively convert bit groups to Repl32 form (which, for small 1999 // rotation factors, involves no other change), and then coalesce, it might 2000 // be the case that a single 64-bit masking operation could handle both 2001 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32 2002 // form allowed coalescing, then we must use a 32-bit rotaton in order to 2003 // completely capture the new combined bit group. 2004 2005 for (ValueRotInfo &VRI : ValueRotsVec) { 2006 uint64_t Mask = 0; 2007 2008 // We need to add to the mask all bits from the associated bit groups. 2009 // If Repl32 is false, we need to add bits from bit groups that have 2010 // Repl32 true, but are trivially convertable to Repl32 false. Such a 2011 // group is trivially convertable if it overlaps only with the lower 32 2012 // bits, and the group has not been coalesced. 2013 auto MatchingBG = [VRI](const BitGroup &BG) { 2014 if (VRI.V != BG.V) 2015 return false; 2016 2017 unsigned EffRLAmt = BG.RLAmt; 2018 if (!VRI.Repl32 && BG.Repl32) { 2019 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx && 2020 !BG.Repl32Coalesced) { 2021 if (BG.Repl32CR) 2022 EffRLAmt += 32; 2023 } else { 2024 return false; 2025 } 2026 } else if (VRI.Repl32 != BG.Repl32) { 2027 return false; 2028 } 2029 2030 return VRI.RLAmt == EffRLAmt; 2031 }; 2032 2033 for (auto &BG : BitGroups) { 2034 if (!MatchingBG(BG)) 2035 continue; 2036 2037 if (BG.StartIdx <= BG.EndIdx) { 2038 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) 2039 Mask |= (UINT64_C(1) << i); 2040 } else { 2041 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) 2042 Mask |= (UINT64_C(1) << i); 2043 for (unsigned i = 0; i <= BG.EndIdx; ++i) 2044 Mask |= (UINT64_C(1) << i); 2045 } 2046 } 2047 2048 // We can use the 32-bit andi/andis technique if the mask does not 2049 // require any higher-order bits. This can save an instruction compared 2050 // to always using the general 64-bit technique. 2051 bool Use32BitInsts = isUInt<32>(Mask); 2052 // Compute the masks for andi/andis that would be necessary. 2053 unsigned ANDIMask = (Mask & UINT16_MAX), 2054 ANDISMask = (Mask >> 16) & UINT16_MAX; 2055 2056 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)); 2057 2058 unsigned NumAndInsts = (unsigned) NeedsRotate + 2059 (unsigned) (bool) Res; 2060 if (Use32BitInsts) 2061 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) + 2062 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 2063 else 2064 NumAndInsts += selectI64ImmInstrCount(Mask) + /* and */ 1; 2065 2066 unsigned NumRLInsts = 0; 2067 bool FirstBG = true; 2068 bool MoreBG = false; 2069 for (auto &BG : BitGroups) { 2070 if (!MatchingBG(BG)) { 2071 MoreBG = true; 2072 continue; 2073 } 2074 NumRLInsts += 2075 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx, 2076 !FirstBG); 2077 FirstBG = false; 2078 } 2079 2080 LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() 2081 << " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") 2082 << "\n\t\t\tisel using masking: " << NumAndInsts 2083 << " using rotates: " << NumRLInsts << "\n"); 2084 2085 // When we'd use andi/andis, we bias toward using the rotates (andi only 2086 // has a record form, and is cracked on POWER cores). However, when using 2087 // general 64-bit constant formation, bias toward the constant form, 2088 // because that exposes more opportunities for CSE. 2089 if (NumAndInsts > NumRLInsts) 2090 continue; 2091 // When merging multiple bit groups, instruction or is used. 2092 // But when rotate is used, rldimi can inert the rotated value into any 2093 // register, so instruction or can be avoided. 2094 if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts) 2095 continue; 2096 2097 LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n"); 2098 2099 if (InstCnt) *InstCnt += NumAndInsts; 2100 2101 SDValue VRot; 2102 // We actually need to generate a rotation if we have a non-zero rotation 2103 // factor or, in the Repl32 case, if we care about any of the 2104 // higher-order replicated bits. In the latter case, we generate a mask 2105 // backward so that it actually includes the entire 64 bits. 2106 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask))) 2107 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32, 2108 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63); 2109 else 2110 VRot = VRI.V; 2111 2112 SDValue TotalVal; 2113 if (Use32BitInsts) { 2114 assert((ANDIMask != 0 || ANDISMask != 0) && 2115 "No set bits in mask when using 32-bit ands for 64-bit value"); 2116 2117 SDValue ANDIVal, ANDISVal; 2118 if (ANDIMask != 0) 2119 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64, 2120 ExtendToInt64(VRot, dl), 2121 getI32Imm(ANDIMask, dl)), 2122 0); 2123 if (ANDISMask != 0) 2124 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64, 2125 ExtendToInt64(VRot, dl), 2126 getI32Imm(ANDISMask, dl)), 2127 0); 2128 2129 if (!ANDIVal) 2130 TotalVal = ANDISVal; 2131 else if (!ANDISVal) 2132 TotalVal = ANDIVal; 2133 else 2134 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 2135 ExtendToInt64(ANDIVal, dl), ANDISVal), 0); 2136 } else { 2137 TotalVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0); 2138 TotalVal = 2139 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64, 2140 ExtendToInt64(VRot, dl), TotalVal), 2141 0); 2142 } 2143 2144 if (!Res) 2145 Res = TotalVal; 2146 else 2147 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 2148 ExtendToInt64(Res, dl), TotalVal), 2149 0); 2150 2151 // Now, remove all groups with this underlying value and rotation 2152 // factor. 2153 eraseMatchingBitGroups(MatchingBG); 2154 } 2155 } 2156 2157 // Instruction selection for the 64-bit case. 2158 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) { 2159 SDLoc dl(N); 2160 SDValue Res; 2161 2162 if (InstCnt) *InstCnt = 0; 2163 2164 // Take care of cases that should use andi/andis first. 2165 SelectAndParts64(dl, Res, InstCnt); 2166 2167 // If we've not yet selected a 'starting' instruction, and we have no zeros 2168 // to fill in, select the (Value, RLAmt) with the highest priority (largest 2169 // number of groups), and start with this rotated value. 2170 if ((!NeedMask || LateMask) && !Res) { 2171 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32 2172 // groups will come first, and so the VRI representing the largest number 2173 // of groups might not be first (it might be the first Repl32 groups). 2174 unsigned MaxGroupsIdx = 0; 2175 if (!ValueRotsVec[0].Repl32) { 2176 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i) 2177 if (ValueRotsVec[i].Repl32) { 2178 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups) 2179 MaxGroupsIdx = i; 2180 break; 2181 } 2182 } 2183 2184 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx]; 2185 bool NeedsRotate = false; 2186 if (VRI.RLAmt) { 2187 NeedsRotate = true; 2188 } else if (VRI.Repl32) { 2189 for (auto &BG : BitGroups) { 2190 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt || 2191 BG.Repl32 != VRI.Repl32) 2192 continue; 2193 2194 // We don't need a rotate if the bit group is confined to the lower 2195 // 32 bits. 2196 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx) 2197 continue; 2198 2199 NeedsRotate = true; 2200 break; 2201 } 2202 } 2203 2204 if (NeedsRotate) 2205 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32, 2206 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63, 2207 InstCnt); 2208 else 2209 Res = VRI.V; 2210 2211 // Now, remove all groups with this underlying value and rotation factor. 2212 if (Res) 2213 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 2214 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt && 2215 BG.Repl32 == VRI.Repl32; 2216 }); 2217 } 2218 2219 // Because 64-bit rotates are more flexible than inserts, we might have a 2220 // preference regarding which one we do first (to save one instruction). 2221 if (!Res) 2222 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) { 2223 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx, 2224 false) < 2225 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx, 2226 true)) { 2227 if (I != BitGroups.begin()) { 2228 BitGroup BG = *I; 2229 BitGroups.erase(I); 2230 BitGroups.insert(BitGroups.begin(), BG); 2231 } 2232 2233 break; 2234 } 2235 } 2236 2237 // Insert the other groups (one at a time). 2238 for (auto &BG : BitGroups) { 2239 if (!Res) 2240 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx, 2241 BG.EndIdx, InstCnt); 2242 else 2243 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32, 2244 BG.StartIdx, BG.EndIdx, InstCnt); 2245 } 2246 2247 if (LateMask) { 2248 uint64_t Mask = getZerosMask(); 2249 2250 // We can use the 32-bit andi/andis technique if the mask does not 2251 // require any higher-order bits. This can save an instruction compared 2252 // to always using the general 64-bit technique. 2253 bool Use32BitInsts = isUInt<32>(Mask); 2254 // Compute the masks for andi/andis that would be necessary. 2255 unsigned ANDIMask = (Mask & UINT16_MAX), 2256 ANDISMask = (Mask >> 16) & UINT16_MAX; 2257 2258 if (Use32BitInsts) { 2259 assert((ANDIMask != 0 || ANDISMask != 0) && 2260 "No set bits in mask when using 32-bit ands for 64-bit value"); 2261 2262 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) + 2263 (unsigned) (ANDISMask != 0) + 2264 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 2265 2266 SDValue ANDIVal, ANDISVal; 2267 if (ANDIMask != 0) 2268 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64, 2269 ExtendToInt64(Res, dl), getI32Imm(ANDIMask, dl)), 0); 2270 if (ANDISMask != 0) 2271 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64, 2272 ExtendToInt64(Res, dl), getI32Imm(ANDISMask, dl)), 0); 2273 2274 if (!ANDIVal) 2275 Res = ANDISVal; 2276 else if (!ANDISVal) 2277 Res = ANDIVal; 2278 else 2279 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 2280 ExtendToInt64(ANDIVal, dl), ANDISVal), 0); 2281 } else { 2282 if (InstCnt) *InstCnt += selectI64ImmInstrCount(Mask) + /* and */ 1; 2283 2284 SDValue MaskVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0); 2285 Res = 2286 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64, 2287 ExtendToInt64(Res, dl), MaskVal), 0); 2288 } 2289 } 2290 2291 return Res.getNode(); 2292 } 2293 2294 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) { 2295 // Fill in BitGroups. 2296 collectBitGroups(LateMask); 2297 if (BitGroups.empty()) 2298 return nullptr; 2299 2300 // For 64-bit values, figure out when we can use 32-bit instructions. 2301 if (Bits.size() == 64) 2302 assignRepl32BitGroups(); 2303 2304 // Fill in ValueRotsVec. 2305 collectValueRotInfo(); 2306 2307 if (Bits.size() == 32) { 2308 return Select32(N, LateMask, InstCnt); 2309 } else { 2310 assert(Bits.size() == 64 && "Not 64 bits here?"); 2311 return Select64(N, LateMask, InstCnt); 2312 } 2313 2314 return nullptr; 2315 } 2316 2317 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) { 2318 BitGroups.erase(remove_if(BitGroups, F), BitGroups.end()); 2319 } 2320 2321 SmallVector<ValueBit, 64> Bits; 2322 2323 bool NeedMask; 2324 SmallVector<unsigned, 64> RLAmt; 2325 2326 SmallVector<BitGroup, 16> BitGroups; 2327 2328 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots; 2329 SmallVector<ValueRotInfo, 16> ValueRotsVec; 2330 2331 SelectionDAG *CurDAG; 2332 2333 public: 2334 BitPermutationSelector(SelectionDAG *DAG) 2335 : CurDAG(DAG) {} 2336 2337 // Here we try to match complex bit permutations into a set of 2338 // rotate-and-shift/shift/and/or instructions, using a set of heuristics 2339 // known to produce optimial code for common cases (like i32 byte swapping). 2340 SDNode *Select(SDNode *N) { 2341 Memoizer.clear(); 2342 auto Result = 2343 getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits()); 2344 if (!Result.first) 2345 return nullptr; 2346 Bits = std::move(*Result.second); 2347 2348 LLVM_DEBUG(dbgs() << "Considering bit-permutation-based instruction" 2349 " selection for: "); 2350 LLVM_DEBUG(N->dump(CurDAG)); 2351 2352 // Fill it RLAmt and set NeedMask. 2353 computeRotationAmounts(); 2354 2355 if (!NeedMask) 2356 return Select(N, false); 2357 2358 // We currently have two techniques for handling results with zeros: early 2359 // masking (the default) and late masking. Late masking is sometimes more 2360 // efficient, but because the structure of the bit groups is different, it 2361 // is hard to tell without generating both and comparing the results. With 2362 // late masking, we ignore zeros in the resulting value when inserting each 2363 // set of bit groups, and then mask in the zeros at the end. With early 2364 // masking, we only insert the non-zero parts of the result at every step. 2365 2366 unsigned InstCnt = 0, InstCntLateMask = 0; 2367 LLVM_DEBUG(dbgs() << "\tEarly masking:\n"); 2368 SDNode *RN = Select(N, false, &InstCnt); 2369 LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n"); 2370 2371 LLVM_DEBUG(dbgs() << "\tLate masking:\n"); 2372 SDNode *RNLM = Select(N, true, &InstCntLateMask); 2373 LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask 2374 << " instructions\n"); 2375 2376 if (InstCnt <= InstCntLateMask) { 2377 LLVM_DEBUG(dbgs() << "\tUsing early-masking for isel\n"); 2378 return RN; 2379 } 2380 2381 LLVM_DEBUG(dbgs() << "\tUsing late-masking for isel\n"); 2382 return RNLM; 2383 } 2384 }; 2385 2386 class IntegerCompareEliminator { 2387 SelectionDAG *CurDAG; 2388 PPCDAGToDAGISel *S; 2389 // Conversion type for interpreting results of a 32-bit instruction as 2390 // a 64-bit value or vice versa. 2391 enum ExtOrTruncConversion { Ext, Trunc }; 2392 2393 // Modifiers to guide how an ISD::SETCC node's result is to be computed 2394 // in a GPR. 2395 // ZExtOrig - use the original condition code, zero-extend value 2396 // ZExtInvert - invert the condition code, zero-extend value 2397 // SExtOrig - use the original condition code, sign-extend value 2398 // SExtInvert - invert the condition code, sign-extend value 2399 enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert }; 2400 2401 // Comparisons against zero to emit GPR code sequences for. Each of these 2402 // sequences may need to be emitted for two or more equivalent patterns. 2403 // For example (a >= 0) == (a > -1). The direction of the comparison (</>) 2404 // matters as well as the extension type: sext (-1/0), zext (1/0). 2405 // GEZExt - (zext (LHS >= 0)) 2406 // GESExt - (sext (LHS >= 0)) 2407 // LEZExt - (zext (LHS <= 0)) 2408 // LESExt - (sext (LHS <= 0)) 2409 enum ZeroCompare { GEZExt, GESExt, LEZExt, LESExt }; 2410 2411 SDNode *tryEXTEND(SDNode *N); 2412 SDNode *tryLogicOpOfCompares(SDNode *N); 2413 SDValue computeLogicOpInGPR(SDValue LogicOp); 2414 SDValue signExtendInputIfNeeded(SDValue Input); 2415 SDValue zeroExtendInputIfNeeded(SDValue Input); 2416 SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv); 2417 SDValue getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl, 2418 ZeroCompare CmpTy); 2419 SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2420 int64_t RHSValue, SDLoc dl); 2421 SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2422 int64_t RHSValue, SDLoc dl); 2423 SDValue get64BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2424 int64_t RHSValue, SDLoc dl); 2425 SDValue get64BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC, 2426 int64_t RHSValue, SDLoc dl); 2427 SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts); 2428 2429 public: 2430 IntegerCompareEliminator(SelectionDAG *DAG, 2431 PPCDAGToDAGISel *Sel) : CurDAG(DAG), S(Sel) { 2432 assert(CurDAG->getTargetLoweringInfo() 2433 .getPointerTy(CurDAG->getDataLayout()).getSizeInBits() == 64 && 2434 "Only expecting to use this on 64 bit targets."); 2435 } 2436 SDNode *Select(SDNode *N) { 2437 if (CmpInGPR == ICGPR_None) 2438 return nullptr; 2439 switch (N->getOpcode()) { 2440 default: break; 2441 case ISD::ZERO_EXTEND: 2442 if (CmpInGPR == ICGPR_Sext || CmpInGPR == ICGPR_SextI32 || 2443 CmpInGPR == ICGPR_SextI64) 2444 return nullptr; 2445 LLVM_FALLTHROUGH; 2446 case ISD::SIGN_EXTEND: 2447 if (CmpInGPR == ICGPR_Zext || CmpInGPR == ICGPR_ZextI32 || 2448 CmpInGPR == ICGPR_ZextI64) 2449 return nullptr; 2450 return tryEXTEND(N); 2451 case ISD::AND: 2452 case ISD::OR: 2453 case ISD::XOR: 2454 return tryLogicOpOfCompares(N); 2455 } 2456 return nullptr; 2457 } 2458 }; 2459 2460 static bool isLogicOp(unsigned Opc) { 2461 return Opc == ISD::AND || Opc == ISD::OR || Opc == ISD::XOR; 2462 } 2463 // The obvious case for wanting to keep the value in a GPR. Namely, the 2464 // result of the comparison is actually needed in a GPR. 2465 SDNode *IntegerCompareEliminator::tryEXTEND(SDNode *N) { 2466 assert((N->getOpcode() == ISD::ZERO_EXTEND || 2467 N->getOpcode() == ISD::SIGN_EXTEND) && 2468 "Expecting a zero/sign extend node!"); 2469 SDValue WideRes; 2470 // If we are zero-extending the result of a logical operation on i1 2471 // values, we can keep the values in GPRs. 2472 if (isLogicOp(N->getOperand(0).getOpcode()) && 2473 N->getOperand(0).getValueType() == MVT::i1 && 2474 N->getOpcode() == ISD::ZERO_EXTEND) 2475 WideRes = computeLogicOpInGPR(N->getOperand(0)); 2476 else if (N->getOperand(0).getOpcode() != ISD::SETCC) 2477 return nullptr; 2478 else 2479 WideRes = 2480 getSETCCInGPR(N->getOperand(0), 2481 N->getOpcode() == ISD::SIGN_EXTEND ? 2482 SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig); 2483 2484 if (!WideRes) 2485 return nullptr; 2486 2487 SDLoc dl(N); 2488 bool Input32Bit = WideRes.getValueType() == MVT::i32; 2489 bool Output32Bit = N->getValueType(0) == MVT::i32; 2490 2491 NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0; 2492 NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1; 2493 2494 SDValue ConvOp = WideRes; 2495 if (Input32Bit != Output32Bit) 2496 ConvOp = addExtOrTrunc(WideRes, Input32Bit ? ExtOrTruncConversion::Ext : 2497 ExtOrTruncConversion::Trunc); 2498 return ConvOp.getNode(); 2499 } 2500 2501 // Attempt to perform logical operations on the results of comparisons while 2502 // keeping the values in GPRs. Without doing so, these would end up being 2503 // lowered to CR-logical operations which suffer from significant latency and 2504 // low ILP. 2505 SDNode *IntegerCompareEliminator::tryLogicOpOfCompares(SDNode *N) { 2506 if (N->getValueType(0) != MVT::i1) 2507 return nullptr; 2508 assert(isLogicOp(N->getOpcode()) && 2509 "Expected a logic operation on setcc results."); 2510 SDValue LoweredLogical = computeLogicOpInGPR(SDValue(N, 0)); 2511 if (!LoweredLogical) 2512 return nullptr; 2513 2514 SDLoc dl(N); 2515 bool IsBitwiseNegate = LoweredLogical.getMachineOpcode() == PPC::XORI8; 2516 unsigned SubRegToExtract = IsBitwiseNegate ? PPC::sub_eq : PPC::sub_gt; 2517 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32); 2518 SDValue LHS = LoweredLogical.getOperand(0); 2519 SDValue RHS = LoweredLogical.getOperand(1); 2520 SDValue WideOp; 2521 SDValue OpToConvToRecForm; 2522 2523 // Look through any 32-bit to 64-bit implicit extend nodes to find the 2524 // opcode that is input to the XORI. 2525 if (IsBitwiseNegate && 2526 LoweredLogical.getOperand(0).getMachineOpcode() == PPC::INSERT_SUBREG) 2527 OpToConvToRecForm = LoweredLogical.getOperand(0).getOperand(1); 2528 else if (IsBitwiseNegate) 2529 // If the input to the XORI isn't an extension, that's what we're after. 2530 OpToConvToRecForm = LoweredLogical.getOperand(0); 2531 else 2532 // If this is not an XORI, it is a reg-reg logical op and we can convert 2533 // it to record-form. 2534 OpToConvToRecForm = LoweredLogical; 2535 2536 // Get the record-form version of the node we're looking to use to get the 2537 // CR result from. 2538 uint16_t NonRecOpc = OpToConvToRecForm.getMachineOpcode(); 2539 int NewOpc = PPCInstrInfo::getRecordFormOpcode(NonRecOpc); 2540 2541 // Convert the right node to record-form. This is either the logical we're 2542 // looking at or it is the input node to the negation (if we're looking at 2543 // a bitwise negation). 2544 if (NewOpc != -1 && IsBitwiseNegate) { 2545 // The input to the XORI has a record-form. Use it. 2546 assert(LoweredLogical.getConstantOperandVal(1) == 1 && 2547 "Expected a PPC::XORI8 only for bitwise negation."); 2548 // Emit the record-form instruction. 2549 std::vector<SDValue> Ops; 2550 for (int i = 0, e = OpToConvToRecForm.getNumOperands(); i < e; i++) 2551 Ops.push_back(OpToConvToRecForm.getOperand(i)); 2552 2553 WideOp = 2554 SDValue(CurDAG->getMachineNode(NewOpc, dl, 2555 OpToConvToRecForm.getValueType(), 2556 MVT::Glue, Ops), 0); 2557 } else { 2558 assert((NewOpc != -1 || !IsBitwiseNegate) && 2559 "No record form available for AND8/OR8/XOR8?"); 2560 WideOp = 2561 SDValue(CurDAG->getMachineNode(NewOpc == -1 ? PPC::ANDIo8 : NewOpc, dl, 2562 MVT::i64, MVT::Glue, LHS, RHS), 0); 2563 } 2564 2565 // Select this node to a single bit from CR0 set by the record-form node 2566 // just created. For bitwise negation, use the EQ bit which is the equivalent 2567 // of negating the result (i.e. it is a bit set when the result of the 2568 // operation is zero). 2569 SDValue SRIdxVal = 2570 CurDAG->getTargetConstant(SubRegToExtract, dl, MVT::i32); 2571 SDValue CRBit = 2572 SDValue(CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, 2573 MVT::i1, CR0Reg, SRIdxVal, 2574 WideOp.getValue(1)), 0); 2575 return CRBit.getNode(); 2576 } 2577 2578 // Lower a logical operation on i1 values into a GPR sequence if possible. 2579 // The result can be kept in a GPR if requested. 2580 // Three types of inputs can be handled: 2581 // - SETCC 2582 // - TRUNCATE 2583 // - Logical operation (AND/OR/XOR) 2584 // There is also a special case that is handled (namely a complement operation 2585 // achieved with xor %a, -1). 2586 SDValue IntegerCompareEliminator::computeLogicOpInGPR(SDValue LogicOp) { 2587 assert(isLogicOp(LogicOp.getOpcode()) && 2588 "Can only handle logic operations here."); 2589 assert(LogicOp.getValueType() == MVT::i1 && 2590 "Can only handle logic operations on i1 values here."); 2591 SDLoc dl(LogicOp); 2592 SDValue LHS, RHS; 2593 2594 // Special case: xor %a, -1 2595 bool IsBitwiseNegation = isBitwiseNot(LogicOp); 2596 2597 // Produces a GPR sequence for each operand of the binary logic operation. 2598 // For SETCC, it produces the respective comparison, for TRUNCATE it truncates 2599 // the value in a GPR and for logic operations, it will recursively produce 2600 // a GPR sequence for the operation. 2601 auto getLogicOperand = [&] (SDValue Operand) -> SDValue { 2602 unsigned OperandOpcode = Operand.getOpcode(); 2603 if (OperandOpcode == ISD::SETCC) 2604 return getSETCCInGPR(Operand, SetccInGPROpts::ZExtOrig); 2605 else if (OperandOpcode == ISD::TRUNCATE) { 2606 SDValue InputOp = Operand.getOperand(0); 2607 EVT InVT = InputOp.getValueType(); 2608 return SDValue(CurDAG->getMachineNode(InVT == MVT::i32 ? PPC::RLDICL_32 : 2609 PPC::RLDICL, dl, InVT, InputOp, 2610 S->getI64Imm(0, dl), 2611 S->getI64Imm(63, dl)), 0); 2612 } else if (isLogicOp(OperandOpcode)) 2613 return computeLogicOpInGPR(Operand); 2614 return SDValue(); 2615 }; 2616 LHS = getLogicOperand(LogicOp.getOperand(0)); 2617 RHS = getLogicOperand(LogicOp.getOperand(1)); 2618 2619 // If a GPR sequence can't be produced for the LHS we can't proceed. 2620 // Not producing a GPR sequence for the RHS is only a problem if this isn't 2621 // a bitwise negation operation. 2622 if (!LHS || (!RHS && !IsBitwiseNegation)) 2623 return SDValue(); 2624 2625 NumLogicOpsOnComparison++; 2626 2627 // We will use the inputs as 64-bit values. 2628 if (LHS.getValueType() == MVT::i32) 2629 LHS = addExtOrTrunc(LHS, ExtOrTruncConversion::Ext); 2630 if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32) 2631 RHS = addExtOrTrunc(RHS, ExtOrTruncConversion::Ext); 2632 2633 unsigned NewOpc; 2634 switch (LogicOp.getOpcode()) { 2635 default: llvm_unreachable("Unknown logic operation."); 2636 case ISD::AND: NewOpc = PPC::AND8; break; 2637 case ISD::OR: NewOpc = PPC::OR8; break; 2638 case ISD::XOR: NewOpc = PPC::XOR8; break; 2639 } 2640 2641 if (IsBitwiseNegation) { 2642 RHS = S->getI64Imm(1, dl); 2643 NewOpc = PPC::XORI8; 2644 } 2645 2646 return SDValue(CurDAG->getMachineNode(NewOpc, dl, MVT::i64, LHS, RHS), 0); 2647 2648 } 2649 2650 /// If the value isn't guaranteed to be sign-extended to 64-bits, extend it. 2651 /// Otherwise just reinterpret it as a 64-bit value. 2652 /// Useful when emitting comparison code for 32-bit values without using 2653 /// the compare instruction (which only considers the lower 32-bits). 2654 SDValue IntegerCompareEliminator::signExtendInputIfNeeded(SDValue Input) { 2655 assert(Input.getValueType() == MVT::i32 && 2656 "Can only sign-extend 32-bit values here."); 2657 unsigned Opc = Input.getOpcode(); 2658 2659 // The value was sign extended and then truncated to 32-bits. No need to 2660 // sign extend it again. 2661 if (Opc == ISD::TRUNCATE && 2662 (Input.getOperand(0).getOpcode() == ISD::AssertSext || 2663 Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND)) 2664 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2665 2666 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input); 2667 // The input is a sign-extending load. All ppc sign-extending loads 2668 // sign-extend to the full 64-bits. 2669 if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD) 2670 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2671 2672 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input); 2673 // We don't sign-extend constants. 2674 if (InputConst) 2675 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2676 2677 SDLoc dl(Input); 2678 SignExtensionsAdded++; 2679 return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32_64, dl, 2680 MVT::i64, Input), 0); 2681 } 2682 2683 /// If the value isn't guaranteed to be zero-extended to 64-bits, extend it. 2684 /// Otherwise just reinterpret it as a 64-bit value. 2685 /// Useful when emitting comparison code for 32-bit values without using 2686 /// the compare instruction (which only considers the lower 32-bits). 2687 SDValue IntegerCompareEliminator::zeroExtendInputIfNeeded(SDValue Input) { 2688 assert(Input.getValueType() == MVT::i32 && 2689 "Can only zero-extend 32-bit values here."); 2690 unsigned Opc = Input.getOpcode(); 2691 2692 // The only condition under which we can omit the actual extend instruction: 2693 // - The value is a positive constant 2694 // - The value comes from a load that isn't a sign-extending load 2695 // An ISD::TRUNCATE needs to be zero-extended unless it is fed by a zext. 2696 bool IsTruncateOfZExt = Opc == ISD::TRUNCATE && 2697 (Input.getOperand(0).getOpcode() == ISD::AssertZext || 2698 Input.getOperand(0).getOpcode() == ISD::ZERO_EXTEND); 2699 if (IsTruncateOfZExt) 2700 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2701 2702 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input); 2703 if (InputConst && InputConst->getSExtValue() >= 0) 2704 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2705 2706 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input); 2707 // The input is a load that doesn't sign-extend (it will be zero-extended). 2708 if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD) 2709 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext); 2710 2711 // None of the above, need to zero-extend. 2712 SDLoc dl(Input); 2713 ZeroExtensionsAdded++; 2714 return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32_64, dl, MVT::i64, Input, 2715 S->getI64Imm(0, dl), 2716 S->getI64Imm(32, dl)), 0); 2717 } 2718 2719 // Handle a 32-bit value in a 64-bit register and vice-versa. These are of 2720 // course not actual zero/sign extensions that will generate machine code, 2721 // they're just a way to reinterpret a 32 bit value in a register as a 2722 // 64 bit value and vice-versa. 2723 SDValue IntegerCompareEliminator::addExtOrTrunc(SDValue NatWidthRes, 2724 ExtOrTruncConversion Conv) { 2725 SDLoc dl(NatWidthRes); 2726 2727 // For reinterpreting 32-bit values as 64 bit values, we generate 2728 // INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<1> 2729 if (Conv == ExtOrTruncConversion::Ext) { 2730 SDValue ImDef(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, MVT::i64), 0); 2731 SDValue SubRegIdx = 2732 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32); 2733 return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64, 2734 ImDef, NatWidthRes, SubRegIdx), 0); 2735 } 2736 2737 assert(Conv == ExtOrTruncConversion::Trunc && 2738 "Unknown convertion between 32 and 64 bit values."); 2739 // For reinterpreting 64-bit values as 32-bit values, we just need to 2740 // EXTRACT_SUBREG (i.e. extract the low word). 2741 SDValue SubRegIdx = 2742 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32); 2743 return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32, 2744 NatWidthRes, SubRegIdx), 0); 2745 } 2746 2747 // Produce a GPR sequence for compound comparisons (<=, >=) against zero. 2748 // Handle both zero-extensions and sign-extensions. 2749 SDValue 2750 IntegerCompareEliminator::getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl, 2751 ZeroCompare CmpTy) { 2752 EVT InVT = LHS.getValueType(); 2753 bool Is32Bit = InVT == MVT::i32; 2754 SDValue ToExtend; 2755 2756 // Produce the value that needs to be either zero or sign extended. 2757 switch (CmpTy) { 2758 case ZeroCompare::GEZExt: 2759 case ZeroCompare::GESExt: 2760 ToExtend = SDValue(CurDAG->getMachineNode(Is32Bit ? PPC::NOR : PPC::NOR8, 2761 dl, InVT, LHS, LHS), 0); 2762 break; 2763 case ZeroCompare::LEZExt: 2764 case ZeroCompare::LESExt: { 2765 if (Is32Bit) { 2766 // Upper 32 bits cannot be undefined for this sequence. 2767 LHS = signExtendInputIfNeeded(LHS); 2768 SDValue Neg = 2769 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0); 2770 ToExtend = 2771 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 2772 Neg, S->getI64Imm(1, dl), 2773 S->getI64Imm(63, dl)), 0); 2774 } else { 2775 SDValue Addi = 2776 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS, 2777 S->getI64Imm(~0ULL, dl)), 0); 2778 ToExtend = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 2779 Addi, LHS), 0); 2780 } 2781 break; 2782 } 2783 } 2784 2785 // For 64-bit sequences, the extensions are the same for the GE/LE cases. 2786 if (!Is32Bit && 2787 (CmpTy == ZeroCompare::GEZExt || CmpTy == ZeroCompare::LEZExt)) 2788 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 2789 ToExtend, S->getI64Imm(1, dl), 2790 S->getI64Imm(63, dl)), 0); 2791 if (!Is32Bit && 2792 (CmpTy == ZeroCompare::GESExt || CmpTy == ZeroCompare::LESExt)) 2793 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, ToExtend, 2794 S->getI64Imm(63, dl)), 0); 2795 2796 assert(Is32Bit && "Should have handled the 32-bit sequences above."); 2797 // For 32-bit sequences, the extensions differ between GE/LE cases. 2798 switch (CmpTy) { 2799 case ZeroCompare::GEZExt: { 2800 SDValue ShiftOps[] = { ToExtend, S->getI32Imm(1, dl), S->getI32Imm(31, dl), 2801 S->getI32Imm(31, dl) }; 2802 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, 2803 ShiftOps), 0); 2804 } 2805 case ZeroCompare::GESExt: 2806 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, ToExtend, 2807 S->getI32Imm(31, dl)), 0); 2808 case ZeroCompare::LEZExt: 2809 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, ToExtend, 2810 S->getI32Imm(1, dl)), 0); 2811 case ZeroCompare::LESExt: 2812 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, ToExtend, 2813 S->getI32Imm(-1, dl)), 0); 2814 } 2815 2816 // The above case covers all the enumerators so it can't have a default clause 2817 // to avoid compiler warnings. 2818 llvm_unreachable("Unknown zero-comparison type."); 2819 } 2820 2821 /// Produces a zero-extended result of comparing two 32-bit values according to 2822 /// the passed condition code. 2823 SDValue 2824 IntegerCompareEliminator::get32BitZExtCompare(SDValue LHS, SDValue RHS, 2825 ISD::CondCode CC, 2826 int64_t RHSValue, SDLoc dl) { 2827 if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 || 2828 CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Sext) 2829 return SDValue(); 2830 bool IsRHSZero = RHSValue == 0; 2831 bool IsRHSOne = RHSValue == 1; 2832 bool IsRHSNegOne = RHSValue == -1LL; 2833 switch (CC) { 2834 default: return SDValue(); 2835 case ISD::SETEQ: { 2836 // (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5) 2837 // (zext (setcc %a, 0, seteq)) -> (lshr (cntlzw %a), 5) 2838 SDValue Xor = IsRHSZero ? LHS : 2839 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0); 2840 SDValue Clz = 2841 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0); 2842 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), 2843 S->getI32Imm(31, dl) }; 2844 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, 2845 ShiftOps), 0); 2846 } 2847 case ISD::SETNE: { 2848 // (zext (setcc %a, %b, setne)) -> (xor (lshr (cntlzw (xor %a, %b)), 5), 1) 2849 // (zext (setcc %a, 0, setne)) -> (xor (lshr (cntlzw %a), 5), 1) 2850 SDValue Xor = IsRHSZero ? LHS : 2851 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0); 2852 SDValue Clz = 2853 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0); 2854 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), 2855 S->getI32Imm(31, dl) }; 2856 SDValue Shift = 2857 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0); 2858 return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift, 2859 S->getI32Imm(1, dl)), 0); 2860 } 2861 case ISD::SETGE: { 2862 // (zext (setcc %a, %b, setge)) -> (xor (lshr (sub %a, %b), 63), 1) 2863 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 31) 2864 if(IsRHSZero) 2865 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt); 2866 2867 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a) 2868 // by swapping inputs and falling through. 2869 std::swap(LHS, RHS); 2870 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 2871 IsRHSZero = RHSConst && RHSConst->isNullValue(); 2872 LLVM_FALLTHROUGH; 2873 } 2874 case ISD::SETLE: { 2875 if (CmpInGPR == ICGPR_NonExtIn) 2876 return SDValue(); 2877 // (zext (setcc %a, %b, setle)) -> (xor (lshr (sub %b, %a), 63), 1) 2878 // (zext (setcc %a, 0, setle)) -> (xor (lshr (- %a), 63), 1) 2879 if(IsRHSZero) { 2880 if (CmpInGPR == ICGPR_NonExtIn) 2881 return SDValue(); 2882 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt); 2883 } 2884 2885 // The upper 32-bits of the register can't be undefined for this sequence. 2886 LHS = signExtendInputIfNeeded(LHS); 2887 RHS = signExtendInputIfNeeded(RHS); 2888 SDValue Sub = 2889 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0); 2890 SDValue Shift = 2891 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Sub, 2892 S->getI64Imm(1, dl), S->getI64Imm(63, dl)), 2893 0); 2894 return 2895 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, 2896 MVT::i64, Shift, S->getI32Imm(1, dl)), 0); 2897 } 2898 case ISD::SETGT: { 2899 // (zext (setcc %a, %b, setgt)) -> (lshr (sub %b, %a), 63) 2900 // (zext (setcc %a, -1, setgt)) -> (lshr (~ %a), 31) 2901 // (zext (setcc %a, 0, setgt)) -> (lshr (- %a), 63) 2902 // Handle SETLT -1 (which is equivalent to SETGE 0). 2903 if (IsRHSNegOne) 2904 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt); 2905 2906 if (IsRHSZero) { 2907 if (CmpInGPR == ICGPR_NonExtIn) 2908 return SDValue(); 2909 // The upper 32-bits of the register can't be undefined for this sequence. 2910 LHS = signExtendInputIfNeeded(LHS); 2911 RHS = signExtendInputIfNeeded(RHS); 2912 SDValue Neg = 2913 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0); 2914 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 2915 Neg, S->getI32Imm(1, dl), S->getI32Imm(63, dl)), 0); 2916 } 2917 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as 2918 // (%b < %a) by swapping inputs and falling through. 2919 std::swap(LHS, RHS); 2920 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 2921 IsRHSZero = RHSConst && RHSConst->isNullValue(); 2922 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1; 2923 LLVM_FALLTHROUGH; 2924 } 2925 case ISD::SETLT: { 2926 // (zext (setcc %a, %b, setlt)) -> (lshr (sub %a, %b), 63) 2927 // (zext (setcc %a, 1, setlt)) -> (xor (lshr (- %a), 63), 1) 2928 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 31) 2929 // Handle SETLT 1 (which is equivalent to SETLE 0). 2930 if (IsRHSOne) { 2931 if (CmpInGPR == ICGPR_NonExtIn) 2932 return SDValue(); 2933 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt); 2934 } 2935 2936 if (IsRHSZero) { 2937 SDValue ShiftOps[] = { LHS, S->getI32Imm(1, dl), S->getI32Imm(31, dl), 2938 S->getI32Imm(31, dl) }; 2939 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, 2940 ShiftOps), 0); 2941 } 2942 2943 if (CmpInGPR == ICGPR_NonExtIn) 2944 return SDValue(); 2945 // The upper 32-bits of the register can't be undefined for this sequence. 2946 LHS = signExtendInputIfNeeded(LHS); 2947 RHS = signExtendInputIfNeeded(RHS); 2948 SDValue SUBFNode = 2949 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0); 2950 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 2951 SUBFNode, S->getI64Imm(1, dl), 2952 S->getI64Imm(63, dl)), 0); 2953 } 2954 case ISD::SETUGE: 2955 // (zext (setcc %a, %b, setuge)) -> (xor (lshr (sub %b, %a), 63), 1) 2956 // (zext (setcc %a, %b, setule)) -> (xor (lshr (sub %a, %b), 63), 1) 2957 std::swap(LHS, RHS); 2958 LLVM_FALLTHROUGH; 2959 case ISD::SETULE: { 2960 if (CmpInGPR == ICGPR_NonExtIn) 2961 return SDValue(); 2962 // The upper 32-bits of the register can't be undefined for this sequence. 2963 LHS = zeroExtendInputIfNeeded(LHS); 2964 RHS = zeroExtendInputIfNeeded(RHS); 2965 SDValue Subtract = 2966 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0); 2967 SDValue SrdiNode = 2968 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 2969 Subtract, S->getI64Imm(1, dl), 2970 S->getI64Imm(63, dl)), 0); 2971 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, SrdiNode, 2972 S->getI32Imm(1, dl)), 0); 2973 } 2974 case ISD::SETUGT: 2975 // (zext (setcc %a, %b, setugt)) -> (lshr (sub %b, %a), 63) 2976 // (zext (setcc %a, %b, setult)) -> (lshr (sub %a, %b), 63) 2977 std::swap(LHS, RHS); 2978 LLVM_FALLTHROUGH; 2979 case ISD::SETULT: { 2980 if (CmpInGPR == ICGPR_NonExtIn) 2981 return SDValue(); 2982 // The upper 32-bits of the register can't be undefined for this sequence. 2983 LHS = zeroExtendInputIfNeeded(LHS); 2984 RHS = zeroExtendInputIfNeeded(RHS); 2985 SDValue Subtract = 2986 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0); 2987 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 2988 Subtract, S->getI64Imm(1, dl), 2989 S->getI64Imm(63, dl)), 0); 2990 } 2991 } 2992 } 2993 2994 /// Produces a sign-extended result of comparing two 32-bit values according to 2995 /// the passed condition code. 2996 SDValue 2997 IntegerCompareEliminator::get32BitSExtCompare(SDValue LHS, SDValue RHS, 2998 ISD::CondCode CC, 2999 int64_t RHSValue, SDLoc dl) { 3000 if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 || 3001 CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Zext) 3002 return SDValue(); 3003 bool IsRHSZero = RHSValue == 0; 3004 bool IsRHSOne = RHSValue == 1; 3005 bool IsRHSNegOne = RHSValue == -1LL; 3006 3007 switch (CC) { 3008 default: return SDValue(); 3009 case ISD::SETEQ: { 3010 // (sext (setcc %a, %b, seteq)) -> 3011 // (ashr (shl (ctlz (xor %a, %b)), 58), 63) 3012 // (sext (setcc %a, 0, seteq)) -> 3013 // (ashr (shl (ctlz %a), 58), 63) 3014 SDValue CountInput = IsRHSZero ? LHS : 3015 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0); 3016 SDValue Cntlzw = 3017 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0); 3018 SDValue SHLOps[] = { Cntlzw, S->getI32Imm(27, dl), 3019 S->getI32Imm(5, dl), S->getI32Imm(31, dl) }; 3020 SDValue Slwi = 3021 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, SHLOps), 0); 3022 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Slwi), 0); 3023 } 3024 case ISD::SETNE: { 3025 // Bitwise xor the operands, count leading zeros, shift right by 5 bits and 3026 // flip the bit, finally take 2's complement. 3027 // (sext (setcc %a, %b, setne)) -> 3028 // (neg (xor (lshr (ctlz (xor %a, %b)), 5), 1)) 3029 // Same as above, but the first xor is not needed. 3030 // (sext (setcc %a, 0, setne)) -> 3031 // (neg (xor (lshr (ctlz %a), 5), 1)) 3032 SDValue Xor = IsRHSZero ? LHS : 3033 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0); 3034 SDValue Clz = 3035 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0); 3036 SDValue ShiftOps[] = 3037 { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), S->getI32Imm(31, dl) }; 3038 SDValue Shift = 3039 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0); 3040 SDValue Xori = 3041 SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift, 3042 S->getI32Imm(1, dl)), 0); 3043 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Xori), 0); 3044 } 3045 case ISD::SETGE: { 3046 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %a, %b), 63), -1) 3047 // (sext (setcc %a, 0, setge)) -> (ashr (~ %a), 31) 3048 if (IsRHSZero) 3049 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt); 3050 3051 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a) 3052 // by swapping inputs and falling through. 3053 std::swap(LHS, RHS); 3054 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3055 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3056 LLVM_FALLTHROUGH; 3057 } 3058 case ISD::SETLE: { 3059 if (CmpInGPR == ICGPR_NonExtIn) 3060 return SDValue(); 3061 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %b, %a), 63), -1) 3062 // (sext (setcc %a, 0, setle)) -> (add (lshr (- %a), 63), -1) 3063 if (IsRHSZero) 3064 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt); 3065 3066 // The upper 32-bits of the register can't be undefined for this sequence. 3067 LHS = signExtendInputIfNeeded(LHS); 3068 RHS = signExtendInputIfNeeded(RHS); 3069 SDValue SUBFNode = 3070 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, MVT::Glue, 3071 LHS, RHS), 0); 3072 SDValue Srdi = 3073 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 3074 SUBFNode, S->getI64Imm(1, dl), 3075 S->getI64Imm(63, dl)), 0); 3076 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Srdi, 3077 S->getI32Imm(-1, dl)), 0); 3078 } 3079 case ISD::SETGT: { 3080 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %b, %a), 63) 3081 // (sext (setcc %a, -1, setgt)) -> (ashr (~ %a), 31) 3082 // (sext (setcc %a, 0, setgt)) -> (ashr (- %a), 63) 3083 if (IsRHSNegOne) 3084 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt); 3085 if (IsRHSZero) { 3086 if (CmpInGPR == ICGPR_NonExtIn) 3087 return SDValue(); 3088 // The upper 32-bits of the register can't be undefined for this sequence. 3089 LHS = signExtendInputIfNeeded(LHS); 3090 RHS = signExtendInputIfNeeded(RHS); 3091 SDValue Neg = 3092 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0); 3093 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Neg, 3094 S->getI64Imm(63, dl)), 0); 3095 } 3096 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as 3097 // (%b < %a) by swapping inputs and falling through. 3098 std::swap(LHS, RHS); 3099 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3100 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3101 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1; 3102 LLVM_FALLTHROUGH; 3103 } 3104 case ISD::SETLT: { 3105 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %a, %b), 63) 3106 // (sext (setcc %a, 1, setgt)) -> (add (lshr (- %a), 63), -1) 3107 // (sext (setcc %a, 0, setgt)) -> (ashr %a, 31) 3108 if (IsRHSOne) { 3109 if (CmpInGPR == ICGPR_NonExtIn) 3110 return SDValue(); 3111 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt); 3112 } 3113 if (IsRHSZero) 3114 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, LHS, 3115 S->getI32Imm(31, dl)), 0); 3116 3117 if (CmpInGPR == ICGPR_NonExtIn) 3118 return SDValue(); 3119 // The upper 32-bits of the register can't be undefined for this sequence. 3120 LHS = signExtendInputIfNeeded(LHS); 3121 RHS = signExtendInputIfNeeded(RHS); 3122 SDValue SUBFNode = 3123 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0); 3124 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, 3125 SUBFNode, S->getI64Imm(63, dl)), 0); 3126 } 3127 case ISD::SETUGE: 3128 // (sext (setcc %a, %b, setuge)) -> (add (lshr (sub %a, %b), 63), -1) 3129 // (sext (setcc %a, %b, setule)) -> (add (lshr (sub %b, %a), 63), -1) 3130 std::swap(LHS, RHS); 3131 LLVM_FALLTHROUGH; 3132 case ISD::SETULE: { 3133 if (CmpInGPR == ICGPR_NonExtIn) 3134 return SDValue(); 3135 // The upper 32-bits of the register can't be undefined for this sequence. 3136 LHS = zeroExtendInputIfNeeded(LHS); 3137 RHS = zeroExtendInputIfNeeded(RHS); 3138 SDValue Subtract = 3139 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0); 3140 SDValue Shift = 3141 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Subtract, 3142 S->getI32Imm(1, dl), S->getI32Imm(63,dl)), 3143 0); 3144 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Shift, 3145 S->getI32Imm(-1, dl)), 0); 3146 } 3147 case ISD::SETUGT: 3148 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %b, %a), 63) 3149 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %a, %b), 63) 3150 std::swap(LHS, RHS); 3151 LLVM_FALLTHROUGH; 3152 case ISD::SETULT: { 3153 if (CmpInGPR == ICGPR_NonExtIn) 3154 return SDValue(); 3155 // The upper 32-bits of the register can't be undefined for this sequence. 3156 LHS = zeroExtendInputIfNeeded(LHS); 3157 RHS = zeroExtendInputIfNeeded(RHS); 3158 SDValue Subtract = 3159 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0); 3160 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, 3161 Subtract, S->getI64Imm(63, dl)), 0); 3162 } 3163 } 3164 } 3165 3166 /// Produces a zero-extended result of comparing two 64-bit values according to 3167 /// the passed condition code. 3168 SDValue 3169 IntegerCompareEliminator::get64BitZExtCompare(SDValue LHS, SDValue RHS, 3170 ISD::CondCode CC, 3171 int64_t RHSValue, SDLoc dl) { 3172 if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 || 3173 CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Sext) 3174 return SDValue(); 3175 bool IsRHSZero = RHSValue == 0; 3176 bool IsRHSOne = RHSValue == 1; 3177 bool IsRHSNegOne = RHSValue == -1LL; 3178 switch (CC) { 3179 default: return SDValue(); 3180 case ISD::SETEQ: { 3181 // (zext (setcc %a, %b, seteq)) -> (lshr (ctlz (xor %a, %b)), 6) 3182 // (zext (setcc %a, 0, seteq)) -> (lshr (ctlz %a), 6) 3183 SDValue Xor = IsRHSZero ? LHS : 3184 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0); 3185 SDValue Clz = 3186 SDValue(CurDAG->getMachineNode(PPC::CNTLZD, dl, MVT::i64, Xor), 0); 3187 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Clz, 3188 S->getI64Imm(58, dl), 3189 S->getI64Imm(63, dl)), 0); 3190 } 3191 case ISD::SETNE: { 3192 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1) 3193 // (zext (setcc %a, %b, setne)) -> (sube addc.reg, addc.reg, addc.CA) 3194 // {addcz.reg, addcz.CA} = (addcarry %a, -1) 3195 // (zext (setcc %a, 0, setne)) -> (sube addcz.reg, addcz.reg, addcz.CA) 3196 SDValue Xor = IsRHSZero ? LHS : 3197 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0); 3198 SDValue AC = 3199 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue, 3200 Xor, S->getI32Imm(~0U, dl)), 0); 3201 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, AC, 3202 Xor, AC.getValue(1)), 0); 3203 } 3204 case ISD::SETGE: { 3205 // {subc.reg, subc.CA} = (subcarry %a, %b) 3206 // (zext (setcc %a, %b, setge)) -> 3207 // (adde (lshr %b, 63), (ashr %a, 63), subc.CA) 3208 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 63) 3209 if (IsRHSZero) 3210 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt); 3211 std::swap(LHS, RHS); 3212 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3213 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3214 LLVM_FALLTHROUGH; 3215 } 3216 case ISD::SETLE: { 3217 // {subc.reg, subc.CA} = (subcarry %b, %a) 3218 // (zext (setcc %a, %b, setge)) -> 3219 // (adde (lshr %a, 63), (ashr %b, 63), subc.CA) 3220 // (zext (setcc %a, 0, setge)) -> (lshr (or %a, (add %a, -1)), 63) 3221 if (IsRHSZero) 3222 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt); 3223 SDValue ShiftL = 3224 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS, 3225 S->getI64Imm(1, dl), 3226 S->getI64Imm(63, dl)), 0); 3227 SDValue ShiftR = 3228 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS, 3229 S->getI64Imm(63, dl)), 0); 3230 SDValue SubtractCarry = 3231 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3232 LHS, RHS), 1); 3233 return SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue, 3234 ShiftR, ShiftL, SubtractCarry), 0); 3235 } 3236 case ISD::SETGT: { 3237 // {subc.reg, subc.CA} = (subcarry %b, %a) 3238 // (zext (setcc %a, %b, setgt)) -> 3239 // (xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1) 3240 // (zext (setcc %a, 0, setgt)) -> (lshr (nor (add %a, -1), %a), 63) 3241 if (IsRHSNegOne) 3242 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt); 3243 if (IsRHSZero) { 3244 SDValue Addi = 3245 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS, 3246 S->getI64Imm(~0ULL, dl)), 0); 3247 SDValue Nor = 3248 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Addi, LHS), 0); 3249 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Nor, 3250 S->getI64Imm(1, dl), 3251 S->getI64Imm(63, dl)), 0); 3252 } 3253 std::swap(LHS, RHS); 3254 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3255 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3256 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1; 3257 LLVM_FALLTHROUGH; 3258 } 3259 case ISD::SETLT: { 3260 // {subc.reg, subc.CA} = (subcarry %a, %b) 3261 // (zext (setcc %a, %b, setlt)) -> 3262 // (xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1) 3263 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 63) 3264 if (IsRHSOne) 3265 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt); 3266 if (IsRHSZero) 3267 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS, 3268 S->getI64Imm(1, dl), 3269 S->getI64Imm(63, dl)), 0); 3270 SDValue SRADINode = 3271 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, 3272 LHS, S->getI64Imm(63, dl)), 0); 3273 SDValue SRDINode = 3274 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 3275 RHS, S->getI64Imm(1, dl), 3276 S->getI64Imm(63, dl)), 0); 3277 SDValue SUBFC8Carry = 3278 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3279 RHS, LHS), 1); 3280 SDValue ADDE8Node = 3281 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue, 3282 SRDINode, SRADINode, SUBFC8Carry), 0); 3283 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, 3284 ADDE8Node, S->getI64Imm(1, dl)), 0); 3285 } 3286 case ISD::SETUGE: 3287 // {subc.reg, subc.CA} = (subcarry %a, %b) 3288 // (zext (setcc %a, %b, setuge)) -> (add (sube %b, %b, subc.CA), 1) 3289 std::swap(LHS, RHS); 3290 LLVM_FALLTHROUGH; 3291 case ISD::SETULE: { 3292 // {subc.reg, subc.CA} = (subcarry %b, %a) 3293 // (zext (setcc %a, %b, setule)) -> (add (sube %a, %a, subc.CA), 1) 3294 SDValue SUBFC8Carry = 3295 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3296 LHS, RHS), 1); 3297 SDValue SUBFE8Node = 3298 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue, 3299 LHS, LHS, SUBFC8Carry), 0); 3300 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, 3301 SUBFE8Node, S->getI64Imm(1, dl)), 0); 3302 } 3303 case ISD::SETUGT: 3304 // {subc.reg, subc.CA} = (subcarry %b, %a) 3305 // (zext (setcc %a, %b, setugt)) -> -(sube %b, %b, subc.CA) 3306 std::swap(LHS, RHS); 3307 LLVM_FALLTHROUGH; 3308 case ISD::SETULT: { 3309 // {subc.reg, subc.CA} = (subcarry %a, %b) 3310 // (zext (setcc %a, %b, setult)) -> -(sube %a, %a, subc.CA) 3311 SDValue SubtractCarry = 3312 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3313 RHS, LHS), 1); 3314 SDValue ExtSub = 3315 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, 3316 LHS, LHS, SubtractCarry), 0); 3317 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, 3318 ExtSub), 0); 3319 } 3320 } 3321 } 3322 3323 /// Produces a sign-extended result of comparing two 64-bit values according to 3324 /// the passed condition code. 3325 SDValue 3326 IntegerCompareEliminator::get64BitSExtCompare(SDValue LHS, SDValue RHS, 3327 ISD::CondCode CC, 3328 int64_t RHSValue, SDLoc dl) { 3329 if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 || 3330 CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Zext) 3331 return SDValue(); 3332 bool IsRHSZero = RHSValue == 0; 3333 bool IsRHSOne = RHSValue == 1; 3334 bool IsRHSNegOne = RHSValue == -1LL; 3335 switch (CC) { 3336 default: return SDValue(); 3337 case ISD::SETEQ: { 3338 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1) 3339 // (sext (setcc %a, %b, seteq)) -> (sube addc.reg, addc.reg, addc.CA) 3340 // {addcz.reg, addcz.CA} = (addcarry %a, -1) 3341 // (sext (setcc %a, 0, seteq)) -> (sube addcz.reg, addcz.reg, addcz.CA) 3342 SDValue AddInput = IsRHSZero ? LHS : 3343 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0); 3344 SDValue Addic = 3345 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue, 3346 AddInput, S->getI32Imm(~0U, dl)), 0); 3347 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, Addic, 3348 Addic, Addic.getValue(1)), 0); 3349 } 3350 case ISD::SETNE: { 3351 // {subfc.reg, subfc.CA} = (subcarry 0, (xor %a, %b)) 3352 // (sext (setcc %a, %b, setne)) -> (sube subfc.reg, subfc.reg, subfc.CA) 3353 // {subfcz.reg, subfcz.CA} = (subcarry 0, %a) 3354 // (sext (setcc %a, 0, setne)) -> (sube subfcz.reg, subfcz.reg, subfcz.CA) 3355 SDValue Xor = IsRHSZero ? LHS : 3356 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0); 3357 SDValue SC = 3358 SDValue(CurDAG->getMachineNode(PPC::SUBFIC8, dl, MVT::i64, MVT::Glue, 3359 Xor, S->getI32Imm(0, dl)), 0); 3360 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, SC, 3361 SC, SC.getValue(1)), 0); 3362 } 3363 case ISD::SETGE: { 3364 // {subc.reg, subc.CA} = (subcarry %a, %b) 3365 // (zext (setcc %a, %b, setge)) -> 3366 // (- (adde (lshr %b, 63), (ashr %a, 63), subc.CA)) 3367 // (zext (setcc %a, 0, setge)) -> (~ (ashr %a, 63)) 3368 if (IsRHSZero) 3369 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt); 3370 std::swap(LHS, RHS); 3371 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3372 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3373 LLVM_FALLTHROUGH; 3374 } 3375 case ISD::SETLE: { 3376 // {subc.reg, subc.CA} = (subcarry %b, %a) 3377 // (zext (setcc %a, %b, setge)) -> 3378 // (- (adde (lshr %a, 63), (ashr %b, 63), subc.CA)) 3379 // (zext (setcc %a, 0, setge)) -> (ashr (or %a, (add %a, -1)), 63) 3380 if (IsRHSZero) 3381 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt); 3382 SDValue ShiftR = 3383 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS, 3384 S->getI64Imm(63, dl)), 0); 3385 SDValue ShiftL = 3386 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS, 3387 S->getI64Imm(1, dl), 3388 S->getI64Imm(63, dl)), 0); 3389 SDValue SubtractCarry = 3390 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3391 LHS, RHS), 1); 3392 SDValue Adde = 3393 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue, 3394 ShiftR, ShiftL, SubtractCarry), 0); 3395 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, Adde), 0); 3396 } 3397 case ISD::SETGT: { 3398 // {subc.reg, subc.CA} = (subcarry %b, %a) 3399 // (zext (setcc %a, %b, setgt)) -> 3400 // -(xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1) 3401 // (zext (setcc %a, 0, setgt)) -> (ashr (nor (add %a, -1), %a), 63) 3402 if (IsRHSNegOne) 3403 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt); 3404 if (IsRHSZero) { 3405 SDValue Add = 3406 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS, 3407 S->getI64Imm(-1, dl)), 0); 3408 SDValue Nor = 3409 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Add, LHS), 0); 3410 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Nor, 3411 S->getI64Imm(63, dl)), 0); 3412 } 3413 std::swap(LHS, RHS); 3414 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3415 IsRHSZero = RHSConst && RHSConst->isNullValue(); 3416 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1; 3417 LLVM_FALLTHROUGH; 3418 } 3419 case ISD::SETLT: { 3420 // {subc.reg, subc.CA} = (subcarry %a, %b) 3421 // (zext (setcc %a, %b, setlt)) -> 3422 // -(xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1) 3423 // (zext (setcc %a, 0, setlt)) -> (ashr %a, 63) 3424 if (IsRHSOne) 3425 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt); 3426 if (IsRHSZero) { 3427 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, LHS, 3428 S->getI64Imm(63, dl)), 0); 3429 } 3430 SDValue SRADINode = 3431 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, 3432 LHS, S->getI64Imm(63, dl)), 0); 3433 SDValue SRDINode = 3434 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, 3435 RHS, S->getI64Imm(1, dl), 3436 S->getI64Imm(63, dl)), 0); 3437 SDValue SUBFC8Carry = 3438 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3439 RHS, LHS), 1); 3440 SDValue ADDE8Node = 3441 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, 3442 SRDINode, SRADINode, SUBFC8Carry), 0); 3443 SDValue XORI8Node = 3444 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, 3445 ADDE8Node, S->getI64Imm(1, dl)), 0); 3446 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, 3447 XORI8Node), 0); 3448 } 3449 case ISD::SETUGE: 3450 // {subc.reg, subc.CA} = (subcarry %a, %b) 3451 // (sext (setcc %a, %b, setuge)) -> ~(sube %b, %b, subc.CA) 3452 std::swap(LHS, RHS); 3453 LLVM_FALLTHROUGH; 3454 case ISD::SETULE: { 3455 // {subc.reg, subc.CA} = (subcarry %b, %a) 3456 // (sext (setcc %a, %b, setule)) -> ~(sube %a, %a, subc.CA) 3457 SDValue SubtractCarry = 3458 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3459 LHS, RHS), 1); 3460 SDValue ExtSub = 3461 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue, LHS, 3462 LHS, SubtractCarry), 0); 3463 return SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, 3464 ExtSub, ExtSub), 0); 3465 } 3466 case ISD::SETUGT: 3467 // {subc.reg, subc.CA} = (subcarry %b, %a) 3468 // (sext (setcc %a, %b, setugt)) -> (sube %b, %b, subc.CA) 3469 std::swap(LHS, RHS); 3470 LLVM_FALLTHROUGH; 3471 case ISD::SETULT: { 3472 // {subc.reg, subc.CA} = (subcarry %a, %b) 3473 // (sext (setcc %a, %b, setult)) -> (sube %a, %a, subc.CA) 3474 SDValue SubCarry = 3475 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue, 3476 RHS, LHS), 1); 3477 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, 3478 LHS, LHS, SubCarry), 0); 3479 } 3480 } 3481 } 3482 3483 /// Do all uses of this SDValue need the result in a GPR? 3484 /// This is meant to be used on values that have type i1 since 3485 /// it is somewhat meaningless to ask if values of other types 3486 /// should be kept in GPR's. 3487 static bool allUsesExtend(SDValue Compare, SelectionDAG *CurDAG) { 3488 assert(Compare.getOpcode() == ISD::SETCC && 3489 "An ISD::SETCC node required here."); 3490 3491 // For values that have a single use, the caller should obviously already have 3492 // checked if that use is an extending use. We check the other uses here. 3493 if (Compare.hasOneUse()) 3494 return true; 3495 // We want the value in a GPR if it is being extended, used for a select, or 3496 // used in logical operations. 3497 for (auto CompareUse : Compare.getNode()->uses()) 3498 if (CompareUse->getOpcode() != ISD::SIGN_EXTEND && 3499 CompareUse->getOpcode() != ISD::ZERO_EXTEND && 3500 CompareUse->getOpcode() != ISD::SELECT && 3501 !isLogicOp(CompareUse->getOpcode())) { 3502 OmittedForNonExtendUses++; 3503 return false; 3504 } 3505 return true; 3506 } 3507 3508 /// Returns an equivalent of a SETCC node but with the result the same width as 3509 /// the inputs. This can also be used for SELECT_CC if either the true or false 3510 /// values is a power of two while the other is zero. 3511 SDValue IntegerCompareEliminator::getSETCCInGPR(SDValue Compare, 3512 SetccInGPROpts ConvOpts) { 3513 assert((Compare.getOpcode() == ISD::SETCC || 3514 Compare.getOpcode() == ISD::SELECT_CC) && 3515 "An ISD::SETCC node required here."); 3516 3517 // Don't convert this comparison to a GPR sequence because there are uses 3518 // of the i1 result (i.e. uses that require the result in the CR). 3519 if ((Compare.getOpcode() == ISD::SETCC) && !allUsesExtend(Compare, CurDAG)) 3520 return SDValue(); 3521 3522 SDValue LHS = Compare.getOperand(0); 3523 SDValue RHS = Compare.getOperand(1); 3524 3525 // The condition code is operand 2 for SETCC and operand 4 for SELECT_CC. 3526 int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2; 3527 ISD::CondCode CC = 3528 cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get(); 3529 EVT InputVT = LHS.getValueType(); 3530 if (InputVT != MVT::i32 && InputVT != MVT::i64) 3531 return SDValue(); 3532 3533 if (ConvOpts == SetccInGPROpts::ZExtInvert || 3534 ConvOpts == SetccInGPROpts::SExtInvert) 3535 CC = ISD::getSetCCInverse(CC, true); 3536 3537 bool Inputs32Bit = InputVT == MVT::i32; 3538 3539 SDLoc dl(Compare); 3540 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS); 3541 int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX; 3542 bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig || 3543 ConvOpts == SetccInGPROpts::SExtInvert; 3544 3545 if (IsSext && Inputs32Bit) 3546 return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl); 3547 else if (Inputs32Bit) 3548 return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl); 3549 else if (IsSext) 3550 return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl); 3551 return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl); 3552 } 3553 3554 } // end anonymous namespace 3555 3556 bool PPCDAGToDAGISel::tryIntCompareInGPR(SDNode *N) { 3557 if (N->getValueType(0) != MVT::i32 && 3558 N->getValueType(0) != MVT::i64) 3559 return false; 3560 3561 // This optimization will emit code that assumes 64-bit registers 3562 // so we don't want to run it in 32-bit mode. Also don't run it 3563 // on functions that are not to be optimized. 3564 if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64()) 3565 return false; 3566 3567 switch (N->getOpcode()) { 3568 default: break; 3569 case ISD::ZERO_EXTEND: 3570 case ISD::SIGN_EXTEND: 3571 case ISD::AND: 3572 case ISD::OR: 3573 case ISD::XOR: { 3574 IntegerCompareEliminator ICmpElim(CurDAG, this); 3575 if (SDNode *New = ICmpElim.Select(N)) { 3576 ReplaceNode(N, New); 3577 return true; 3578 } 3579 } 3580 } 3581 return false; 3582 } 3583 3584 bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) { 3585 if (N->getValueType(0) != MVT::i32 && 3586 N->getValueType(0) != MVT::i64) 3587 return false; 3588 3589 if (!UseBitPermRewriter) 3590 return false; 3591 3592 switch (N->getOpcode()) { 3593 default: break; 3594 case ISD::ROTL: 3595 case ISD::SHL: 3596 case ISD::SRL: 3597 case ISD::AND: 3598 case ISD::OR: { 3599 BitPermutationSelector BPS(CurDAG); 3600 if (SDNode *New = BPS.Select(N)) { 3601 ReplaceNode(N, New); 3602 return true; 3603 } 3604 return false; 3605 } 3606 } 3607 3608 return false; 3609 } 3610 3611 /// SelectCC - Select a comparison of the specified values with the specified 3612 /// condition code, returning the CR# of the expression. 3613 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, 3614 const SDLoc &dl) { 3615 // Always select the LHS. 3616 unsigned Opc; 3617 3618 if (LHS.getValueType() == MVT::i32) { 3619 unsigned Imm; 3620 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3621 if (isInt32Immediate(RHS, Imm)) { 3622 // SETEQ/SETNE comparison with 16-bit immediate, fold it. 3623 if (isUInt<16>(Imm)) 3624 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS, 3625 getI32Imm(Imm & 0xFFFF, dl)), 3626 0); 3627 // If this is a 16-bit signed immediate, fold it. 3628 if (isInt<16>((int)Imm)) 3629 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS, 3630 getI32Imm(Imm & 0xFFFF, dl)), 3631 0); 3632 3633 // For non-equality comparisons, the default code would materialize the 3634 // constant, then compare against it, like this: 3635 // lis r2, 4660 3636 // ori r2, r2, 22136 3637 // cmpw cr0, r3, r2 3638 // Since we are just comparing for equality, we can emit this instead: 3639 // xoris r0,r3,0x1234 3640 // cmplwi cr0,r0,0x5678 3641 // beq cr0,L6 3642 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS, 3643 getI32Imm(Imm >> 16, dl)), 0); 3644 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor, 3645 getI32Imm(Imm & 0xFFFF, dl)), 0); 3646 } 3647 Opc = PPC::CMPLW; 3648 } else if (ISD::isUnsignedIntSetCC(CC)) { 3649 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm)) 3650 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS, 3651 getI32Imm(Imm & 0xFFFF, dl)), 0); 3652 Opc = PPC::CMPLW; 3653 } else { 3654 int16_t SImm; 3655 if (isIntS16Immediate(RHS, SImm)) 3656 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS, 3657 getI32Imm((int)SImm & 0xFFFF, 3658 dl)), 3659 0); 3660 Opc = PPC::CMPW; 3661 } 3662 } else if (LHS.getValueType() == MVT::i64) { 3663 uint64_t Imm; 3664 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 3665 if (isInt64Immediate(RHS.getNode(), Imm)) { 3666 // SETEQ/SETNE comparison with 16-bit immediate, fold it. 3667 if (isUInt<16>(Imm)) 3668 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS, 3669 getI32Imm(Imm & 0xFFFF, dl)), 3670 0); 3671 // If this is a 16-bit signed immediate, fold it. 3672 if (isInt<16>(Imm)) 3673 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS, 3674 getI32Imm(Imm & 0xFFFF, dl)), 3675 0); 3676 3677 // For non-equality comparisons, the default code would materialize the 3678 // constant, then compare against it, like this: 3679 // lis r2, 4660 3680 // ori r2, r2, 22136 3681 // cmpd cr0, r3, r2 3682 // Since we are just comparing for equality, we can emit this instead: 3683 // xoris r0,r3,0x1234 3684 // cmpldi cr0,r0,0x5678 3685 // beq cr0,L6 3686 if (isUInt<32>(Imm)) { 3687 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS, 3688 getI64Imm(Imm >> 16, dl)), 0); 3689 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor, 3690 getI64Imm(Imm & 0xFFFF, dl)), 3691 0); 3692 } 3693 } 3694 Opc = PPC::CMPLD; 3695 } else if (ISD::isUnsignedIntSetCC(CC)) { 3696 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm)) 3697 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS, 3698 getI64Imm(Imm & 0xFFFF, dl)), 0); 3699 Opc = PPC::CMPLD; 3700 } else { 3701 int16_t SImm; 3702 if (isIntS16Immediate(RHS, SImm)) 3703 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS, 3704 getI64Imm(SImm & 0xFFFF, dl)), 3705 0); 3706 Opc = PPC::CMPD; 3707 } 3708 } else if (LHS.getValueType() == MVT::f32) { 3709 if (PPCSubTarget->hasSPE()) { 3710 switch (CC) { 3711 default: 3712 case ISD::SETEQ: 3713 case ISD::SETNE: 3714 Opc = PPC::EFSCMPEQ; 3715 break; 3716 case ISD::SETLT: 3717 case ISD::SETGE: 3718 case ISD::SETOLT: 3719 case ISD::SETOGE: 3720 case ISD::SETULT: 3721 case ISD::SETUGE: 3722 Opc = PPC::EFSCMPLT; 3723 break; 3724 case ISD::SETGT: 3725 case ISD::SETLE: 3726 case ISD::SETOGT: 3727 case ISD::SETOLE: 3728 case ISD::SETUGT: 3729 case ISD::SETULE: 3730 Opc = PPC::EFSCMPGT; 3731 break; 3732 } 3733 } else 3734 Opc = PPC::FCMPUS; 3735 } else if (LHS.getValueType() == MVT::f64) { 3736 if (PPCSubTarget->hasSPE()) { 3737 switch (CC) { 3738 default: 3739 case ISD::SETEQ: 3740 case ISD::SETNE: 3741 Opc = PPC::EFDCMPEQ; 3742 break; 3743 case ISD::SETLT: 3744 case ISD::SETGE: 3745 case ISD::SETOLT: 3746 case ISD::SETOGE: 3747 case ISD::SETULT: 3748 case ISD::SETUGE: 3749 Opc = PPC::EFDCMPLT; 3750 break; 3751 case ISD::SETGT: 3752 case ISD::SETLE: 3753 case ISD::SETOGT: 3754 case ISD::SETOLE: 3755 case ISD::SETUGT: 3756 case ISD::SETULE: 3757 Opc = PPC::EFDCMPGT; 3758 break; 3759 } 3760 } else 3761 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD; 3762 } else { 3763 assert(LHS.getValueType() == MVT::f128 && "Unknown vt!"); 3764 assert(PPCSubTarget->hasVSX() && "__float128 requires VSX"); 3765 Opc = PPC::XSCMPUQP; 3766 } 3767 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0); 3768 } 3769 3770 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) { 3771 switch (CC) { 3772 case ISD::SETUEQ: 3773 case ISD::SETONE: 3774 case ISD::SETOLE: 3775 case ISD::SETOGE: 3776 llvm_unreachable("Should be lowered by legalize!"); 3777 default: llvm_unreachable("Unknown condition!"); 3778 case ISD::SETOEQ: 3779 case ISD::SETEQ: return PPC::PRED_EQ; 3780 case ISD::SETUNE: 3781 case ISD::SETNE: return PPC::PRED_NE; 3782 case ISD::SETOLT: 3783 case ISD::SETLT: return PPC::PRED_LT; 3784 case ISD::SETULE: 3785 case ISD::SETLE: return PPC::PRED_LE; 3786 case ISD::SETOGT: 3787 case ISD::SETGT: return PPC::PRED_GT; 3788 case ISD::SETUGE: 3789 case ISD::SETGE: return PPC::PRED_GE; 3790 case ISD::SETO: return PPC::PRED_NU; 3791 case ISD::SETUO: return PPC::PRED_UN; 3792 // These two are invalid for floating point. Assume we have int. 3793 case ISD::SETULT: return PPC::PRED_LT; 3794 case ISD::SETUGT: return PPC::PRED_GT; 3795 } 3796 } 3797 3798 /// getCRIdxForSetCC - Return the index of the condition register field 3799 /// associated with the SetCC condition, and whether or not the field is 3800 /// treated as inverted. That is, lt = 0; ge = 0 inverted. 3801 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) { 3802 Invert = false; 3803 switch (CC) { 3804 default: llvm_unreachable("Unknown condition!"); 3805 case ISD::SETOLT: 3806 case ISD::SETLT: return 0; // Bit #0 = SETOLT 3807 case ISD::SETOGT: 3808 case ISD::SETGT: return 1; // Bit #1 = SETOGT 3809 case ISD::SETOEQ: 3810 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ 3811 case ISD::SETUO: return 3; // Bit #3 = SETUO 3812 case ISD::SETUGE: 3813 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE 3814 case ISD::SETULE: 3815 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE 3816 case ISD::SETUNE: 3817 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE 3818 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO 3819 case ISD::SETUEQ: 3820 case ISD::SETOGE: 3821 case ISD::SETOLE: 3822 case ISD::SETONE: 3823 llvm_unreachable("Invalid branch code: should be expanded by legalize"); 3824 // These are invalid for floating point. Assume integer. 3825 case ISD::SETULT: return 0; 3826 case ISD::SETUGT: return 1; 3827 } 3828 } 3829 3830 // getVCmpInst: return the vector compare instruction for the specified 3831 // vector type and condition code. Since this is for altivec specific code, 3832 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32). 3833 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC, 3834 bool HasVSX, bool &Swap, bool &Negate) { 3835 Swap = false; 3836 Negate = false; 3837 3838 if (VecVT.isFloatingPoint()) { 3839 /* Handle some cases by swapping input operands. */ 3840 switch (CC) { 3841 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break; 3842 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break; 3843 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break; 3844 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break; 3845 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break; 3846 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break; 3847 default: break; 3848 } 3849 /* Handle some cases by negating the result. */ 3850 switch (CC) { 3851 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break; 3852 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break; 3853 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break; 3854 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break; 3855 default: break; 3856 } 3857 /* We have instructions implementing the remaining cases. */ 3858 switch (CC) { 3859 case ISD::SETEQ: 3860 case ISD::SETOEQ: 3861 if (VecVT == MVT::v4f32) 3862 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP; 3863 else if (VecVT == MVT::v2f64) 3864 return PPC::XVCMPEQDP; 3865 break; 3866 case ISD::SETGT: 3867 case ISD::SETOGT: 3868 if (VecVT == MVT::v4f32) 3869 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP; 3870 else if (VecVT == MVT::v2f64) 3871 return PPC::XVCMPGTDP; 3872 break; 3873 case ISD::SETGE: 3874 case ISD::SETOGE: 3875 if (VecVT == MVT::v4f32) 3876 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP; 3877 else if (VecVT == MVT::v2f64) 3878 return PPC::XVCMPGEDP; 3879 break; 3880 default: 3881 break; 3882 } 3883 llvm_unreachable("Invalid floating-point vector compare condition"); 3884 } else { 3885 /* Handle some cases by swapping input operands. */ 3886 switch (CC) { 3887 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break; 3888 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break; 3889 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break; 3890 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break; 3891 default: break; 3892 } 3893 /* Handle some cases by negating the result. */ 3894 switch (CC) { 3895 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break; 3896 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break; 3897 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break; 3898 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break; 3899 default: break; 3900 } 3901 /* We have instructions implementing the remaining cases. */ 3902 switch (CC) { 3903 case ISD::SETEQ: 3904 case ISD::SETUEQ: 3905 if (VecVT == MVT::v16i8) 3906 return PPC::VCMPEQUB; 3907 else if (VecVT == MVT::v8i16) 3908 return PPC::VCMPEQUH; 3909 else if (VecVT == MVT::v4i32) 3910 return PPC::VCMPEQUW; 3911 else if (VecVT == MVT::v2i64) 3912 return PPC::VCMPEQUD; 3913 break; 3914 case ISD::SETGT: 3915 if (VecVT == MVT::v16i8) 3916 return PPC::VCMPGTSB; 3917 else if (VecVT == MVT::v8i16) 3918 return PPC::VCMPGTSH; 3919 else if (VecVT == MVT::v4i32) 3920 return PPC::VCMPGTSW; 3921 else if (VecVT == MVT::v2i64) 3922 return PPC::VCMPGTSD; 3923 break; 3924 case ISD::SETUGT: 3925 if (VecVT == MVT::v16i8) 3926 return PPC::VCMPGTUB; 3927 else if (VecVT == MVT::v8i16) 3928 return PPC::VCMPGTUH; 3929 else if (VecVT == MVT::v4i32) 3930 return PPC::VCMPGTUW; 3931 else if (VecVT == MVT::v2i64) 3932 return PPC::VCMPGTUD; 3933 break; 3934 default: 3935 break; 3936 } 3937 llvm_unreachable("Invalid integer vector compare condition"); 3938 } 3939 } 3940 3941 bool PPCDAGToDAGISel::trySETCC(SDNode *N) { 3942 SDLoc dl(N); 3943 unsigned Imm; 3944 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 3945 EVT PtrVT = 3946 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout()); 3947 bool isPPC64 = (PtrVT == MVT::i64); 3948 3949 if (!PPCSubTarget->useCRBits() && 3950 isInt32Immediate(N->getOperand(1), Imm)) { 3951 // We can codegen setcc op, imm very efficiently compared to a brcond. 3952 // Check for those cases here. 3953 // setcc op, 0 3954 if (Imm == 0) { 3955 SDValue Op = N->getOperand(0); 3956 switch (CC) { 3957 default: break; 3958 case ISD::SETEQ: { 3959 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0); 3960 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl), 3961 getI32Imm(31, dl) }; 3962 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 3963 return true; 3964 } 3965 case ISD::SETNE: { 3966 if (isPPC64) break; 3967 SDValue AD = 3968 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 3969 Op, getI32Imm(~0U, dl)), 0); 3970 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1)); 3971 return true; 3972 } 3973 case ISD::SETLT: { 3974 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl), 3975 getI32Imm(31, dl) }; 3976 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 3977 return true; 3978 } 3979 case ISD::SETGT: { 3980 SDValue T = 3981 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0); 3982 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0); 3983 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl), 3984 getI32Imm(31, dl) }; 3985 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 3986 return true; 3987 } 3988 } 3989 } else if (Imm == ~0U) { // setcc op, -1 3990 SDValue Op = N->getOperand(0); 3991 switch (CC) { 3992 default: break; 3993 case ISD::SETEQ: 3994 if (isPPC64) break; 3995 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 3996 Op, getI32Imm(1, dl)), 0); 3997 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 3998 SDValue(CurDAG->getMachineNode(PPC::LI, dl, 3999 MVT::i32, 4000 getI32Imm(0, dl)), 4001 0), Op.getValue(1)); 4002 return true; 4003 case ISD::SETNE: { 4004 if (isPPC64) break; 4005 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0); 4006 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 4007 Op, getI32Imm(~0U, dl)); 4008 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op, 4009 SDValue(AD, 1)); 4010 return true; 4011 } 4012 case ISD::SETLT: { 4013 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op, 4014 getI32Imm(1, dl)), 0); 4015 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD, 4016 Op), 0); 4017 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl), 4018 getI32Imm(31, dl) }; 4019 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4020 return true; 4021 } 4022 case ISD::SETGT: { 4023 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl), 4024 getI32Imm(31, dl) }; 4025 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 4026 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl)); 4027 return true; 4028 } 4029 } 4030 } 4031 } 4032 4033 SDValue LHS = N->getOperand(0); 4034 SDValue RHS = N->getOperand(1); 4035 4036 // Altivec Vector compare instructions do not set any CR register by default and 4037 // vector compare operations return the same type as the operands. 4038 if (LHS.getValueType().isVector()) { 4039 if (PPCSubTarget->hasQPX() || PPCSubTarget->hasSPE()) 4040 return false; 4041 4042 EVT VecVT = LHS.getValueType(); 4043 bool Swap, Negate; 4044 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC, 4045 PPCSubTarget->hasVSX(), Swap, Negate); 4046 if (Swap) 4047 std::swap(LHS, RHS); 4048 4049 EVT ResVT = VecVT.changeVectorElementTypeToInteger(); 4050 if (Negate) { 4051 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0); 4052 CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR, 4053 ResVT, VCmp, VCmp); 4054 return true; 4055 } 4056 4057 CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS); 4058 return true; 4059 } 4060 4061 if (PPCSubTarget->useCRBits()) 4062 return false; 4063 4064 bool Inv; 4065 unsigned Idx = getCRIdxForSetCC(CC, Inv); 4066 SDValue CCReg = SelectCC(LHS, RHS, CC, dl); 4067 SDValue IntCR; 4068 4069 // SPE e*cmp* instructions only set the 'gt' bit, so hard-code that 4070 // The correct compare instruction is already set by SelectCC() 4071 if (PPCSubTarget->hasSPE() && LHS.getValueType().isFloatingPoint()) { 4072 Idx = 1; 4073 } 4074 4075 // Force the ccreg into CR7. 4076 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32); 4077 4078 SDValue InFlag(nullptr, 0); // Null incoming flag value. 4079 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg, 4080 InFlag).getValue(1); 4081 4082 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg, 4083 CCReg), 0); 4084 4085 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl), 4086 getI32Imm(31, dl), getI32Imm(31, dl) }; 4087 if (!Inv) { 4088 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4089 return true; 4090 } 4091 4092 // Get the specified bit. 4093 SDValue Tmp = 4094 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 4095 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl)); 4096 return true; 4097 } 4098 4099 /// Does this node represent a load/store node whose address can be represented 4100 /// with a register plus an immediate that's a multiple of \p Val: 4101 bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const { 4102 LoadSDNode *LDN = dyn_cast<LoadSDNode>(N); 4103 StoreSDNode *STN = dyn_cast<StoreSDNode>(N); 4104 SDValue AddrOp; 4105 if (LDN) 4106 AddrOp = LDN->getOperand(1); 4107 else if (STN) 4108 AddrOp = STN->getOperand(2); 4109 4110 // If the address points a frame object or a frame object with an offset, 4111 // we need to check the object alignment. 4112 short Imm = 0; 4113 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>( 4114 AddrOp.getOpcode() == ISD::ADD ? AddrOp.getOperand(0) : 4115 AddrOp)) { 4116 // If op0 is a frame index that is under aligned, we can't do it either, 4117 // because it is translated to r31 or r1 + slot + offset. We won't know the 4118 // slot number until the stack frame is finalized. 4119 const MachineFrameInfo &MFI = CurDAG->getMachineFunction().getFrameInfo(); 4120 unsigned SlotAlign = MFI.getObjectAlignment(FI->getIndex()); 4121 if ((SlotAlign % Val) != 0) 4122 return false; 4123 4124 // If we have an offset, we need further check on the offset. 4125 if (AddrOp.getOpcode() != ISD::ADD) 4126 return true; 4127 } 4128 4129 if (AddrOp.getOpcode() == ISD::ADD) 4130 return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val); 4131 4132 // If the address comes from the outside, the offset will be zero. 4133 return AddrOp.getOpcode() == ISD::CopyFromReg; 4134 } 4135 4136 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) { 4137 // Transfer memoperands. 4138 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand(); 4139 CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp}); 4140 } 4141 4142 static bool mayUseP9Setb(SDNode *N, const ISD::CondCode &CC, SelectionDAG *DAG, 4143 bool &NeedSwapOps, bool &IsUnCmp) { 4144 4145 assert(N->getOpcode() == ISD::SELECT_CC && "Expecting a SELECT_CC here."); 4146 4147 SDValue LHS = N->getOperand(0); 4148 SDValue RHS = N->getOperand(1); 4149 SDValue TrueRes = N->getOperand(2); 4150 SDValue FalseRes = N->getOperand(3); 4151 ConstantSDNode *TrueConst = dyn_cast<ConstantSDNode>(TrueRes); 4152 if (!TrueConst) 4153 return false; 4154 4155 assert((N->getSimpleValueType(0) == MVT::i64 || 4156 N->getSimpleValueType(0) == MVT::i32) && 4157 "Expecting either i64 or i32 here."); 4158 4159 // We are looking for any of: 4160 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, cc2)), cc1) 4161 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, cc2)), cc1) 4162 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, 1, -1, cc2), seteq) 4163 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, -1, 1, cc2), seteq) 4164 int64_t TrueResVal = TrueConst->getSExtValue(); 4165 if ((TrueResVal < -1 || TrueResVal > 1) || 4166 (TrueResVal == -1 && FalseRes.getOpcode() != ISD::ZERO_EXTEND) || 4167 (TrueResVal == 1 && FalseRes.getOpcode() != ISD::SIGN_EXTEND) || 4168 (TrueResVal == 0 && 4169 (FalseRes.getOpcode() != ISD::SELECT_CC || CC != ISD::SETEQ))) 4170 return false; 4171 4172 bool InnerIsSel = FalseRes.getOpcode() == ISD::SELECT_CC; 4173 SDValue SetOrSelCC = InnerIsSel ? FalseRes : FalseRes.getOperand(0); 4174 if (SetOrSelCC.getOpcode() != ISD::SETCC && 4175 SetOrSelCC.getOpcode() != ISD::SELECT_CC) 4176 return false; 4177 4178 // Without this setb optimization, the outer SELECT_CC will be manually 4179 // selected to SELECT_CC_I4/SELECT_CC_I8 Pseudo, then expand-isel-pseudos pass 4180 // transforms pseduo instruction to isel instruction. When there are more than 4181 // one use for result like zext/sext, with current optimization we only see 4182 // isel is replaced by setb but can't see any significant gain. Since 4183 // setb has longer latency than original isel, we should avoid this. Another 4184 // point is that setb requires comparison always kept, it can break the 4185 // oppotunity to get the comparison away if we have in future. 4186 if (!SetOrSelCC.hasOneUse() || (!InnerIsSel && !FalseRes.hasOneUse())) 4187 return false; 4188 4189 SDValue InnerLHS = SetOrSelCC.getOperand(0); 4190 SDValue InnerRHS = SetOrSelCC.getOperand(1); 4191 ISD::CondCode InnerCC = 4192 cast<CondCodeSDNode>(SetOrSelCC.getOperand(InnerIsSel ? 4 : 2))->get(); 4193 // If the inner comparison is a select_cc, make sure the true/false values are 4194 // 1/-1 and canonicalize it if needed. 4195 if (InnerIsSel) { 4196 ConstantSDNode *SelCCTrueConst = 4197 dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(2)); 4198 ConstantSDNode *SelCCFalseConst = 4199 dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(3)); 4200 if (!SelCCTrueConst || !SelCCFalseConst) 4201 return false; 4202 int64_t SelCCTVal = SelCCTrueConst->getSExtValue(); 4203 int64_t SelCCFVal = SelCCFalseConst->getSExtValue(); 4204 // The values must be -1/1 (requiring a swap) or 1/-1. 4205 if (SelCCTVal == -1 && SelCCFVal == 1) { 4206 std::swap(InnerLHS, InnerRHS); 4207 } else if (SelCCTVal != 1 || SelCCFVal != -1) 4208 return false; 4209 } 4210 4211 // Canonicalize unsigned case 4212 if (InnerCC == ISD::SETULT || InnerCC == ISD::SETUGT) { 4213 IsUnCmp = true; 4214 InnerCC = (InnerCC == ISD::SETULT) ? ISD::SETLT : ISD::SETGT; 4215 } 4216 4217 bool InnerSwapped = false; 4218 if (LHS == InnerRHS && RHS == InnerLHS) 4219 InnerSwapped = true; 4220 else if (LHS != InnerLHS || RHS != InnerRHS) 4221 return false; 4222 4223 switch (CC) { 4224 // (select_cc lhs, rhs, 0, \ 4225 // (select_cc [lr]hs, [lr]hs, 1, -1, setlt/setgt), seteq) 4226 case ISD::SETEQ: 4227 if (!InnerIsSel) 4228 return false; 4229 if (InnerCC != ISD::SETLT && InnerCC != ISD::SETGT) 4230 return false; 4231 NeedSwapOps = (InnerCC == ISD::SETGT) ? InnerSwapped : !InnerSwapped; 4232 break; 4233 4234 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?lt) 4235 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setgt)), setu?lt) 4236 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setlt)), setu?lt) 4237 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?lt) 4238 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setgt)), setu?lt) 4239 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setlt)), setu?lt) 4240 case ISD::SETULT: 4241 if (!IsUnCmp && InnerCC != ISD::SETNE) 4242 return false; 4243 IsUnCmp = true; 4244 LLVM_FALLTHROUGH; 4245 case ISD::SETLT: 4246 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETGT && !InnerSwapped) || 4247 (InnerCC == ISD::SETLT && InnerSwapped)) 4248 NeedSwapOps = (TrueResVal == 1); 4249 else 4250 return false; 4251 break; 4252 4253 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?gt) 4254 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setlt)), setu?gt) 4255 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setgt)), setu?gt) 4256 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?gt) 4257 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setlt)), setu?gt) 4258 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setgt)), setu?gt) 4259 case ISD::SETUGT: 4260 if (!IsUnCmp && InnerCC != ISD::SETNE) 4261 return false; 4262 IsUnCmp = true; 4263 LLVM_FALLTHROUGH; 4264 case ISD::SETGT: 4265 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETLT && !InnerSwapped) || 4266 (InnerCC == ISD::SETGT && InnerSwapped)) 4267 NeedSwapOps = (TrueResVal == -1); 4268 else 4269 return false; 4270 break; 4271 4272 default: 4273 return false; 4274 } 4275 4276 LLVM_DEBUG(dbgs() << "Found a node that can be lowered to a SETB: "); 4277 LLVM_DEBUG(N->dump()); 4278 4279 return true; 4280 } 4281 4282 // Select - Convert the specified operand from a target-independent to a 4283 // target-specific node if it hasn't already been changed. 4284 void PPCDAGToDAGISel::Select(SDNode *N) { 4285 SDLoc dl(N); 4286 if (N->isMachineOpcode()) { 4287 N->setNodeId(-1); 4288 return; // Already selected. 4289 } 4290 4291 // In case any misguided DAG-level optimizations form an ADD with a 4292 // TargetConstant operand, crash here instead of miscompiling (by selecting 4293 // an r+r add instead of some kind of r+i add). 4294 if (N->getOpcode() == ISD::ADD && 4295 N->getOperand(1).getOpcode() == ISD::TargetConstant) 4296 llvm_unreachable("Invalid ADD with TargetConstant operand"); 4297 4298 // Try matching complex bit permutations before doing anything else. 4299 if (tryBitPermutation(N)) 4300 return; 4301 4302 // Try to emit integer compares as GPR-only sequences (i.e. no use of CR). 4303 if (tryIntCompareInGPR(N)) 4304 return; 4305 4306 switch (N->getOpcode()) { 4307 default: break; 4308 4309 case ISD::Constant: 4310 if (N->getValueType(0) == MVT::i64) { 4311 ReplaceNode(N, selectI64Imm(CurDAG, N)); 4312 return; 4313 } 4314 break; 4315 4316 case ISD::SETCC: 4317 if (trySETCC(N)) 4318 return; 4319 break; 4320 4321 case PPCISD::CALL: { 4322 const Module *M = MF->getFunction().getParent(); 4323 4324 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 || 4325 !PPCSubTarget->isSecurePlt() || !PPCSubTarget->isTargetELF() || 4326 M->getPICLevel() == PICLevel::SmallPIC) 4327 break; 4328 4329 SDValue Op = N->getOperand(1); 4330 4331 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) { 4332 if (GA->getTargetFlags() == PPCII::MO_PLT) 4333 getGlobalBaseReg(); 4334 } 4335 else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) { 4336 if (ES->getTargetFlags() == PPCII::MO_PLT) 4337 getGlobalBaseReg(); 4338 } 4339 } 4340 break; 4341 4342 case PPCISD::GlobalBaseReg: 4343 ReplaceNode(N, getGlobalBaseReg()); 4344 return; 4345 4346 case ISD::FrameIndex: 4347 selectFrameIndex(N, N); 4348 return; 4349 4350 case PPCISD::MFOCRF: { 4351 SDValue InFlag = N->getOperand(1); 4352 ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, 4353 N->getOperand(0), InFlag)); 4354 return; 4355 } 4356 4357 case PPCISD::READ_TIME_BASE: 4358 ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32, 4359 MVT::Other, N->getOperand(0))); 4360 return; 4361 4362 case PPCISD::SRA_ADDZE: { 4363 SDValue N0 = N->getOperand(0); 4364 SDValue ShiftAmt = 4365 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))-> 4366 getConstantIntValue(), dl, 4367 N->getValueType(0)); 4368 if (N->getValueType(0) == MVT::i64) { 4369 SDNode *Op = 4370 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue, 4371 N0, ShiftAmt); 4372 CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0), 4373 SDValue(Op, 1)); 4374 return; 4375 } else { 4376 assert(N->getValueType(0) == MVT::i32 && 4377 "Expecting i64 or i32 in PPCISD::SRA_ADDZE"); 4378 SDNode *Op = 4379 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue, 4380 N0, ShiftAmt); 4381 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0), 4382 SDValue(Op, 1)); 4383 return; 4384 } 4385 } 4386 4387 case ISD::STORE: { 4388 // Change TLS initial-exec D-form stores to X-form stores. 4389 StoreSDNode *ST = cast<StoreSDNode>(N); 4390 if (EnableTLSOpt && PPCSubTarget->isELFv2ABI() && 4391 ST->getAddressingMode() != ISD::PRE_INC) 4392 if (tryTLSXFormStore(ST)) 4393 return; 4394 break; 4395 } 4396 case ISD::LOAD: { 4397 // Handle preincrement loads. 4398 LoadSDNode *LD = cast<LoadSDNode>(N); 4399 EVT LoadedVT = LD->getMemoryVT(); 4400 4401 // Normal loads are handled by code generated from the .td file. 4402 if (LD->getAddressingMode() != ISD::PRE_INC) { 4403 // Change TLS initial-exec D-form loads to X-form loads. 4404 if (EnableTLSOpt && PPCSubTarget->isELFv2ABI()) 4405 if (tryTLSXFormLoad(LD)) 4406 return; 4407 break; 4408 } 4409 4410 SDValue Offset = LD->getOffset(); 4411 if (Offset.getOpcode() == ISD::TargetConstant || 4412 Offset.getOpcode() == ISD::TargetGlobalAddress) { 4413 4414 unsigned Opcode; 4415 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD; 4416 if (LD->getValueType(0) != MVT::i64) { 4417 // Handle PPC32 integer and normal FP loads. 4418 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 4419 switch (LoadedVT.getSimpleVT().SimpleTy) { 4420 default: llvm_unreachable("Invalid PPC load type!"); 4421 case MVT::f64: Opcode = PPC::LFDU; break; 4422 case MVT::f32: Opcode = PPC::LFSU; break; 4423 case MVT::i32: Opcode = PPC::LWZU; break; 4424 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break; 4425 case MVT::i1: 4426 case MVT::i8: Opcode = PPC::LBZU; break; 4427 } 4428 } else { 4429 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!"); 4430 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 4431 switch (LoadedVT.getSimpleVT().SimpleTy) { 4432 default: llvm_unreachable("Invalid PPC load type!"); 4433 case MVT::i64: Opcode = PPC::LDU; break; 4434 case MVT::i32: Opcode = PPC::LWZU8; break; 4435 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break; 4436 case MVT::i1: 4437 case MVT::i8: Opcode = PPC::LBZU8; break; 4438 } 4439 } 4440 4441 SDValue Chain = LD->getChain(); 4442 SDValue Base = LD->getBasePtr(); 4443 SDValue Ops[] = { Offset, Base, Chain }; 4444 SDNode *MN = CurDAG->getMachineNode( 4445 Opcode, dl, LD->getValueType(0), 4446 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops); 4447 transferMemOperands(N, MN); 4448 ReplaceNode(N, MN); 4449 return; 4450 } else { 4451 unsigned Opcode; 4452 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD; 4453 if (LD->getValueType(0) != MVT::i64) { 4454 // Handle PPC32 integer and normal FP loads. 4455 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 4456 switch (LoadedVT.getSimpleVT().SimpleTy) { 4457 default: llvm_unreachable("Invalid PPC load type!"); 4458 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX 4459 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX 4460 case MVT::f64: Opcode = PPC::LFDUX; break; 4461 case MVT::f32: Opcode = PPC::LFSUX; break; 4462 case MVT::i32: Opcode = PPC::LWZUX; break; 4463 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break; 4464 case MVT::i1: 4465 case MVT::i8: Opcode = PPC::LBZUX; break; 4466 } 4467 } else { 4468 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!"); 4469 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) && 4470 "Invalid sext update load"); 4471 switch (LoadedVT.getSimpleVT().SimpleTy) { 4472 default: llvm_unreachable("Invalid PPC load type!"); 4473 case MVT::i64: Opcode = PPC::LDUX; break; 4474 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break; 4475 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break; 4476 case MVT::i1: 4477 case MVT::i8: Opcode = PPC::LBZUX8; break; 4478 } 4479 } 4480 4481 SDValue Chain = LD->getChain(); 4482 SDValue Base = LD->getBasePtr(); 4483 SDValue Ops[] = { Base, Offset, Chain }; 4484 SDNode *MN = CurDAG->getMachineNode( 4485 Opcode, dl, LD->getValueType(0), 4486 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops); 4487 transferMemOperands(N, MN); 4488 ReplaceNode(N, MN); 4489 return; 4490 } 4491 } 4492 4493 case ISD::AND: { 4494 unsigned Imm, Imm2, SH, MB, ME; 4495 uint64_t Imm64; 4496 4497 // If this is an and of a value rotated between 0 and 31 bits and then and'd 4498 // with a mask, emit rlwinm 4499 if (isInt32Immediate(N->getOperand(1), Imm) && 4500 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) { 4501 SDValue Val = N->getOperand(0).getOperand(0); 4502 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl), 4503 getI32Imm(ME, dl) }; 4504 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4505 return; 4506 } 4507 // If this is just a masked value where the input is not handled above, and 4508 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm 4509 if (isInt32Immediate(N->getOperand(1), Imm) && 4510 isRunOfOnes(Imm, MB, ME) && 4511 N->getOperand(0).getOpcode() != ISD::ROTL) { 4512 SDValue Val = N->getOperand(0); 4513 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl), 4514 getI32Imm(ME, dl) }; 4515 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4516 return; 4517 } 4518 // If this is a 64-bit zero-extension mask, emit rldicl. 4519 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) && 4520 isMask_64(Imm64)) { 4521 SDValue Val = N->getOperand(0); 4522 MB = 64 - countTrailingOnes(Imm64); 4523 SH = 0; 4524 4525 if (Val.getOpcode() == ISD::ANY_EXTEND) { 4526 auto Op0 = Val.getOperand(0); 4527 if ( Op0.getOpcode() == ISD::SRL && 4528 isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) { 4529 4530 auto ResultType = Val.getNode()->getValueType(0); 4531 auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, 4532 ResultType); 4533 SDValue IDVal (ImDef, 0); 4534 4535 Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, 4536 ResultType, IDVal, Op0.getOperand(0), 4537 getI32Imm(1, dl)), 0); 4538 SH = 64 - Imm; 4539 } 4540 } 4541 4542 // If the operand is a logical right shift, we can fold it into this 4543 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb) 4544 // for n <= mb. The right shift is really a left rotate followed by a 4545 // mask, and this mask is a more-restrictive sub-mask of the mask implied 4546 // by the shift. 4547 if (Val.getOpcode() == ISD::SRL && 4548 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) { 4549 assert(Imm < 64 && "Illegal shift amount"); 4550 Val = Val.getOperand(0); 4551 SH = 64 - Imm; 4552 } 4553 4554 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) }; 4555 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops); 4556 return; 4557 } 4558 // If this is a negated 64-bit zero-extension mask, 4559 // i.e. the immediate is a sequence of ones from most significant side 4560 // and all zero for reminder, we should use rldicr. 4561 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) && 4562 isMask_64(~Imm64)) { 4563 SDValue Val = N->getOperand(0); 4564 MB = 63 - countTrailingOnes(~Imm64); 4565 SH = 0; 4566 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) }; 4567 CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops); 4568 return; 4569 } 4570 4571 // AND X, 0 -> 0, not "rlwinm 32". 4572 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) { 4573 ReplaceUses(SDValue(N, 0), N->getOperand(1)); 4574 return; 4575 } 4576 // ISD::OR doesn't get all the bitfield insertion fun. 4577 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a 4578 // bitfield insert. 4579 if (isInt32Immediate(N->getOperand(1), Imm) && 4580 N->getOperand(0).getOpcode() == ISD::OR && 4581 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) { 4582 // The idea here is to check whether this is equivalent to: 4583 // (c1 & m) | (x & ~m) 4584 // where m is a run-of-ones mask. The logic here is that, for each bit in 4585 // c1 and c2: 4586 // - if both are 1, then the output will be 1. 4587 // - if both are 0, then the output will be 0. 4588 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will 4589 // come from x. 4590 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will 4591 // be 0. 4592 // If that last condition is never the case, then we can form m from the 4593 // bits that are the same between c1 and c2. 4594 unsigned MB, ME; 4595 if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) { 4596 SDValue Ops[] = { N->getOperand(0).getOperand(0), 4597 N->getOperand(0).getOperand(1), 4598 getI32Imm(0, dl), getI32Imm(MB, dl), 4599 getI32Imm(ME, dl) }; 4600 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops)); 4601 return; 4602 } 4603 } 4604 4605 // Other cases are autogenerated. 4606 break; 4607 } 4608 case ISD::OR: { 4609 if (N->getValueType(0) == MVT::i32) 4610 if (tryBitfieldInsert(N)) 4611 return; 4612 4613 int16_t Imm; 4614 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex && 4615 isIntS16Immediate(N->getOperand(1), Imm)) { 4616 KnownBits LHSKnown; 4617 CurDAG->computeKnownBits(N->getOperand(0), LHSKnown); 4618 4619 // If this is equivalent to an add, then we can fold it with the 4620 // FrameIndex calculation. 4621 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) { 4622 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm); 4623 return; 4624 } 4625 } 4626 4627 // OR with a 32-bit immediate can be handled by ori + oris 4628 // without creating an immediate in a GPR. 4629 uint64_t Imm64 = 0; 4630 bool IsPPC64 = PPCSubTarget->isPPC64(); 4631 if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) && 4632 (Imm64 & ~0xFFFFFFFFuLL) == 0) { 4633 // If ImmHi (ImmHi) is zero, only one ori (oris) is generated later. 4634 uint64_t ImmHi = Imm64 >> 16; 4635 uint64_t ImmLo = Imm64 & 0xFFFF; 4636 if (ImmHi != 0 && ImmLo != 0) { 4637 SDNode *Lo = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, 4638 N->getOperand(0), 4639 getI16Imm(ImmLo, dl)); 4640 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)}; 4641 CurDAG->SelectNodeTo(N, PPC::ORIS8, MVT::i64, Ops1); 4642 return; 4643 } 4644 } 4645 4646 // Other cases are autogenerated. 4647 break; 4648 } 4649 case ISD::XOR: { 4650 // XOR with a 32-bit immediate can be handled by xori + xoris 4651 // without creating an immediate in a GPR. 4652 uint64_t Imm64 = 0; 4653 bool IsPPC64 = PPCSubTarget->isPPC64(); 4654 if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) && 4655 (Imm64 & ~0xFFFFFFFFuLL) == 0) { 4656 // If ImmHi (ImmHi) is zero, only one xori (xoris) is generated later. 4657 uint64_t ImmHi = Imm64 >> 16; 4658 uint64_t ImmLo = Imm64 & 0xFFFF; 4659 if (ImmHi != 0 && ImmLo != 0) { 4660 SDNode *Lo = CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, 4661 N->getOperand(0), 4662 getI16Imm(ImmLo, dl)); 4663 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)}; 4664 CurDAG->SelectNodeTo(N, PPC::XORIS8, MVT::i64, Ops1); 4665 return; 4666 } 4667 } 4668 4669 break; 4670 } 4671 case ISD::ADD: { 4672 int16_t Imm; 4673 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex && 4674 isIntS16Immediate(N->getOperand(1), Imm)) { 4675 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm); 4676 return; 4677 } 4678 4679 break; 4680 } 4681 case ISD::SHL: { 4682 unsigned Imm, SH, MB, ME; 4683 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) && 4684 isRotateAndMask(N, Imm, true, SH, MB, ME)) { 4685 SDValue Ops[] = { N->getOperand(0).getOperand(0), 4686 getI32Imm(SH, dl), getI32Imm(MB, dl), 4687 getI32Imm(ME, dl) }; 4688 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4689 return; 4690 } 4691 4692 // Other cases are autogenerated. 4693 break; 4694 } 4695 case ISD::SRL: { 4696 unsigned Imm, SH, MB, ME; 4697 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) && 4698 isRotateAndMask(N, Imm, true, SH, MB, ME)) { 4699 SDValue Ops[] = { N->getOperand(0).getOperand(0), 4700 getI32Imm(SH, dl), getI32Imm(MB, dl), 4701 getI32Imm(ME, dl) }; 4702 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 4703 return; 4704 } 4705 4706 // Other cases are autogenerated. 4707 break; 4708 } 4709 // FIXME: Remove this once the ANDI glue bug is fixed: 4710 case PPCISD::ANDIo_1_EQ_BIT: 4711 case PPCISD::ANDIo_1_GT_BIT: { 4712 if (!ANDIGlueBug) 4713 break; 4714 4715 EVT InVT = N->getOperand(0).getValueType(); 4716 assert((InVT == MVT::i64 || InVT == MVT::i32) && 4717 "Invalid input type for ANDIo_1_EQ_BIT"); 4718 4719 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo; 4720 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue, 4721 N->getOperand(0), 4722 CurDAG->getTargetConstant(1, dl, InVT)), 4723 0); 4724 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32); 4725 SDValue SRIdxVal = 4726 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ? 4727 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32); 4728 4729 CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg, 4730 SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */); 4731 return; 4732 } 4733 case ISD::SELECT_CC: { 4734 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get(); 4735 EVT PtrVT = 4736 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout()); 4737 bool isPPC64 = (PtrVT == MVT::i64); 4738 4739 // If this is a select of i1 operands, we'll pattern match it. 4740 if (PPCSubTarget->useCRBits() && 4741 N->getOperand(0).getValueType() == MVT::i1) 4742 break; 4743 4744 if (PPCSubTarget->isISA3_0() && PPCSubTarget->isPPC64()) { 4745 bool NeedSwapOps = false; 4746 bool IsUnCmp = false; 4747 if (mayUseP9Setb(N, CC, CurDAG, NeedSwapOps, IsUnCmp)) { 4748 SDValue LHS = N->getOperand(0); 4749 SDValue RHS = N->getOperand(1); 4750 if (NeedSwapOps) 4751 std::swap(LHS, RHS); 4752 4753 // Make use of SelectCC to generate the comparison to set CR bits, for 4754 // equality comparisons having one literal operand, SelectCC probably 4755 // doesn't need to materialize the whole literal and just use xoris to 4756 // check it first, it leads the following comparison result can't 4757 // exactly represent GT/LT relationship. So to avoid this we specify 4758 // SETGT/SETUGT here instead of SETEQ. 4759 SDValue GenCC = 4760 SelectCC(LHS, RHS, IsUnCmp ? ISD::SETUGT : ISD::SETGT, dl); 4761 CurDAG->SelectNodeTo( 4762 N, N->getSimpleValueType(0) == MVT::i64 ? PPC::SETB8 : PPC::SETB, 4763 N->getValueType(0), GenCC); 4764 NumP9Setb++; 4765 return; 4766 } 4767 } 4768 4769 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc 4770 if (!isPPC64) 4771 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1))) 4772 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2))) 4773 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3))) 4774 if (N1C->isNullValue() && N3C->isNullValue() && 4775 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE && 4776 // FIXME: Implement this optzn for PPC64. 4777 N->getValueType(0) == MVT::i32) { 4778 SDNode *Tmp = 4779 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 4780 N->getOperand(0), getI32Imm(~0U, dl)); 4781 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0), 4782 N->getOperand(0), SDValue(Tmp, 1)); 4783 return; 4784 } 4785 4786 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl); 4787 4788 if (N->getValueType(0) == MVT::i1) { 4789 // An i1 select is: (c & t) | (!c & f). 4790 bool Inv; 4791 unsigned Idx = getCRIdxForSetCC(CC, Inv); 4792 4793 unsigned SRI; 4794 switch (Idx) { 4795 default: llvm_unreachable("Invalid CC index"); 4796 case 0: SRI = PPC::sub_lt; break; 4797 case 1: SRI = PPC::sub_gt; break; 4798 case 2: SRI = PPC::sub_eq; break; 4799 case 3: SRI = PPC::sub_un; break; 4800 } 4801 4802 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg); 4803 4804 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1, 4805 CCBit, CCBit), 0); 4806 SDValue C = Inv ? NotCCBit : CCBit, 4807 NotC = Inv ? CCBit : NotCCBit; 4808 4809 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1, 4810 C, N->getOperand(2)), 0); 4811 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1, 4812 NotC, N->getOperand(3)), 0); 4813 4814 CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF); 4815 return; 4816 } 4817 4818 unsigned BROpc = getPredicateForSetCC(CC); 4819 4820 unsigned SelectCCOp; 4821 if (N->getValueType(0) == MVT::i32) 4822 SelectCCOp = PPC::SELECT_CC_I4; 4823 else if (N->getValueType(0) == MVT::i64) 4824 SelectCCOp = PPC::SELECT_CC_I8; 4825 else if (N->getValueType(0) == MVT::f32) { 4826 if (PPCSubTarget->hasP8Vector()) 4827 SelectCCOp = PPC::SELECT_CC_VSSRC; 4828 else if (PPCSubTarget->hasSPE()) 4829 SelectCCOp = PPC::SELECT_CC_SPE4; 4830 else 4831 SelectCCOp = PPC::SELECT_CC_F4; 4832 } else if (N->getValueType(0) == MVT::f64) { 4833 if (PPCSubTarget->hasVSX()) 4834 SelectCCOp = PPC::SELECT_CC_VSFRC; 4835 else if (PPCSubTarget->hasSPE()) 4836 SelectCCOp = PPC::SELECT_CC_SPE; 4837 else 4838 SelectCCOp = PPC::SELECT_CC_F8; 4839 } else if (N->getValueType(0) == MVT::f128) 4840 SelectCCOp = PPC::SELECT_CC_F16; 4841 else if (PPCSubTarget->hasSPE()) 4842 SelectCCOp = PPC::SELECT_CC_SPE; 4843 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64) 4844 SelectCCOp = PPC::SELECT_CC_QFRC; 4845 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32) 4846 SelectCCOp = PPC::SELECT_CC_QSRC; 4847 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1) 4848 SelectCCOp = PPC::SELECT_CC_QBRC; 4849 else if (N->getValueType(0) == MVT::v2f64 || 4850 N->getValueType(0) == MVT::v2i64) 4851 SelectCCOp = PPC::SELECT_CC_VSRC; 4852 else 4853 SelectCCOp = PPC::SELECT_CC_VRRC; 4854 4855 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3), 4856 getI32Imm(BROpc, dl) }; 4857 CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops); 4858 return; 4859 } 4860 case ISD::VECTOR_SHUFFLE: 4861 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 || 4862 N->getValueType(0) == MVT::v2i64)) { 4863 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 4864 4865 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1), 4866 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1); 4867 unsigned DM[2]; 4868 4869 for (int i = 0; i < 2; ++i) 4870 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2) 4871 DM[i] = 0; 4872 else 4873 DM[i] = 1; 4874 4875 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 && 4876 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR && 4877 isa<LoadSDNode>(Op1.getOperand(0))) { 4878 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0)); 4879 SDValue Base, Offset; 4880 4881 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() && 4882 (LD->getMemoryVT() == MVT::f64 || 4883 LD->getMemoryVT() == MVT::i64) && 4884 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) { 4885 SDValue Chain = LD->getChain(); 4886 SDValue Ops[] = { Base, Offset, Chain }; 4887 MachineMemOperand *MemOp = LD->getMemOperand(); 4888 SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX, 4889 N->getValueType(0), Ops); 4890 CurDAG->setNodeMemRefs(cast<MachineSDNode>(NewN), {MemOp}); 4891 return; 4892 } 4893 } 4894 4895 // For little endian, we must swap the input operands and adjust 4896 // the mask elements (reverse and invert them). 4897 if (PPCSubTarget->isLittleEndian()) { 4898 std::swap(Op1, Op2); 4899 unsigned tmp = DM[0]; 4900 DM[0] = 1 - DM[1]; 4901 DM[1] = 1 - tmp; 4902 } 4903 4904 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl, 4905 MVT::i32); 4906 SDValue Ops[] = { Op1, Op2, DMV }; 4907 CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops); 4908 return; 4909 } 4910 4911 break; 4912 case PPCISD::BDNZ: 4913 case PPCISD::BDZ: { 4914 bool IsPPC64 = PPCSubTarget->isPPC64(); 4915 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) }; 4916 CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ 4917 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) 4918 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ), 4919 MVT::Other, Ops); 4920 return; 4921 } 4922 case PPCISD::COND_BRANCH: { 4923 // Op #0 is the Chain. 4924 // Op #1 is the PPC::PRED_* number. 4925 // Op #2 is the CR# 4926 // Op #3 is the Dest MBB 4927 // Op #4 is the Flag. 4928 // Prevent PPC::PRED_* from being selected into LI. 4929 unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 4930 if (EnableBranchHint) 4931 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(3)); 4932 4933 SDValue Pred = getI32Imm(PCC, dl); 4934 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3), 4935 N->getOperand(0), N->getOperand(4) }; 4936 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops); 4937 return; 4938 } 4939 case ISD::BR_CC: { 4940 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 4941 unsigned PCC = getPredicateForSetCC(CC); 4942 4943 if (N->getOperand(2).getValueType() == MVT::i1) { 4944 unsigned Opc; 4945 bool Swap; 4946 switch (PCC) { 4947 default: llvm_unreachable("Unexpected Boolean-operand predicate"); 4948 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break; 4949 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break; 4950 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break; 4951 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break; 4952 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break; 4953 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break; 4954 } 4955 4956 // A signed comparison of i1 values produces the opposite result to an 4957 // unsigned one if the condition code includes less-than or greater-than. 4958 // This is because 1 is the most negative signed i1 number and the most 4959 // positive unsigned i1 number. The CR-logical operations used for such 4960 // comparisons are non-commutative so for signed comparisons vs. unsigned 4961 // ones, the input operands just need to be swapped. 4962 if (ISD::isSignedIntSetCC(CC)) 4963 Swap = !Swap; 4964 4965 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1, 4966 N->getOperand(Swap ? 3 : 2), 4967 N->getOperand(Swap ? 2 : 3)), 0); 4968 CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4), 4969 N->getOperand(0)); 4970 return; 4971 } 4972 4973 if (EnableBranchHint) 4974 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(4)); 4975 4976 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl); 4977 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode, 4978 N->getOperand(4), N->getOperand(0) }; 4979 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops); 4980 return; 4981 } 4982 case ISD::BRIND: { 4983 // FIXME: Should custom lower this. 4984 SDValue Chain = N->getOperand(0); 4985 SDValue Target = N->getOperand(1); 4986 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8; 4987 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8; 4988 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target, 4989 Chain), 0); 4990 CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain); 4991 return; 4992 } 4993 case PPCISD::TOC_ENTRY: { 4994 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) && 4995 "Only supported for 64-bit ABI and 32-bit SVR4"); 4996 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) { 4997 SDValue GA = N->getOperand(0); 4998 SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA, 4999 N->getOperand(1)); 5000 transferMemOperands(N, MN); 5001 ReplaceNode(N, MN); 5002 return; 5003 } 5004 5005 // For medium and large code model, we generate two instructions as 5006 // described below. Otherwise we allow SelectCodeCommon to handle this, 5007 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA. 5008 CodeModel::Model CModel = TM.getCodeModel(); 5009 if (CModel != CodeModel::Medium && CModel != CodeModel::Large) 5010 break; 5011 5012 // The first source operand is a TargetGlobalAddress or a TargetJumpTable. 5013 // If it must be toc-referenced according to PPCSubTarget, we generate: 5014 // LDtocL(@sym, ADDIStocHA(%x2, @sym)) 5015 // Otherwise we generate: 5016 // ADDItocL(ADDIStocHA(%x2, @sym), @sym) 5017 SDValue GA = N->getOperand(0); 5018 SDValue TOCbase = N->getOperand(1); 5019 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64, 5020 TOCbase, GA); 5021 if (PPCLowering->isAccessedAsGotIndirect(GA)) { 5022 // If it is access as got-indirect, we need an extra LD to load 5023 // the address. 5024 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA, 5025 SDValue(Tmp, 0)); 5026 transferMemOperands(N, MN); 5027 ReplaceNode(N, MN); 5028 return; 5029 } 5030 5031 // Build the address relative to the TOC-pointer.. 5032 ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64, 5033 SDValue(Tmp, 0), GA)); 5034 return; 5035 } 5036 case PPCISD::PPC32_PICGOT: 5037 // Generate a PIC-safe GOT reference. 5038 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() && 5039 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4"); 5040 CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, 5041 PPCLowering->getPointerTy(CurDAG->getDataLayout()), 5042 MVT::i32); 5043 return; 5044 5045 case PPCISD::VADD_SPLAT: { 5046 // This expands into one of three sequences, depending on whether 5047 // the first operand is odd or even, positive or negative. 5048 assert(isa<ConstantSDNode>(N->getOperand(0)) && 5049 isa<ConstantSDNode>(N->getOperand(1)) && 5050 "Invalid operand on VADD_SPLAT!"); 5051 5052 int Elt = N->getConstantOperandVal(0); 5053 int EltSize = N->getConstantOperandVal(1); 5054 unsigned Opc1, Opc2, Opc3; 5055 EVT VT; 5056 5057 if (EltSize == 1) { 5058 Opc1 = PPC::VSPLTISB; 5059 Opc2 = PPC::VADDUBM; 5060 Opc3 = PPC::VSUBUBM; 5061 VT = MVT::v16i8; 5062 } else if (EltSize == 2) { 5063 Opc1 = PPC::VSPLTISH; 5064 Opc2 = PPC::VADDUHM; 5065 Opc3 = PPC::VSUBUHM; 5066 VT = MVT::v8i16; 5067 } else { 5068 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!"); 5069 Opc1 = PPC::VSPLTISW; 5070 Opc2 = PPC::VADDUWM; 5071 Opc3 = PPC::VSUBUWM; 5072 VT = MVT::v4i32; 5073 } 5074 5075 if ((Elt & 1) == 0) { 5076 // Elt is even, in the range [-32,-18] + [16,30]. 5077 // 5078 // Convert: VADD_SPLAT elt, size 5079 // Into: tmp = VSPLTIS[BHW] elt 5080 // VADDU[BHW]M tmp, tmp 5081 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4 5082 SDValue EltVal = getI32Imm(Elt >> 1, dl); 5083 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 5084 SDValue TmpVal = SDValue(Tmp, 0); 5085 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal)); 5086 return; 5087 } else if (Elt > 0) { 5088 // Elt is odd and positive, in the range [17,31]. 5089 // 5090 // Convert: VADD_SPLAT elt, size 5091 // Into: tmp1 = VSPLTIS[BHW] elt-16 5092 // tmp2 = VSPLTIS[BHW] -16 5093 // VSUBU[BHW]M tmp1, tmp2 5094 SDValue EltVal = getI32Imm(Elt - 16, dl); 5095 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 5096 EltVal = getI32Imm(-16, dl); 5097 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 5098 ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0), 5099 SDValue(Tmp2, 0))); 5100 return; 5101 } else { 5102 // Elt is odd and negative, in the range [-31,-17]. 5103 // 5104 // Convert: VADD_SPLAT elt, size 5105 // Into: tmp1 = VSPLTIS[BHW] elt+16 5106 // tmp2 = VSPLTIS[BHW] -16 5107 // VADDU[BHW]M tmp1, tmp2 5108 SDValue EltVal = getI32Imm(Elt + 16, dl); 5109 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 5110 EltVal = getI32Imm(-16, dl); 5111 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 5112 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0), 5113 SDValue(Tmp2, 0))); 5114 return; 5115 } 5116 } 5117 } 5118 5119 SelectCode(N); 5120 } 5121 5122 // If the target supports the cmpb instruction, do the idiom recognition here. 5123 // We don't do this as a DAG combine because we don't want to do it as nodes 5124 // are being combined (because we might miss part of the eventual idiom). We 5125 // don't want to do it during instruction selection because we want to reuse 5126 // the logic for lowering the masking operations already part of the 5127 // instruction selector. 5128 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) { 5129 SDLoc dl(N); 5130 5131 assert(N->getOpcode() == ISD::OR && 5132 "Only OR nodes are supported for CMPB"); 5133 5134 SDValue Res; 5135 if (!PPCSubTarget->hasCMPB()) 5136 return Res; 5137 5138 if (N->getValueType(0) != MVT::i32 && 5139 N->getValueType(0) != MVT::i64) 5140 return Res; 5141 5142 EVT VT = N->getValueType(0); 5143 5144 SDValue RHS, LHS; 5145 bool BytesFound[8] = {false, false, false, false, false, false, false, false}; 5146 uint64_t Mask = 0, Alt = 0; 5147 5148 auto IsByteSelectCC = [this](SDValue O, unsigned &b, 5149 uint64_t &Mask, uint64_t &Alt, 5150 SDValue &LHS, SDValue &RHS) { 5151 if (O.getOpcode() != ISD::SELECT_CC) 5152 return false; 5153 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get(); 5154 5155 if (!isa<ConstantSDNode>(O.getOperand(2)) || 5156 !isa<ConstantSDNode>(O.getOperand(3))) 5157 return false; 5158 5159 uint64_t PM = O.getConstantOperandVal(2); 5160 uint64_t PAlt = O.getConstantOperandVal(3); 5161 for (b = 0; b < 8; ++b) { 5162 uint64_t Mask = UINT64_C(0xFF) << (8*b); 5163 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt) 5164 break; 5165 } 5166 5167 if (b == 8) 5168 return false; 5169 Mask |= PM; 5170 Alt |= PAlt; 5171 5172 if (!isa<ConstantSDNode>(O.getOperand(1)) || 5173 O.getConstantOperandVal(1) != 0) { 5174 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1); 5175 if (Op0.getOpcode() == ISD::TRUNCATE) 5176 Op0 = Op0.getOperand(0); 5177 if (Op1.getOpcode() == ISD::TRUNCATE) 5178 Op1 = Op1.getOperand(0); 5179 5180 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL && 5181 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ && 5182 isa<ConstantSDNode>(Op0.getOperand(1))) { 5183 5184 unsigned Bits = Op0.getValueSizeInBits(); 5185 if (b != Bits/8-1) 5186 return false; 5187 if (Op0.getConstantOperandVal(1) != Bits-8) 5188 return false; 5189 5190 LHS = Op0.getOperand(0); 5191 RHS = Op1.getOperand(0); 5192 return true; 5193 } 5194 5195 // When we have small integers (i16 to be specific), the form present 5196 // post-legalization uses SETULT in the SELECT_CC for the 5197 // higher-order byte, depending on the fact that the 5198 // even-higher-order bytes are known to all be zero, for example: 5199 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult 5200 // (so when the second byte is the same, because all higher-order 5201 // bits from bytes 3 and 4 are known to be zero, the result of the 5202 // xor can be at most 255) 5203 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT && 5204 isa<ConstantSDNode>(O.getOperand(1))) { 5205 5206 uint64_t ULim = O.getConstantOperandVal(1); 5207 if (ULim != (UINT64_C(1) << b*8)) 5208 return false; 5209 5210 // Now we need to make sure that the upper bytes are known to be 5211 // zero. 5212 unsigned Bits = Op0.getValueSizeInBits(); 5213 if (!CurDAG->MaskedValueIsZero( 5214 Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8))) 5215 return false; 5216 5217 LHS = Op0.getOperand(0); 5218 RHS = Op0.getOperand(1); 5219 return true; 5220 } 5221 5222 return false; 5223 } 5224 5225 if (CC != ISD::SETEQ) 5226 return false; 5227 5228 SDValue Op = O.getOperand(0); 5229 if (Op.getOpcode() == ISD::AND) { 5230 if (!isa<ConstantSDNode>(Op.getOperand(1))) 5231 return false; 5232 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b))) 5233 return false; 5234 5235 SDValue XOR = Op.getOperand(0); 5236 if (XOR.getOpcode() == ISD::TRUNCATE) 5237 XOR = XOR.getOperand(0); 5238 if (XOR.getOpcode() != ISD::XOR) 5239 return false; 5240 5241 LHS = XOR.getOperand(0); 5242 RHS = XOR.getOperand(1); 5243 return true; 5244 } else if (Op.getOpcode() == ISD::SRL) { 5245 if (!isa<ConstantSDNode>(Op.getOperand(1))) 5246 return false; 5247 unsigned Bits = Op.getValueSizeInBits(); 5248 if (b != Bits/8-1) 5249 return false; 5250 if (Op.getConstantOperandVal(1) != Bits-8) 5251 return false; 5252 5253 SDValue XOR = Op.getOperand(0); 5254 if (XOR.getOpcode() == ISD::TRUNCATE) 5255 XOR = XOR.getOperand(0); 5256 if (XOR.getOpcode() != ISD::XOR) 5257 return false; 5258 5259 LHS = XOR.getOperand(0); 5260 RHS = XOR.getOperand(1); 5261 return true; 5262 } 5263 5264 return false; 5265 }; 5266 5267 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0)); 5268 while (!Queue.empty()) { 5269 SDValue V = Queue.pop_back_val(); 5270 5271 for (const SDValue &O : V.getNode()->ops()) { 5272 unsigned b; 5273 uint64_t M = 0, A = 0; 5274 SDValue OLHS, ORHS; 5275 if (O.getOpcode() == ISD::OR) { 5276 Queue.push_back(O); 5277 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) { 5278 if (!LHS) { 5279 LHS = OLHS; 5280 RHS = ORHS; 5281 BytesFound[b] = true; 5282 Mask |= M; 5283 Alt |= A; 5284 } else if ((LHS == ORHS && RHS == OLHS) || 5285 (RHS == ORHS && LHS == OLHS)) { 5286 BytesFound[b] = true; 5287 Mask |= M; 5288 Alt |= A; 5289 } else { 5290 return Res; 5291 } 5292 } else { 5293 return Res; 5294 } 5295 } 5296 } 5297 5298 unsigned LastB = 0, BCnt = 0; 5299 for (unsigned i = 0; i < 8; ++i) 5300 if (BytesFound[LastB]) { 5301 ++BCnt; 5302 LastB = i; 5303 } 5304 5305 if (!LastB || BCnt < 2) 5306 return Res; 5307 5308 // Because we'll be zero-extending the output anyway if don't have a specific 5309 // value for each input byte (via the Mask), we can 'anyext' the inputs. 5310 if (LHS.getValueType() != VT) { 5311 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT); 5312 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT); 5313 } 5314 5315 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS); 5316 5317 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1); 5318 if (NonTrivialMask && !Alt) { 5319 // Res = Mask & CMPB 5320 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, 5321 CurDAG->getConstant(Mask, dl, VT)); 5322 } else if (Alt) { 5323 // Res = (CMPB & Mask) | (~CMPB & Alt) 5324 // Which, as suggested here: 5325 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge 5326 // can be written as: 5327 // Res = Alt ^ ((Alt ^ Mask) & CMPB) 5328 // useful because the (Alt ^ Mask) can be pre-computed. 5329 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, 5330 CurDAG->getConstant(Mask ^ Alt, dl, VT)); 5331 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res, 5332 CurDAG->getConstant(Alt, dl, VT)); 5333 } 5334 5335 return Res; 5336 } 5337 5338 // When CR bit registers are enabled, an extension of an i1 variable to a i32 5339 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus 5340 // involves constant materialization of a 0 or a 1 or both. If the result of 5341 // the extension is then operated upon by some operator that can be constant 5342 // folded with a constant 0 or 1, and that constant can be materialized using 5343 // only one instruction (like a zero or one), then we should fold in those 5344 // operations with the select. 5345 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) { 5346 if (!PPCSubTarget->useCRBits()) 5347 return; 5348 5349 if (N->getOpcode() != ISD::ZERO_EXTEND && 5350 N->getOpcode() != ISD::SIGN_EXTEND && 5351 N->getOpcode() != ISD::ANY_EXTEND) 5352 return; 5353 5354 if (N->getOperand(0).getValueType() != MVT::i1) 5355 return; 5356 5357 if (!N->hasOneUse()) 5358 return; 5359 5360 SDLoc dl(N); 5361 EVT VT = N->getValueType(0); 5362 SDValue Cond = N->getOperand(0); 5363 SDValue ConstTrue = 5364 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT); 5365 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT); 5366 5367 do { 5368 SDNode *User = *N->use_begin(); 5369 if (User->getNumOperands() != 2) 5370 break; 5371 5372 auto TryFold = [this, N, User, dl](SDValue Val) { 5373 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1); 5374 SDValue O0 = UserO0.getNode() == N ? Val : UserO0; 5375 SDValue O1 = UserO1.getNode() == N ? Val : UserO1; 5376 5377 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl, 5378 User->getValueType(0), 5379 O0.getNode(), O1.getNode()); 5380 }; 5381 5382 // FIXME: When the semantics of the interaction between select and undef 5383 // are clearly defined, it may turn out to be unnecessary to break here. 5384 SDValue TrueRes = TryFold(ConstTrue); 5385 if (!TrueRes || TrueRes.isUndef()) 5386 break; 5387 SDValue FalseRes = TryFold(ConstFalse); 5388 if (!FalseRes || FalseRes.isUndef()) 5389 break; 5390 5391 // For us to materialize these using one instruction, we must be able to 5392 // represent them as signed 16-bit integers. 5393 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(), 5394 False = cast<ConstantSDNode>(FalseRes)->getZExtValue(); 5395 if (!isInt<16>(True) || !isInt<16>(False)) 5396 break; 5397 5398 // We can replace User with a new SELECT node, and try again to see if we 5399 // can fold the select with its user. 5400 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes); 5401 N = User; 5402 ConstTrue = TrueRes; 5403 ConstFalse = FalseRes; 5404 } while (N->hasOneUse()); 5405 } 5406 5407 void PPCDAGToDAGISel::PreprocessISelDAG() { 5408 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end(); 5409 5410 bool MadeChange = false; 5411 while (Position != CurDAG->allnodes_begin()) { 5412 SDNode *N = &*--Position; 5413 if (N->use_empty()) 5414 continue; 5415 5416 SDValue Res; 5417 switch (N->getOpcode()) { 5418 default: break; 5419 case ISD::OR: 5420 Res = combineToCMPB(N); 5421 break; 5422 } 5423 5424 if (!Res) 5425 foldBoolExts(Res, N); 5426 5427 if (Res) { 5428 LLVM_DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: "); 5429 LLVM_DEBUG(N->dump(CurDAG)); 5430 LLVM_DEBUG(dbgs() << "\nNew: "); 5431 LLVM_DEBUG(Res.getNode()->dump(CurDAG)); 5432 LLVM_DEBUG(dbgs() << "\n"); 5433 5434 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); 5435 MadeChange = true; 5436 } 5437 } 5438 5439 if (MadeChange) 5440 CurDAG->RemoveDeadNodes(); 5441 } 5442 5443 /// PostprocessISelDAG - Perform some late peephole optimizations 5444 /// on the DAG representation. 5445 void PPCDAGToDAGISel::PostprocessISelDAG() { 5446 // Skip peepholes at -O0. 5447 if (TM.getOptLevel() == CodeGenOpt::None) 5448 return; 5449 5450 PeepholePPC64(); 5451 PeepholeCROps(); 5452 PeepholePPC64ZExt(); 5453 } 5454 5455 // Check if all users of this node will become isel where the second operand 5456 // is the constant zero. If this is so, and if we can negate the condition, 5457 // then we can flip the true and false operands. This will allow the zero to 5458 // be folded with the isel so that we don't need to materialize a register 5459 // containing zero. 5460 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) { 5461 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5462 UI != UE; ++UI) { 5463 SDNode *User = *UI; 5464 if (!User->isMachineOpcode()) 5465 return false; 5466 if (User->getMachineOpcode() != PPC::SELECT_I4 && 5467 User->getMachineOpcode() != PPC::SELECT_I8) 5468 return false; 5469 5470 SDNode *Op2 = User->getOperand(2).getNode(); 5471 if (!Op2->isMachineOpcode()) 5472 return false; 5473 5474 if (Op2->getMachineOpcode() != PPC::LI && 5475 Op2->getMachineOpcode() != PPC::LI8) 5476 return false; 5477 5478 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0)); 5479 if (!C) 5480 return false; 5481 5482 if (!C->isNullValue()) 5483 return false; 5484 } 5485 5486 return true; 5487 } 5488 5489 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) { 5490 SmallVector<SDNode *, 4> ToReplace; 5491 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 5492 UI != UE; ++UI) { 5493 SDNode *User = *UI; 5494 assert((User->getMachineOpcode() == PPC::SELECT_I4 || 5495 User->getMachineOpcode() == PPC::SELECT_I8) && 5496 "Must have all select users"); 5497 ToReplace.push_back(User); 5498 } 5499 5500 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(), 5501 UE = ToReplace.end(); UI != UE; ++UI) { 5502 SDNode *User = *UI; 5503 SDNode *ResNode = 5504 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User), 5505 User->getValueType(0), User->getOperand(0), 5506 User->getOperand(2), 5507 User->getOperand(1)); 5508 5509 LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: "); 5510 LLVM_DEBUG(User->dump(CurDAG)); 5511 LLVM_DEBUG(dbgs() << "\nNew: "); 5512 LLVM_DEBUG(ResNode->dump(CurDAG)); 5513 LLVM_DEBUG(dbgs() << "\n"); 5514 5515 ReplaceUses(User, ResNode); 5516 } 5517 } 5518 5519 void PPCDAGToDAGISel::PeepholeCROps() { 5520 bool IsModified; 5521 do { 5522 IsModified = false; 5523 for (SDNode &Node : CurDAG->allnodes()) { 5524 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node); 5525 if (!MachineNode || MachineNode->use_empty()) 5526 continue; 5527 SDNode *ResNode = MachineNode; 5528 5529 bool Op1Set = false, Op1Unset = false, 5530 Op1Not = false, 5531 Op2Set = false, Op2Unset = false, 5532 Op2Not = false; 5533 5534 unsigned Opcode = MachineNode->getMachineOpcode(); 5535 switch (Opcode) { 5536 default: break; 5537 case PPC::CRAND: 5538 case PPC::CRNAND: 5539 case PPC::CROR: 5540 case PPC::CRXOR: 5541 case PPC::CRNOR: 5542 case PPC::CREQV: 5543 case PPC::CRANDC: 5544 case PPC::CRORC: { 5545 SDValue Op = MachineNode->getOperand(1); 5546 if (Op.isMachineOpcode()) { 5547 if (Op.getMachineOpcode() == PPC::CRSET) 5548 Op2Set = true; 5549 else if (Op.getMachineOpcode() == PPC::CRUNSET) 5550 Op2Unset = true; 5551 else if (Op.getMachineOpcode() == PPC::CRNOR && 5552 Op.getOperand(0) == Op.getOperand(1)) 5553 Op2Not = true; 5554 } 5555 LLVM_FALLTHROUGH; 5556 } 5557 case PPC::BC: 5558 case PPC::BCn: 5559 case PPC::SELECT_I4: 5560 case PPC::SELECT_I8: 5561 case PPC::SELECT_F4: 5562 case PPC::SELECT_F8: 5563 case PPC::SELECT_QFRC: 5564 case PPC::SELECT_QSRC: 5565 case PPC::SELECT_QBRC: 5566 case PPC::SELECT_SPE: 5567 case PPC::SELECT_SPE4: 5568 case PPC::SELECT_VRRC: 5569 case PPC::SELECT_VSFRC: 5570 case PPC::SELECT_VSSRC: 5571 case PPC::SELECT_VSRC: { 5572 SDValue Op = MachineNode->getOperand(0); 5573 if (Op.isMachineOpcode()) { 5574 if (Op.getMachineOpcode() == PPC::CRSET) 5575 Op1Set = true; 5576 else if (Op.getMachineOpcode() == PPC::CRUNSET) 5577 Op1Unset = true; 5578 else if (Op.getMachineOpcode() == PPC::CRNOR && 5579 Op.getOperand(0) == Op.getOperand(1)) 5580 Op1Not = true; 5581 } 5582 } 5583 break; 5584 } 5585 5586 bool SelectSwap = false; 5587 switch (Opcode) { 5588 default: break; 5589 case PPC::CRAND: 5590 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 5591 // x & x = x 5592 ResNode = MachineNode->getOperand(0).getNode(); 5593 else if (Op1Set) 5594 // 1 & y = y 5595 ResNode = MachineNode->getOperand(1).getNode(); 5596 else if (Op2Set) 5597 // x & 1 = x 5598 ResNode = MachineNode->getOperand(0).getNode(); 5599 else if (Op1Unset || Op2Unset) 5600 // x & 0 = 0 & y = 0 5601 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 5602 MVT::i1); 5603 else if (Op1Not) 5604 // ~x & y = andc(y, x) 5605 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 5606 MVT::i1, MachineNode->getOperand(1), 5607 MachineNode->getOperand(0). 5608 getOperand(0)); 5609 else if (Op2Not) 5610 // x & ~y = andc(x, y) 5611 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 5612 MVT::i1, MachineNode->getOperand(0), 5613 MachineNode->getOperand(1). 5614 getOperand(0)); 5615 else if (AllUsersSelectZero(MachineNode)) { 5616 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode), 5617 MVT::i1, MachineNode->getOperand(0), 5618 MachineNode->getOperand(1)); 5619 SelectSwap = true; 5620 } 5621 break; 5622 case PPC::CRNAND: 5623 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 5624 // nand(x, x) -> nor(x, x) 5625 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5626 MVT::i1, MachineNode->getOperand(0), 5627 MachineNode->getOperand(0)); 5628 else if (Op1Set) 5629 // nand(1, y) -> nor(y, y) 5630 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5631 MVT::i1, MachineNode->getOperand(1), 5632 MachineNode->getOperand(1)); 5633 else if (Op2Set) 5634 // nand(x, 1) -> nor(x, x) 5635 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5636 MVT::i1, MachineNode->getOperand(0), 5637 MachineNode->getOperand(0)); 5638 else if (Op1Unset || Op2Unset) 5639 // nand(x, 0) = nand(0, y) = 1 5640 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 5641 MVT::i1); 5642 else if (Op1Not) 5643 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y) 5644 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 5645 MVT::i1, MachineNode->getOperand(0). 5646 getOperand(0), 5647 MachineNode->getOperand(1)); 5648 else if (Op2Not) 5649 // nand(x, ~y) = ~x | y = orc(y, x) 5650 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 5651 MVT::i1, MachineNode->getOperand(1). 5652 getOperand(0), 5653 MachineNode->getOperand(0)); 5654 else if (AllUsersSelectZero(MachineNode)) { 5655 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode), 5656 MVT::i1, MachineNode->getOperand(0), 5657 MachineNode->getOperand(1)); 5658 SelectSwap = true; 5659 } 5660 break; 5661 case PPC::CROR: 5662 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 5663 // x | x = x 5664 ResNode = MachineNode->getOperand(0).getNode(); 5665 else if (Op1Set || Op2Set) 5666 // x | 1 = 1 | y = 1 5667 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 5668 MVT::i1); 5669 else if (Op1Unset) 5670 // 0 | y = y 5671 ResNode = MachineNode->getOperand(1).getNode(); 5672 else if (Op2Unset) 5673 // x | 0 = x 5674 ResNode = MachineNode->getOperand(0).getNode(); 5675 else if (Op1Not) 5676 // ~x | y = orc(y, x) 5677 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 5678 MVT::i1, MachineNode->getOperand(1), 5679 MachineNode->getOperand(0). 5680 getOperand(0)); 5681 else if (Op2Not) 5682 // x | ~y = orc(x, y) 5683 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 5684 MVT::i1, MachineNode->getOperand(0), 5685 MachineNode->getOperand(1). 5686 getOperand(0)); 5687 else if (AllUsersSelectZero(MachineNode)) { 5688 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5689 MVT::i1, MachineNode->getOperand(0), 5690 MachineNode->getOperand(1)); 5691 SelectSwap = true; 5692 } 5693 break; 5694 case PPC::CRXOR: 5695 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 5696 // xor(x, x) = 0 5697 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 5698 MVT::i1); 5699 else if (Op1Set) 5700 // xor(1, y) -> nor(y, y) 5701 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5702 MVT::i1, MachineNode->getOperand(1), 5703 MachineNode->getOperand(1)); 5704 else if (Op2Set) 5705 // xor(x, 1) -> nor(x, x) 5706 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5707 MVT::i1, MachineNode->getOperand(0), 5708 MachineNode->getOperand(0)); 5709 else if (Op1Unset) 5710 // xor(0, y) = y 5711 ResNode = MachineNode->getOperand(1).getNode(); 5712 else if (Op2Unset) 5713 // xor(x, 0) = x 5714 ResNode = MachineNode->getOperand(0).getNode(); 5715 else if (Op1Not) 5716 // xor(~x, y) = eqv(x, y) 5717 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 5718 MVT::i1, MachineNode->getOperand(0). 5719 getOperand(0), 5720 MachineNode->getOperand(1)); 5721 else if (Op2Not) 5722 // xor(x, ~y) = eqv(x, y) 5723 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 5724 MVT::i1, MachineNode->getOperand(0), 5725 MachineNode->getOperand(1). 5726 getOperand(0)); 5727 else if (AllUsersSelectZero(MachineNode)) { 5728 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 5729 MVT::i1, MachineNode->getOperand(0), 5730 MachineNode->getOperand(1)); 5731 SelectSwap = true; 5732 } 5733 break; 5734 case PPC::CRNOR: 5735 if (Op1Set || Op2Set) 5736 // nor(1, y) -> 0 5737 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 5738 MVT::i1); 5739 else if (Op1Unset) 5740 // nor(0, y) = ~y -> nor(y, y) 5741 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5742 MVT::i1, MachineNode->getOperand(1), 5743 MachineNode->getOperand(1)); 5744 else if (Op2Unset) 5745 // nor(x, 0) = ~x 5746 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5747 MVT::i1, MachineNode->getOperand(0), 5748 MachineNode->getOperand(0)); 5749 else if (Op1Not) 5750 // nor(~x, y) = andc(x, y) 5751 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 5752 MVT::i1, MachineNode->getOperand(0). 5753 getOperand(0), 5754 MachineNode->getOperand(1)); 5755 else if (Op2Not) 5756 // nor(x, ~y) = andc(y, x) 5757 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 5758 MVT::i1, MachineNode->getOperand(1). 5759 getOperand(0), 5760 MachineNode->getOperand(0)); 5761 else if (AllUsersSelectZero(MachineNode)) { 5762 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode), 5763 MVT::i1, MachineNode->getOperand(0), 5764 MachineNode->getOperand(1)); 5765 SelectSwap = true; 5766 } 5767 break; 5768 case PPC::CREQV: 5769 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 5770 // eqv(x, x) = 1 5771 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 5772 MVT::i1); 5773 else if (Op1Set) 5774 // eqv(1, y) = y 5775 ResNode = MachineNode->getOperand(1).getNode(); 5776 else if (Op2Set) 5777 // eqv(x, 1) = x 5778 ResNode = MachineNode->getOperand(0).getNode(); 5779 else if (Op1Unset) 5780 // eqv(0, y) = ~y -> nor(y, y) 5781 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5782 MVT::i1, MachineNode->getOperand(1), 5783 MachineNode->getOperand(1)); 5784 else if (Op2Unset) 5785 // eqv(x, 0) = ~x 5786 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5787 MVT::i1, MachineNode->getOperand(0), 5788 MachineNode->getOperand(0)); 5789 else if (Op1Not) 5790 // eqv(~x, y) = xor(x, y) 5791 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 5792 MVT::i1, MachineNode->getOperand(0). 5793 getOperand(0), 5794 MachineNode->getOperand(1)); 5795 else if (Op2Not) 5796 // eqv(x, ~y) = xor(x, y) 5797 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 5798 MVT::i1, MachineNode->getOperand(0), 5799 MachineNode->getOperand(1). 5800 getOperand(0)); 5801 else if (AllUsersSelectZero(MachineNode)) { 5802 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 5803 MVT::i1, MachineNode->getOperand(0), 5804 MachineNode->getOperand(1)); 5805 SelectSwap = true; 5806 } 5807 break; 5808 case PPC::CRANDC: 5809 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 5810 // andc(x, x) = 0 5811 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 5812 MVT::i1); 5813 else if (Op1Set) 5814 // andc(1, y) = ~y 5815 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5816 MVT::i1, MachineNode->getOperand(1), 5817 MachineNode->getOperand(1)); 5818 else if (Op1Unset || Op2Set) 5819 // andc(0, y) = andc(x, 1) = 0 5820 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 5821 MVT::i1); 5822 else if (Op2Unset) 5823 // andc(x, 0) = x 5824 ResNode = MachineNode->getOperand(0).getNode(); 5825 else if (Op1Not) 5826 // andc(~x, y) = ~(x | y) = nor(x, y) 5827 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5828 MVT::i1, MachineNode->getOperand(0). 5829 getOperand(0), 5830 MachineNode->getOperand(1)); 5831 else if (Op2Not) 5832 // andc(x, ~y) = x & y 5833 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode), 5834 MVT::i1, MachineNode->getOperand(0), 5835 MachineNode->getOperand(1). 5836 getOperand(0)); 5837 else if (AllUsersSelectZero(MachineNode)) { 5838 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 5839 MVT::i1, MachineNode->getOperand(1), 5840 MachineNode->getOperand(0)); 5841 SelectSwap = true; 5842 } 5843 break; 5844 case PPC::CRORC: 5845 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 5846 // orc(x, x) = 1 5847 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 5848 MVT::i1); 5849 else if (Op1Set || Op2Unset) 5850 // orc(1, y) = orc(x, 0) = 1 5851 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 5852 MVT::i1); 5853 else if (Op2Set) 5854 // orc(x, 1) = x 5855 ResNode = MachineNode->getOperand(0).getNode(); 5856 else if (Op1Unset) 5857 // orc(0, y) = ~y 5858 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 5859 MVT::i1, MachineNode->getOperand(1), 5860 MachineNode->getOperand(1)); 5861 else if (Op1Not) 5862 // orc(~x, y) = ~(x & y) = nand(x, y) 5863 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode), 5864 MVT::i1, MachineNode->getOperand(0). 5865 getOperand(0), 5866 MachineNode->getOperand(1)); 5867 else if (Op2Not) 5868 // orc(x, ~y) = x | y 5869 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode), 5870 MVT::i1, MachineNode->getOperand(0), 5871 MachineNode->getOperand(1). 5872 getOperand(0)); 5873 else if (AllUsersSelectZero(MachineNode)) { 5874 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 5875 MVT::i1, MachineNode->getOperand(1), 5876 MachineNode->getOperand(0)); 5877 SelectSwap = true; 5878 } 5879 break; 5880 case PPC::SELECT_I4: 5881 case PPC::SELECT_I8: 5882 case PPC::SELECT_F4: 5883 case PPC::SELECT_F8: 5884 case PPC::SELECT_QFRC: 5885 case PPC::SELECT_QSRC: 5886 case PPC::SELECT_QBRC: 5887 case PPC::SELECT_SPE: 5888 case PPC::SELECT_SPE4: 5889 case PPC::SELECT_VRRC: 5890 case PPC::SELECT_VSFRC: 5891 case PPC::SELECT_VSSRC: 5892 case PPC::SELECT_VSRC: 5893 if (Op1Set) 5894 ResNode = MachineNode->getOperand(1).getNode(); 5895 else if (Op1Unset) 5896 ResNode = MachineNode->getOperand(2).getNode(); 5897 else if (Op1Not) 5898 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(), 5899 SDLoc(MachineNode), 5900 MachineNode->getValueType(0), 5901 MachineNode->getOperand(0). 5902 getOperand(0), 5903 MachineNode->getOperand(2), 5904 MachineNode->getOperand(1)); 5905 break; 5906 case PPC::BC: 5907 case PPC::BCn: 5908 if (Op1Not) 5909 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn : 5910 PPC::BC, 5911 SDLoc(MachineNode), 5912 MVT::Other, 5913 MachineNode->getOperand(0). 5914 getOperand(0), 5915 MachineNode->getOperand(1), 5916 MachineNode->getOperand(2)); 5917 // FIXME: Handle Op1Set, Op1Unset here too. 5918 break; 5919 } 5920 5921 // If we're inverting this node because it is used only by selects that 5922 // we'd like to swap, then swap the selects before the node replacement. 5923 if (SelectSwap) 5924 SwapAllSelectUsers(MachineNode); 5925 5926 if (ResNode != MachineNode) { 5927 LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: "); 5928 LLVM_DEBUG(MachineNode->dump(CurDAG)); 5929 LLVM_DEBUG(dbgs() << "\nNew: "); 5930 LLVM_DEBUG(ResNode->dump(CurDAG)); 5931 LLVM_DEBUG(dbgs() << "\n"); 5932 5933 ReplaceUses(MachineNode, ResNode); 5934 IsModified = true; 5935 } 5936 } 5937 if (IsModified) 5938 CurDAG->RemoveDeadNodes(); 5939 } while (IsModified); 5940 } 5941 5942 // Gather the set of 32-bit operations that are known to have their 5943 // higher-order 32 bits zero, where ToPromote contains all such operations. 5944 static bool PeepholePPC64ZExtGather(SDValue Op32, 5945 SmallPtrSetImpl<SDNode *> &ToPromote) { 5946 if (!Op32.isMachineOpcode()) 5947 return false; 5948 5949 // First, check for the "frontier" instructions (those that will clear the 5950 // higher-order 32 bits. 5951 5952 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap 5953 // around. If it does not, then these instructions will clear the 5954 // higher-order bits. 5955 if ((Op32.getMachineOpcode() == PPC::RLWINM || 5956 Op32.getMachineOpcode() == PPC::RLWNM) && 5957 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) { 5958 ToPromote.insert(Op32.getNode()); 5959 return true; 5960 } 5961 5962 // SLW and SRW always clear the higher-order bits. 5963 if (Op32.getMachineOpcode() == PPC::SLW || 5964 Op32.getMachineOpcode() == PPC::SRW) { 5965 ToPromote.insert(Op32.getNode()); 5966 return true; 5967 } 5968 5969 // For LI and LIS, we need the immediate to be positive (so that it is not 5970 // sign extended). 5971 if (Op32.getMachineOpcode() == PPC::LI || 5972 Op32.getMachineOpcode() == PPC::LIS) { 5973 if (!isUInt<15>(Op32.getConstantOperandVal(0))) 5974 return false; 5975 5976 ToPromote.insert(Op32.getNode()); 5977 return true; 5978 } 5979 5980 // LHBRX and LWBRX always clear the higher-order bits. 5981 if (Op32.getMachineOpcode() == PPC::LHBRX || 5982 Op32.getMachineOpcode() == PPC::LWBRX) { 5983 ToPromote.insert(Op32.getNode()); 5984 return true; 5985 } 5986 5987 // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended. 5988 if (Op32.getMachineOpcode() == PPC::CNTLZW || 5989 Op32.getMachineOpcode() == PPC::CNTTZW) { 5990 ToPromote.insert(Op32.getNode()); 5991 return true; 5992 } 5993 5994 // Next, check for those instructions we can look through. 5995 5996 // Assuming the mask does not wrap around, then the higher-order bits are 5997 // taken directly from the first operand. 5998 if (Op32.getMachineOpcode() == PPC::RLWIMI && 5999 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) { 6000 SmallPtrSet<SDNode *, 16> ToPromote1; 6001 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1)) 6002 return false; 6003 6004 ToPromote.insert(Op32.getNode()); 6005 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 6006 return true; 6007 } 6008 6009 // For OR, the higher-order bits are zero if that is true for both operands. 6010 // For SELECT_I4, the same is true (but the relevant operand numbers are 6011 // shifted by 1). 6012 if (Op32.getMachineOpcode() == PPC::OR || 6013 Op32.getMachineOpcode() == PPC::SELECT_I4) { 6014 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0; 6015 SmallPtrSet<SDNode *, 16> ToPromote1; 6016 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1)) 6017 return false; 6018 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1)) 6019 return false; 6020 6021 ToPromote.insert(Op32.getNode()); 6022 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 6023 return true; 6024 } 6025 6026 // For ORI and ORIS, we need the higher-order bits of the first operand to be 6027 // zero, and also for the constant to be positive (so that it is not sign 6028 // extended). 6029 if (Op32.getMachineOpcode() == PPC::ORI || 6030 Op32.getMachineOpcode() == PPC::ORIS) { 6031 SmallPtrSet<SDNode *, 16> ToPromote1; 6032 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1)) 6033 return false; 6034 if (!isUInt<15>(Op32.getConstantOperandVal(1))) 6035 return false; 6036 6037 ToPromote.insert(Op32.getNode()); 6038 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 6039 return true; 6040 } 6041 6042 // The higher-order bits of AND are zero if that is true for at least one of 6043 // the operands. 6044 if (Op32.getMachineOpcode() == PPC::AND) { 6045 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2; 6046 bool Op0OK = 6047 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1); 6048 bool Op1OK = 6049 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2); 6050 if (!Op0OK && !Op1OK) 6051 return false; 6052 6053 ToPromote.insert(Op32.getNode()); 6054 6055 if (Op0OK) 6056 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 6057 6058 if (Op1OK) 6059 ToPromote.insert(ToPromote2.begin(), ToPromote2.end()); 6060 6061 return true; 6062 } 6063 6064 // For ANDI and ANDIS, the higher-order bits are zero if either that is true 6065 // of the first operand, or if the second operand is positive (so that it is 6066 // not sign extended). 6067 if (Op32.getMachineOpcode() == PPC::ANDIo || 6068 Op32.getMachineOpcode() == PPC::ANDISo) { 6069 SmallPtrSet<SDNode *, 16> ToPromote1; 6070 bool Op0OK = 6071 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1); 6072 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1)); 6073 if (!Op0OK && !Op1OK) 6074 return false; 6075 6076 ToPromote.insert(Op32.getNode()); 6077 6078 if (Op0OK) 6079 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 6080 6081 return true; 6082 } 6083 6084 return false; 6085 } 6086 6087 void PPCDAGToDAGISel::PeepholePPC64ZExt() { 6088 if (!PPCSubTarget->isPPC64()) 6089 return; 6090 6091 // When we zero-extend from i32 to i64, we use a pattern like this: 6092 // def : Pat<(i64 (zext i32:$in)), 6093 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32), 6094 // 0, 32)>; 6095 // There are several 32-bit shift/rotate instructions, however, that will 6096 // clear the higher-order bits of their output, rendering the RLDICL 6097 // unnecessary. When that happens, we remove it here, and redefine the 6098 // relevant 32-bit operation to be a 64-bit operation. 6099 6100 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end(); 6101 6102 bool MadeChange = false; 6103 while (Position != CurDAG->allnodes_begin()) { 6104 SDNode *N = &*--Position; 6105 // Skip dead nodes and any non-machine opcodes. 6106 if (N->use_empty() || !N->isMachineOpcode()) 6107 continue; 6108 6109 if (N->getMachineOpcode() != PPC::RLDICL) 6110 continue; 6111 6112 if (N->getConstantOperandVal(1) != 0 || 6113 N->getConstantOperandVal(2) != 32) 6114 continue; 6115 6116 SDValue ISR = N->getOperand(0); 6117 if (!ISR.isMachineOpcode() || 6118 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG) 6119 continue; 6120 6121 if (!ISR.hasOneUse()) 6122 continue; 6123 6124 if (ISR.getConstantOperandVal(2) != PPC::sub_32) 6125 continue; 6126 6127 SDValue IDef = ISR.getOperand(0); 6128 if (!IDef.isMachineOpcode() || 6129 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF) 6130 continue; 6131 6132 // We now know that we're looking at a canonical i32 -> i64 zext. See if we 6133 // can get rid of it. 6134 6135 SDValue Op32 = ISR->getOperand(1); 6136 if (!Op32.isMachineOpcode()) 6137 continue; 6138 6139 // There are some 32-bit instructions that always clear the high-order 32 6140 // bits, there are also some instructions (like AND) that we can look 6141 // through. 6142 SmallPtrSet<SDNode *, 16> ToPromote; 6143 if (!PeepholePPC64ZExtGather(Op32, ToPromote)) 6144 continue; 6145 6146 // If the ToPromote set contains nodes that have uses outside of the set 6147 // (except for the original INSERT_SUBREG), then abort the transformation. 6148 bool OutsideUse = false; 6149 for (SDNode *PN : ToPromote) { 6150 for (SDNode *UN : PN->uses()) { 6151 if (!ToPromote.count(UN) && UN != ISR.getNode()) { 6152 OutsideUse = true; 6153 break; 6154 } 6155 } 6156 6157 if (OutsideUse) 6158 break; 6159 } 6160 if (OutsideUse) 6161 continue; 6162 6163 MadeChange = true; 6164 6165 // We now know that this zero extension can be removed by promoting to 6166 // nodes in ToPromote to 64-bit operations, where for operations in the 6167 // frontier of the set, we need to insert INSERT_SUBREGs for their 6168 // operands. 6169 for (SDNode *PN : ToPromote) { 6170 unsigned NewOpcode; 6171 switch (PN->getMachineOpcode()) { 6172 default: 6173 llvm_unreachable("Don't know the 64-bit variant of this instruction"); 6174 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break; 6175 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break; 6176 case PPC::SLW: NewOpcode = PPC::SLW8; break; 6177 case PPC::SRW: NewOpcode = PPC::SRW8; break; 6178 case PPC::LI: NewOpcode = PPC::LI8; break; 6179 case PPC::LIS: NewOpcode = PPC::LIS8; break; 6180 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break; 6181 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break; 6182 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break; 6183 case PPC::CNTTZW: NewOpcode = PPC::CNTTZW8; break; 6184 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break; 6185 case PPC::OR: NewOpcode = PPC::OR8; break; 6186 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break; 6187 case PPC::ORI: NewOpcode = PPC::ORI8; break; 6188 case PPC::ORIS: NewOpcode = PPC::ORIS8; break; 6189 case PPC::AND: NewOpcode = PPC::AND8; break; 6190 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break; 6191 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break; 6192 } 6193 6194 // Note: During the replacement process, the nodes will be in an 6195 // inconsistent state (some instructions will have operands with values 6196 // of the wrong type). Once done, however, everything should be right 6197 // again. 6198 6199 SmallVector<SDValue, 4> Ops; 6200 for (const SDValue &V : PN->ops()) { 6201 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 && 6202 !isa<ConstantSDNode>(V)) { 6203 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) }; 6204 SDNode *ReplOp = 6205 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V), 6206 ISR.getNode()->getVTList(), ReplOpOps); 6207 Ops.push_back(SDValue(ReplOp, 0)); 6208 } else { 6209 Ops.push_back(V); 6210 } 6211 } 6212 6213 // Because all to-be-promoted nodes only have users that are other 6214 // promoted nodes (or the original INSERT_SUBREG), we can safely replace 6215 // the i32 result value type with i64. 6216 6217 SmallVector<EVT, 2> NewVTs; 6218 SDVTList VTs = PN->getVTList(); 6219 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i) 6220 if (VTs.VTs[i] == MVT::i32) 6221 NewVTs.push_back(MVT::i64); 6222 else 6223 NewVTs.push_back(VTs.VTs[i]); 6224 6225 LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: "); 6226 LLVM_DEBUG(PN->dump(CurDAG)); 6227 6228 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops); 6229 6230 LLVM_DEBUG(dbgs() << "\nNew: "); 6231 LLVM_DEBUG(PN->dump(CurDAG)); 6232 LLVM_DEBUG(dbgs() << "\n"); 6233 } 6234 6235 // Now we replace the original zero extend and its associated INSERT_SUBREG 6236 // with the value feeding the INSERT_SUBREG (which has now been promoted to 6237 // return an i64). 6238 6239 LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: "); 6240 LLVM_DEBUG(N->dump(CurDAG)); 6241 LLVM_DEBUG(dbgs() << "\nNew: "); 6242 LLVM_DEBUG(Op32.getNode()->dump(CurDAG)); 6243 LLVM_DEBUG(dbgs() << "\n"); 6244 6245 ReplaceUses(N, Op32.getNode()); 6246 } 6247 6248 if (MadeChange) 6249 CurDAG->RemoveDeadNodes(); 6250 } 6251 6252 void PPCDAGToDAGISel::PeepholePPC64() { 6253 // These optimizations are currently supported only for 64-bit SVR4. 6254 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64()) 6255 return; 6256 6257 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end(); 6258 6259 while (Position != CurDAG->allnodes_begin()) { 6260 SDNode *N = &*--Position; 6261 // Skip dead nodes and any non-machine opcodes. 6262 if (N->use_empty() || !N->isMachineOpcode()) 6263 continue; 6264 6265 unsigned FirstOp; 6266 unsigned StorageOpcode = N->getMachineOpcode(); 6267 bool RequiresMod4Offset = false; 6268 6269 switch (StorageOpcode) { 6270 default: continue; 6271 6272 case PPC::LWA: 6273 case PPC::LD: 6274 case PPC::DFLOADf64: 6275 case PPC::DFLOADf32: 6276 RequiresMod4Offset = true; 6277 LLVM_FALLTHROUGH; 6278 case PPC::LBZ: 6279 case PPC::LBZ8: 6280 case PPC::LFD: 6281 case PPC::LFS: 6282 case PPC::LHA: 6283 case PPC::LHA8: 6284 case PPC::LHZ: 6285 case PPC::LHZ8: 6286 case PPC::LWZ: 6287 case PPC::LWZ8: 6288 FirstOp = 0; 6289 break; 6290 6291 case PPC::STD: 6292 case PPC::DFSTOREf64: 6293 case PPC::DFSTOREf32: 6294 RequiresMod4Offset = true; 6295 LLVM_FALLTHROUGH; 6296 case PPC::STB: 6297 case PPC::STB8: 6298 case PPC::STFD: 6299 case PPC::STFS: 6300 case PPC::STH: 6301 case PPC::STH8: 6302 case PPC::STW: 6303 case PPC::STW8: 6304 FirstOp = 1; 6305 break; 6306 } 6307 6308 // If this is a load or store with a zero offset, or within the alignment, 6309 // we may be able to fold an add-immediate into the memory operation. 6310 // The check against alignment is below, as it can't occur until we check 6311 // the arguments to N 6312 if (!isa<ConstantSDNode>(N->getOperand(FirstOp))) 6313 continue; 6314 6315 SDValue Base = N->getOperand(FirstOp + 1); 6316 if (!Base.isMachineOpcode()) 6317 continue; 6318 6319 unsigned Flags = 0; 6320 bool ReplaceFlags = true; 6321 6322 // When the feeding operation is an add-immediate of some sort, 6323 // determine whether we need to add relocation information to the 6324 // target flags on the immediate operand when we fold it into the 6325 // load instruction. 6326 // 6327 // For something like ADDItocL, the relocation information is 6328 // inferred from the opcode; when we process it in the AsmPrinter, 6329 // we add the necessary relocation there. A load, though, can receive 6330 // relocation from various flavors of ADDIxxx, so we need to carry 6331 // the relocation information in the target flags. 6332 switch (Base.getMachineOpcode()) { 6333 default: continue; 6334 6335 case PPC::ADDI8: 6336 case PPC::ADDI: 6337 // In some cases (such as TLS) the relocation information 6338 // is already in place on the operand, so copying the operand 6339 // is sufficient. 6340 ReplaceFlags = false; 6341 // For these cases, the immediate may not be divisible by 4, in 6342 // which case the fold is illegal for DS-form instructions. (The 6343 // other cases provide aligned addresses and are always safe.) 6344 if (RequiresMod4Offset && 6345 (!isa<ConstantSDNode>(Base.getOperand(1)) || 6346 Base.getConstantOperandVal(1) % 4 != 0)) 6347 continue; 6348 break; 6349 case PPC::ADDIdtprelL: 6350 Flags = PPCII::MO_DTPREL_LO; 6351 break; 6352 case PPC::ADDItlsldL: 6353 Flags = PPCII::MO_TLSLD_LO; 6354 break; 6355 case PPC::ADDItocL: 6356 Flags = PPCII::MO_TOC_LO; 6357 break; 6358 } 6359 6360 SDValue ImmOpnd = Base.getOperand(1); 6361 6362 // On PPC64, the TOC base pointer is guaranteed by the ABI only to have 6363 // 8-byte alignment, and so we can only use offsets less than 8 (otherwise, 6364 // we might have needed different @ha relocation values for the offset 6365 // pointers). 6366 int MaxDisplacement = 7; 6367 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) { 6368 const GlobalValue *GV = GA->getGlobal(); 6369 MaxDisplacement = std::min((int) GV->getAlignment() - 1, MaxDisplacement); 6370 } 6371 6372 bool UpdateHBase = false; 6373 SDValue HBase = Base.getOperand(0); 6374 6375 int Offset = N->getConstantOperandVal(FirstOp); 6376 if (ReplaceFlags) { 6377 if (Offset < 0 || Offset > MaxDisplacement) { 6378 // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only 6379 // one use, then we can do this for any offset, we just need to also 6380 // update the offset (i.e. the symbol addend) on the addis also. 6381 if (Base.getMachineOpcode() != PPC::ADDItocL) 6382 continue; 6383 6384 if (!HBase.isMachineOpcode() || 6385 HBase.getMachineOpcode() != PPC::ADDIStocHA) 6386 continue; 6387 6388 if (!Base.hasOneUse() || !HBase.hasOneUse()) 6389 continue; 6390 6391 SDValue HImmOpnd = HBase.getOperand(1); 6392 if (HImmOpnd != ImmOpnd) 6393 continue; 6394 6395 UpdateHBase = true; 6396 } 6397 } else { 6398 // If we're directly folding the addend from an addi instruction, then: 6399 // 1. In general, the offset on the memory access must be zero. 6400 // 2. If the addend is a constant, then it can be combined with a 6401 // non-zero offset, but only if the result meets the encoding 6402 // requirements. 6403 if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) { 6404 Offset += C->getSExtValue(); 6405 6406 if (RequiresMod4Offset && (Offset % 4) != 0) 6407 continue; 6408 6409 if (!isInt<16>(Offset)) 6410 continue; 6411 6412 ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd), 6413 ImmOpnd.getValueType()); 6414 } else if (Offset != 0) { 6415 continue; 6416 } 6417 } 6418 6419 // We found an opportunity. Reverse the operands from the add 6420 // immediate and substitute them into the load or store. If 6421 // needed, update the target flags for the immediate operand to 6422 // reflect the necessary relocation information. 6423 LLVM_DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: "); 6424 LLVM_DEBUG(Base->dump(CurDAG)); 6425 LLVM_DEBUG(dbgs() << "\nN: "); 6426 LLVM_DEBUG(N->dump(CurDAG)); 6427 LLVM_DEBUG(dbgs() << "\n"); 6428 6429 // If the relocation information isn't already present on the 6430 // immediate operand, add it now. 6431 if (ReplaceFlags) { 6432 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) { 6433 SDLoc dl(GA); 6434 const GlobalValue *GV = GA->getGlobal(); 6435 // We can't perform this optimization for data whose alignment 6436 // is insufficient for the instruction encoding. 6437 if (GV->getAlignment() < 4 && 6438 (RequiresMod4Offset || (Offset % 4) != 0)) { 6439 LLVM_DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n"); 6440 continue; 6441 } 6442 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags); 6443 } else if (ConstantPoolSDNode *CP = 6444 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) { 6445 const Constant *C = CP->getConstVal(); 6446 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64, 6447 CP->getAlignment(), 6448 Offset, Flags); 6449 } 6450 } 6451 6452 if (FirstOp == 1) // Store 6453 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd, 6454 Base.getOperand(0), N->getOperand(3)); 6455 else // Load 6456 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0), 6457 N->getOperand(2)); 6458 6459 if (UpdateHBase) 6460 (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0), 6461 ImmOpnd); 6462 6463 // The add-immediate may now be dead, in which case remove it. 6464 if (Base.getNode()->use_empty()) 6465 CurDAG->RemoveDeadNode(Base.getNode()); 6466 } 6467 } 6468 6469 /// createPPCISelDag - This pass converts a legalized DAG into a 6470 /// PowerPC-specific DAG, ready for instruction scheduling. 6471 /// 6472 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM, 6473 CodeGenOpt::Level OptLevel) { 6474 return new PPCDAGToDAGISel(TM, OptLevel); 6475 } 6476