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