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