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