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 "PPC.h" 16 #include "MCTargetDesc/PPCPredicates.h" 17 #include "PPCMachineFunctionInfo.h" 18 #include "PPCTargetMachine.h" 19 #include "llvm/Analysis/BranchProbabilityInfo.h" 20 #include "llvm/CodeGen/FunctionLoweringInfo.h" 21 #include "llvm/CodeGen/MachineFunction.h" 22 #include "llvm/CodeGen/MachineInstrBuilder.h" 23 #include "llvm/CodeGen/MachineRegisterInfo.h" 24 #include "llvm/CodeGen/SelectionDAG.h" 25 #include "llvm/CodeGen/SelectionDAGISel.h" 26 #include "llvm/IR/Constants.h" 27 #include "llvm/IR/Function.h" 28 #include "llvm/IR/GlobalAlias.h" 29 #include "llvm/IR/GlobalValue.h" 30 #include "llvm/IR/GlobalVariable.h" 31 #include "llvm/IR/Intrinsics.h" 32 #include "llvm/IR/Module.h" 33 #include "llvm/Support/CommandLine.h" 34 #include "llvm/Support/Debug.h" 35 #include "llvm/Support/ErrorHandling.h" 36 #include "llvm/Support/MathExtras.h" 37 #include "llvm/Support/raw_ostream.h" 38 #include "llvm/Target/TargetOptions.h" 39 using namespace llvm; 40 41 #define DEBUG_TYPE "ppc-codegen" 42 43 // FIXME: Remove this once the bug has been fixed! 44 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug", 45 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden); 46 47 static cl::opt<bool> 48 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true), 49 cl::desc("use aggressive ppc isel for bit permutations"), 50 cl::Hidden); 51 static cl::opt<bool> BPermRewriterNoMasking( 52 "ppc-bit-perm-rewriter-stress-rotates", 53 cl::desc("stress rotate selection in aggressive ppc isel for " 54 "bit permutations"), 55 cl::Hidden); 56 57 static cl::opt<bool> EnableBranchHint( 58 "ppc-use-branch-hint", cl::init(true), 59 cl::desc("Enable static hinting of branches on ppc"), 60 cl::Hidden); 61 62 namespace { 63 //===--------------------------------------------------------------------===// 64 /// PPCDAGToDAGISel - PPC specific code to select PPC machine 65 /// instructions for SelectionDAG operations. 66 /// 67 class PPCDAGToDAGISel : public SelectionDAGISel { 68 const PPCTargetMachine &TM; 69 const PPCSubtarget *PPCSubTarget; 70 const PPCTargetLowering *PPCLowering; 71 unsigned GlobalBaseReg; 72 public: 73 explicit PPCDAGToDAGISel(PPCTargetMachine &tm) 74 : SelectionDAGISel(tm), TM(tm) {} 75 76 bool runOnMachineFunction(MachineFunction &MF) override { 77 // Make sure we re-emit a set of the global base reg if necessary 78 GlobalBaseReg = 0; 79 PPCSubTarget = &MF.getSubtarget<PPCSubtarget>(); 80 PPCLowering = PPCSubTarget->getTargetLowering(); 81 SelectionDAGISel::runOnMachineFunction(MF); 82 83 if (!PPCSubTarget->isSVR4ABI()) 84 InsertVRSaveCode(MF); 85 86 return true; 87 } 88 89 void PreprocessISelDAG() override; 90 void PostprocessISelDAG() override; 91 92 /// getI32Imm - Return a target constant with the specified value, of type 93 /// i32. 94 inline SDValue getI32Imm(unsigned Imm, SDLoc dl) { 95 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 96 } 97 98 /// getI64Imm - Return a target constant with the specified value, of type 99 /// i64. 100 inline SDValue getI64Imm(uint64_t Imm, SDLoc dl) { 101 return CurDAG->getTargetConstant(Imm, dl, MVT::i64); 102 } 103 104 /// getSmallIPtrImm - Return a target constant of pointer type. 105 inline SDValue getSmallIPtrImm(unsigned Imm, SDLoc dl) { 106 return CurDAG->getTargetConstant( 107 Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout())); 108 } 109 110 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a 111 /// rotate and mask opcode and mask operation. 112 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask, 113 unsigned &SH, unsigned &MB, unsigned &ME); 114 115 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC 116 /// base register. Return the virtual register that holds this value. 117 SDNode *getGlobalBaseReg(); 118 119 void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0); 120 121 // Select - Convert the specified operand from a target-independent to a 122 // target-specific node if it hasn't already been changed. 123 void Select(SDNode *N) override; 124 125 bool tryBitfieldInsert(SDNode *N); 126 bool tryBitPermutation(SDNode *N); 127 128 /// SelectCC - Select a comparison of the specified values with the 129 /// specified condition code, returning the CR# of the expression. 130 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl); 131 132 /// SelectAddrImm - Returns true if the address N can be represented by 133 /// a base register plus a signed 16-bit displacement [r+imm]. 134 bool SelectAddrImm(SDValue N, SDValue &Disp, 135 SDValue &Base) { 136 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false); 137 } 138 139 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc 140 /// immediate field. Note that the operand at this point is already the 141 /// result of a prior SelectAddressRegImm call. 142 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const { 143 if (N.getOpcode() == ISD::TargetConstant || 144 N.getOpcode() == ISD::TargetGlobalAddress) { 145 Out = N; 146 return true; 147 } 148 149 return false; 150 } 151 152 /// SelectAddrIdx - Given the specified addressed, check to see if it can be 153 /// represented as an indexed [r+r] operation. Returns false if it can 154 /// be represented by [r+imm], which are preferred. 155 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) { 156 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG); 157 } 158 159 /// SelectAddrIdxOnly - Given the specified addressed, force it to be 160 /// represented as an indexed [r+r] operation. 161 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) { 162 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG); 163 } 164 165 /// SelectAddrImmX4 - Returns true if the address N can be represented by 166 /// a base register plus a signed 16-bit displacement that is a multiple of 4. 167 /// Suitable for use by STD and friends. 168 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) { 169 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true); 170 } 171 172 // Select an address into a single register. 173 bool SelectAddr(SDValue N, SDValue &Base) { 174 Base = N; 175 return true; 176 } 177 178 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for 179 /// inline asm expressions. It is always correct to compute the value into 180 /// a register. The case of adding a (possibly relocatable) constant to a 181 /// register can be improved, but it is wrong to substitute Reg+Reg for 182 /// Reg in an asm, because the load or store opcode would have to change. 183 bool SelectInlineAsmMemoryOperand(const SDValue &Op, 184 unsigned ConstraintID, 185 std::vector<SDValue> &OutOps) override { 186 187 switch(ConstraintID) { 188 default: 189 errs() << "ConstraintID: " << ConstraintID << "\n"; 190 llvm_unreachable("Unexpected asm memory constraint"); 191 case InlineAsm::Constraint_es: 192 case InlineAsm::Constraint_i: 193 case InlineAsm::Constraint_m: 194 case InlineAsm::Constraint_o: 195 case InlineAsm::Constraint_Q: 196 case InlineAsm::Constraint_Z: 197 case InlineAsm::Constraint_Zy: 198 // We need to make sure that this one operand does not end up in r0 199 // (because we might end up lowering this as 0(%op)). 200 const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo(); 201 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1); 202 SDLoc dl(Op); 203 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32); 204 SDValue NewOp = 205 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS, 206 dl, Op.getValueType(), 207 Op, RC), 0); 208 209 OutOps.push_back(NewOp); 210 return false; 211 } 212 return true; 213 } 214 215 void InsertVRSaveCode(MachineFunction &MF); 216 217 const char *getPassName() const override { 218 return "PowerPC DAG->DAG Pattern Instruction Selection"; 219 } 220 221 // Include the pieces autogenerated from the target description. 222 #include "PPCGenDAGISel.inc" 223 224 private: 225 bool trySETCC(SDNode *N); 226 227 void PeepholePPC64(); 228 void PeepholePPC64ZExt(); 229 void PeepholeCROps(); 230 231 SDValue combineToCMPB(SDNode *N); 232 void foldBoolExts(SDValue &Res, SDNode *&N); 233 234 bool AllUsersSelectZero(SDNode *N); 235 void SwapAllSelectUsers(SDNode *N); 236 237 void transferMemOperands(SDNode *N, SDNode *Result); 238 }; 239 } 240 241 /// InsertVRSaveCode - Once the entire function has been instruction selected, 242 /// all virtual registers are created and all machine instructions are built, 243 /// check to see if we need to save/restore VRSAVE. If so, do it. 244 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) { 245 // Check to see if this function uses vector registers, which means we have to 246 // save and restore the VRSAVE register and update it with the regs we use. 247 // 248 // In this case, there will be virtual registers of vector type created 249 // by the scheduler. Detect them now. 250 bool HasVectorVReg = false; 251 for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) { 252 unsigned Reg = TargetRegisterInfo::index2VirtReg(i); 253 if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) { 254 HasVectorVReg = true; 255 break; 256 } 257 } 258 if (!HasVectorVReg) return; // nothing to do. 259 260 // If we have a vector register, we want to emit code into the entry and exit 261 // blocks to save and restore the VRSAVE register. We do this here (instead 262 // of marking all vector instructions as clobbering VRSAVE) for two reasons: 263 // 264 // 1. This (trivially) reduces the load on the register allocator, by not 265 // having to represent the live range of the VRSAVE register. 266 // 2. This (more significantly) allows us to create a temporary virtual 267 // register to hold the saved VRSAVE value, allowing this temporary to be 268 // register allocated, instead of forcing it to be spilled to the stack. 269 270 // Create two vregs - one to hold the VRSAVE register that is live-in to the 271 // function and one for the value after having bits or'd into it. 272 unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass); 273 unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass); 274 275 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo(); 276 MachineBasicBlock &EntryBB = *Fn.begin(); 277 DebugLoc dl; 278 // Emit the following code into the entry block: 279 // InVRSAVE = MFVRSAVE 280 // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE 281 // MTVRSAVE UpdatedVRSAVE 282 MachineBasicBlock::iterator IP = EntryBB.begin(); // Insert Point 283 BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE); 284 BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE), 285 UpdatedVRSAVE).addReg(InVRSAVE); 286 BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE); 287 288 // Find all return blocks, outputting a restore in each epilog. 289 for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) { 290 if (BB->isReturnBlock()) { 291 IP = BB->end(); --IP; 292 293 // Skip over all terminator instructions, which are part of the return 294 // sequence. 295 MachineBasicBlock::iterator I2 = IP; 296 while (I2 != BB->begin() && (--I2)->isTerminator()) 297 IP = I2; 298 299 // Emit: MTVRSAVE InVRSave 300 BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE); 301 } 302 } 303 } 304 305 306 /// getGlobalBaseReg - Output the instructions required to put the 307 /// base address to use for accessing globals into a register. 308 /// 309 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() { 310 if (!GlobalBaseReg) { 311 const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo(); 312 // Insert the set of GlobalBaseReg into the first MBB of the function 313 MachineBasicBlock &FirstMBB = MF->front(); 314 MachineBasicBlock::iterator MBBI = FirstMBB.begin(); 315 const Module *M = MF->getFunction()->getParent(); 316 DebugLoc dl; 317 318 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) { 319 if (PPCSubTarget->isTargetELF()) { 320 GlobalBaseReg = PPC::R30; 321 if (M->getPICLevel() == PICLevel::Small) { 322 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR)); 323 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 324 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true); 325 } else { 326 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR)); 327 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 328 unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass); 329 BuildMI(FirstMBB, MBBI, dl, 330 TII.get(PPC::UpdateGBR), GlobalBaseReg) 331 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg); 332 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true); 333 } 334 } else { 335 GlobalBaseReg = 336 RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass); 337 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR)); 338 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg); 339 } 340 } else { 341 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass); 342 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8)); 343 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg); 344 } 345 } 346 return CurDAG->getRegister(GlobalBaseReg, 347 PPCLowering->getPointerTy(CurDAG->getDataLayout())) 348 .getNode(); 349 } 350 351 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit 352 /// or 64-bit immediate, and if the value can be accurately represented as a 353 /// sign extension from a 16-bit value. If so, this returns true and the 354 /// immediate. 355 static bool isIntS16Immediate(SDNode *N, short &Imm) { 356 if (N->getOpcode() != ISD::Constant) 357 return false; 358 359 Imm = (short)cast<ConstantSDNode>(N)->getZExtValue(); 360 if (N->getValueType(0) == MVT::i32) 361 return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue(); 362 else 363 return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue(); 364 } 365 366 static bool isIntS16Immediate(SDValue Op, short &Imm) { 367 return isIntS16Immediate(Op.getNode(), Imm); 368 } 369 370 371 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant 372 /// operand. If so Imm will receive the 32-bit value. 373 static bool isInt32Immediate(SDNode *N, unsigned &Imm) { 374 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) { 375 Imm = cast<ConstantSDNode>(N)->getZExtValue(); 376 return true; 377 } 378 return false; 379 } 380 381 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant 382 /// operand. If so Imm will receive the 64-bit value. 383 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) { 384 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) { 385 Imm = cast<ConstantSDNode>(N)->getZExtValue(); 386 return true; 387 } 388 return false; 389 } 390 391 // isInt32Immediate - This method tests to see if a constant operand. 392 // If so Imm will receive the 32 bit value. 393 static bool isInt32Immediate(SDValue N, unsigned &Imm) { 394 return isInt32Immediate(N.getNode(), Imm); 395 } 396 397 static unsigned getBranchHint(unsigned PCC, FunctionLoweringInfo *FuncInfo, 398 const SDValue &DestMBB) { 399 assert(isa<BasicBlockSDNode>(DestMBB)); 400 401 if (!FuncInfo->BPI) return PPC::BR_NO_HINT; 402 403 const BasicBlock *BB = FuncInfo->MBB->getBasicBlock(); 404 const TerminatorInst *BBTerm = BB->getTerminator(); 405 406 if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT; 407 408 const BasicBlock *TBB = BBTerm->getSuccessor(0); 409 const BasicBlock *FBB = BBTerm->getSuccessor(1); 410 411 auto TProb = FuncInfo->BPI->getEdgeProbability(BB, TBB); 412 auto FProb = FuncInfo->BPI->getEdgeProbability(BB, FBB); 413 414 // We only want to handle cases which are easy to predict at static time, e.g. 415 // C++ throw statement, that is very likely not taken, or calling never 416 // returned function, e.g. stdlib exit(). So we set Threshold to filter 417 // unwanted cases. 418 // 419 // Below is LLVM branch weight table, we only want to handle case 1, 2 420 // 421 // Case Taken:Nontaken Example 422 // 1. Unreachable 1048575:1 C++ throw, stdlib exit(), 423 // 2. Invoke-terminating 1:1048575 424 // 3. Coldblock 4:64 __builtin_expect 425 // 4. Loop Branch 124:4 For loop 426 // 5. PH/ZH/FPH 20:12 427 const uint32_t Threshold = 10000; 428 429 if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb)) 430 return PPC::BR_NO_HINT; 431 432 DEBUG(dbgs() << "Use branch hint for '" << FuncInfo->Fn->getName() << "::" 433 << BB->getName() << "'\n" 434 << " -> " << TBB->getName() << ": " << TProb << "\n" 435 << " -> " << FBB->getName() << ": " << FProb << "\n"); 436 437 const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB); 438 439 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities, 440 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock 441 if (BBDN->getBasicBlock()->getBasicBlock() != TBB) 442 std::swap(TProb, FProb); 443 444 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT; 445 } 446 447 // isOpcWithIntImmediate - This method tests to see if the node is a specific 448 // opcode and that it has a immediate integer right operand. 449 // If so Imm will receive the 32 bit value. 450 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) { 451 return N->getOpcode() == Opc 452 && isInt32Immediate(N->getOperand(1).getNode(), Imm); 453 } 454 455 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) { 456 SDLoc dl(SN); 457 int FI = cast<FrameIndexSDNode>(N)->getIndex(); 458 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0)); 459 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8; 460 if (SN->hasOneUse()) 461 CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI, 462 getSmallIPtrImm(Offset, dl)); 463 else 464 ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI, 465 getSmallIPtrImm(Offset, dl))); 466 } 467 468 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask, 469 bool isShiftMask, unsigned &SH, 470 unsigned &MB, unsigned &ME) { 471 // Don't even go down this path for i64, since different logic will be 472 // necessary for rldicl/rldicr/rldimi. 473 if (N->getValueType(0) != MVT::i32) 474 return false; 475 476 unsigned Shift = 32; 477 unsigned Indeterminant = ~0; // bit mask marking indeterminant results 478 unsigned Opcode = N->getOpcode(); 479 if (N->getNumOperands() != 2 || 480 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31)) 481 return false; 482 483 if (Opcode == ISD::SHL) { 484 // apply shift left to mask if it comes first 485 if (isShiftMask) Mask = Mask << Shift; 486 // determine which bits are made indeterminant by shift 487 Indeterminant = ~(0xFFFFFFFFu << Shift); 488 } else if (Opcode == ISD::SRL) { 489 // apply shift right to mask if it comes first 490 if (isShiftMask) Mask = Mask >> Shift; 491 // determine which bits are made indeterminant by shift 492 Indeterminant = ~(0xFFFFFFFFu >> Shift); 493 // adjust for the left rotate 494 Shift = 32 - Shift; 495 } else if (Opcode == ISD::ROTL) { 496 Indeterminant = 0; 497 } else { 498 return false; 499 } 500 501 // if the mask doesn't intersect any Indeterminant bits 502 if (Mask && !(Mask & Indeterminant)) { 503 SH = Shift & 31; 504 // make sure the mask is still a mask (wrap arounds may not be) 505 return isRunOfOnes(Mask, MB, ME); 506 } 507 return false; 508 } 509 510 /// Turn an or of two masked values into the rotate left word immediate then 511 /// mask insert (rlwimi) instruction. 512 bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) { 513 SDValue Op0 = N->getOperand(0); 514 SDValue Op1 = N->getOperand(1); 515 SDLoc dl(N); 516 517 APInt LKZ, LKO, RKZ, RKO; 518 CurDAG->computeKnownBits(Op0, LKZ, LKO); 519 CurDAG->computeKnownBits(Op1, RKZ, RKO); 520 521 unsigned TargetMask = LKZ.getZExtValue(); 522 unsigned InsertMask = RKZ.getZExtValue(); 523 524 if ((TargetMask | InsertMask) == 0xFFFFFFFF) { 525 unsigned Op0Opc = Op0.getOpcode(); 526 unsigned Op1Opc = Op1.getOpcode(); 527 unsigned Value, SH = 0; 528 TargetMask = ~TargetMask; 529 InsertMask = ~InsertMask; 530 531 // If the LHS has a foldable shift and the RHS does not, then swap it to the 532 // RHS so that we can fold the shift into the insert. 533 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) { 534 if (Op0.getOperand(0).getOpcode() == ISD::SHL || 535 Op0.getOperand(0).getOpcode() == ISD::SRL) { 536 if (Op1.getOperand(0).getOpcode() != ISD::SHL && 537 Op1.getOperand(0).getOpcode() != ISD::SRL) { 538 std::swap(Op0, Op1); 539 std::swap(Op0Opc, Op1Opc); 540 std::swap(TargetMask, InsertMask); 541 } 542 } 543 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) { 544 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL && 545 Op1.getOperand(0).getOpcode() != ISD::SRL) { 546 std::swap(Op0, Op1); 547 std::swap(Op0Opc, Op1Opc); 548 std::swap(TargetMask, InsertMask); 549 } 550 } 551 552 unsigned MB, ME; 553 if (isRunOfOnes(InsertMask, MB, ME)) { 554 SDValue Tmp1, Tmp2; 555 556 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) && 557 isInt32Immediate(Op1.getOperand(1), Value)) { 558 Op1 = Op1.getOperand(0); 559 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value; 560 } 561 if (Op1Opc == ISD::AND) { 562 // The AND mask might not be a constant, and we need to make sure that 563 // if we're going to fold the masking with the insert, all bits not 564 // know to be zero in the mask are known to be one. 565 APInt MKZ, MKO; 566 CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO); 567 bool CanFoldMask = InsertMask == MKO.getZExtValue(); 568 569 unsigned SHOpc = Op1.getOperand(0).getOpcode(); 570 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask && 571 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) { 572 // Note that Value must be in range here (less than 32) because 573 // otherwise there would not be any bits set in InsertMask. 574 Op1 = Op1.getOperand(0).getOperand(0); 575 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value; 576 } 577 } 578 579 SH &= 31; 580 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl), 581 getI32Imm(ME, dl) }; 582 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops)); 583 return true; 584 } 585 } 586 return false; 587 } 588 589 // Predict the number of instructions that would be generated by calling 590 // getInt64(N). 591 static unsigned getInt64CountDirect(int64_t Imm) { 592 // Assume no remaining bits. 593 unsigned Remainder = 0; 594 // Assume no shift required. 595 unsigned Shift = 0; 596 597 // If it can't be represented as a 32 bit value. 598 if (!isInt<32>(Imm)) { 599 Shift = countTrailingZeros<uint64_t>(Imm); 600 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift; 601 602 // If the shifted value fits 32 bits. 603 if (isInt<32>(ImmSh)) { 604 // Go with the shifted value. 605 Imm = ImmSh; 606 } else { 607 // Still stuck with a 64 bit value. 608 Remainder = Imm; 609 Shift = 32; 610 Imm >>= 32; 611 } 612 } 613 614 // Intermediate operand. 615 unsigned Result = 0; 616 617 // Handle first 32 bits. 618 unsigned Lo = Imm & 0xFFFF; 619 620 // Simple value. 621 if (isInt<16>(Imm)) { 622 // Just the Lo bits. 623 ++Result; 624 } else if (Lo) { 625 // Handle the Hi bits and Lo bits. 626 Result += 2; 627 } else { 628 // Just the Hi bits. 629 ++Result; 630 } 631 632 // If no shift, we're done. 633 if (!Shift) return Result; 634 635 // Shift for next step if the upper 32-bits were not zero. 636 if (Imm) 637 ++Result; 638 639 // Add in the last bits as required. 640 if ((Remainder >> 16) & 0xFFFF) 641 ++Result; 642 if (Remainder & 0xFFFF) 643 ++Result; 644 645 return Result; 646 } 647 648 static uint64_t Rot64(uint64_t Imm, unsigned R) { 649 return (Imm << R) | (Imm >> (64 - R)); 650 } 651 652 static unsigned getInt64Count(int64_t Imm) { 653 unsigned Count = getInt64CountDirect(Imm); 654 if (Count == 1) 655 return Count; 656 657 for (unsigned r = 1; r < 63; ++r) { 658 uint64_t RImm = Rot64(Imm, r); 659 unsigned RCount = getInt64CountDirect(RImm) + 1; 660 Count = std::min(Count, RCount); 661 662 // See comments in getInt64 for an explanation of the logic below. 663 unsigned LS = findLastSet(RImm); 664 if (LS != r-1) 665 continue; 666 667 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1)); 668 uint64_t RImmWithOnes = RImm | OnesMask; 669 670 RCount = getInt64CountDirect(RImmWithOnes) + 1; 671 Count = std::min(Count, RCount); 672 } 673 674 return Count; 675 } 676 677 // Select a 64-bit constant. For cost-modeling purposes, getInt64Count 678 // (above) needs to be kept in sync with this function. 679 static SDNode *getInt64Direct(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) { 680 // Assume no remaining bits. 681 unsigned Remainder = 0; 682 // Assume no shift required. 683 unsigned Shift = 0; 684 685 // If it can't be represented as a 32 bit value. 686 if (!isInt<32>(Imm)) { 687 Shift = countTrailingZeros<uint64_t>(Imm); 688 int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift; 689 690 // If the shifted value fits 32 bits. 691 if (isInt<32>(ImmSh)) { 692 // Go with the shifted value. 693 Imm = ImmSh; 694 } else { 695 // Still stuck with a 64 bit value. 696 Remainder = Imm; 697 Shift = 32; 698 Imm >>= 32; 699 } 700 } 701 702 // Intermediate operand. 703 SDNode *Result; 704 705 // Handle first 32 bits. 706 unsigned Lo = Imm & 0xFFFF; 707 unsigned Hi = (Imm >> 16) & 0xFFFF; 708 709 auto getI32Imm = [CurDAG, dl](unsigned Imm) { 710 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 711 }; 712 713 // Simple value. 714 if (isInt<16>(Imm)) { 715 // Just the Lo bits. 716 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo)); 717 } else if (Lo) { 718 // Handle the Hi bits. 719 unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8; 720 Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi)); 721 // And Lo bits. 722 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, 723 SDValue(Result, 0), getI32Imm(Lo)); 724 } else { 725 // Just the Hi bits. 726 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi)); 727 } 728 729 // If no shift, we're done. 730 if (!Shift) return Result; 731 732 // Shift for next step if the upper 32-bits were not zero. 733 if (Imm) { 734 Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, 735 SDValue(Result, 0), 736 getI32Imm(Shift), 737 getI32Imm(63 - Shift)); 738 } 739 740 // Add in the last bits as required. 741 if ((Hi = (Remainder >> 16) & 0xFFFF)) { 742 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64, 743 SDValue(Result, 0), getI32Imm(Hi)); 744 } 745 if ((Lo = Remainder & 0xFFFF)) { 746 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, 747 SDValue(Result, 0), getI32Imm(Lo)); 748 } 749 750 return Result; 751 } 752 753 static SDNode *getInt64(SelectionDAG *CurDAG, SDLoc dl, int64_t Imm) { 754 unsigned Count = getInt64CountDirect(Imm); 755 if (Count == 1) 756 return getInt64Direct(CurDAG, dl, Imm); 757 758 unsigned RMin = 0; 759 760 int64_t MatImm; 761 unsigned MaskEnd; 762 763 for (unsigned r = 1; r < 63; ++r) { 764 uint64_t RImm = Rot64(Imm, r); 765 unsigned RCount = getInt64CountDirect(RImm) + 1; 766 if (RCount < Count) { 767 Count = RCount; 768 RMin = r; 769 MatImm = RImm; 770 MaskEnd = 63; 771 } 772 773 // If the immediate to generate has many trailing zeros, it might be 774 // worthwhile to generate a rotated value with too many leading ones 775 // (because that's free with li/lis's sign-extension semantics), and then 776 // mask them off after rotation. 777 778 unsigned LS = findLastSet(RImm); 779 // We're adding (63-LS) higher-order ones, and we expect to mask them off 780 // after performing the inverse rotation by (64-r). So we need that: 781 // 63-LS == 64-r => LS == r-1 782 if (LS != r-1) 783 continue; 784 785 uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1)); 786 uint64_t RImmWithOnes = RImm | OnesMask; 787 788 RCount = getInt64CountDirect(RImmWithOnes) + 1; 789 if (RCount < Count) { 790 Count = RCount; 791 RMin = r; 792 MatImm = RImmWithOnes; 793 MaskEnd = LS; 794 } 795 } 796 797 if (!RMin) 798 return getInt64Direct(CurDAG, dl, Imm); 799 800 auto getI32Imm = [CurDAG, dl](unsigned Imm) { 801 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 802 }; 803 804 SDValue Val = SDValue(getInt64Direct(CurDAG, dl, MatImm), 0); 805 return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val, 806 getI32Imm(64 - RMin), getI32Imm(MaskEnd)); 807 } 808 809 // Select a 64-bit constant. 810 static SDNode *getInt64(SelectionDAG *CurDAG, SDNode *N) { 811 SDLoc dl(N); 812 813 // Get 64 bit value. 814 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue(); 815 return getInt64(CurDAG, dl, Imm); 816 } 817 818 namespace { 819 class BitPermutationSelector { 820 struct ValueBit { 821 SDValue V; 822 823 // The bit number in the value, using a convention where bit 0 is the 824 // lowest-order bit. 825 unsigned Idx; 826 827 enum Kind { 828 ConstZero, 829 Variable 830 } K; 831 832 ValueBit(SDValue V, unsigned I, Kind K = Variable) 833 : V(V), Idx(I), K(K) {} 834 ValueBit(Kind K = Variable) 835 : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {} 836 837 bool isZero() const { 838 return K == ConstZero; 839 } 840 841 bool hasValue() const { 842 return K == Variable; 843 } 844 845 SDValue getValue() const { 846 assert(hasValue() && "Cannot get the value of a constant bit"); 847 return V; 848 } 849 850 unsigned getValueBitIndex() const { 851 assert(hasValue() && "Cannot get the value bit index of a constant bit"); 852 return Idx; 853 } 854 }; 855 856 // A bit group has the same underlying value and the same rotate factor. 857 struct BitGroup { 858 SDValue V; 859 unsigned RLAmt; 860 unsigned StartIdx, EndIdx; 861 862 // This rotation amount assumes that the lower 32 bits of the quantity are 863 // replicated in the high 32 bits by the rotation operator (which is done 864 // by rlwinm and friends in 64-bit mode). 865 bool Repl32; 866 // Did converting to Repl32 == true change the rotation factor? If it did, 867 // it decreased it by 32. 868 bool Repl32CR; 869 // Was this group coalesced after setting Repl32 to true? 870 bool Repl32Coalesced; 871 872 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E) 873 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false), 874 Repl32Coalesced(false) { 875 DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R << 876 " [" << S << ", " << E << "]\n"); 877 } 878 }; 879 880 // Information on each (Value, RLAmt) pair (like the number of groups 881 // associated with each) used to choose the lowering method. 882 struct ValueRotInfo { 883 SDValue V; 884 unsigned RLAmt; 885 unsigned NumGroups; 886 unsigned FirstGroupStartIdx; 887 bool Repl32; 888 889 ValueRotInfo() 890 : RLAmt(UINT32_MAX), NumGroups(0), FirstGroupStartIdx(UINT32_MAX), 891 Repl32(false) {} 892 893 // For sorting (in reverse order) by NumGroups, and then by 894 // FirstGroupStartIdx. 895 bool operator < (const ValueRotInfo &Other) const { 896 // We need to sort so that the non-Repl32 come first because, when we're 897 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit 898 // masking operation. 899 if (Repl32 < Other.Repl32) 900 return true; 901 else if (Repl32 > Other.Repl32) 902 return false; 903 else if (NumGroups > Other.NumGroups) 904 return true; 905 else if (NumGroups < Other.NumGroups) 906 return false; 907 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx) 908 return true; 909 return false; 910 } 911 }; 912 913 // Return true if something interesting was deduced, return false if we're 914 // providing only a generic representation of V (or something else likewise 915 // uninteresting for instruction selection). 916 bool getValueBits(SDValue V, SmallVector<ValueBit, 64> &Bits) { 917 switch (V.getOpcode()) { 918 default: break; 919 case ISD::ROTL: 920 if (isa<ConstantSDNode>(V.getOperand(1))) { 921 unsigned RotAmt = V.getConstantOperandVal(1); 922 923 SmallVector<ValueBit, 64> LHSBits(Bits.size()); 924 getValueBits(V.getOperand(0), LHSBits); 925 926 for (unsigned i = 0; i < Bits.size(); ++i) 927 Bits[i] = LHSBits[i < RotAmt ? i + (Bits.size() - RotAmt) : i - RotAmt]; 928 929 return true; 930 } 931 break; 932 case ISD::SHL: 933 if (isa<ConstantSDNode>(V.getOperand(1))) { 934 unsigned ShiftAmt = V.getConstantOperandVal(1); 935 936 SmallVector<ValueBit, 64> LHSBits(Bits.size()); 937 getValueBits(V.getOperand(0), LHSBits); 938 939 for (unsigned i = ShiftAmt; i < Bits.size(); ++i) 940 Bits[i] = LHSBits[i - ShiftAmt]; 941 942 for (unsigned i = 0; i < ShiftAmt; ++i) 943 Bits[i] = ValueBit(ValueBit::ConstZero); 944 945 return true; 946 } 947 break; 948 case ISD::SRL: 949 if (isa<ConstantSDNode>(V.getOperand(1))) { 950 unsigned ShiftAmt = V.getConstantOperandVal(1); 951 952 SmallVector<ValueBit, 64> LHSBits(Bits.size()); 953 getValueBits(V.getOperand(0), LHSBits); 954 955 for (unsigned i = 0; i < Bits.size() - ShiftAmt; ++i) 956 Bits[i] = LHSBits[i + ShiftAmt]; 957 958 for (unsigned i = Bits.size() - ShiftAmt; i < Bits.size(); ++i) 959 Bits[i] = ValueBit(ValueBit::ConstZero); 960 961 return true; 962 } 963 break; 964 case ISD::AND: 965 if (isa<ConstantSDNode>(V.getOperand(1))) { 966 uint64_t Mask = V.getConstantOperandVal(1); 967 968 SmallVector<ValueBit, 64> LHSBits(Bits.size()); 969 bool LHSTrivial = getValueBits(V.getOperand(0), LHSBits); 970 971 for (unsigned i = 0; i < Bits.size(); ++i) 972 if (((Mask >> i) & 1) == 1) 973 Bits[i] = LHSBits[i]; 974 else 975 Bits[i] = ValueBit(ValueBit::ConstZero); 976 977 // Mark this as interesting, only if the LHS was also interesting. This 978 // prevents the overall procedure from matching a single immediate 'and' 979 // (which is non-optimal because such an and might be folded with other 980 // things if we don't select it here). 981 return LHSTrivial; 982 } 983 break; 984 case ISD::OR: { 985 SmallVector<ValueBit, 64> LHSBits(Bits.size()), RHSBits(Bits.size()); 986 getValueBits(V.getOperand(0), LHSBits); 987 getValueBits(V.getOperand(1), RHSBits); 988 989 bool AllDisjoint = true; 990 for (unsigned i = 0; i < Bits.size(); ++i) 991 if (LHSBits[i].isZero()) 992 Bits[i] = RHSBits[i]; 993 else if (RHSBits[i].isZero()) 994 Bits[i] = LHSBits[i]; 995 else { 996 AllDisjoint = false; 997 break; 998 } 999 1000 if (!AllDisjoint) 1001 break; 1002 1003 return true; 1004 } 1005 } 1006 1007 for (unsigned i = 0; i < Bits.size(); ++i) 1008 Bits[i] = ValueBit(V, i); 1009 1010 return false; 1011 } 1012 1013 // For each value (except the constant ones), compute the left-rotate amount 1014 // to get it from its original to final position. 1015 void computeRotationAmounts() { 1016 HasZeros = false; 1017 RLAmt.resize(Bits.size()); 1018 for (unsigned i = 0; i < Bits.size(); ++i) 1019 if (Bits[i].hasValue()) { 1020 unsigned VBI = Bits[i].getValueBitIndex(); 1021 if (i >= VBI) 1022 RLAmt[i] = i - VBI; 1023 else 1024 RLAmt[i] = Bits.size() - (VBI - i); 1025 } else if (Bits[i].isZero()) { 1026 HasZeros = true; 1027 RLAmt[i] = UINT32_MAX; 1028 } else { 1029 llvm_unreachable("Unknown value bit type"); 1030 } 1031 } 1032 1033 // Collect groups of consecutive bits with the same underlying value and 1034 // rotation factor. If we're doing late masking, we ignore zeros, otherwise 1035 // they break up groups. 1036 void collectBitGroups(bool LateMask) { 1037 BitGroups.clear(); 1038 1039 unsigned LastRLAmt = RLAmt[0]; 1040 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue(); 1041 unsigned LastGroupStartIdx = 0; 1042 for (unsigned i = 1; i < Bits.size(); ++i) { 1043 unsigned ThisRLAmt = RLAmt[i]; 1044 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue(); 1045 if (LateMask && !ThisValue) { 1046 ThisValue = LastValue; 1047 ThisRLAmt = LastRLAmt; 1048 // If we're doing late masking, then the first bit group always starts 1049 // at zero (even if the first bits were zero). 1050 if (BitGroups.empty()) 1051 LastGroupStartIdx = 0; 1052 } 1053 1054 // If this bit has the same underlying value and the same rotate factor as 1055 // the last one, then they're part of the same group. 1056 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue) 1057 continue; 1058 1059 if (LastValue.getNode()) 1060 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx, 1061 i-1)); 1062 LastRLAmt = ThisRLAmt; 1063 LastValue = ThisValue; 1064 LastGroupStartIdx = i; 1065 } 1066 if (LastValue.getNode()) 1067 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx, 1068 Bits.size()-1)); 1069 1070 if (BitGroups.empty()) 1071 return; 1072 1073 // We might be able to combine the first and last groups. 1074 if (BitGroups.size() > 1) { 1075 // If the first and last groups are the same, then remove the first group 1076 // in favor of the last group, making the ending index of the last group 1077 // equal to the ending index of the to-be-removed first group. 1078 if (BitGroups[0].StartIdx == 0 && 1079 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 && 1080 BitGroups[0].V == BitGroups[BitGroups.size()-1].V && 1081 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) { 1082 DEBUG(dbgs() << "\tcombining final bit group with initial one\n"); 1083 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx; 1084 BitGroups.erase(BitGroups.begin()); 1085 } 1086 } 1087 } 1088 1089 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups 1090 // associated with each. If there is a degeneracy, pick the one that occurs 1091 // first (in the final value). 1092 void collectValueRotInfo() { 1093 ValueRots.clear(); 1094 1095 for (auto &BG : BitGroups) { 1096 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0); 1097 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)]; 1098 VRI.V = BG.V; 1099 VRI.RLAmt = BG.RLAmt; 1100 VRI.Repl32 = BG.Repl32; 1101 VRI.NumGroups += 1; 1102 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx); 1103 } 1104 1105 // Now that we've collected the various ValueRotInfo instances, we need to 1106 // sort them. 1107 ValueRotsVec.clear(); 1108 for (auto &I : ValueRots) { 1109 ValueRotsVec.push_back(I.second); 1110 } 1111 std::sort(ValueRotsVec.begin(), ValueRotsVec.end()); 1112 } 1113 1114 // In 64-bit mode, rlwinm and friends have a rotation operator that 1115 // replicates the low-order 32 bits into the high-order 32-bits. The mask 1116 // indices of these instructions can only be in the lower 32 bits, so they 1117 // can only represent some 64-bit bit groups. However, when they can be used, 1118 // the 32-bit replication can be used to represent, as a single bit group, 1119 // otherwise separate bit groups. We'll convert to replicated-32-bit bit 1120 // groups when possible. Returns true if any of the bit groups were 1121 // converted. 1122 void assignRepl32BitGroups() { 1123 // If we have bits like this: 1124 // 1125 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 1126 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24 1127 // Groups: | RLAmt = 8 | RLAmt = 40 | 1128 // 1129 // But, making use of a 32-bit operation that replicates the low-order 32 1130 // bits into the high-order 32 bits, this can be one bit group with a RLAmt 1131 // of 8. 1132 1133 auto IsAllLow32 = [this](BitGroup & BG) { 1134 if (BG.StartIdx <= BG.EndIdx) { 1135 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) { 1136 if (!Bits[i].hasValue()) 1137 continue; 1138 if (Bits[i].getValueBitIndex() >= 32) 1139 return false; 1140 } 1141 } else { 1142 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) { 1143 if (!Bits[i].hasValue()) 1144 continue; 1145 if (Bits[i].getValueBitIndex() >= 32) 1146 return false; 1147 } 1148 for (unsigned i = 0; i <= BG.EndIdx; ++i) { 1149 if (!Bits[i].hasValue()) 1150 continue; 1151 if (Bits[i].getValueBitIndex() >= 32) 1152 return false; 1153 } 1154 } 1155 1156 return true; 1157 }; 1158 1159 for (auto &BG : BitGroups) { 1160 if (BG.StartIdx < 32 && BG.EndIdx < 32) { 1161 if (IsAllLow32(BG)) { 1162 if (BG.RLAmt >= 32) { 1163 BG.RLAmt -= 32; 1164 BG.Repl32CR = true; 1165 } 1166 1167 BG.Repl32 = true; 1168 1169 DEBUG(dbgs() << "\t32-bit replicated bit group for " << 1170 BG.V.getNode() << " RLAmt = " << BG.RLAmt << 1171 " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n"); 1172 } 1173 } 1174 } 1175 1176 // Now walk through the bit groups, consolidating where possible. 1177 for (auto I = BitGroups.begin(); I != BitGroups.end();) { 1178 // We might want to remove this bit group by merging it with the previous 1179 // group (which might be the ending group). 1180 auto IP = (I == BitGroups.begin()) ? 1181 std::prev(BitGroups.end()) : std::prev(I); 1182 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt && 1183 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) { 1184 1185 DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " << 1186 I->V.getNode() << " RLAmt = " << I->RLAmt << 1187 " [" << I->StartIdx << ", " << I->EndIdx << 1188 "] with group with range [" << 1189 IP->StartIdx << ", " << IP->EndIdx << "]\n"); 1190 1191 IP->EndIdx = I->EndIdx; 1192 IP->Repl32CR = IP->Repl32CR || I->Repl32CR; 1193 IP->Repl32Coalesced = true; 1194 I = BitGroups.erase(I); 1195 continue; 1196 } else { 1197 // There is a special case worth handling: If there is a single group 1198 // covering the entire upper 32 bits, and it can be merged with both 1199 // the next and previous groups (which might be the same group), then 1200 // do so. If it is the same group (so there will be only one group in 1201 // total), then we need to reverse the order of the range so that it 1202 // covers the entire 64 bits. 1203 if (I->StartIdx == 32 && I->EndIdx == 63) { 1204 assert(std::next(I) == BitGroups.end() && 1205 "bit group ends at index 63 but there is another?"); 1206 auto IN = BitGroups.begin(); 1207 1208 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V && 1209 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt && 1210 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP && 1211 IsAllLow32(*I)) { 1212 1213 DEBUG(dbgs() << "\tcombining bit group for " << 1214 I->V.getNode() << " RLAmt = " << I->RLAmt << 1215 " [" << I->StartIdx << ", " << I->EndIdx << 1216 "] with 32-bit replicated groups with ranges [" << 1217 IP->StartIdx << ", " << IP->EndIdx << "] and [" << 1218 IN->StartIdx << ", " << IN->EndIdx << "]\n"); 1219 1220 if (IP == IN) { 1221 // There is only one other group; change it to cover the whole 1222 // range (backward, so that it can still be Repl32 but cover the 1223 // whole 64-bit range). 1224 IP->StartIdx = 31; 1225 IP->EndIdx = 30; 1226 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32; 1227 IP->Repl32Coalesced = true; 1228 I = BitGroups.erase(I); 1229 } else { 1230 // There are two separate groups, one before this group and one 1231 // after us (at the beginning). We're going to remove this group, 1232 // but also the group at the very beginning. 1233 IP->EndIdx = IN->EndIdx; 1234 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32; 1235 IP->Repl32Coalesced = true; 1236 I = BitGroups.erase(I); 1237 BitGroups.erase(BitGroups.begin()); 1238 } 1239 1240 // This must be the last group in the vector (and we might have 1241 // just invalidated the iterator above), so break here. 1242 break; 1243 } 1244 } 1245 } 1246 1247 ++I; 1248 } 1249 } 1250 1251 SDValue getI32Imm(unsigned Imm, SDLoc dl) { 1252 return CurDAG->getTargetConstant(Imm, dl, MVT::i32); 1253 } 1254 1255 uint64_t getZerosMask() { 1256 uint64_t Mask = 0; 1257 for (unsigned i = 0; i < Bits.size(); ++i) { 1258 if (Bits[i].hasValue()) 1259 continue; 1260 Mask |= (UINT64_C(1) << i); 1261 } 1262 1263 return ~Mask; 1264 } 1265 1266 // Depending on the number of groups for a particular value, it might be 1267 // better to rotate, mask explicitly (using andi/andis), and then or the 1268 // result. Select this part of the result first. 1269 void SelectAndParts32(SDLoc dl, SDValue &Res, unsigned *InstCnt) { 1270 if (BPermRewriterNoMasking) 1271 return; 1272 1273 for (ValueRotInfo &VRI : ValueRotsVec) { 1274 unsigned Mask = 0; 1275 for (unsigned i = 0; i < Bits.size(); ++i) { 1276 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V) 1277 continue; 1278 if (RLAmt[i] != VRI.RLAmt) 1279 continue; 1280 Mask |= (1u << i); 1281 } 1282 1283 // Compute the masks for andi/andis that would be necessary. 1284 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16; 1285 assert((ANDIMask != 0 || ANDISMask != 0) && 1286 "No set bits in mask for value bit groups"); 1287 bool NeedsRotate = VRI.RLAmt != 0; 1288 1289 // We're trying to minimize the number of instructions. If we have one 1290 // group, using one of andi/andis can break even. If we have three 1291 // groups, we can use both andi and andis and break even (to use both 1292 // andi and andis we also need to or the results together). We need four 1293 // groups if we also need to rotate. To use andi/andis we need to do more 1294 // than break even because rotate-and-mask instructions tend to be easier 1295 // to schedule. 1296 1297 // FIXME: We've biased here against using andi/andis, which is right for 1298 // POWER cores, but not optimal everywhere. For example, on the A2, 1299 // andi/andis have single-cycle latency whereas the rotate-and-mask 1300 // instructions take two cycles, and it would be better to bias toward 1301 // andi/andis in break-even cases. 1302 1303 unsigned NumAndInsts = (unsigned) NeedsRotate + 1304 (unsigned) (ANDIMask != 0) + 1305 (unsigned) (ANDISMask != 0) + 1306 (unsigned) (ANDIMask != 0 && ANDISMask != 0) + 1307 (unsigned) (bool) Res; 1308 1309 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() << 1310 " RL: " << VRI.RLAmt << ":" << 1311 "\n\t\t\tisel using masking: " << NumAndInsts << 1312 " using rotates: " << VRI.NumGroups << "\n"); 1313 1314 if (NumAndInsts >= VRI.NumGroups) 1315 continue; 1316 1317 DEBUG(dbgs() << "\t\t\t\tusing masking\n"); 1318 1319 if (InstCnt) *InstCnt += NumAndInsts; 1320 1321 SDValue VRot; 1322 if (VRI.RLAmt) { 1323 SDValue Ops[] = 1324 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl), 1325 getI32Imm(31, dl) }; 1326 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, 1327 Ops), 0); 1328 } else { 1329 VRot = VRI.V; 1330 } 1331 1332 SDValue ANDIVal, ANDISVal; 1333 if (ANDIMask != 0) 1334 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32, 1335 VRot, getI32Imm(ANDIMask, dl)), 0); 1336 if (ANDISMask != 0) 1337 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32, 1338 VRot, getI32Imm(ANDISMask, dl)), 0); 1339 1340 SDValue TotalVal; 1341 if (!ANDIVal) 1342 TotalVal = ANDISVal; 1343 else if (!ANDISVal) 1344 TotalVal = ANDIVal; 1345 else 1346 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1347 ANDIVal, ANDISVal), 0); 1348 1349 if (!Res) 1350 Res = TotalVal; 1351 else 1352 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1353 Res, TotalVal), 0); 1354 1355 // Now, remove all groups with this underlying value and rotation 1356 // factor. 1357 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 1358 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt; 1359 }); 1360 } 1361 } 1362 1363 // Instruction selection for the 32-bit case. 1364 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) { 1365 SDLoc dl(N); 1366 SDValue Res; 1367 1368 if (InstCnt) *InstCnt = 0; 1369 1370 // Take care of cases that should use andi/andis first. 1371 SelectAndParts32(dl, Res, InstCnt); 1372 1373 // If we've not yet selected a 'starting' instruction, and we have no zeros 1374 // to fill in, select the (Value, RLAmt) with the highest priority (largest 1375 // number of groups), and start with this rotated value. 1376 if ((!HasZeros || LateMask) && !Res) { 1377 ValueRotInfo &VRI = ValueRotsVec[0]; 1378 if (VRI.RLAmt) { 1379 if (InstCnt) *InstCnt += 1; 1380 SDValue Ops[] = 1381 { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl), 1382 getI32Imm(31, dl) }; 1383 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 1384 0); 1385 } else { 1386 Res = VRI.V; 1387 } 1388 1389 // Now, remove all groups with this underlying value and rotation factor. 1390 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 1391 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt; 1392 }); 1393 } 1394 1395 if (InstCnt) *InstCnt += BitGroups.size(); 1396 1397 // Insert the other groups (one at a time). 1398 for (auto &BG : BitGroups) { 1399 if (!Res) { 1400 SDValue Ops[] = 1401 { BG.V, getI32Imm(BG.RLAmt, dl), 1402 getI32Imm(Bits.size() - BG.EndIdx - 1, dl), 1403 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) }; 1404 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 1405 } else { 1406 SDValue Ops[] = 1407 { Res, BG.V, getI32Imm(BG.RLAmt, dl), 1408 getI32Imm(Bits.size() - BG.EndIdx - 1, dl), 1409 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) }; 1410 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0); 1411 } 1412 } 1413 1414 if (LateMask) { 1415 unsigned Mask = (unsigned) getZerosMask(); 1416 1417 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16; 1418 assert((ANDIMask != 0 || ANDISMask != 0) && 1419 "No set bits in zeros mask?"); 1420 1421 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) + 1422 (unsigned) (ANDISMask != 0) + 1423 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 1424 1425 SDValue ANDIVal, ANDISVal; 1426 if (ANDIMask != 0) 1427 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32, 1428 Res, getI32Imm(ANDIMask, dl)), 0); 1429 if (ANDISMask != 0) 1430 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32, 1431 Res, getI32Imm(ANDISMask, dl)), 0); 1432 1433 if (!ANDIVal) 1434 Res = ANDISVal; 1435 else if (!ANDISVal) 1436 Res = ANDIVal; 1437 else 1438 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32, 1439 ANDIVal, ANDISVal), 0); 1440 } 1441 1442 return Res.getNode(); 1443 } 1444 1445 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32, 1446 unsigned MaskStart, unsigned MaskEnd, 1447 bool IsIns) { 1448 // In the notation used by the instructions, 'start' and 'end' are reversed 1449 // because bits are counted from high to low order. 1450 unsigned InstMaskStart = 64 - MaskEnd - 1, 1451 InstMaskEnd = 64 - MaskStart - 1; 1452 1453 if (Repl32) 1454 return 1; 1455 1456 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) || 1457 InstMaskEnd == 63 - RLAmt) 1458 return 1; 1459 1460 return 2; 1461 } 1462 1463 // For 64-bit values, not all combinations of rotates and masks are 1464 // available. Produce one if it is available. 1465 SDValue SelectRotMask64(SDValue V, SDLoc dl, unsigned RLAmt, bool Repl32, 1466 unsigned MaskStart, unsigned MaskEnd, 1467 unsigned *InstCnt = nullptr) { 1468 // In the notation used by the instructions, 'start' and 'end' are reversed 1469 // because bits are counted from high to low order. 1470 unsigned InstMaskStart = 64 - MaskEnd - 1, 1471 InstMaskEnd = 64 - MaskStart - 1; 1472 1473 if (InstCnt) *InstCnt += 1; 1474 1475 if (Repl32) { 1476 // This rotation amount assumes that the lower 32 bits of the quantity 1477 // are replicated in the high 32 bits by the rotation operator (which is 1478 // done by rlwinm and friends). 1479 assert(InstMaskStart >= 32 && "Mask cannot start out of range"); 1480 assert(InstMaskEnd >= 32 && "Mask cannot end out of range"); 1481 SDValue Ops[] = 1482 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl), 1483 getI32Imm(InstMaskEnd - 32, dl) }; 1484 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64, 1485 Ops), 0); 1486 } 1487 1488 if (InstMaskEnd == 63) { 1489 SDValue Ops[] = 1490 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) }; 1491 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0); 1492 } 1493 1494 if (InstMaskStart == 0) { 1495 SDValue Ops[] = 1496 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskEnd, dl) }; 1497 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0); 1498 } 1499 1500 if (InstMaskEnd == 63 - RLAmt) { 1501 SDValue Ops[] = 1502 { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) }; 1503 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0); 1504 } 1505 1506 // We cannot do this with a single instruction, so we'll use two. The 1507 // problem is that we're not free to choose both a rotation amount and mask 1508 // start and end independently. We can choose an arbitrary mask start and 1509 // end, but then the rotation amount is fixed. Rotation, however, can be 1510 // inverted, and so by applying an "inverse" rotation first, we can get the 1511 // desired result. 1512 if (InstCnt) *InstCnt += 1; 1513 1514 // The rotation mask for the second instruction must be MaskStart. 1515 unsigned RLAmt2 = MaskStart; 1516 // The first instruction must rotate V so that the overall rotation amount 1517 // is RLAmt. 1518 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64; 1519 if (RLAmt1) 1520 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63); 1521 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd); 1522 } 1523 1524 // For 64-bit values, not all combinations of rotates and masks are 1525 // available. Produce a rotate-mask-and-insert if one is available. 1526 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, SDLoc dl, unsigned RLAmt, 1527 bool Repl32, unsigned MaskStart, 1528 unsigned MaskEnd, unsigned *InstCnt = nullptr) { 1529 // In the notation used by the instructions, 'start' and 'end' are reversed 1530 // because bits are counted from high to low order. 1531 unsigned InstMaskStart = 64 - MaskEnd - 1, 1532 InstMaskEnd = 64 - MaskStart - 1; 1533 1534 if (InstCnt) *InstCnt += 1; 1535 1536 if (Repl32) { 1537 // This rotation amount assumes that the lower 32 bits of the quantity 1538 // are replicated in the high 32 bits by the rotation operator (which is 1539 // done by rlwinm and friends). 1540 assert(InstMaskStart >= 32 && "Mask cannot start out of range"); 1541 assert(InstMaskEnd >= 32 && "Mask cannot end out of range"); 1542 SDValue Ops[] = 1543 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl), 1544 getI32Imm(InstMaskEnd - 32, dl) }; 1545 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64, 1546 Ops), 0); 1547 } 1548 1549 if (InstMaskEnd == 63 - RLAmt) { 1550 SDValue Ops[] = 1551 { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) }; 1552 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0); 1553 } 1554 1555 // We cannot do this with a single instruction, so we'll use two. The 1556 // problem is that we're not free to choose both a rotation amount and mask 1557 // start and end independently. We can choose an arbitrary mask start and 1558 // end, but then the rotation amount is fixed. Rotation, however, can be 1559 // inverted, and so by applying an "inverse" rotation first, we can get the 1560 // desired result. 1561 if (InstCnt) *InstCnt += 1; 1562 1563 // The rotation mask for the second instruction must be MaskStart. 1564 unsigned RLAmt2 = MaskStart; 1565 // The first instruction must rotate V so that the overall rotation amount 1566 // is RLAmt. 1567 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64; 1568 if (RLAmt1) 1569 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63); 1570 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd); 1571 } 1572 1573 void SelectAndParts64(SDLoc dl, SDValue &Res, unsigned *InstCnt) { 1574 if (BPermRewriterNoMasking) 1575 return; 1576 1577 // The idea here is the same as in the 32-bit version, but with additional 1578 // complications from the fact that Repl32 might be true. Because we 1579 // aggressively convert bit groups to Repl32 form (which, for small 1580 // rotation factors, involves no other change), and then coalesce, it might 1581 // be the case that a single 64-bit masking operation could handle both 1582 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32 1583 // form allowed coalescing, then we must use a 32-bit rotaton in order to 1584 // completely capture the new combined bit group. 1585 1586 for (ValueRotInfo &VRI : ValueRotsVec) { 1587 uint64_t Mask = 0; 1588 1589 // We need to add to the mask all bits from the associated bit groups. 1590 // If Repl32 is false, we need to add bits from bit groups that have 1591 // Repl32 true, but are trivially convertable to Repl32 false. Such a 1592 // group is trivially convertable if it overlaps only with the lower 32 1593 // bits, and the group has not been coalesced. 1594 auto MatchingBG = [VRI](const BitGroup &BG) { 1595 if (VRI.V != BG.V) 1596 return false; 1597 1598 unsigned EffRLAmt = BG.RLAmt; 1599 if (!VRI.Repl32 && BG.Repl32) { 1600 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx && 1601 !BG.Repl32Coalesced) { 1602 if (BG.Repl32CR) 1603 EffRLAmt += 32; 1604 } else { 1605 return false; 1606 } 1607 } else if (VRI.Repl32 != BG.Repl32) { 1608 return false; 1609 } 1610 1611 return VRI.RLAmt == EffRLAmt; 1612 }; 1613 1614 for (auto &BG : BitGroups) { 1615 if (!MatchingBG(BG)) 1616 continue; 1617 1618 if (BG.StartIdx <= BG.EndIdx) { 1619 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) 1620 Mask |= (UINT64_C(1) << i); 1621 } else { 1622 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) 1623 Mask |= (UINT64_C(1) << i); 1624 for (unsigned i = 0; i <= BG.EndIdx; ++i) 1625 Mask |= (UINT64_C(1) << i); 1626 } 1627 } 1628 1629 // We can use the 32-bit andi/andis technique if the mask does not 1630 // require any higher-order bits. This can save an instruction compared 1631 // to always using the general 64-bit technique. 1632 bool Use32BitInsts = isUInt<32>(Mask); 1633 // Compute the masks for andi/andis that would be necessary. 1634 unsigned ANDIMask = (Mask & UINT16_MAX), 1635 ANDISMask = (Mask >> 16) & UINT16_MAX; 1636 1637 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)); 1638 1639 unsigned NumAndInsts = (unsigned) NeedsRotate + 1640 (unsigned) (bool) Res; 1641 if (Use32BitInsts) 1642 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) + 1643 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 1644 else 1645 NumAndInsts += getInt64Count(Mask) + /* and */ 1; 1646 1647 unsigned NumRLInsts = 0; 1648 bool FirstBG = true; 1649 for (auto &BG : BitGroups) { 1650 if (!MatchingBG(BG)) 1651 continue; 1652 NumRLInsts += 1653 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx, 1654 !FirstBG); 1655 FirstBG = false; 1656 } 1657 1658 DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() << 1659 " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") << 1660 "\n\t\t\tisel using masking: " << NumAndInsts << 1661 " using rotates: " << NumRLInsts << "\n"); 1662 1663 // When we'd use andi/andis, we bias toward using the rotates (andi only 1664 // has a record form, and is cracked on POWER cores). However, when using 1665 // general 64-bit constant formation, bias toward the constant form, 1666 // because that exposes more opportunities for CSE. 1667 if (NumAndInsts > NumRLInsts) 1668 continue; 1669 if (Use32BitInsts && NumAndInsts == NumRLInsts) 1670 continue; 1671 1672 DEBUG(dbgs() << "\t\t\t\tusing masking\n"); 1673 1674 if (InstCnt) *InstCnt += NumAndInsts; 1675 1676 SDValue VRot; 1677 // We actually need to generate a rotation if we have a non-zero rotation 1678 // factor or, in the Repl32 case, if we care about any of the 1679 // higher-order replicated bits. In the latter case, we generate a mask 1680 // backward so that it actually includes the entire 64 bits. 1681 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask))) 1682 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32, 1683 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63); 1684 else 1685 VRot = VRI.V; 1686 1687 SDValue TotalVal; 1688 if (Use32BitInsts) { 1689 assert((ANDIMask != 0 || ANDISMask != 0) && 1690 "No set bits in mask when using 32-bit ands for 64-bit value"); 1691 1692 SDValue ANDIVal, ANDISVal; 1693 if (ANDIMask != 0) 1694 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64, 1695 VRot, getI32Imm(ANDIMask, dl)), 0); 1696 if (ANDISMask != 0) 1697 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64, 1698 VRot, getI32Imm(ANDISMask, dl)), 0); 1699 1700 if (!ANDIVal) 1701 TotalVal = ANDISVal; 1702 else if (!ANDISVal) 1703 TotalVal = ANDIVal; 1704 else 1705 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 1706 ANDIVal, ANDISVal), 0); 1707 } else { 1708 TotalVal = SDValue(getInt64(CurDAG, dl, Mask), 0); 1709 TotalVal = 1710 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64, 1711 VRot, TotalVal), 0); 1712 } 1713 1714 if (!Res) 1715 Res = TotalVal; 1716 else 1717 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 1718 Res, TotalVal), 0); 1719 1720 // Now, remove all groups with this underlying value and rotation 1721 // factor. 1722 eraseMatchingBitGroups(MatchingBG); 1723 } 1724 } 1725 1726 // Instruction selection for the 64-bit case. 1727 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) { 1728 SDLoc dl(N); 1729 SDValue Res; 1730 1731 if (InstCnt) *InstCnt = 0; 1732 1733 // Take care of cases that should use andi/andis first. 1734 SelectAndParts64(dl, Res, InstCnt); 1735 1736 // If we've not yet selected a 'starting' instruction, and we have no zeros 1737 // to fill in, select the (Value, RLAmt) with the highest priority (largest 1738 // number of groups), and start with this rotated value. 1739 if ((!HasZeros || LateMask) && !Res) { 1740 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32 1741 // groups will come first, and so the VRI representing the largest number 1742 // of groups might not be first (it might be the first Repl32 groups). 1743 unsigned MaxGroupsIdx = 0; 1744 if (!ValueRotsVec[0].Repl32) { 1745 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i) 1746 if (ValueRotsVec[i].Repl32) { 1747 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups) 1748 MaxGroupsIdx = i; 1749 break; 1750 } 1751 } 1752 1753 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx]; 1754 bool NeedsRotate = false; 1755 if (VRI.RLAmt) { 1756 NeedsRotate = true; 1757 } else if (VRI.Repl32) { 1758 for (auto &BG : BitGroups) { 1759 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt || 1760 BG.Repl32 != VRI.Repl32) 1761 continue; 1762 1763 // We don't need a rotate if the bit group is confined to the lower 1764 // 32 bits. 1765 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx) 1766 continue; 1767 1768 NeedsRotate = true; 1769 break; 1770 } 1771 } 1772 1773 if (NeedsRotate) 1774 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32, 1775 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63, 1776 InstCnt); 1777 else 1778 Res = VRI.V; 1779 1780 // Now, remove all groups with this underlying value and rotation factor. 1781 if (Res) 1782 eraseMatchingBitGroups([VRI](const BitGroup &BG) { 1783 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt && 1784 BG.Repl32 == VRI.Repl32; 1785 }); 1786 } 1787 1788 // Because 64-bit rotates are more flexible than inserts, we might have a 1789 // preference regarding which one we do first (to save one instruction). 1790 if (!Res) 1791 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) { 1792 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx, 1793 false) < 1794 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx, 1795 true)) { 1796 if (I != BitGroups.begin()) { 1797 BitGroup BG = *I; 1798 BitGroups.erase(I); 1799 BitGroups.insert(BitGroups.begin(), BG); 1800 } 1801 1802 break; 1803 } 1804 } 1805 1806 // Insert the other groups (one at a time). 1807 for (auto &BG : BitGroups) { 1808 if (!Res) 1809 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx, 1810 BG.EndIdx, InstCnt); 1811 else 1812 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32, 1813 BG.StartIdx, BG.EndIdx, InstCnt); 1814 } 1815 1816 if (LateMask) { 1817 uint64_t Mask = getZerosMask(); 1818 1819 // We can use the 32-bit andi/andis technique if the mask does not 1820 // require any higher-order bits. This can save an instruction compared 1821 // to always using the general 64-bit technique. 1822 bool Use32BitInsts = isUInt<32>(Mask); 1823 // Compute the masks for andi/andis that would be necessary. 1824 unsigned ANDIMask = (Mask & UINT16_MAX), 1825 ANDISMask = (Mask >> 16) & UINT16_MAX; 1826 1827 if (Use32BitInsts) { 1828 assert((ANDIMask != 0 || ANDISMask != 0) && 1829 "No set bits in mask when using 32-bit ands for 64-bit value"); 1830 1831 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) + 1832 (unsigned) (ANDISMask != 0) + 1833 (unsigned) (ANDIMask != 0 && ANDISMask != 0); 1834 1835 SDValue ANDIVal, ANDISVal; 1836 if (ANDIMask != 0) 1837 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64, 1838 Res, getI32Imm(ANDIMask, dl)), 0); 1839 if (ANDISMask != 0) 1840 ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64, 1841 Res, getI32Imm(ANDISMask, dl)), 0); 1842 1843 if (!ANDIVal) 1844 Res = ANDISVal; 1845 else if (!ANDISVal) 1846 Res = ANDIVal; 1847 else 1848 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64, 1849 ANDIVal, ANDISVal), 0); 1850 } else { 1851 if (InstCnt) *InstCnt += getInt64Count(Mask) + /* and */ 1; 1852 1853 SDValue MaskVal = SDValue(getInt64(CurDAG, dl, Mask), 0); 1854 Res = 1855 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64, 1856 Res, MaskVal), 0); 1857 } 1858 } 1859 1860 return Res.getNode(); 1861 } 1862 1863 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) { 1864 // Fill in BitGroups. 1865 collectBitGroups(LateMask); 1866 if (BitGroups.empty()) 1867 return nullptr; 1868 1869 // For 64-bit values, figure out when we can use 32-bit instructions. 1870 if (Bits.size() == 64) 1871 assignRepl32BitGroups(); 1872 1873 // Fill in ValueRotsVec. 1874 collectValueRotInfo(); 1875 1876 if (Bits.size() == 32) { 1877 return Select32(N, LateMask, InstCnt); 1878 } else { 1879 assert(Bits.size() == 64 && "Not 64 bits here?"); 1880 return Select64(N, LateMask, InstCnt); 1881 } 1882 1883 return nullptr; 1884 } 1885 1886 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) { 1887 BitGroups.erase(std::remove_if(BitGroups.begin(), BitGroups.end(), F), 1888 BitGroups.end()); 1889 } 1890 1891 SmallVector<ValueBit, 64> Bits; 1892 1893 bool HasZeros; 1894 SmallVector<unsigned, 64> RLAmt; 1895 1896 SmallVector<BitGroup, 16> BitGroups; 1897 1898 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots; 1899 SmallVector<ValueRotInfo, 16> ValueRotsVec; 1900 1901 SelectionDAG *CurDAG; 1902 1903 public: 1904 BitPermutationSelector(SelectionDAG *DAG) 1905 : CurDAG(DAG) {} 1906 1907 // Here we try to match complex bit permutations into a set of 1908 // rotate-and-shift/shift/and/or instructions, using a set of heuristics 1909 // known to produce optimial code for common cases (like i32 byte swapping). 1910 SDNode *Select(SDNode *N) { 1911 Bits.resize(N->getValueType(0).getSizeInBits()); 1912 if (!getValueBits(SDValue(N, 0), Bits)) 1913 return nullptr; 1914 1915 DEBUG(dbgs() << "Considering bit-permutation-based instruction" 1916 " selection for: "); 1917 DEBUG(N->dump(CurDAG)); 1918 1919 // Fill it RLAmt and set HasZeros. 1920 computeRotationAmounts(); 1921 1922 if (!HasZeros) 1923 return Select(N, false); 1924 1925 // We currently have two techniques for handling results with zeros: early 1926 // masking (the default) and late masking. Late masking is sometimes more 1927 // efficient, but because the structure of the bit groups is different, it 1928 // is hard to tell without generating both and comparing the results. With 1929 // late masking, we ignore zeros in the resulting value when inserting each 1930 // set of bit groups, and then mask in the zeros at the end. With early 1931 // masking, we only insert the non-zero parts of the result at every step. 1932 1933 unsigned InstCnt, InstCntLateMask; 1934 DEBUG(dbgs() << "\tEarly masking:\n"); 1935 SDNode *RN = Select(N, false, &InstCnt); 1936 DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n"); 1937 1938 DEBUG(dbgs() << "\tLate masking:\n"); 1939 SDNode *RNLM = Select(N, true, &InstCntLateMask); 1940 DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask << 1941 " instructions\n"); 1942 1943 if (InstCnt <= InstCntLateMask) { 1944 DEBUG(dbgs() << "\tUsing early-masking for isel\n"); 1945 return RN; 1946 } 1947 1948 DEBUG(dbgs() << "\tUsing late-masking for isel\n"); 1949 return RNLM; 1950 } 1951 }; 1952 } // anonymous namespace 1953 1954 bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) { 1955 if (N->getValueType(0) != MVT::i32 && 1956 N->getValueType(0) != MVT::i64) 1957 return false; 1958 1959 if (!UseBitPermRewriter) 1960 return false; 1961 1962 switch (N->getOpcode()) { 1963 default: break; 1964 case ISD::ROTL: 1965 case ISD::SHL: 1966 case ISD::SRL: 1967 case ISD::AND: 1968 case ISD::OR: { 1969 BitPermutationSelector BPS(CurDAG); 1970 if (SDNode *New = BPS.Select(N)) { 1971 ReplaceNode(N, New); 1972 return true; 1973 } 1974 return false; 1975 } 1976 } 1977 1978 return false; 1979 } 1980 1981 /// SelectCC - Select a comparison of the specified values with the specified 1982 /// condition code, returning the CR# of the expression. 1983 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, 1984 ISD::CondCode CC, SDLoc dl) { 1985 // Always select the LHS. 1986 unsigned Opc; 1987 1988 if (LHS.getValueType() == MVT::i32) { 1989 unsigned Imm; 1990 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 1991 if (isInt32Immediate(RHS, Imm)) { 1992 // SETEQ/SETNE comparison with 16-bit immediate, fold it. 1993 if (isUInt<16>(Imm)) 1994 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS, 1995 getI32Imm(Imm & 0xFFFF, dl)), 1996 0); 1997 // If this is a 16-bit signed immediate, fold it. 1998 if (isInt<16>((int)Imm)) 1999 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS, 2000 getI32Imm(Imm & 0xFFFF, dl)), 2001 0); 2002 2003 // For non-equality comparisons, the default code would materialize the 2004 // constant, then compare against it, like this: 2005 // lis r2, 4660 2006 // ori r2, r2, 22136 2007 // cmpw cr0, r3, r2 2008 // Since we are just comparing for equality, we can emit this instead: 2009 // xoris r0,r3,0x1234 2010 // cmplwi cr0,r0,0x5678 2011 // beq cr0,L6 2012 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS, 2013 getI32Imm(Imm >> 16, dl)), 0); 2014 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor, 2015 getI32Imm(Imm & 0xFFFF, dl)), 0); 2016 } 2017 Opc = PPC::CMPLW; 2018 } else if (ISD::isUnsignedIntSetCC(CC)) { 2019 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm)) 2020 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS, 2021 getI32Imm(Imm & 0xFFFF, dl)), 0); 2022 Opc = PPC::CMPLW; 2023 } else { 2024 short SImm; 2025 if (isIntS16Immediate(RHS, SImm)) 2026 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS, 2027 getI32Imm((int)SImm & 0xFFFF, 2028 dl)), 2029 0); 2030 Opc = PPC::CMPW; 2031 } 2032 } else if (LHS.getValueType() == MVT::i64) { 2033 uint64_t Imm; 2034 if (CC == ISD::SETEQ || CC == ISD::SETNE) { 2035 if (isInt64Immediate(RHS.getNode(), Imm)) { 2036 // SETEQ/SETNE comparison with 16-bit immediate, fold it. 2037 if (isUInt<16>(Imm)) 2038 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS, 2039 getI32Imm(Imm & 0xFFFF, dl)), 2040 0); 2041 // If this is a 16-bit signed immediate, fold it. 2042 if (isInt<16>(Imm)) 2043 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS, 2044 getI32Imm(Imm & 0xFFFF, dl)), 2045 0); 2046 2047 // For non-equality comparisons, the default code would materialize the 2048 // constant, then compare against it, like this: 2049 // lis r2, 4660 2050 // ori r2, r2, 22136 2051 // cmpd cr0, r3, r2 2052 // Since we are just comparing for equality, we can emit this instead: 2053 // xoris r0,r3,0x1234 2054 // cmpldi cr0,r0,0x5678 2055 // beq cr0,L6 2056 if (isUInt<32>(Imm)) { 2057 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS, 2058 getI64Imm(Imm >> 16, dl)), 0); 2059 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor, 2060 getI64Imm(Imm & 0xFFFF, dl)), 2061 0); 2062 } 2063 } 2064 Opc = PPC::CMPLD; 2065 } else if (ISD::isUnsignedIntSetCC(CC)) { 2066 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm)) 2067 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS, 2068 getI64Imm(Imm & 0xFFFF, dl)), 0); 2069 Opc = PPC::CMPLD; 2070 } else { 2071 short SImm; 2072 if (isIntS16Immediate(RHS, SImm)) 2073 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS, 2074 getI64Imm(SImm & 0xFFFF, dl)), 2075 0); 2076 Opc = PPC::CMPD; 2077 } 2078 } else if (LHS.getValueType() == MVT::f32) { 2079 Opc = PPC::FCMPUS; 2080 } else { 2081 assert(LHS.getValueType() == MVT::f64 && "Unknown vt!"); 2082 Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD; 2083 } 2084 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0); 2085 } 2086 2087 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) { 2088 switch (CC) { 2089 case ISD::SETUEQ: 2090 case ISD::SETONE: 2091 case ISD::SETOLE: 2092 case ISD::SETOGE: 2093 llvm_unreachable("Should be lowered by legalize!"); 2094 default: llvm_unreachable("Unknown condition!"); 2095 case ISD::SETOEQ: 2096 case ISD::SETEQ: return PPC::PRED_EQ; 2097 case ISD::SETUNE: 2098 case ISD::SETNE: return PPC::PRED_NE; 2099 case ISD::SETOLT: 2100 case ISD::SETLT: return PPC::PRED_LT; 2101 case ISD::SETULE: 2102 case ISD::SETLE: return PPC::PRED_LE; 2103 case ISD::SETOGT: 2104 case ISD::SETGT: return PPC::PRED_GT; 2105 case ISD::SETUGE: 2106 case ISD::SETGE: return PPC::PRED_GE; 2107 case ISD::SETO: return PPC::PRED_NU; 2108 case ISD::SETUO: return PPC::PRED_UN; 2109 // These two are invalid for floating point. Assume we have int. 2110 case ISD::SETULT: return PPC::PRED_LT; 2111 case ISD::SETUGT: return PPC::PRED_GT; 2112 } 2113 } 2114 2115 /// getCRIdxForSetCC - Return the index of the condition register field 2116 /// associated with the SetCC condition, and whether or not the field is 2117 /// treated as inverted. That is, lt = 0; ge = 0 inverted. 2118 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) { 2119 Invert = false; 2120 switch (CC) { 2121 default: llvm_unreachable("Unknown condition!"); 2122 case ISD::SETOLT: 2123 case ISD::SETLT: return 0; // Bit #0 = SETOLT 2124 case ISD::SETOGT: 2125 case ISD::SETGT: return 1; // Bit #1 = SETOGT 2126 case ISD::SETOEQ: 2127 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ 2128 case ISD::SETUO: return 3; // Bit #3 = SETUO 2129 case ISD::SETUGE: 2130 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE 2131 case ISD::SETULE: 2132 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE 2133 case ISD::SETUNE: 2134 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE 2135 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO 2136 case ISD::SETUEQ: 2137 case ISD::SETOGE: 2138 case ISD::SETOLE: 2139 case ISD::SETONE: 2140 llvm_unreachable("Invalid branch code: should be expanded by legalize"); 2141 // These are invalid for floating point. Assume integer. 2142 case ISD::SETULT: return 0; 2143 case ISD::SETUGT: return 1; 2144 } 2145 } 2146 2147 // getVCmpInst: return the vector compare instruction for the specified 2148 // vector type and condition code. Since this is for altivec specific code, 2149 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32). 2150 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC, 2151 bool HasVSX, bool &Swap, bool &Negate) { 2152 Swap = false; 2153 Negate = false; 2154 2155 if (VecVT.isFloatingPoint()) { 2156 /* Handle some cases by swapping input operands. */ 2157 switch (CC) { 2158 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break; 2159 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break; 2160 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break; 2161 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break; 2162 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break; 2163 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break; 2164 default: break; 2165 } 2166 /* Handle some cases by negating the result. */ 2167 switch (CC) { 2168 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break; 2169 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break; 2170 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break; 2171 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break; 2172 default: break; 2173 } 2174 /* We have instructions implementing the remaining cases. */ 2175 switch (CC) { 2176 case ISD::SETEQ: 2177 case ISD::SETOEQ: 2178 if (VecVT == MVT::v4f32) 2179 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP; 2180 else if (VecVT == MVT::v2f64) 2181 return PPC::XVCMPEQDP; 2182 break; 2183 case ISD::SETGT: 2184 case ISD::SETOGT: 2185 if (VecVT == MVT::v4f32) 2186 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP; 2187 else if (VecVT == MVT::v2f64) 2188 return PPC::XVCMPGTDP; 2189 break; 2190 case ISD::SETGE: 2191 case ISD::SETOGE: 2192 if (VecVT == MVT::v4f32) 2193 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP; 2194 else if (VecVT == MVT::v2f64) 2195 return PPC::XVCMPGEDP; 2196 break; 2197 default: 2198 break; 2199 } 2200 llvm_unreachable("Invalid floating-point vector compare condition"); 2201 } else { 2202 /* Handle some cases by swapping input operands. */ 2203 switch (CC) { 2204 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break; 2205 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break; 2206 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break; 2207 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break; 2208 default: break; 2209 } 2210 /* Handle some cases by negating the result. */ 2211 switch (CC) { 2212 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break; 2213 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break; 2214 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break; 2215 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break; 2216 default: break; 2217 } 2218 /* We have instructions implementing the remaining cases. */ 2219 switch (CC) { 2220 case ISD::SETEQ: 2221 case ISD::SETUEQ: 2222 if (VecVT == MVT::v16i8) 2223 return PPC::VCMPEQUB; 2224 else if (VecVT == MVT::v8i16) 2225 return PPC::VCMPEQUH; 2226 else if (VecVT == MVT::v4i32) 2227 return PPC::VCMPEQUW; 2228 else if (VecVT == MVT::v2i64) 2229 return PPC::VCMPEQUD; 2230 break; 2231 case ISD::SETGT: 2232 if (VecVT == MVT::v16i8) 2233 return PPC::VCMPGTSB; 2234 else if (VecVT == MVT::v8i16) 2235 return PPC::VCMPGTSH; 2236 else if (VecVT == MVT::v4i32) 2237 return PPC::VCMPGTSW; 2238 else if (VecVT == MVT::v2i64) 2239 return PPC::VCMPGTSD; 2240 break; 2241 case ISD::SETUGT: 2242 if (VecVT == MVT::v16i8) 2243 return PPC::VCMPGTUB; 2244 else if (VecVT == MVT::v8i16) 2245 return PPC::VCMPGTUH; 2246 else if (VecVT == MVT::v4i32) 2247 return PPC::VCMPGTUW; 2248 else if (VecVT == MVT::v2i64) 2249 return PPC::VCMPGTUD; 2250 break; 2251 default: 2252 break; 2253 } 2254 llvm_unreachable("Invalid integer vector compare condition"); 2255 } 2256 } 2257 2258 bool PPCDAGToDAGISel::trySETCC(SDNode *N) { 2259 SDLoc dl(N); 2260 unsigned Imm; 2261 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get(); 2262 EVT PtrVT = 2263 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout()); 2264 bool isPPC64 = (PtrVT == MVT::i64); 2265 2266 if (!PPCSubTarget->useCRBits() && 2267 isInt32Immediate(N->getOperand(1), Imm)) { 2268 // We can codegen setcc op, imm very efficiently compared to a brcond. 2269 // Check for those cases here. 2270 // setcc op, 0 2271 if (Imm == 0) { 2272 SDValue Op = N->getOperand(0); 2273 switch (CC) { 2274 default: break; 2275 case ISD::SETEQ: { 2276 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0); 2277 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl), 2278 getI32Imm(31, dl) }; 2279 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2280 return true; 2281 } 2282 case ISD::SETNE: { 2283 if (isPPC64) break; 2284 SDValue AD = 2285 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 2286 Op, getI32Imm(~0U, dl)), 0); 2287 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1)); 2288 return true; 2289 } 2290 case ISD::SETLT: { 2291 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl), 2292 getI32Imm(31, dl) }; 2293 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2294 return true; 2295 } 2296 case ISD::SETGT: { 2297 SDValue T = 2298 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0); 2299 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0); 2300 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl), 2301 getI32Imm(31, dl) }; 2302 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2303 return true; 2304 } 2305 } 2306 } else if (Imm == ~0U) { // setcc op, -1 2307 SDValue Op = N->getOperand(0); 2308 switch (CC) { 2309 default: break; 2310 case ISD::SETEQ: 2311 if (isPPC64) break; 2312 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 2313 Op, getI32Imm(1, dl)), 0); 2314 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 2315 SDValue(CurDAG->getMachineNode(PPC::LI, dl, 2316 MVT::i32, 2317 getI32Imm(0, dl)), 2318 0), Op.getValue(1)); 2319 return true; 2320 case ISD::SETNE: { 2321 if (isPPC64) break; 2322 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0); 2323 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 2324 Op, getI32Imm(~0U, dl)); 2325 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op, 2326 SDValue(AD, 1)); 2327 return true; 2328 } 2329 case ISD::SETLT: { 2330 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op, 2331 getI32Imm(1, dl)), 0); 2332 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD, 2333 Op), 0); 2334 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl), 2335 getI32Imm(31, dl) }; 2336 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2337 return true; 2338 } 2339 case ISD::SETGT: { 2340 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl), 2341 getI32Imm(31, dl) }; 2342 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 2343 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl)); 2344 return true; 2345 } 2346 } 2347 } 2348 } 2349 2350 SDValue LHS = N->getOperand(0); 2351 SDValue RHS = N->getOperand(1); 2352 2353 // Altivec Vector compare instructions do not set any CR register by default and 2354 // vector compare operations return the same type as the operands. 2355 if (LHS.getValueType().isVector()) { 2356 if (PPCSubTarget->hasQPX()) 2357 return false; 2358 2359 EVT VecVT = LHS.getValueType(); 2360 bool Swap, Negate; 2361 unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC, 2362 PPCSubTarget->hasVSX(), Swap, Negate); 2363 if (Swap) 2364 std::swap(LHS, RHS); 2365 2366 EVT ResVT = VecVT.changeVectorElementTypeToInteger(); 2367 if (Negate) { 2368 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0); 2369 CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR, 2370 ResVT, VCmp, VCmp); 2371 return true; 2372 } 2373 2374 CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS); 2375 return true; 2376 } 2377 2378 if (PPCSubTarget->useCRBits()) 2379 return false; 2380 2381 bool Inv; 2382 unsigned Idx = getCRIdxForSetCC(CC, Inv); 2383 SDValue CCReg = SelectCC(LHS, RHS, CC, dl); 2384 SDValue IntCR; 2385 2386 // Force the ccreg into CR7. 2387 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32); 2388 2389 SDValue InFlag(nullptr, 0); // Null incoming flag value. 2390 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg, 2391 InFlag).getValue(1); 2392 2393 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg, 2394 CCReg), 0); 2395 2396 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl), 2397 getI32Imm(31, dl), getI32Imm(31, dl) }; 2398 if (!Inv) { 2399 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2400 return true; 2401 } 2402 2403 // Get the specified bit. 2404 SDValue Tmp = 2405 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0); 2406 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl)); 2407 return true; 2408 } 2409 2410 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) { 2411 // Transfer memoperands. 2412 MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1); 2413 MemOp[0] = cast<MemSDNode>(N)->getMemOperand(); 2414 cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1); 2415 } 2416 2417 2418 // Select - Convert the specified operand from a target-independent to a 2419 // target-specific node if it hasn't already been changed. 2420 void PPCDAGToDAGISel::Select(SDNode *N) { 2421 SDLoc dl(N); 2422 if (N->isMachineOpcode()) { 2423 N->setNodeId(-1); 2424 return; // Already selected. 2425 } 2426 2427 // In case any misguided DAG-level optimizations form an ADD with a 2428 // TargetConstant operand, crash here instead of miscompiling (by selecting 2429 // an r+r add instead of some kind of r+i add). 2430 if (N->getOpcode() == ISD::ADD && 2431 N->getOperand(1).getOpcode() == ISD::TargetConstant) 2432 llvm_unreachable("Invalid ADD with TargetConstant operand"); 2433 2434 // Try matching complex bit permutations before doing anything else. 2435 if (tryBitPermutation(N)) 2436 return; 2437 2438 switch (N->getOpcode()) { 2439 default: break; 2440 2441 case ISD::Constant: { 2442 if (N->getValueType(0) == MVT::i64) { 2443 ReplaceNode(N, getInt64(CurDAG, N)); 2444 return; 2445 } 2446 break; 2447 } 2448 2449 case ISD::SETCC: { 2450 if (trySETCC(N)) 2451 return; 2452 break; 2453 } 2454 case PPCISD::GlobalBaseReg: 2455 ReplaceNode(N, getGlobalBaseReg()); 2456 return; 2457 2458 case ISD::FrameIndex: 2459 selectFrameIndex(N, N); 2460 return; 2461 2462 case PPCISD::MFOCRF: { 2463 SDValue InFlag = N->getOperand(1); 2464 ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, 2465 N->getOperand(0), InFlag)); 2466 return; 2467 } 2468 2469 case PPCISD::READ_TIME_BASE: { 2470 ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32, 2471 MVT::Other, N->getOperand(0))); 2472 return; 2473 } 2474 2475 case PPCISD::SRA_ADDZE: { 2476 SDValue N0 = N->getOperand(0); 2477 SDValue ShiftAmt = 2478 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))-> 2479 getConstantIntValue(), dl, 2480 N->getValueType(0)); 2481 if (N->getValueType(0) == MVT::i64) { 2482 SDNode *Op = 2483 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue, 2484 N0, ShiftAmt); 2485 CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0), 2486 SDValue(Op, 1)); 2487 return; 2488 } else { 2489 assert(N->getValueType(0) == MVT::i32 && 2490 "Expecting i64 or i32 in PPCISD::SRA_ADDZE"); 2491 SDNode *Op = 2492 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue, 2493 N0, ShiftAmt); 2494 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0), 2495 SDValue(Op, 1)); 2496 return; 2497 } 2498 } 2499 2500 case ISD::LOAD: { 2501 // Handle preincrement loads. 2502 LoadSDNode *LD = cast<LoadSDNode>(N); 2503 EVT LoadedVT = LD->getMemoryVT(); 2504 2505 // Normal loads are handled by code generated from the .td file. 2506 if (LD->getAddressingMode() != ISD::PRE_INC) 2507 break; 2508 2509 SDValue Offset = LD->getOffset(); 2510 if (Offset.getOpcode() == ISD::TargetConstant || 2511 Offset.getOpcode() == ISD::TargetGlobalAddress) { 2512 2513 unsigned Opcode; 2514 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD; 2515 if (LD->getValueType(0) != MVT::i64) { 2516 // Handle PPC32 integer and normal FP loads. 2517 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 2518 switch (LoadedVT.getSimpleVT().SimpleTy) { 2519 default: llvm_unreachable("Invalid PPC load type!"); 2520 case MVT::f64: Opcode = PPC::LFDU; break; 2521 case MVT::f32: Opcode = PPC::LFSU; break; 2522 case MVT::i32: Opcode = PPC::LWZU; break; 2523 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break; 2524 case MVT::i1: 2525 case MVT::i8: Opcode = PPC::LBZU; break; 2526 } 2527 } else { 2528 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!"); 2529 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 2530 switch (LoadedVT.getSimpleVT().SimpleTy) { 2531 default: llvm_unreachable("Invalid PPC load type!"); 2532 case MVT::i64: Opcode = PPC::LDU; break; 2533 case MVT::i32: Opcode = PPC::LWZU8; break; 2534 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break; 2535 case MVT::i1: 2536 case MVT::i8: Opcode = PPC::LBZU8; break; 2537 } 2538 } 2539 2540 SDValue Chain = LD->getChain(); 2541 SDValue Base = LD->getBasePtr(); 2542 SDValue Ops[] = { Offset, Base, Chain }; 2543 SDNode *MN = CurDAG->getMachineNode( 2544 Opcode, dl, LD->getValueType(0), 2545 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops); 2546 transferMemOperands(N, MN); 2547 ReplaceNode(N, MN); 2548 return; 2549 } else { 2550 unsigned Opcode; 2551 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD; 2552 if (LD->getValueType(0) != MVT::i64) { 2553 // Handle PPC32 integer and normal FP loads. 2554 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load"); 2555 switch (LoadedVT.getSimpleVT().SimpleTy) { 2556 default: llvm_unreachable("Invalid PPC load type!"); 2557 case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX 2558 case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX 2559 case MVT::f64: Opcode = PPC::LFDUX; break; 2560 case MVT::f32: Opcode = PPC::LFSUX; break; 2561 case MVT::i32: Opcode = PPC::LWZUX; break; 2562 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break; 2563 case MVT::i1: 2564 case MVT::i8: Opcode = PPC::LBZUX; break; 2565 } 2566 } else { 2567 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!"); 2568 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) && 2569 "Invalid sext update load"); 2570 switch (LoadedVT.getSimpleVT().SimpleTy) { 2571 default: llvm_unreachable("Invalid PPC load type!"); 2572 case MVT::i64: Opcode = PPC::LDUX; break; 2573 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break; 2574 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break; 2575 case MVT::i1: 2576 case MVT::i8: Opcode = PPC::LBZUX8; break; 2577 } 2578 } 2579 2580 SDValue Chain = LD->getChain(); 2581 SDValue Base = LD->getBasePtr(); 2582 SDValue Ops[] = { Base, Offset, Chain }; 2583 SDNode *MN = CurDAG->getMachineNode( 2584 Opcode, dl, LD->getValueType(0), 2585 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops); 2586 transferMemOperands(N, MN); 2587 ReplaceNode(N, MN); 2588 return; 2589 } 2590 } 2591 2592 case ISD::AND: { 2593 unsigned Imm, Imm2, SH, MB, ME; 2594 uint64_t Imm64; 2595 2596 // If this is an and of a value rotated between 0 and 31 bits and then and'd 2597 // with a mask, emit rlwinm 2598 if (isInt32Immediate(N->getOperand(1), Imm) && 2599 isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) { 2600 SDValue Val = N->getOperand(0).getOperand(0); 2601 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl), 2602 getI32Imm(ME, dl) }; 2603 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2604 return; 2605 } 2606 // If this is just a masked value where the input is not handled above, and 2607 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm 2608 if (isInt32Immediate(N->getOperand(1), Imm) && 2609 isRunOfOnes(Imm, MB, ME) && 2610 N->getOperand(0).getOpcode() != ISD::ROTL) { 2611 SDValue Val = N->getOperand(0); 2612 SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl), 2613 getI32Imm(ME, dl) }; 2614 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2615 return; 2616 } 2617 // If this is a 64-bit zero-extension mask, emit rldicl. 2618 if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) && 2619 isMask_64(Imm64)) { 2620 SDValue Val = N->getOperand(0); 2621 MB = 64 - countTrailingOnes(Imm64); 2622 SH = 0; 2623 2624 // If the operand is a logical right shift, we can fold it into this 2625 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb) 2626 // for n <= mb. The right shift is really a left rotate followed by a 2627 // mask, and this mask is a more-restrictive sub-mask of the mask implied 2628 // by the shift. 2629 if (Val.getOpcode() == ISD::SRL && 2630 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) { 2631 assert(Imm < 64 && "Illegal shift amount"); 2632 Val = Val.getOperand(0); 2633 SH = 64 - Imm; 2634 } 2635 2636 SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) }; 2637 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops); 2638 return; 2639 } 2640 // AND X, 0 -> 0, not "rlwinm 32". 2641 if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) { 2642 ReplaceUses(SDValue(N, 0), N->getOperand(1)); 2643 return; 2644 } 2645 // ISD::OR doesn't get all the bitfield insertion fun. 2646 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a 2647 // bitfield insert. 2648 if (isInt32Immediate(N->getOperand(1), Imm) && 2649 N->getOperand(0).getOpcode() == ISD::OR && 2650 isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) { 2651 // The idea here is to check whether this is equivalent to: 2652 // (c1 & m) | (x & ~m) 2653 // where m is a run-of-ones mask. The logic here is that, for each bit in 2654 // c1 and c2: 2655 // - if both are 1, then the output will be 1. 2656 // - if both are 0, then the output will be 0. 2657 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will 2658 // come from x. 2659 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will 2660 // be 0. 2661 // If that last condition is never the case, then we can form m from the 2662 // bits that are the same between c1 and c2. 2663 unsigned MB, ME; 2664 if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) { 2665 SDValue Ops[] = { N->getOperand(0).getOperand(0), 2666 N->getOperand(0).getOperand(1), 2667 getI32Imm(0, dl), getI32Imm(MB, dl), 2668 getI32Imm(ME, dl) }; 2669 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops)); 2670 return; 2671 } 2672 } 2673 2674 // Other cases are autogenerated. 2675 break; 2676 } 2677 case ISD::OR: { 2678 if (N->getValueType(0) == MVT::i32) 2679 if (tryBitfieldInsert(N)) 2680 return; 2681 2682 short Imm; 2683 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex && 2684 isIntS16Immediate(N->getOperand(1), Imm)) { 2685 APInt LHSKnownZero, LHSKnownOne; 2686 CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne); 2687 2688 // If this is equivalent to an add, then we can fold it with the 2689 // FrameIndex calculation. 2690 if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) { 2691 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm); 2692 return; 2693 } 2694 } 2695 2696 // Other cases are autogenerated. 2697 break; 2698 } 2699 case ISD::ADD: { 2700 short Imm; 2701 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex && 2702 isIntS16Immediate(N->getOperand(1), Imm)) { 2703 selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm); 2704 return; 2705 } 2706 2707 break; 2708 } 2709 case ISD::SHL: { 2710 unsigned Imm, SH, MB, ME; 2711 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) && 2712 isRotateAndMask(N, Imm, true, SH, MB, ME)) { 2713 SDValue Ops[] = { N->getOperand(0).getOperand(0), 2714 getI32Imm(SH, dl), getI32Imm(MB, dl), 2715 getI32Imm(ME, dl) }; 2716 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2717 return; 2718 } 2719 2720 // Other cases are autogenerated. 2721 break; 2722 } 2723 case ISD::SRL: { 2724 unsigned Imm, SH, MB, ME; 2725 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) && 2726 isRotateAndMask(N, Imm, true, SH, MB, ME)) { 2727 SDValue Ops[] = { N->getOperand(0).getOperand(0), 2728 getI32Imm(SH, dl), getI32Imm(MB, dl), 2729 getI32Imm(ME, dl) }; 2730 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops); 2731 return; 2732 } 2733 2734 // Other cases are autogenerated. 2735 break; 2736 } 2737 // FIXME: Remove this once the ANDI glue bug is fixed: 2738 case PPCISD::ANDIo_1_EQ_BIT: 2739 case PPCISD::ANDIo_1_GT_BIT: { 2740 if (!ANDIGlueBug) 2741 break; 2742 2743 EVT InVT = N->getOperand(0).getValueType(); 2744 assert((InVT == MVT::i64 || InVT == MVT::i32) && 2745 "Invalid input type for ANDIo_1_EQ_BIT"); 2746 2747 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo; 2748 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue, 2749 N->getOperand(0), 2750 CurDAG->getTargetConstant(1, dl, InVT)), 2751 0); 2752 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32); 2753 SDValue SRIdxVal = 2754 CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ? 2755 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32); 2756 2757 CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg, 2758 SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */); 2759 return; 2760 } 2761 case ISD::SELECT_CC: { 2762 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get(); 2763 EVT PtrVT = 2764 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout()); 2765 bool isPPC64 = (PtrVT == MVT::i64); 2766 2767 // If this is a select of i1 operands, we'll pattern match it. 2768 if (PPCSubTarget->useCRBits() && 2769 N->getOperand(0).getValueType() == MVT::i1) 2770 break; 2771 2772 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc 2773 if (!isPPC64) 2774 if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1))) 2775 if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2))) 2776 if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3))) 2777 if (N1C->isNullValue() && N3C->isNullValue() && 2778 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE && 2779 // FIXME: Implement this optzn for PPC64. 2780 N->getValueType(0) == MVT::i32) { 2781 SDNode *Tmp = 2782 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue, 2783 N->getOperand(0), getI32Imm(~0U, dl)); 2784 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0), 2785 N->getOperand(0), SDValue(Tmp, 1)); 2786 return; 2787 } 2788 2789 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl); 2790 2791 if (N->getValueType(0) == MVT::i1) { 2792 // An i1 select is: (c & t) | (!c & f). 2793 bool Inv; 2794 unsigned Idx = getCRIdxForSetCC(CC, Inv); 2795 2796 unsigned SRI; 2797 switch (Idx) { 2798 default: llvm_unreachable("Invalid CC index"); 2799 case 0: SRI = PPC::sub_lt; break; 2800 case 1: SRI = PPC::sub_gt; break; 2801 case 2: SRI = PPC::sub_eq; break; 2802 case 3: SRI = PPC::sub_un; break; 2803 } 2804 2805 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg); 2806 2807 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1, 2808 CCBit, CCBit), 0); 2809 SDValue C = Inv ? NotCCBit : CCBit, 2810 NotC = Inv ? CCBit : NotCCBit; 2811 2812 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1, 2813 C, N->getOperand(2)), 0); 2814 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1, 2815 NotC, N->getOperand(3)), 0); 2816 2817 CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF); 2818 return; 2819 } 2820 2821 unsigned BROpc = getPredicateForSetCC(CC); 2822 2823 unsigned SelectCCOp; 2824 if (N->getValueType(0) == MVT::i32) 2825 SelectCCOp = PPC::SELECT_CC_I4; 2826 else if (N->getValueType(0) == MVT::i64) 2827 SelectCCOp = PPC::SELECT_CC_I8; 2828 else if (N->getValueType(0) == MVT::f32) 2829 if (PPCSubTarget->hasP8Vector()) 2830 SelectCCOp = PPC::SELECT_CC_VSSRC; 2831 else 2832 SelectCCOp = PPC::SELECT_CC_F4; 2833 else if (N->getValueType(0) == MVT::f64) 2834 if (PPCSubTarget->hasVSX()) 2835 SelectCCOp = PPC::SELECT_CC_VSFRC; 2836 else 2837 SelectCCOp = PPC::SELECT_CC_F8; 2838 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64) 2839 SelectCCOp = PPC::SELECT_CC_QFRC; 2840 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32) 2841 SelectCCOp = PPC::SELECT_CC_QSRC; 2842 else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1) 2843 SelectCCOp = PPC::SELECT_CC_QBRC; 2844 else if (N->getValueType(0) == MVT::v2f64 || 2845 N->getValueType(0) == MVT::v2i64) 2846 SelectCCOp = PPC::SELECT_CC_VSRC; 2847 else 2848 SelectCCOp = PPC::SELECT_CC_VRRC; 2849 2850 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3), 2851 getI32Imm(BROpc, dl) }; 2852 CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops); 2853 return; 2854 } 2855 case ISD::VSELECT: 2856 if (PPCSubTarget->hasVSX()) { 2857 SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) }; 2858 CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops); 2859 return; 2860 } 2861 2862 break; 2863 case ISD::VECTOR_SHUFFLE: 2864 if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 || 2865 N->getValueType(0) == MVT::v2i64)) { 2866 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N); 2867 2868 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1), 2869 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1); 2870 unsigned DM[2]; 2871 2872 for (int i = 0; i < 2; ++i) 2873 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2) 2874 DM[i] = 0; 2875 else 2876 DM[i] = 1; 2877 2878 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 && 2879 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR && 2880 isa<LoadSDNode>(Op1.getOperand(0))) { 2881 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0)); 2882 SDValue Base, Offset; 2883 2884 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() && 2885 (LD->getMemoryVT() == MVT::f64 || 2886 LD->getMemoryVT() == MVT::i64) && 2887 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) { 2888 SDValue Chain = LD->getChain(); 2889 SDValue Ops[] = { Base, Offset, Chain }; 2890 CurDAG->SelectNodeTo(N, PPC::LXVDSX, N->getValueType(0), Ops); 2891 return; 2892 } 2893 } 2894 2895 // For little endian, we must swap the input operands and adjust 2896 // the mask elements (reverse and invert them). 2897 if (PPCSubTarget->isLittleEndian()) { 2898 std::swap(Op1, Op2); 2899 unsigned tmp = DM[0]; 2900 DM[0] = 1 - DM[1]; 2901 DM[1] = 1 - tmp; 2902 } 2903 2904 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl, 2905 MVT::i32); 2906 SDValue Ops[] = { Op1, Op2, DMV }; 2907 CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops); 2908 return; 2909 } 2910 2911 break; 2912 case PPCISD::BDNZ: 2913 case PPCISD::BDZ: { 2914 bool IsPPC64 = PPCSubTarget->isPPC64(); 2915 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) }; 2916 CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ 2917 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) 2918 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ), 2919 MVT::Other, Ops); 2920 return; 2921 } 2922 case PPCISD::COND_BRANCH: { 2923 // Op #0 is the Chain. 2924 // Op #1 is the PPC::PRED_* number. 2925 // Op #2 is the CR# 2926 // Op #3 is the Dest MBB 2927 // Op #4 is the Flag. 2928 // Prevent PPC::PRED_* from being selected into LI. 2929 unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue(); 2930 if (EnableBranchHint) 2931 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(3)); 2932 2933 SDValue Pred = getI32Imm(PCC, dl); 2934 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3), 2935 N->getOperand(0), N->getOperand(4) }; 2936 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops); 2937 return; 2938 } 2939 case ISD::BR_CC: { 2940 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get(); 2941 unsigned PCC = getPredicateForSetCC(CC); 2942 2943 if (N->getOperand(2).getValueType() == MVT::i1) { 2944 unsigned Opc; 2945 bool Swap; 2946 switch (PCC) { 2947 default: llvm_unreachable("Unexpected Boolean-operand predicate"); 2948 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break; 2949 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break; 2950 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break; 2951 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break; 2952 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break; 2953 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break; 2954 } 2955 2956 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1, 2957 N->getOperand(Swap ? 3 : 2), 2958 N->getOperand(Swap ? 2 : 3)), 0); 2959 CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4), 2960 N->getOperand(0)); 2961 return; 2962 } 2963 2964 if (EnableBranchHint) 2965 PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(4)); 2966 2967 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl); 2968 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode, 2969 N->getOperand(4), N->getOperand(0) }; 2970 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops); 2971 return; 2972 } 2973 case ISD::BRIND: { 2974 // FIXME: Should custom lower this. 2975 SDValue Chain = N->getOperand(0); 2976 SDValue Target = N->getOperand(1); 2977 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8; 2978 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8; 2979 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target, 2980 Chain), 0); 2981 CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain); 2982 return; 2983 } 2984 case PPCISD::TOC_ENTRY: { 2985 assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) && 2986 "Only supported for 64-bit ABI and 32-bit SVR4"); 2987 if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) { 2988 SDValue GA = N->getOperand(0); 2989 SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA, 2990 N->getOperand(1)); 2991 transferMemOperands(N, MN); 2992 ReplaceNode(N, MN); 2993 return; 2994 } 2995 2996 // For medium and large code model, we generate two instructions as 2997 // described below. Otherwise we allow SelectCodeCommon to handle this, 2998 // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA. 2999 CodeModel::Model CModel = TM.getCodeModel(); 3000 if (CModel != CodeModel::Medium && CModel != CodeModel::Large) 3001 break; 3002 3003 // The first source operand is a TargetGlobalAddress or a TargetJumpTable. 3004 // If it must be toc-referenced according to PPCSubTarget, we generate: 3005 // LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>)) 3006 // Otherwise we generate: 3007 // ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>) 3008 SDValue GA = N->getOperand(0); 3009 SDValue TOCbase = N->getOperand(1); 3010 SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64, 3011 TOCbase, GA); 3012 3013 if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) || 3014 CModel == CodeModel::Large) { 3015 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA, 3016 SDValue(Tmp, 0)); 3017 transferMemOperands(N, MN); 3018 ReplaceNode(N, MN); 3019 return; 3020 } 3021 3022 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) { 3023 const GlobalValue *GV = G->getGlobal(); 3024 unsigned char GVFlags = PPCSubTarget->classifyGlobalReference(GV); 3025 if (GVFlags & PPCII::MO_NLP_FLAG) { 3026 SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA, 3027 SDValue(Tmp, 0)); 3028 transferMemOperands(N, MN); 3029 ReplaceNode(N, MN); 3030 return; 3031 } 3032 } 3033 3034 ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64, 3035 SDValue(Tmp, 0), GA)); 3036 return; 3037 } 3038 case PPCISD::PPC32_PICGOT: { 3039 // Generate a PIC-safe GOT reference. 3040 assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() && 3041 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4"); 3042 CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, 3043 PPCLowering->getPointerTy(CurDAG->getDataLayout()), 3044 MVT::i32); 3045 return; 3046 } 3047 case PPCISD::VADD_SPLAT: { 3048 // This expands into one of three sequences, depending on whether 3049 // the first operand is odd or even, positive or negative. 3050 assert(isa<ConstantSDNode>(N->getOperand(0)) && 3051 isa<ConstantSDNode>(N->getOperand(1)) && 3052 "Invalid operand on VADD_SPLAT!"); 3053 3054 int Elt = N->getConstantOperandVal(0); 3055 int EltSize = N->getConstantOperandVal(1); 3056 unsigned Opc1, Opc2, Opc3; 3057 EVT VT; 3058 3059 if (EltSize == 1) { 3060 Opc1 = PPC::VSPLTISB; 3061 Opc2 = PPC::VADDUBM; 3062 Opc3 = PPC::VSUBUBM; 3063 VT = MVT::v16i8; 3064 } else if (EltSize == 2) { 3065 Opc1 = PPC::VSPLTISH; 3066 Opc2 = PPC::VADDUHM; 3067 Opc3 = PPC::VSUBUHM; 3068 VT = MVT::v8i16; 3069 } else { 3070 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!"); 3071 Opc1 = PPC::VSPLTISW; 3072 Opc2 = PPC::VADDUWM; 3073 Opc3 = PPC::VSUBUWM; 3074 VT = MVT::v4i32; 3075 } 3076 3077 if ((Elt & 1) == 0) { 3078 // Elt is even, in the range [-32,-18] + [16,30]. 3079 // 3080 // Convert: VADD_SPLAT elt, size 3081 // Into: tmp = VSPLTIS[BHW] elt 3082 // VADDU[BHW]M tmp, tmp 3083 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4 3084 SDValue EltVal = getI32Imm(Elt >> 1, dl); 3085 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 3086 SDValue TmpVal = SDValue(Tmp, 0); 3087 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal)); 3088 return; 3089 3090 } else if (Elt > 0) { 3091 // Elt is odd and positive, in the range [17,31]. 3092 // 3093 // Convert: VADD_SPLAT elt, size 3094 // Into: tmp1 = VSPLTIS[BHW] elt-16 3095 // tmp2 = VSPLTIS[BHW] -16 3096 // VSUBU[BHW]M tmp1, tmp2 3097 SDValue EltVal = getI32Imm(Elt - 16, dl); 3098 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 3099 EltVal = getI32Imm(-16, dl); 3100 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 3101 ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0), 3102 SDValue(Tmp2, 0))); 3103 return; 3104 3105 } else { 3106 // Elt is odd and negative, in the range [-31,-17]. 3107 // 3108 // Convert: VADD_SPLAT elt, size 3109 // Into: tmp1 = VSPLTIS[BHW] elt+16 3110 // tmp2 = VSPLTIS[BHW] -16 3111 // VADDU[BHW]M tmp1, tmp2 3112 SDValue EltVal = getI32Imm(Elt + 16, dl); 3113 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 3114 EltVal = getI32Imm(-16, dl); 3115 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal); 3116 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0), 3117 SDValue(Tmp2, 0))); 3118 return; 3119 } 3120 } 3121 } 3122 3123 SelectCode(N); 3124 } 3125 3126 // If the target supports the cmpb instruction, do the idiom recognition here. 3127 // We don't do this as a DAG combine because we don't want to do it as nodes 3128 // are being combined (because we might miss part of the eventual idiom). We 3129 // don't want to do it during instruction selection because we want to reuse 3130 // the logic for lowering the masking operations already part of the 3131 // instruction selector. 3132 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) { 3133 SDLoc dl(N); 3134 3135 assert(N->getOpcode() == ISD::OR && 3136 "Only OR nodes are supported for CMPB"); 3137 3138 SDValue Res; 3139 if (!PPCSubTarget->hasCMPB()) 3140 return Res; 3141 3142 if (N->getValueType(0) != MVT::i32 && 3143 N->getValueType(0) != MVT::i64) 3144 return Res; 3145 3146 EVT VT = N->getValueType(0); 3147 3148 SDValue RHS, LHS; 3149 bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 }; 3150 uint64_t Mask = 0, Alt = 0; 3151 3152 auto IsByteSelectCC = [this](SDValue O, unsigned &b, 3153 uint64_t &Mask, uint64_t &Alt, 3154 SDValue &LHS, SDValue &RHS) { 3155 if (O.getOpcode() != ISD::SELECT_CC) 3156 return false; 3157 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get(); 3158 3159 if (!isa<ConstantSDNode>(O.getOperand(2)) || 3160 !isa<ConstantSDNode>(O.getOperand(3))) 3161 return false; 3162 3163 uint64_t PM = O.getConstantOperandVal(2); 3164 uint64_t PAlt = O.getConstantOperandVal(3); 3165 for (b = 0; b < 8; ++b) { 3166 uint64_t Mask = UINT64_C(0xFF) << (8*b); 3167 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt) 3168 break; 3169 } 3170 3171 if (b == 8) 3172 return false; 3173 Mask |= PM; 3174 Alt |= PAlt; 3175 3176 if (!isa<ConstantSDNode>(O.getOperand(1)) || 3177 O.getConstantOperandVal(1) != 0) { 3178 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1); 3179 if (Op0.getOpcode() == ISD::TRUNCATE) 3180 Op0 = Op0.getOperand(0); 3181 if (Op1.getOpcode() == ISD::TRUNCATE) 3182 Op1 = Op1.getOperand(0); 3183 3184 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL && 3185 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ && 3186 isa<ConstantSDNode>(Op0.getOperand(1))) { 3187 3188 unsigned Bits = Op0.getValueType().getSizeInBits(); 3189 if (b != Bits/8-1) 3190 return false; 3191 if (Op0.getConstantOperandVal(1) != Bits-8) 3192 return false; 3193 3194 LHS = Op0.getOperand(0); 3195 RHS = Op1.getOperand(0); 3196 return true; 3197 } 3198 3199 // When we have small integers (i16 to be specific), the form present 3200 // post-legalization uses SETULT in the SELECT_CC for the 3201 // higher-order byte, depending on the fact that the 3202 // even-higher-order bytes are known to all be zero, for example: 3203 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult 3204 // (so when the second byte is the same, because all higher-order 3205 // bits from bytes 3 and 4 are known to be zero, the result of the 3206 // xor can be at most 255) 3207 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT && 3208 isa<ConstantSDNode>(O.getOperand(1))) { 3209 3210 uint64_t ULim = O.getConstantOperandVal(1); 3211 if (ULim != (UINT64_C(1) << b*8)) 3212 return false; 3213 3214 // Now we need to make sure that the upper bytes are known to be 3215 // zero. 3216 unsigned Bits = Op0.getValueType().getSizeInBits(); 3217 if (!CurDAG->MaskedValueIsZero(Op0, 3218 APInt::getHighBitsSet(Bits, Bits - (b+1)*8))) 3219 return false; 3220 3221 LHS = Op0.getOperand(0); 3222 RHS = Op0.getOperand(1); 3223 return true; 3224 } 3225 3226 return false; 3227 } 3228 3229 if (CC != ISD::SETEQ) 3230 return false; 3231 3232 SDValue Op = O.getOperand(0); 3233 if (Op.getOpcode() == ISD::AND) { 3234 if (!isa<ConstantSDNode>(Op.getOperand(1))) 3235 return false; 3236 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b))) 3237 return false; 3238 3239 SDValue XOR = Op.getOperand(0); 3240 if (XOR.getOpcode() == ISD::TRUNCATE) 3241 XOR = XOR.getOperand(0); 3242 if (XOR.getOpcode() != ISD::XOR) 3243 return false; 3244 3245 LHS = XOR.getOperand(0); 3246 RHS = XOR.getOperand(1); 3247 return true; 3248 } else if (Op.getOpcode() == ISD::SRL) { 3249 if (!isa<ConstantSDNode>(Op.getOperand(1))) 3250 return false; 3251 unsigned Bits = Op.getValueType().getSizeInBits(); 3252 if (b != Bits/8-1) 3253 return false; 3254 if (Op.getConstantOperandVal(1) != Bits-8) 3255 return false; 3256 3257 SDValue XOR = Op.getOperand(0); 3258 if (XOR.getOpcode() == ISD::TRUNCATE) 3259 XOR = XOR.getOperand(0); 3260 if (XOR.getOpcode() != ISD::XOR) 3261 return false; 3262 3263 LHS = XOR.getOperand(0); 3264 RHS = XOR.getOperand(1); 3265 return true; 3266 } 3267 3268 return false; 3269 }; 3270 3271 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0)); 3272 while (!Queue.empty()) { 3273 SDValue V = Queue.pop_back_val(); 3274 3275 for (const SDValue &O : V.getNode()->ops()) { 3276 unsigned b; 3277 uint64_t M = 0, A = 0; 3278 SDValue OLHS, ORHS; 3279 if (O.getOpcode() == ISD::OR) { 3280 Queue.push_back(O); 3281 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) { 3282 if (!LHS) { 3283 LHS = OLHS; 3284 RHS = ORHS; 3285 BytesFound[b] = true; 3286 Mask |= M; 3287 Alt |= A; 3288 } else if ((LHS == ORHS && RHS == OLHS) || 3289 (RHS == ORHS && LHS == OLHS)) { 3290 BytesFound[b] = true; 3291 Mask |= M; 3292 Alt |= A; 3293 } else { 3294 return Res; 3295 } 3296 } else { 3297 return Res; 3298 } 3299 } 3300 } 3301 3302 unsigned LastB = 0, BCnt = 0; 3303 for (unsigned i = 0; i < 8; ++i) 3304 if (BytesFound[LastB]) { 3305 ++BCnt; 3306 LastB = i; 3307 } 3308 3309 if (!LastB || BCnt < 2) 3310 return Res; 3311 3312 // Because we'll be zero-extending the output anyway if don't have a specific 3313 // value for each input byte (via the Mask), we can 'anyext' the inputs. 3314 if (LHS.getValueType() != VT) { 3315 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT); 3316 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT); 3317 } 3318 3319 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS); 3320 3321 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1); 3322 if (NonTrivialMask && !Alt) { 3323 // Res = Mask & CMPB 3324 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, 3325 CurDAG->getConstant(Mask, dl, VT)); 3326 } else if (Alt) { 3327 // Res = (CMPB & Mask) | (~CMPB & Alt) 3328 // Which, as suggested here: 3329 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge 3330 // can be written as: 3331 // Res = Alt ^ ((Alt ^ Mask) & CMPB) 3332 // useful because the (Alt ^ Mask) can be pre-computed. 3333 Res = CurDAG->getNode(ISD::AND, dl, VT, Res, 3334 CurDAG->getConstant(Mask ^ Alt, dl, VT)); 3335 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res, 3336 CurDAG->getConstant(Alt, dl, VT)); 3337 } 3338 3339 return Res; 3340 } 3341 3342 // When CR bit registers are enabled, an extension of an i1 variable to a i32 3343 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus 3344 // involves constant materialization of a 0 or a 1 or both. If the result of 3345 // the extension is then operated upon by some operator that can be constant 3346 // folded with a constant 0 or 1, and that constant can be materialized using 3347 // only one instruction (like a zero or one), then we should fold in those 3348 // operations with the select. 3349 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) { 3350 if (!PPCSubTarget->useCRBits()) 3351 return; 3352 3353 if (N->getOpcode() != ISD::ZERO_EXTEND && 3354 N->getOpcode() != ISD::SIGN_EXTEND && 3355 N->getOpcode() != ISD::ANY_EXTEND) 3356 return; 3357 3358 if (N->getOperand(0).getValueType() != MVT::i1) 3359 return; 3360 3361 if (!N->hasOneUse()) 3362 return; 3363 3364 SDLoc dl(N); 3365 EVT VT = N->getValueType(0); 3366 SDValue Cond = N->getOperand(0); 3367 SDValue ConstTrue = 3368 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT); 3369 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT); 3370 3371 do { 3372 SDNode *User = *N->use_begin(); 3373 if (User->getNumOperands() != 2) 3374 break; 3375 3376 auto TryFold = [this, N, User, dl](SDValue Val) { 3377 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1); 3378 SDValue O0 = UserO0.getNode() == N ? Val : UserO0; 3379 SDValue O1 = UserO1.getNode() == N ? Val : UserO1; 3380 3381 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl, 3382 User->getValueType(0), 3383 O0.getNode(), O1.getNode()); 3384 }; 3385 3386 SDValue TrueRes = TryFold(ConstTrue); 3387 if (!TrueRes) 3388 break; 3389 SDValue FalseRes = TryFold(ConstFalse); 3390 if (!FalseRes) 3391 break; 3392 3393 // For us to materialize these using one instruction, we must be able to 3394 // represent them as signed 16-bit integers. 3395 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(), 3396 False = cast<ConstantSDNode>(FalseRes)->getZExtValue(); 3397 if (!isInt<16>(True) || !isInt<16>(False)) 3398 break; 3399 3400 // We can replace User with a new SELECT node, and try again to see if we 3401 // can fold the select with its user. 3402 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes); 3403 N = User; 3404 ConstTrue = TrueRes; 3405 ConstFalse = FalseRes; 3406 } while (N->hasOneUse()); 3407 } 3408 3409 void PPCDAGToDAGISel::PreprocessISelDAG() { 3410 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode()); 3411 ++Position; 3412 3413 bool MadeChange = false; 3414 while (Position != CurDAG->allnodes_begin()) { 3415 SDNode *N = &*--Position; 3416 if (N->use_empty()) 3417 continue; 3418 3419 SDValue Res; 3420 switch (N->getOpcode()) { 3421 default: break; 3422 case ISD::OR: 3423 Res = combineToCMPB(N); 3424 break; 3425 } 3426 3427 if (!Res) 3428 foldBoolExts(Res, N); 3429 3430 if (Res) { 3431 DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: "); 3432 DEBUG(N->dump(CurDAG)); 3433 DEBUG(dbgs() << "\nNew: "); 3434 DEBUG(Res.getNode()->dump(CurDAG)); 3435 DEBUG(dbgs() << "\n"); 3436 3437 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res); 3438 MadeChange = true; 3439 } 3440 } 3441 3442 if (MadeChange) 3443 CurDAG->RemoveDeadNodes(); 3444 } 3445 3446 /// PostprocessISelDAG - Perform some late peephole optimizations 3447 /// on the DAG representation. 3448 void PPCDAGToDAGISel::PostprocessISelDAG() { 3449 3450 // Skip peepholes at -O0. 3451 if (TM.getOptLevel() == CodeGenOpt::None) 3452 return; 3453 3454 PeepholePPC64(); 3455 PeepholeCROps(); 3456 PeepholePPC64ZExt(); 3457 } 3458 3459 // Check if all users of this node will become isel where the second operand 3460 // is the constant zero. If this is so, and if we can negate the condition, 3461 // then we can flip the true and false operands. This will allow the zero to 3462 // be folded with the isel so that we don't need to materialize a register 3463 // containing zero. 3464 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) { 3465 // If we're not using isel, then this does not matter. 3466 if (!PPCSubTarget->hasISEL()) 3467 return false; 3468 3469 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 3470 UI != UE; ++UI) { 3471 SDNode *User = *UI; 3472 if (!User->isMachineOpcode()) 3473 return false; 3474 if (User->getMachineOpcode() != PPC::SELECT_I4 && 3475 User->getMachineOpcode() != PPC::SELECT_I8) 3476 return false; 3477 3478 SDNode *Op2 = User->getOperand(2).getNode(); 3479 if (!Op2->isMachineOpcode()) 3480 return false; 3481 3482 if (Op2->getMachineOpcode() != PPC::LI && 3483 Op2->getMachineOpcode() != PPC::LI8) 3484 return false; 3485 3486 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0)); 3487 if (!C) 3488 return false; 3489 3490 if (!C->isNullValue()) 3491 return false; 3492 } 3493 3494 return true; 3495 } 3496 3497 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) { 3498 SmallVector<SDNode *, 4> ToReplace; 3499 for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end(); 3500 UI != UE; ++UI) { 3501 SDNode *User = *UI; 3502 assert((User->getMachineOpcode() == PPC::SELECT_I4 || 3503 User->getMachineOpcode() == PPC::SELECT_I8) && 3504 "Must have all select users"); 3505 ToReplace.push_back(User); 3506 } 3507 3508 for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(), 3509 UE = ToReplace.end(); UI != UE; ++UI) { 3510 SDNode *User = *UI; 3511 SDNode *ResNode = 3512 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User), 3513 User->getValueType(0), User->getOperand(0), 3514 User->getOperand(2), 3515 User->getOperand(1)); 3516 3517 DEBUG(dbgs() << "CR Peephole replacing:\nOld: "); 3518 DEBUG(User->dump(CurDAG)); 3519 DEBUG(dbgs() << "\nNew: "); 3520 DEBUG(ResNode->dump(CurDAG)); 3521 DEBUG(dbgs() << "\n"); 3522 3523 ReplaceUses(User, ResNode); 3524 } 3525 } 3526 3527 void PPCDAGToDAGISel::PeepholeCROps() { 3528 bool IsModified; 3529 do { 3530 IsModified = false; 3531 for (SDNode &Node : CurDAG->allnodes()) { 3532 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node); 3533 if (!MachineNode || MachineNode->use_empty()) 3534 continue; 3535 SDNode *ResNode = MachineNode; 3536 3537 bool Op1Set = false, Op1Unset = false, 3538 Op1Not = false, 3539 Op2Set = false, Op2Unset = false, 3540 Op2Not = false; 3541 3542 unsigned Opcode = MachineNode->getMachineOpcode(); 3543 switch (Opcode) { 3544 default: break; 3545 case PPC::CRAND: 3546 case PPC::CRNAND: 3547 case PPC::CROR: 3548 case PPC::CRXOR: 3549 case PPC::CRNOR: 3550 case PPC::CREQV: 3551 case PPC::CRANDC: 3552 case PPC::CRORC: { 3553 SDValue Op = MachineNode->getOperand(1); 3554 if (Op.isMachineOpcode()) { 3555 if (Op.getMachineOpcode() == PPC::CRSET) 3556 Op2Set = true; 3557 else if (Op.getMachineOpcode() == PPC::CRUNSET) 3558 Op2Unset = true; 3559 else if (Op.getMachineOpcode() == PPC::CRNOR && 3560 Op.getOperand(0) == Op.getOperand(1)) 3561 Op2Not = true; 3562 } 3563 } // fallthrough 3564 case PPC::BC: 3565 case PPC::BCn: 3566 case PPC::SELECT_I4: 3567 case PPC::SELECT_I8: 3568 case PPC::SELECT_F4: 3569 case PPC::SELECT_F8: 3570 case PPC::SELECT_QFRC: 3571 case PPC::SELECT_QSRC: 3572 case PPC::SELECT_QBRC: 3573 case PPC::SELECT_VRRC: 3574 case PPC::SELECT_VSFRC: 3575 case PPC::SELECT_VSSRC: 3576 case PPC::SELECT_VSRC: { 3577 SDValue Op = MachineNode->getOperand(0); 3578 if (Op.isMachineOpcode()) { 3579 if (Op.getMachineOpcode() == PPC::CRSET) 3580 Op1Set = true; 3581 else if (Op.getMachineOpcode() == PPC::CRUNSET) 3582 Op1Unset = true; 3583 else if (Op.getMachineOpcode() == PPC::CRNOR && 3584 Op.getOperand(0) == Op.getOperand(1)) 3585 Op1Not = true; 3586 } 3587 } 3588 break; 3589 } 3590 3591 bool SelectSwap = false; 3592 switch (Opcode) { 3593 default: break; 3594 case PPC::CRAND: 3595 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3596 // x & x = x 3597 ResNode = MachineNode->getOperand(0).getNode(); 3598 else if (Op1Set) 3599 // 1 & y = y 3600 ResNode = MachineNode->getOperand(1).getNode(); 3601 else if (Op2Set) 3602 // x & 1 = x 3603 ResNode = MachineNode->getOperand(0).getNode(); 3604 else if (Op1Unset || Op2Unset) 3605 // x & 0 = 0 & y = 0 3606 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 3607 MVT::i1); 3608 else if (Op1Not) 3609 // ~x & y = andc(y, x) 3610 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 3611 MVT::i1, MachineNode->getOperand(1), 3612 MachineNode->getOperand(0). 3613 getOperand(0)); 3614 else if (Op2Not) 3615 // x & ~y = andc(x, y) 3616 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 3617 MVT::i1, MachineNode->getOperand(0), 3618 MachineNode->getOperand(1). 3619 getOperand(0)); 3620 else if (AllUsersSelectZero(MachineNode)) { 3621 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode), 3622 MVT::i1, MachineNode->getOperand(0), 3623 MachineNode->getOperand(1)); 3624 SelectSwap = true; 3625 } 3626 break; 3627 case PPC::CRNAND: 3628 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3629 // nand(x, x) -> nor(x, x) 3630 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3631 MVT::i1, MachineNode->getOperand(0), 3632 MachineNode->getOperand(0)); 3633 else if (Op1Set) 3634 // nand(1, y) -> nor(y, y) 3635 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3636 MVT::i1, MachineNode->getOperand(1), 3637 MachineNode->getOperand(1)); 3638 else if (Op2Set) 3639 // nand(x, 1) -> nor(x, x) 3640 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3641 MVT::i1, MachineNode->getOperand(0), 3642 MachineNode->getOperand(0)); 3643 else if (Op1Unset || Op2Unset) 3644 // nand(x, 0) = nand(0, y) = 1 3645 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 3646 MVT::i1); 3647 else if (Op1Not) 3648 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y) 3649 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 3650 MVT::i1, MachineNode->getOperand(0). 3651 getOperand(0), 3652 MachineNode->getOperand(1)); 3653 else if (Op2Not) 3654 // nand(x, ~y) = ~x | y = orc(y, x) 3655 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 3656 MVT::i1, MachineNode->getOperand(1). 3657 getOperand(0), 3658 MachineNode->getOperand(0)); 3659 else if (AllUsersSelectZero(MachineNode)) { 3660 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode), 3661 MVT::i1, MachineNode->getOperand(0), 3662 MachineNode->getOperand(1)); 3663 SelectSwap = true; 3664 } 3665 break; 3666 case PPC::CROR: 3667 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3668 // x | x = x 3669 ResNode = MachineNode->getOperand(0).getNode(); 3670 else if (Op1Set || Op2Set) 3671 // x | 1 = 1 | y = 1 3672 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 3673 MVT::i1); 3674 else if (Op1Unset) 3675 // 0 | y = y 3676 ResNode = MachineNode->getOperand(1).getNode(); 3677 else if (Op2Unset) 3678 // x | 0 = x 3679 ResNode = MachineNode->getOperand(0).getNode(); 3680 else if (Op1Not) 3681 // ~x | y = orc(y, x) 3682 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 3683 MVT::i1, MachineNode->getOperand(1), 3684 MachineNode->getOperand(0). 3685 getOperand(0)); 3686 else if (Op2Not) 3687 // x | ~y = orc(x, y) 3688 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 3689 MVT::i1, MachineNode->getOperand(0), 3690 MachineNode->getOperand(1). 3691 getOperand(0)); 3692 else if (AllUsersSelectZero(MachineNode)) { 3693 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3694 MVT::i1, MachineNode->getOperand(0), 3695 MachineNode->getOperand(1)); 3696 SelectSwap = true; 3697 } 3698 break; 3699 case PPC::CRXOR: 3700 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3701 // xor(x, x) = 0 3702 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 3703 MVT::i1); 3704 else if (Op1Set) 3705 // xor(1, y) -> nor(y, y) 3706 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3707 MVT::i1, MachineNode->getOperand(1), 3708 MachineNode->getOperand(1)); 3709 else if (Op2Set) 3710 // xor(x, 1) -> nor(x, x) 3711 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3712 MVT::i1, MachineNode->getOperand(0), 3713 MachineNode->getOperand(0)); 3714 else if (Op1Unset) 3715 // xor(0, y) = y 3716 ResNode = MachineNode->getOperand(1).getNode(); 3717 else if (Op2Unset) 3718 // xor(x, 0) = x 3719 ResNode = MachineNode->getOperand(0).getNode(); 3720 else if (Op1Not) 3721 // xor(~x, y) = eqv(x, y) 3722 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 3723 MVT::i1, MachineNode->getOperand(0). 3724 getOperand(0), 3725 MachineNode->getOperand(1)); 3726 else if (Op2Not) 3727 // xor(x, ~y) = eqv(x, y) 3728 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 3729 MVT::i1, MachineNode->getOperand(0), 3730 MachineNode->getOperand(1). 3731 getOperand(0)); 3732 else if (AllUsersSelectZero(MachineNode)) { 3733 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode), 3734 MVT::i1, MachineNode->getOperand(0), 3735 MachineNode->getOperand(1)); 3736 SelectSwap = true; 3737 } 3738 break; 3739 case PPC::CRNOR: 3740 if (Op1Set || Op2Set) 3741 // nor(1, y) -> 0 3742 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 3743 MVT::i1); 3744 else if (Op1Unset) 3745 // nor(0, y) = ~y -> nor(y, y) 3746 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3747 MVT::i1, MachineNode->getOperand(1), 3748 MachineNode->getOperand(1)); 3749 else if (Op2Unset) 3750 // nor(x, 0) = ~x 3751 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3752 MVT::i1, MachineNode->getOperand(0), 3753 MachineNode->getOperand(0)); 3754 else if (Op1Not) 3755 // nor(~x, y) = andc(x, y) 3756 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 3757 MVT::i1, MachineNode->getOperand(0). 3758 getOperand(0), 3759 MachineNode->getOperand(1)); 3760 else if (Op2Not) 3761 // nor(x, ~y) = andc(y, x) 3762 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 3763 MVT::i1, MachineNode->getOperand(1). 3764 getOperand(0), 3765 MachineNode->getOperand(0)); 3766 else if (AllUsersSelectZero(MachineNode)) { 3767 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode), 3768 MVT::i1, MachineNode->getOperand(0), 3769 MachineNode->getOperand(1)); 3770 SelectSwap = true; 3771 } 3772 break; 3773 case PPC::CREQV: 3774 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3775 // eqv(x, x) = 1 3776 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 3777 MVT::i1); 3778 else if (Op1Set) 3779 // eqv(1, y) = y 3780 ResNode = MachineNode->getOperand(1).getNode(); 3781 else if (Op2Set) 3782 // eqv(x, 1) = x 3783 ResNode = MachineNode->getOperand(0).getNode(); 3784 else if (Op1Unset) 3785 // eqv(0, y) = ~y -> nor(y, y) 3786 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3787 MVT::i1, MachineNode->getOperand(1), 3788 MachineNode->getOperand(1)); 3789 else if (Op2Unset) 3790 // eqv(x, 0) = ~x 3791 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3792 MVT::i1, MachineNode->getOperand(0), 3793 MachineNode->getOperand(0)); 3794 else if (Op1Not) 3795 // eqv(~x, y) = xor(x, y) 3796 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 3797 MVT::i1, MachineNode->getOperand(0). 3798 getOperand(0), 3799 MachineNode->getOperand(1)); 3800 else if (Op2Not) 3801 // eqv(x, ~y) = xor(x, y) 3802 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 3803 MVT::i1, MachineNode->getOperand(0), 3804 MachineNode->getOperand(1). 3805 getOperand(0)); 3806 else if (AllUsersSelectZero(MachineNode)) { 3807 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode), 3808 MVT::i1, MachineNode->getOperand(0), 3809 MachineNode->getOperand(1)); 3810 SelectSwap = true; 3811 } 3812 break; 3813 case PPC::CRANDC: 3814 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3815 // andc(x, x) = 0 3816 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 3817 MVT::i1); 3818 else if (Op1Set) 3819 // andc(1, y) = ~y 3820 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3821 MVT::i1, MachineNode->getOperand(1), 3822 MachineNode->getOperand(1)); 3823 else if (Op1Unset || Op2Set) 3824 // andc(0, y) = andc(x, 1) = 0 3825 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode), 3826 MVT::i1); 3827 else if (Op2Unset) 3828 // andc(x, 0) = x 3829 ResNode = MachineNode->getOperand(0).getNode(); 3830 else if (Op1Not) 3831 // andc(~x, y) = ~(x | y) = nor(x, y) 3832 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3833 MVT::i1, MachineNode->getOperand(0). 3834 getOperand(0), 3835 MachineNode->getOperand(1)); 3836 else if (Op2Not) 3837 // andc(x, ~y) = x & y 3838 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode), 3839 MVT::i1, MachineNode->getOperand(0), 3840 MachineNode->getOperand(1). 3841 getOperand(0)); 3842 else if (AllUsersSelectZero(MachineNode)) { 3843 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode), 3844 MVT::i1, MachineNode->getOperand(1), 3845 MachineNode->getOperand(0)); 3846 SelectSwap = true; 3847 } 3848 break; 3849 case PPC::CRORC: 3850 if (MachineNode->getOperand(0) == MachineNode->getOperand(1)) 3851 // orc(x, x) = 1 3852 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 3853 MVT::i1); 3854 else if (Op1Set || Op2Unset) 3855 // orc(1, y) = orc(x, 0) = 1 3856 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode), 3857 MVT::i1); 3858 else if (Op2Set) 3859 // orc(x, 1) = x 3860 ResNode = MachineNode->getOperand(0).getNode(); 3861 else if (Op1Unset) 3862 // orc(0, y) = ~y 3863 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode), 3864 MVT::i1, MachineNode->getOperand(1), 3865 MachineNode->getOperand(1)); 3866 else if (Op1Not) 3867 // orc(~x, y) = ~(x & y) = nand(x, y) 3868 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode), 3869 MVT::i1, MachineNode->getOperand(0). 3870 getOperand(0), 3871 MachineNode->getOperand(1)); 3872 else if (Op2Not) 3873 // orc(x, ~y) = x | y 3874 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode), 3875 MVT::i1, MachineNode->getOperand(0), 3876 MachineNode->getOperand(1). 3877 getOperand(0)); 3878 else if (AllUsersSelectZero(MachineNode)) { 3879 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode), 3880 MVT::i1, MachineNode->getOperand(1), 3881 MachineNode->getOperand(0)); 3882 SelectSwap = true; 3883 } 3884 break; 3885 case PPC::SELECT_I4: 3886 case PPC::SELECT_I8: 3887 case PPC::SELECT_F4: 3888 case PPC::SELECT_F8: 3889 case PPC::SELECT_QFRC: 3890 case PPC::SELECT_QSRC: 3891 case PPC::SELECT_QBRC: 3892 case PPC::SELECT_VRRC: 3893 case PPC::SELECT_VSFRC: 3894 case PPC::SELECT_VSSRC: 3895 case PPC::SELECT_VSRC: 3896 if (Op1Set) 3897 ResNode = MachineNode->getOperand(1).getNode(); 3898 else if (Op1Unset) 3899 ResNode = MachineNode->getOperand(2).getNode(); 3900 else if (Op1Not) 3901 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(), 3902 SDLoc(MachineNode), 3903 MachineNode->getValueType(0), 3904 MachineNode->getOperand(0). 3905 getOperand(0), 3906 MachineNode->getOperand(2), 3907 MachineNode->getOperand(1)); 3908 break; 3909 case PPC::BC: 3910 case PPC::BCn: 3911 if (Op1Not) 3912 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn : 3913 PPC::BC, 3914 SDLoc(MachineNode), 3915 MVT::Other, 3916 MachineNode->getOperand(0). 3917 getOperand(0), 3918 MachineNode->getOperand(1), 3919 MachineNode->getOperand(2)); 3920 // FIXME: Handle Op1Set, Op1Unset here too. 3921 break; 3922 } 3923 3924 // If we're inverting this node because it is used only by selects that 3925 // we'd like to swap, then swap the selects before the node replacement. 3926 if (SelectSwap) 3927 SwapAllSelectUsers(MachineNode); 3928 3929 if (ResNode != MachineNode) { 3930 DEBUG(dbgs() << "CR Peephole replacing:\nOld: "); 3931 DEBUG(MachineNode->dump(CurDAG)); 3932 DEBUG(dbgs() << "\nNew: "); 3933 DEBUG(ResNode->dump(CurDAG)); 3934 DEBUG(dbgs() << "\n"); 3935 3936 ReplaceUses(MachineNode, ResNode); 3937 IsModified = true; 3938 } 3939 } 3940 if (IsModified) 3941 CurDAG->RemoveDeadNodes(); 3942 } while (IsModified); 3943 } 3944 3945 // Gather the set of 32-bit operations that are known to have their 3946 // higher-order 32 bits zero, where ToPromote contains all such operations. 3947 static bool PeepholePPC64ZExtGather(SDValue Op32, 3948 SmallPtrSetImpl<SDNode *> &ToPromote) { 3949 if (!Op32.isMachineOpcode()) 3950 return false; 3951 3952 // First, check for the "frontier" instructions (those that will clear the 3953 // higher-order 32 bits. 3954 3955 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap 3956 // around. If it does not, then these instructions will clear the 3957 // higher-order bits. 3958 if ((Op32.getMachineOpcode() == PPC::RLWINM || 3959 Op32.getMachineOpcode() == PPC::RLWNM) && 3960 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) { 3961 ToPromote.insert(Op32.getNode()); 3962 return true; 3963 } 3964 3965 // SLW and SRW always clear the higher-order bits. 3966 if (Op32.getMachineOpcode() == PPC::SLW || 3967 Op32.getMachineOpcode() == PPC::SRW) { 3968 ToPromote.insert(Op32.getNode()); 3969 return true; 3970 } 3971 3972 // For LI and LIS, we need the immediate to be positive (so that it is not 3973 // sign extended). 3974 if (Op32.getMachineOpcode() == PPC::LI || 3975 Op32.getMachineOpcode() == PPC::LIS) { 3976 if (!isUInt<15>(Op32.getConstantOperandVal(0))) 3977 return false; 3978 3979 ToPromote.insert(Op32.getNode()); 3980 return true; 3981 } 3982 3983 // LHBRX and LWBRX always clear the higher-order bits. 3984 if (Op32.getMachineOpcode() == PPC::LHBRX || 3985 Op32.getMachineOpcode() == PPC::LWBRX) { 3986 ToPromote.insert(Op32.getNode()); 3987 return true; 3988 } 3989 3990 // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended. 3991 if (Op32.getMachineOpcode() == PPC::CNTLZW) { 3992 ToPromote.insert(Op32.getNode()); 3993 return true; 3994 } 3995 3996 // Next, check for those instructions we can look through. 3997 3998 // Assuming the mask does not wrap around, then the higher-order bits are 3999 // taken directly from the first operand. 4000 if (Op32.getMachineOpcode() == PPC::RLWIMI && 4001 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) { 4002 SmallPtrSet<SDNode *, 16> ToPromote1; 4003 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1)) 4004 return false; 4005 4006 ToPromote.insert(Op32.getNode()); 4007 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 4008 return true; 4009 } 4010 4011 // For OR, the higher-order bits are zero if that is true for both operands. 4012 // For SELECT_I4, the same is true (but the relevant operand numbers are 4013 // shifted by 1). 4014 if (Op32.getMachineOpcode() == PPC::OR || 4015 Op32.getMachineOpcode() == PPC::SELECT_I4) { 4016 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0; 4017 SmallPtrSet<SDNode *, 16> ToPromote1; 4018 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1)) 4019 return false; 4020 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1)) 4021 return false; 4022 4023 ToPromote.insert(Op32.getNode()); 4024 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 4025 return true; 4026 } 4027 4028 // For ORI and ORIS, we need the higher-order bits of the first operand to be 4029 // zero, and also for the constant to be positive (so that it is not sign 4030 // extended). 4031 if (Op32.getMachineOpcode() == PPC::ORI || 4032 Op32.getMachineOpcode() == PPC::ORIS) { 4033 SmallPtrSet<SDNode *, 16> ToPromote1; 4034 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1)) 4035 return false; 4036 if (!isUInt<15>(Op32.getConstantOperandVal(1))) 4037 return false; 4038 4039 ToPromote.insert(Op32.getNode()); 4040 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 4041 return true; 4042 } 4043 4044 // The higher-order bits of AND are zero if that is true for at least one of 4045 // the operands. 4046 if (Op32.getMachineOpcode() == PPC::AND) { 4047 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2; 4048 bool Op0OK = 4049 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1); 4050 bool Op1OK = 4051 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2); 4052 if (!Op0OK && !Op1OK) 4053 return false; 4054 4055 ToPromote.insert(Op32.getNode()); 4056 4057 if (Op0OK) 4058 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 4059 4060 if (Op1OK) 4061 ToPromote.insert(ToPromote2.begin(), ToPromote2.end()); 4062 4063 return true; 4064 } 4065 4066 // For ANDI and ANDIS, the higher-order bits are zero if either that is true 4067 // of the first operand, or if the second operand is positive (so that it is 4068 // not sign extended). 4069 if (Op32.getMachineOpcode() == PPC::ANDIo || 4070 Op32.getMachineOpcode() == PPC::ANDISo) { 4071 SmallPtrSet<SDNode *, 16> ToPromote1; 4072 bool Op0OK = 4073 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1); 4074 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1)); 4075 if (!Op0OK && !Op1OK) 4076 return false; 4077 4078 ToPromote.insert(Op32.getNode()); 4079 4080 if (Op0OK) 4081 ToPromote.insert(ToPromote1.begin(), ToPromote1.end()); 4082 4083 return true; 4084 } 4085 4086 return false; 4087 } 4088 4089 void PPCDAGToDAGISel::PeepholePPC64ZExt() { 4090 if (!PPCSubTarget->isPPC64()) 4091 return; 4092 4093 // When we zero-extend from i32 to i64, we use a pattern like this: 4094 // def : Pat<(i64 (zext i32:$in)), 4095 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32), 4096 // 0, 32)>; 4097 // There are several 32-bit shift/rotate instructions, however, that will 4098 // clear the higher-order bits of their output, rendering the RLDICL 4099 // unnecessary. When that happens, we remove it here, and redefine the 4100 // relevant 32-bit operation to be a 64-bit operation. 4101 4102 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode()); 4103 ++Position; 4104 4105 bool MadeChange = false; 4106 while (Position != CurDAG->allnodes_begin()) { 4107 SDNode *N = &*--Position; 4108 // Skip dead nodes and any non-machine opcodes. 4109 if (N->use_empty() || !N->isMachineOpcode()) 4110 continue; 4111 4112 if (N->getMachineOpcode() != PPC::RLDICL) 4113 continue; 4114 4115 if (N->getConstantOperandVal(1) != 0 || 4116 N->getConstantOperandVal(2) != 32) 4117 continue; 4118 4119 SDValue ISR = N->getOperand(0); 4120 if (!ISR.isMachineOpcode() || 4121 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG) 4122 continue; 4123 4124 if (!ISR.hasOneUse()) 4125 continue; 4126 4127 if (ISR.getConstantOperandVal(2) != PPC::sub_32) 4128 continue; 4129 4130 SDValue IDef = ISR.getOperand(0); 4131 if (!IDef.isMachineOpcode() || 4132 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF) 4133 continue; 4134 4135 // We now know that we're looking at a canonical i32 -> i64 zext. See if we 4136 // can get rid of it. 4137 4138 SDValue Op32 = ISR->getOperand(1); 4139 if (!Op32.isMachineOpcode()) 4140 continue; 4141 4142 // There are some 32-bit instructions that always clear the high-order 32 4143 // bits, there are also some instructions (like AND) that we can look 4144 // through. 4145 SmallPtrSet<SDNode *, 16> ToPromote; 4146 if (!PeepholePPC64ZExtGather(Op32, ToPromote)) 4147 continue; 4148 4149 // If the ToPromote set contains nodes that have uses outside of the set 4150 // (except for the original INSERT_SUBREG), then abort the transformation. 4151 bool OutsideUse = false; 4152 for (SDNode *PN : ToPromote) { 4153 for (SDNode *UN : PN->uses()) { 4154 if (!ToPromote.count(UN) && UN != ISR.getNode()) { 4155 OutsideUse = true; 4156 break; 4157 } 4158 } 4159 4160 if (OutsideUse) 4161 break; 4162 } 4163 if (OutsideUse) 4164 continue; 4165 4166 MadeChange = true; 4167 4168 // We now know that this zero extension can be removed by promoting to 4169 // nodes in ToPromote to 64-bit operations, where for operations in the 4170 // frontier of the set, we need to insert INSERT_SUBREGs for their 4171 // operands. 4172 for (SDNode *PN : ToPromote) { 4173 unsigned NewOpcode; 4174 switch (PN->getMachineOpcode()) { 4175 default: 4176 llvm_unreachable("Don't know the 64-bit variant of this instruction"); 4177 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break; 4178 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break; 4179 case PPC::SLW: NewOpcode = PPC::SLW8; break; 4180 case PPC::SRW: NewOpcode = PPC::SRW8; break; 4181 case PPC::LI: NewOpcode = PPC::LI8; break; 4182 case PPC::LIS: NewOpcode = PPC::LIS8; break; 4183 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break; 4184 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break; 4185 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break; 4186 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break; 4187 case PPC::OR: NewOpcode = PPC::OR8; break; 4188 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break; 4189 case PPC::ORI: NewOpcode = PPC::ORI8; break; 4190 case PPC::ORIS: NewOpcode = PPC::ORIS8; break; 4191 case PPC::AND: NewOpcode = PPC::AND8; break; 4192 case PPC::ANDIo: NewOpcode = PPC::ANDIo8; break; 4193 case PPC::ANDISo: NewOpcode = PPC::ANDISo8; break; 4194 } 4195 4196 // Note: During the replacement process, the nodes will be in an 4197 // inconsistent state (some instructions will have operands with values 4198 // of the wrong type). Once done, however, everything should be right 4199 // again. 4200 4201 SmallVector<SDValue, 4> Ops; 4202 for (const SDValue &V : PN->ops()) { 4203 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 && 4204 !isa<ConstantSDNode>(V)) { 4205 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) }; 4206 SDNode *ReplOp = 4207 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V), 4208 ISR.getNode()->getVTList(), ReplOpOps); 4209 Ops.push_back(SDValue(ReplOp, 0)); 4210 } else { 4211 Ops.push_back(V); 4212 } 4213 } 4214 4215 // Because all to-be-promoted nodes only have users that are other 4216 // promoted nodes (or the original INSERT_SUBREG), we can safely replace 4217 // the i32 result value type with i64. 4218 4219 SmallVector<EVT, 2> NewVTs; 4220 SDVTList VTs = PN->getVTList(); 4221 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i) 4222 if (VTs.VTs[i] == MVT::i32) 4223 NewVTs.push_back(MVT::i64); 4224 else 4225 NewVTs.push_back(VTs.VTs[i]); 4226 4227 DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: "); 4228 DEBUG(PN->dump(CurDAG)); 4229 4230 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops); 4231 4232 DEBUG(dbgs() << "\nNew: "); 4233 DEBUG(PN->dump(CurDAG)); 4234 DEBUG(dbgs() << "\n"); 4235 } 4236 4237 // Now we replace the original zero extend and its associated INSERT_SUBREG 4238 // with the value feeding the INSERT_SUBREG (which has now been promoted to 4239 // return an i64). 4240 4241 DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: "); 4242 DEBUG(N->dump(CurDAG)); 4243 DEBUG(dbgs() << "\nNew: "); 4244 DEBUG(Op32.getNode()->dump(CurDAG)); 4245 DEBUG(dbgs() << "\n"); 4246 4247 ReplaceUses(N, Op32.getNode()); 4248 } 4249 4250 if (MadeChange) 4251 CurDAG->RemoveDeadNodes(); 4252 } 4253 4254 void PPCDAGToDAGISel::PeepholePPC64() { 4255 // These optimizations are currently supported only for 64-bit SVR4. 4256 if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64()) 4257 return; 4258 4259 SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode()); 4260 ++Position; 4261 4262 while (Position != CurDAG->allnodes_begin()) { 4263 SDNode *N = &*--Position; 4264 // Skip dead nodes and any non-machine opcodes. 4265 if (N->use_empty() || !N->isMachineOpcode()) 4266 continue; 4267 4268 unsigned FirstOp; 4269 unsigned StorageOpcode = N->getMachineOpcode(); 4270 4271 switch (StorageOpcode) { 4272 default: continue; 4273 4274 case PPC::LBZ: 4275 case PPC::LBZ8: 4276 case PPC::LD: 4277 case PPC::LFD: 4278 case PPC::LFS: 4279 case PPC::LHA: 4280 case PPC::LHA8: 4281 case PPC::LHZ: 4282 case PPC::LHZ8: 4283 case PPC::LWA: 4284 case PPC::LWZ: 4285 case PPC::LWZ8: 4286 FirstOp = 0; 4287 break; 4288 4289 case PPC::STB: 4290 case PPC::STB8: 4291 case PPC::STD: 4292 case PPC::STFD: 4293 case PPC::STFS: 4294 case PPC::STH: 4295 case PPC::STH8: 4296 case PPC::STW: 4297 case PPC::STW8: 4298 FirstOp = 1; 4299 break; 4300 } 4301 4302 // If this is a load or store with a zero offset, or within the alignment, 4303 // we may be able to fold an add-immediate into the memory operation. 4304 // The check against alignment is below, as it can't occur until we check 4305 // the arguments to N 4306 if (!isa<ConstantSDNode>(N->getOperand(FirstOp))) 4307 continue; 4308 4309 SDValue Base = N->getOperand(FirstOp + 1); 4310 if (!Base.isMachineOpcode()) 4311 continue; 4312 4313 // On targets with fusion, we don't want this to fire and remove a fusion 4314 // opportunity, unless a) it results in another fusion opportunity or 4315 // b) optimizing for size. 4316 if (PPCSubTarget->hasFusion() && 4317 (!MF->getFunction()->optForSize() && !Base.hasOneUse())) 4318 continue; 4319 4320 unsigned Flags = 0; 4321 bool ReplaceFlags = true; 4322 4323 // When the feeding operation is an add-immediate of some sort, 4324 // determine whether we need to add relocation information to the 4325 // target flags on the immediate operand when we fold it into the 4326 // load instruction. 4327 // 4328 // For something like ADDItocL, the relocation information is 4329 // inferred from the opcode; when we process it in the AsmPrinter, 4330 // we add the necessary relocation there. A load, though, can receive 4331 // relocation from various flavors of ADDIxxx, so we need to carry 4332 // the relocation information in the target flags. 4333 switch (Base.getMachineOpcode()) { 4334 default: continue; 4335 4336 case PPC::ADDI8: 4337 case PPC::ADDI: 4338 // In some cases (such as TLS) the relocation information 4339 // is already in place on the operand, so copying the operand 4340 // is sufficient. 4341 ReplaceFlags = false; 4342 // For these cases, the immediate may not be divisible by 4, in 4343 // which case the fold is illegal for DS-form instructions. (The 4344 // other cases provide aligned addresses and are always safe.) 4345 if ((StorageOpcode == PPC::LWA || 4346 StorageOpcode == PPC::LD || 4347 StorageOpcode == PPC::STD) && 4348 (!isa<ConstantSDNode>(Base.getOperand(1)) || 4349 Base.getConstantOperandVal(1) % 4 != 0)) 4350 continue; 4351 break; 4352 case PPC::ADDIdtprelL: 4353 Flags = PPCII::MO_DTPREL_LO; 4354 break; 4355 case PPC::ADDItlsldL: 4356 Flags = PPCII::MO_TLSLD_LO; 4357 break; 4358 case PPC::ADDItocL: 4359 Flags = PPCII::MO_TOC_LO; 4360 break; 4361 } 4362 4363 SDValue ImmOpnd = Base.getOperand(1); 4364 int MaxDisplacement = 0; 4365 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) { 4366 const GlobalValue *GV = GA->getGlobal(); 4367 MaxDisplacement = GV->getAlignment() - 1; 4368 } 4369 4370 int Offset = N->getConstantOperandVal(FirstOp); 4371 if (Offset < 0 || Offset > MaxDisplacement) 4372 continue; 4373 4374 // We found an opportunity. Reverse the operands from the add 4375 // immediate and substitute them into the load or store. If 4376 // needed, update the target flags for the immediate operand to 4377 // reflect the necessary relocation information. 4378 DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: "); 4379 DEBUG(Base->dump(CurDAG)); 4380 DEBUG(dbgs() << "\nN: "); 4381 DEBUG(N->dump(CurDAG)); 4382 DEBUG(dbgs() << "\n"); 4383 4384 // If the relocation information isn't already present on the 4385 // immediate operand, add it now. 4386 if (ReplaceFlags) { 4387 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) { 4388 SDLoc dl(GA); 4389 const GlobalValue *GV = GA->getGlobal(); 4390 // We can't perform this optimization for data whose alignment 4391 // is insufficient for the instruction encoding. 4392 if (GV->getAlignment() < 4 && 4393 (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD || 4394 StorageOpcode == PPC::LWA || (Offset % 4) != 0)) { 4395 DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n"); 4396 continue; 4397 } 4398 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags); 4399 } else if (ConstantPoolSDNode *CP = 4400 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) { 4401 const Constant *C = CP->getConstVal(); 4402 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64, 4403 CP->getAlignment(), 4404 Offset, Flags); 4405 } 4406 } 4407 4408 if (FirstOp == 1) // Store 4409 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd, 4410 Base.getOperand(0), N->getOperand(3)); 4411 else // Load 4412 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0), 4413 N->getOperand(2)); 4414 4415 // The add-immediate may now be dead, in which case remove it. 4416 if (Base.getNode()->use_empty()) 4417 CurDAG->RemoveDeadNode(Base.getNode()); 4418 } 4419 } 4420 4421 4422 /// createPPCISelDag - This pass converts a legalized DAG into a 4423 /// PowerPC-specific DAG, ready for instruction scheduling. 4424 /// 4425 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) { 4426 return new PPCDAGToDAGISel(TM); 4427 } 4428