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