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