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