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