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