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