1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file defines a pattern matching instruction selector for PowerPC,
10 // converting from a legalized dag to a PPC dag.
12 //===----------------------------------------------------------------------===//
14 #include "MCTargetDesc/PPCMCTargetDesc.h"
15 #include "MCTargetDesc/PPCPredicates.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/APSInt.h"
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallPtrSet.h"
26 #include "llvm/ADT/SmallVector.h"
27 #include "llvm/ADT/Statistic.h"
28 #include "llvm/Analysis/BranchProbabilityInfo.h"
29 #include "llvm/CodeGen/FunctionLoweringInfo.h"
30 #include "llvm/CodeGen/ISDOpcodes.h"
31 #include "llvm/CodeGen/MachineBasicBlock.h"
32 #include "llvm/CodeGen/MachineFrameInfo.h"
33 #include "llvm/CodeGen/MachineFunction.h"
34 #include "llvm/CodeGen/MachineInstrBuilder.h"
35 #include "llvm/CodeGen/MachineRegisterInfo.h"
36 #include "llvm/CodeGen/MachineValueType.h"
37 #include "llvm/CodeGen/SelectionDAG.h"
38 #include "llvm/CodeGen/SelectionDAGISel.h"
39 #include "llvm/CodeGen/SelectionDAGNodes.h"
40 #include "llvm/CodeGen/TargetInstrInfo.h"
41 #include "llvm/CodeGen/TargetRegisterInfo.h"
42 #include "llvm/CodeGen/ValueTypes.h"
43 #include "llvm/IR/BasicBlock.h"
44 #include "llvm/IR/DebugLoc.h"
45 #include "llvm/IR/Function.h"
46 #include "llvm/IR/GlobalValue.h"
47 #include "llvm/IR/InlineAsm.h"
48 #include "llvm/IR/InstrTypes.h"
49 #include "llvm/IR/IntrinsicsPowerPC.h"
50 #include "llvm/IR/Module.h"
51 #include "llvm/Support/Casting.h"
52 #include "llvm/Support/CodeGen.h"
53 #include "llvm/Support/CommandLine.h"
54 #include "llvm/Support/Compiler.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/ErrorHandling.h"
57 #include "llvm/Support/KnownBits.h"
58 #include "llvm/Support/MathExtras.h"
59 #include "llvm/Support/raw_ostream.h"
72 #define DEBUG_TYPE "ppc-isel"
73 #define PASS_NAME "PowerPC DAG->DAG Pattern Instruction Selection"
75 STATISTIC(NumSextSetcc,
76 "Number of (sext(setcc)) nodes expanded into GPR sequence.");
77 STATISTIC(NumZextSetcc,
78 "Number of (zext(setcc)) nodes expanded into GPR sequence.");
79 STATISTIC(SignExtensionsAdded,
80 "Number of sign extensions for compare inputs added.");
81 STATISTIC(ZeroExtensionsAdded,
82 "Number of zero extensions for compare inputs added.");
83 STATISTIC(NumLogicOpsOnComparison,
84 "Number of logical ops on i1 values calculated in GPR.");
85 STATISTIC(OmittedForNonExtendUses,
86 "Number of compares not eliminated as they have non-extending uses.");
88 "Number of compares lowered to setb.");
90 // FIXME: Remove this once the bug has been fixed!
91 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
92 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
95 UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
96 cl::desc("use aggressive ppc isel for bit permutations"),
98 static cl::opt<bool> BPermRewriterNoMasking(
99 "ppc-bit-perm-rewriter-stress-rotates",
100 cl::desc("stress rotate selection in aggressive ppc isel for "
104 static cl::opt<bool> EnableBranchHint(
105 "ppc-use-branch-hint", cl::init(true),
106 cl::desc("Enable static hinting of branches on ppc"),
109 static cl::opt<bool> EnableTLSOpt(
110 "ppc-tls-opt", cl::init(true),
111 cl::desc("Enable tls optimization peephole"),
114 enum ICmpInGPRType { ICGPR_All, ICGPR_None, ICGPR_I32, ICGPR_I64,
115 ICGPR_NonExtIn, ICGPR_Zext, ICGPR_Sext, ICGPR_ZextI32,
116 ICGPR_SextI32, ICGPR_ZextI64, ICGPR_SextI64 };
118 static cl::opt<ICmpInGPRType> CmpInGPR(
119 "ppc-gpr-icmps", cl::Hidden, cl::init(ICGPR_All),
120 cl::desc("Specify the types of comparisons to emit GPR-only code for."),
121 cl::values(clEnumValN(ICGPR_None, "none", "Do not modify integer comparisons."),
122 clEnumValN(ICGPR_All, "all", "All possible int comparisons in GPRs."),
123 clEnumValN(ICGPR_I32, "i32", "Only i32 comparisons in GPRs."),
124 clEnumValN(ICGPR_I64, "i64", "Only i64 comparisons in GPRs."),
125 clEnumValN(ICGPR_NonExtIn, "nonextin",
126 "Only comparisons where inputs don't need [sz]ext."),
127 clEnumValN(ICGPR_Zext, "zext", "Only comparisons with zext result."),
128 clEnumValN(ICGPR_ZextI32, "zexti32",
129 "Only i32 comparisons with zext result."),
130 clEnumValN(ICGPR_ZextI64, "zexti64",
131 "Only i64 comparisons with zext result."),
132 clEnumValN(ICGPR_Sext, "sext", "Only comparisons with sext result."),
133 clEnumValN(ICGPR_SextI32, "sexti32",
134 "Only i32 comparisons with sext result."),
135 clEnumValN(ICGPR_SextI64, "sexti64",
136 "Only i64 comparisons with sext result.")));
139 //===--------------------------------------------------------------------===//
140 /// PPCDAGToDAGISel - PPC specific code to select PPC machine
141 /// instructions for SelectionDAG operations.
143 class PPCDAGToDAGISel : public SelectionDAGISel {
144 const PPCTargetMachine &TM;
145 const PPCSubtarget *Subtarget = nullptr;
146 const PPCTargetLowering *PPCLowering = nullptr;
147 unsigned GlobalBaseReg = 0;
152 PPCDAGToDAGISel() = delete;
154 explicit PPCDAGToDAGISel(PPCTargetMachine &tm, CodeGenOpt::Level OptLevel)
155 : SelectionDAGISel(ID, tm, OptLevel), TM(tm) {}
157 bool runOnMachineFunction(MachineFunction &MF) override {
158 // Make sure we re-emit a set of the global base reg if necessary
160 Subtarget = &MF.getSubtarget<PPCSubtarget>();
161 PPCLowering = Subtarget->getTargetLowering();
162 if (Subtarget->hasROPProtect()) {
163 // Create a place on the stack for the ROP Protection Hash.
164 // The ROP Protection Hash will always be 8 bytes and aligned to 8
166 MachineFrameInfo &MFI = MF.getFrameInfo();
167 PPCFunctionInfo *FI = MF.getInfo<PPCFunctionInfo>();
168 const int Result = MFI.CreateStackObject(8, Align(8), false);
169 FI->setROPProtectionHashSaveIndex(Result);
171 SelectionDAGISel::runOnMachineFunction(MF);
176 void PreprocessISelDAG() override;
177 void PostprocessISelDAG() override;
179 /// getI16Imm - Return a target constant with the specified value, of type
181 inline SDValue getI16Imm(unsigned Imm, const SDLoc &dl) {
182 return CurDAG->getTargetConstant(Imm, dl, MVT::i16);
185 /// getI32Imm - Return a target constant with the specified value, of type
187 inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
188 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
191 /// getI64Imm - Return a target constant with the specified value, of type
193 inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) {
194 return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
197 /// getSmallIPtrImm - Return a target constant of pointer type.
198 inline SDValue getSmallIPtrImm(uint64_t Imm, const SDLoc &dl) {
199 return CurDAG->getTargetConstant(
200 Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));
203 /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
204 /// rotate and mask opcode and mask operation.
205 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
206 unsigned &SH, unsigned &MB, unsigned &ME);
208 /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
209 /// base register. Return the virtual register that holds this value.
210 SDNode *getGlobalBaseReg();
212 void selectFrameIndex(SDNode *SN, SDNode *N, uint64_t Offset = 0);
214 // Select - Convert the specified operand from a target-independent to a
215 // target-specific node if it hasn't already been changed.
216 void Select(SDNode *N) override;
218 bool tryBitfieldInsert(SDNode *N);
219 bool tryBitPermutation(SDNode *N);
220 bool tryIntCompareInGPR(SDNode *N);
222 // tryTLSXFormLoad - Convert an ISD::LOAD fed by a PPCISD::ADD_TLS into
223 // an X-Form load instruction with the offset being a relocation coming from
224 // the PPCISD::ADD_TLS.
225 bool tryTLSXFormLoad(LoadSDNode *N);
226 // tryTLSXFormStore - Convert an ISD::STORE fed by a PPCISD::ADD_TLS into
227 // an X-Form store instruction with the offset being a relocation coming from
228 // the PPCISD::ADD_TLS.
229 bool tryTLSXFormStore(StoreSDNode *N);
230 /// SelectCC - Select a comparison of the specified values with the
231 /// specified condition code, returning the CR# of the expression.
232 SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
233 const SDLoc &dl, SDValue Chain = SDValue());
235 /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
236 /// immediate field. Note that the operand at this point is already the
237 /// result of a prior SelectAddressRegImm call.
238 bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
239 if (N.getOpcode() == ISD::TargetConstant ||
240 N.getOpcode() == ISD::TargetGlobalAddress) {
248 /// SelectDSForm - Returns true if address N can be represented by the
249 /// addressing mode of DSForm instructions (a base register, plus a signed
250 /// 16-bit displacement that is a multiple of 4.
251 bool SelectDSForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {
252 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,
253 Align(4)) == PPC::AM_DSForm;
256 /// SelectDQForm - Returns true if address N can be represented by the
257 /// addressing mode of DQForm instructions (a base register, plus a signed
258 /// 16-bit displacement that is a multiple of 16.
259 bool SelectDQForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {
260 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,
261 Align(16)) == PPC::AM_DQForm;
264 /// SelectDForm - Returns true if address N can be represented by
265 /// the addressing mode of DForm instructions (a base register, plus a
266 /// signed 16-bit immediate.
267 bool SelectDForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {
268 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,
269 std::nullopt) == PPC::AM_DForm;
272 /// SelectPCRelForm - Returns true if address N can be represented by
273 /// PC-Relative addressing mode.
274 bool SelectPCRelForm(SDNode *Parent, SDValue N, SDValue &Disp,
276 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,
277 std::nullopt) == PPC::AM_PCRel;
280 /// SelectPDForm - Returns true if address N can be represented by Prefixed
281 /// DForm addressing mode (a base register, plus a signed 34-bit immediate.
282 bool SelectPDForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {
283 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,
288 /// SelectXForm - Returns true if address N can be represented by the
289 /// addressing mode of XForm instructions (an indexed [r+r] operation).
290 bool SelectXForm(SDNode *Parent, SDValue N, SDValue &Disp, SDValue &Base) {
291 return PPCLowering->SelectOptimalAddrMode(Parent, N, Disp, Base, *CurDAG,
292 std::nullopt) == PPC::AM_XForm;
295 /// SelectForceXForm - Given the specified address, force it to be
296 /// represented as an indexed [r+r] operation (an XForm instruction).
297 bool SelectForceXForm(SDNode *Parent, SDValue N, SDValue &Disp,
299 return PPCLowering->SelectForceXFormMode(N, Disp, Base, *CurDAG) ==
303 /// SelectAddrIdx - Given the specified address, check to see if it can be
304 /// represented as an indexed [r+r] operation.
305 /// This is for xform instructions whose associated displacement form is D.
306 /// The last parameter \p 0 means associated D form has no requirment for 16
307 /// bit signed displacement.
308 /// Returns false if it can be represented by [r+imm], which are preferred.
309 bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
310 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG,
314 /// SelectAddrIdx4 - Given the specified address, check to see if it can be
315 /// represented as an indexed [r+r] operation.
316 /// This is for xform instructions whose associated displacement form is DS.
317 /// The last parameter \p 4 means associated DS form 16 bit signed
318 /// displacement must be a multiple of 4.
319 /// Returns false if it can be represented by [r+imm], which are preferred.
320 bool SelectAddrIdxX4(SDValue N, SDValue &Base, SDValue &Index) {
321 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG,
325 /// SelectAddrIdx16 - Given the specified address, check to see if it can be
326 /// represented as an indexed [r+r] operation.
327 /// This is for xform instructions whose associated displacement form is DQ.
328 /// The last parameter \p 16 means associated DQ form 16 bit signed
329 /// displacement must be a multiple of 16.
330 /// Returns false if it can be represented by [r+imm], which are preferred.
331 bool SelectAddrIdxX16(SDValue N, SDValue &Base, SDValue &Index) {
332 return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG,
336 /// SelectAddrIdxOnly - Given the specified address, force it to be
337 /// represented as an indexed [r+r] operation.
338 bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
339 return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
342 /// SelectAddrImm - Returns true if the address N can be represented by
343 /// a base register plus a signed 16-bit displacement [r+imm].
344 /// The last parameter \p 0 means D form has no requirment for 16 bit signed
346 bool SelectAddrImm(SDValue N, SDValue &Disp,
348 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG,
352 /// SelectAddrImmX4 - Returns true if the address N can be represented by
353 /// a base register plus a signed 16-bit displacement that is a multiple of
354 /// 4 (last parameter). Suitable for use by STD and friends.
355 bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
356 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, Align(4));
359 /// SelectAddrImmX16 - Returns true if the address N can be represented by
360 /// a base register plus a signed 16-bit displacement that is a multiple of
361 /// 16(last parameter). Suitable for use by STXV and friends.
362 bool SelectAddrImmX16(SDValue N, SDValue &Disp, SDValue &Base) {
363 return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG,
367 /// SelectAddrImmX34 - Returns true if the address N can be represented by
368 /// a base register plus a signed 34-bit displacement. Suitable for use by
369 /// PSTXVP and friends.
370 bool SelectAddrImmX34(SDValue N, SDValue &Disp, SDValue &Base) {
371 return PPCLowering->SelectAddressRegImm34(N, Disp, Base, *CurDAG);
374 // Select an address into a single register.
375 bool SelectAddr(SDValue N, SDValue &Base) {
380 bool SelectAddrPCRel(SDValue N, SDValue &Base) {
381 return PPCLowering->SelectAddressPCRel(N, Base);
384 /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
385 /// inline asm expressions. It is always correct to compute the value into
386 /// a register. The case of adding a (possibly relocatable) constant to a
387 /// register can be improved, but it is wrong to substitute Reg+Reg for
388 /// Reg in an asm, because the load or store opcode would have to change.
389 bool SelectInlineAsmMemoryOperand(const SDValue &Op,
390 unsigned ConstraintID,
391 std::vector<SDValue> &OutOps) override {
392 switch(ConstraintID) {
394 errs() << "ConstraintID: " << ConstraintID << "\n";
395 llvm_unreachable("Unexpected asm memory constraint");
396 case InlineAsm::Constraint_es:
397 case InlineAsm::Constraint_m:
398 case InlineAsm::Constraint_o:
399 case InlineAsm::Constraint_Q:
400 case InlineAsm::Constraint_Z:
401 case InlineAsm::Constraint_Zy:
402 // We need to make sure that this one operand does not end up in r0
403 // (because we might end up lowering this as 0(%op)).
404 const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
405 const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
407 SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
409 SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
410 dl, Op.getValueType(),
413 OutOps.push_back(NewOp);
419 // Include the pieces autogenerated from the target description.
420 #include "PPCGenDAGISel.inc"
423 bool trySETCC(SDNode *N);
424 bool tryFoldSWTestBRCC(SDNode *N);
425 bool trySelectLoopCountIntrinsic(SDNode *N);
426 bool tryAsSingleRLDICL(SDNode *N);
427 bool tryAsSingleRLDICR(SDNode *N);
428 bool tryAsSingleRLWINM(SDNode *N);
429 bool tryAsSingleRLWINM8(SDNode *N);
430 bool tryAsSingleRLWIMI(SDNode *N);
431 bool tryAsPairOfRLDICL(SDNode *N);
432 bool tryAsSingleRLDIMI(SDNode *N);
434 void PeepholePPC64();
435 void PeepholePPC64ZExt();
436 void PeepholeCROps();
438 SDValue combineToCMPB(SDNode *N);
439 void foldBoolExts(SDValue &Res, SDNode *&N);
441 bool AllUsersSelectZero(SDNode *N);
442 void SwapAllSelectUsers(SDNode *N);
444 bool isOffsetMultipleOf(SDNode *N, unsigned Val) const;
445 void transferMemOperands(SDNode *N, SDNode *Result);
448 } // end anonymous namespace
450 char PPCDAGToDAGISel::ID = 0;
452 INITIALIZE_PASS(PPCDAGToDAGISel, DEBUG_TYPE, PASS_NAME, false, false)
454 /// getGlobalBaseReg - Output the instructions required to put the
455 /// base address to use for accessing globals into a register.
457 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
458 if (!GlobalBaseReg) {
459 const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
460 // Insert the set of GlobalBaseReg into the first MBB of the function
461 MachineBasicBlock &FirstMBB = MF->front();
462 MachineBasicBlock::iterator MBBI = FirstMBB.begin();
463 const Module *M = MF->getFunction().getParent();
466 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
467 if (Subtarget->isTargetELF()) {
468 GlobalBaseReg = PPC::R30;
469 if (!Subtarget->isSecurePlt() &&
470 M->getPICLevel() == PICLevel::SmallPIC) {
471 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
472 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
473 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
475 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
476 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
477 Register TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
478 BuildMI(FirstMBB, MBBI, dl,
479 TII.get(PPC::UpdateGBR), GlobalBaseReg)
480 .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
481 MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
485 RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass);
486 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
487 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
490 // We must ensure that this sequence is dominated by the prologue.
491 // FIXME: This is a bit of a big hammer since we don't get the benefits
492 // of shrink-wrapping whenever we emit this instruction. Considering
493 // this is used in any function where we emit a jump table, this may be
494 // a significant limitation. We should consider inserting this in the
495 // block where it is used and then commoning this sequence up if it
496 // appears in multiple places.
497 // Note: on ISA 3.0 cores, we can use lnia (addpcis) instead of
499 MF->getInfo<PPCFunctionInfo>()->setShrinkWrapDisabled(true);
500 GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
501 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
502 BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
505 return CurDAG->getRegister(GlobalBaseReg,
506 PPCLowering->getPointerTy(CurDAG->getDataLayout()))
510 // Check if a SDValue has the toc-data attribute.
511 static bool hasTocDataAttr(SDValue Val, unsigned PointerSize) {
512 GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Val);
516 const GlobalVariable *GV = dyn_cast_or_null<GlobalVariable>(GA->getGlobal());
520 if (!GV->hasAttribute("toc-data"))
523 // TODO: These asserts should be updated as more support for the toc data
524 // transformation is added (struct support, etc.).
527 PointerSize >= GV->getAlign().valueOrOne().value() &&
528 "GlobalVariables with an alignment requirement stricter than TOC entry "
529 "size not supported by the toc data transformation.");
531 Type *GVType = GV->getValueType();
533 assert(GVType->isSized() && "A GlobalVariable's size must be known to be "
534 "supported by the toc data transformation.");
536 if (GVType->isVectorTy())
537 report_fatal_error("A GlobalVariable of Vector type is not currently "
538 "supported by the toc data transformation.");
540 if (GVType->isArrayTy())
541 report_fatal_error("A GlobalVariable of Array type is not currently "
542 "supported by the toc data transformation.");
544 if (GVType->isStructTy())
545 report_fatal_error("A GlobalVariable of Struct type is not currently "
546 "supported by the toc data transformation.");
548 assert(GVType->getPrimitiveSizeInBits() <= PointerSize * 8 &&
549 "A GlobalVariable with size larger than a TOC entry is not currently "
550 "supported by the toc data transformation.");
552 if (GV->hasLocalLinkage() || GV->hasPrivateLinkage())
553 report_fatal_error("A GlobalVariable with private or local linkage is not "
554 "currently supported by the toc data transformation.");
556 assert(!GV->hasCommonLinkage() &&
557 "Tentative definitions cannot have the mapping class XMC_TD.");
562 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
563 /// operand. If so Imm will receive the 32-bit value.
564 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
565 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
566 Imm = cast<ConstantSDNode>(N)->getZExtValue();
572 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
573 /// operand. If so Imm will receive the 64-bit value.
574 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
575 if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
576 Imm = cast<ConstantSDNode>(N)->getZExtValue();
582 // isInt32Immediate - This method tests to see if a constant operand.
583 // If so Imm will receive the 32 bit value.
584 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
585 return isInt32Immediate(N.getNode(), Imm);
588 /// isInt64Immediate - This method tests to see if the value is a 64-bit
589 /// constant operand. If so Imm will receive the 64-bit value.
590 static bool isInt64Immediate(SDValue N, uint64_t &Imm) {
591 return isInt64Immediate(N.getNode(), Imm);
594 static unsigned getBranchHint(unsigned PCC,
595 const FunctionLoweringInfo &FuncInfo,
596 const SDValue &DestMBB) {
597 assert(isa<BasicBlockSDNode>(DestMBB));
599 if (!FuncInfo.BPI) return PPC::BR_NO_HINT;
601 const BasicBlock *BB = FuncInfo.MBB->getBasicBlock();
602 const Instruction *BBTerm = BB->getTerminator();
604 if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;
606 const BasicBlock *TBB = BBTerm->getSuccessor(0);
607 const BasicBlock *FBB = BBTerm->getSuccessor(1);
609 auto TProb = FuncInfo.BPI->getEdgeProbability(BB, TBB);
610 auto FProb = FuncInfo.BPI->getEdgeProbability(BB, FBB);
612 // We only want to handle cases which are easy to predict at static time, e.g.
613 // C++ throw statement, that is very likely not taken, or calling never
614 // returned function, e.g. stdlib exit(). So we set Threshold to filter
617 // Below is LLVM branch weight table, we only want to handle case 1, 2
619 // Case Taken:Nontaken Example
620 // 1. Unreachable 1048575:1 C++ throw, stdlib exit(),
621 // 2. Invoke-terminating 1:1048575
622 // 3. Coldblock 4:64 __builtin_expect
623 // 4. Loop Branch 124:4 For loop
624 // 5. PH/ZH/FPH 20:12
625 const uint32_t Threshold = 10000;
627 if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))
628 return PPC::BR_NO_HINT;
630 LLVM_DEBUG(dbgs() << "Use branch hint for '" << FuncInfo.Fn->getName()
631 << "::" << BB->getName() << "'\n"
632 << " -> " << TBB->getName() << ": " << TProb << "\n"
633 << " -> " << FBB->getName() << ": " << FProb << "\n");
635 const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB);
637 // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
638 // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
639 if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
640 std::swap(TProb, FProb);
642 return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
645 // isOpcWithIntImmediate - This method tests to see if the node is a specific
646 // opcode and that it has a immediate integer right operand.
647 // If so Imm will receive the 32 bit value.
648 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
649 return N->getOpcode() == Opc
650 && isInt32Immediate(N->getOperand(1).getNode(), Imm);
653 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, uint64_t Offset) {
655 int FI = cast<FrameIndexSDNode>(N)->getIndex();
656 SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
657 unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
659 CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
660 getSmallIPtrImm(Offset, dl));
662 ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
663 getSmallIPtrImm(Offset, dl)));
666 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
667 bool isShiftMask, unsigned &SH,
668 unsigned &MB, unsigned &ME) {
669 // Don't even go down this path for i64, since different logic will be
670 // necessary for rldicl/rldicr/rldimi.
671 if (N->getValueType(0) != MVT::i32)
675 unsigned Indeterminant = ~0; // bit mask marking indeterminant results
676 unsigned Opcode = N->getOpcode();
677 if (N->getNumOperands() != 2 ||
678 !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
681 if (Opcode == ISD::SHL) {
682 // apply shift left to mask if it comes first
683 if (isShiftMask) Mask = Mask << Shift;
684 // determine which bits are made indeterminant by shift
685 Indeterminant = ~(0xFFFFFFFFu << Shift);
686 } else if (Opcode == ISD::SRL) {
687 // apply shift right to mask if it comes first
688 if (isShiftMask) Mask = Mask >> Shift;
689 // determine which bits are made indeterminant by shift
690 Indeterminant = ~(0xFFFFFFFFu >> Shift);
691 // adjust for the left rotate
693 } else if (Opcode == ISD::ROTL) {
699 // if the mask doesn't intersect any Indeterminant bits
700 if (Mask && !(Mask & Indeterminant)) {
702 // make sure the mask is still a mask (wrap arounds may not be)
703 return isRunOfOnes(Mask, MB, ME);
708 // isThreadPointerAcquisitionNode - Check if the operands of an ADD_TLS
709 // instruction use the thread pointer.
710 static bool isThreadPointerAcquisitionNode(SDValue Base, SelectionDAG *CurDAG) {
712 Base.getOpcode() == PPCISD::ADD_TLS &&
713 "Only expecting the ADD_TLS instruction to acquire the thread pointer!");
714 const PPCSubtarget &Subtarget =
715 CurDAG->getMachineFunction().getSubtarget<PPCSubtarget>();
716 SDValue ADDTLSOp1 = Base.getOperand(0);
717 unsigned ADDTLSOp1Opcode = ADDTLSOp1.getOpcode();
719 // Account for when ADD_TLS is used for the initial-exec TLS model on Linux.
721 // Although ADD_TLS does not explicitly use the thread pointer
722 // register when LD_GOT_TPREL_L is one of it's operands, the LD_GOT_TPREL_L
723 // instruction will have a relocation specifier, @got@tprel, that is used to
724 // generate a GOT entry. The linker replaces this entry with an offset for a
725 // for a thread local variable, which will be relative to the thread pointer.
726 if (ADDTLSOp1Opcode == PPCISD::LD_GOT_TPREL_L)
728 // When using PC-Relative instructions for initial-exec, a MAT_PCREL_ADDR
729 // node is produced instead to represent the aforementioned situation.
730 LoadSDNode *LD = dyn_cast<LoadSDNode>(ADDTLSOp1);
731 if (LD && LD->getBasePtr().getOpcode() == PPCISD::MAT_PCREL_ADDR)
734 // A GET_TPOINTER PPCISD node (only produced on AIX 32-bit mode) as an operand
735 // to ADD_TLS represents a call to .__get_tpointer to get the thread pointer,
736 // later returning it into R3.
737 if (ADDTLSOp1Opcode == PPCISD::GET_TPOINTER)
740 // The ADD_TLS note is explicitly acquiring the thread pointer (X13/R13).
741 RegisterSDNode *AddFirstOpReg =
742 dyn_cast_or_null<RegisterSDNode>(ADDTLSOp1.getNode());
744 AddFirstOpReg->getReg() == Subtarget.getThreadPointerRegister())
750 // canOptimizeTLSDFormToXForm - Optimize TLS accesses when an ADD_TLS
751 // instruction is present. An ADD_TLS instruction, followed by a D-Form memory
752 // operation, can be optimized to use an X-Form load or store, allowing the
753 // ADD_TLS node to be removed completely.
754 static bool canOptimizeTLSDFormToXForm(SelectionDAG *CurDAG, SDValue Base) {
756 // Do not do this transformation at -O0.
757 if (CurDAG->getTarget().getOptLevel() == CodeGenOpt::None)
760 // In order to perform this optimization inside tryTLSXForm[Load|Store],
761 // Base is expected to be an ADD_TLS node.
762 if (Base.getOpcode() != PPCISD::ADD_TLS)
764 for (auto *ADDTLSUse : Base.getNode()->uses()) {
765 // The optimization to convert the D-Form load/store into its X-Form
766 // counterpart should only occur if the source value offset of the load/
767 // store is 0. This also means that The offset should always be undefined.
768 if (LoadSDNode *LD = dyn_cast<LoadSDNode>(ADDTLSUse)) {
769 if (LD->getSrcValueOffset() != 0 || !LD->getOffset().isUndef())
771 } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(ADDTLSUse)) {
772 if (ST->getSrcValueOffset() != 0 || !ST->getOffset().isUndef())
774 } else // Don't optimize if there are ADD_TLS users that aren't load/stores.
778 if (Base.getOperand(1).getOpcode() == PPCISD::TLS_LOCAL_EXEC_MAT_ADDR)
781 // Does the ADD_TLS node of the load/store use the thread pointer?
782 // If the thread pointer is not used as one of the operands of ADD_TLS,
783 // then this optimization is not valid.
784 return isThreadPointerAcquisitionNode(Base, CurDAG);
787 bool PPCDAGToDAGISel::tryTLSXFormStore(StoreSDNode *ST) {
788 SDValue Base = ST->getBasePtr();
789 if (!canOptimizeTLSDFormToXForm(CurDAG, Base))
793 EVT MemVT = ST->getMemoryVT();
794 EVT RegVT = ST->getValue().getValueType();
797 switch (MemVT.getSimpleVT().SimpleTy) {
801 Opcode = (RegVT == MVT::i32) ? PPC::STBXTLS_32 : PPC::STBXTLS;
805 Opcode = (RegVT == MVT::i32) ? PPC::STHXTLS_32 : PPC::STHXTLS;
809 Opcode = (RegVT == MVT::i32) ? PPC::STWXTLS_32 : PPC::STWXTLS;
813 Opcode = PPC::STDXTLS;
817 Opcode = PPC::STFSXTLS;
821 Opcode = PPC::STFDXTLS;
825 SDValue Chain = ST->getChain();
826 SDVTList VTs = ST->getVTList();
827 SDValue Ops[] = {ST->getValue(), Base.getOperand(0), Base.getOperand(1),
829 SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
830 transferMemOperands(ST, MN);
835 bool PPCDAGToDAGISel::tryTLSXFormLoad(LoadSDNode *LD) {
836 SDValue Base = LD->getBasePtr();
837 if (!canOptimizeTLSDFormToXForm(CurDAG, Base))
841 EVT MemVT = LD->getMemoryVT();
842 EVT RegVT = LD->getValueType(0);
843 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
845 switch (MemVT.getSimpleVT().SimpleTy) {
849 Opcode = (RegVT == MVT::i32) ? PPC::LBZXTLS_32 : PPC::LBZXTLS;
853 if (RegVT == MVT::i32)
854 Opcode = isSExt ? PPC::LHAXTLS_32 : PPC::LHZXTLS_32;
856 Opcode = isSExt ? PPC::LHAXTLS : PPC::LHZXTLS;
860 if (RegVT == MVT::i32)
861 Opcode = isSExt ? PPC::LWAXTLS_32 : PPC::LWZXTLS_32;
863 Opcode = isSExt ? PPC::LWAXTLS : PPC::LWZXTLS;
867 Opcode = PPC::LDXTLS;
871 Opcode = PPC::LFSXTLS;
875 Opcode = PPC::LFDXTLS;
879 SDValue Chain = LD->getChain();
880 SDVTList VTs = LD->getVTList();
881 SDValue Ops[] = {Base.getOperand(0), Base.getOperand(1), Chain};
882 SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
883 transferMemOperands(LD, MN);
888 /// Turn an or of two masked values into the rotate left word immediate then
889 /// mask insert (rlwimi) instruction.
890 bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) {
891 SDValue Op0 = N->getOperand(0);
892 SDValue Op1 = N->getOperand(1);
895 KnownBits LKnown = CurDAG->computeKnownBits(Op0);
896 KnownBits RKnown = CurDAG->computeKnownBits(Op1);
898 unsigned TargetMask = LKnown.Zero.getZExtValue();
899 unsigned InsertMask = RKnown.Zero.getZExtValue();
901 if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
902 unsigned Op0Opc = Op0.getOpcode();
903 unsigned Op1Opc = Op1.getOpcode();
904 unsigned Value, SH = 0;
905 TargetMask = ~TargetMask;
906 InsertMask = ~InsertMask;
908 // If the LHS has a foldable shift and the RHS does not, then swap it to the
909 // RHS so that we can fold the shift into the insert.
910 if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
911 if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
912 Op0.getOperand(0).getOpcode() == ISD::SRL) {
913 if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
914 Op1.getOperand(0).getOpcode() != ISD::SRL) {
916 std::swap(Op0Opc, Op1Opc);
917 std::swap(TargetMask, InsertMask);
920 } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
921 if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
922 Op1.getOperand(0).getOpcode() != ISD::SRL) {
924 std::swap(Op0Opc, Op1Opc);
925 std::swap(TargetMask, InsertMask);
930 if (isRunOfOnes(InsertMask, MB, ME)) {
931 if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
932 isInt32Immediate(Op1.getOperand(1), Value)) {
933 Op1 = Op1.getOperand(0);
934 SH = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
936 if (Op1Opc == ISD::AND) {
937 // The AND mask might not be a constant, and we need to make sure that
938 // if we're going to fold the masking with the insert, all bits not
939 // know to be zero in the mask are known to be one.
940 KnownBits MKnown = CurDAG->computeKnownBits(Op1.getOperand(1));
941 bool CanFoldMask = InsertMask == MKnown.One.getZExtValue();
943 unsigned SHOpc = Op1.getOperand(0).getOpcode();
944 if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
945 isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
946 // Note that Value must be in range here (less than 32) because
947 // otherwise there would not be any bits set in InsertMask.
948 Op1 = Op1.getOperand(0).getOperand(0);
949 SH = (SHOpc == ISD::SHL) ? Value : 32 - Value;
954 SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
956 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
963 static unsigned allUsesTruncate(SelectionDAG *CurDAG, SDNode *N) {
964 unsigned MaxTruncation = 0;
965 // Cannot use range-based for loop here as we need the actual use (i.e. we
966 // need the operand number corresponding to the use). A range-based for
967 // will unbox the use and provide an SDNode*.
968 for (SDNode::use_iterator Use = N->use_begin(), UseEnd = N->use_end();
969 Use != UseEnd; ++Use) {
971 Use->isMachineOpcode() ? Use->getMachineOpcode() : Use->getOpcode();
975 if (Use->isMachineOpcode())
978 std::max(MaxTruncation, (unsigned)Use->getValueType(0).getSizeInBits());
981 if (Use->isMachineOpcode())
983 StoreSDNode *STN = cast<StoreSDNode>(*Use);
984 unsigned MemVTSize = STN->getMemoryVT().getSizeInBits();
985 if (MemVTSize == 64 || Use.getOperandNo() != 0)
987 MaxTruncation = std::max(MaxTruncation, MemVTSize);
994 if (Use.getOperandNo() != 0)
996 MaxTruncation = std::max(MaxTruncation, 32u);
1002 if (Use.getOperandNo() != 0)
1004 MaxTruncation = std::max(MaxTruncation, 16u);
1010 if (Use.getOperandNo() != 0)
1012 MaxTruncation = std::max(MaxTruncation, 8u);
1016 return MaxTruncation;
1019 // For any 32 < Num < 64, check if the Imm contains at least Num consecutive
1020 // zeros and return the number of bits by the left of these consecutive zeros.
1021 static int findContiguousZerosAtLeast(uint64_t Imm, unsigned Num) {
1022 unsigned HiTZ = llvm::countr_zero<uint32_t>(Hi_32(Imm));
1023 unsigned LoLZ = llvm::countl_zero<uint32_t>(Lo_32(Imm));
1024 if ((HiTZ + LoLZ) >= Num)
1029 // Direct materialization of 64-bit constants by enumerated patterns.
1030 static SDNode *selectI64ImmDirect(SelectionDAG *CurDAG, const SDLoc &dl,
1031 uint64_t Imm, unsigned &InstCnt) {
1032 unsigned TZ = llvm::countr_zero<uint64_t>(Imm);
1033 unsigned LZ = llvm::countl_zero<uint64_t>(Imm);
1034 unsigned TO = llvm::countr_one<uint64_t>(Imm);
1035 unsigned LO = llvm::countl_one<uint64_t>(Imm);
1036 unsigned Hi32 = Hi_32(Imm);
1037 unsigned Lo32 = Lo_32(Imm);
1038 SDNode *Result = nullptr;
1041 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
1042 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1045 // Following patterns use 1 instructions to materialize the Imm.
1047 // 1-1) Patterns : {zeros}{15-bit valve}
1048 // {ones}{15-bit valve}
1049 if (isInt<16>(Imm)) {
1050 SDValue SDImm = CurDAG->getTargetConstant(Imm, dl, MVT::i64);
1051 return CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm);
1053 // 1-2) Patterns : {zeros}{15-bit valve}{16 zeros}
1054 // {ones}{15-bit valve}{16 zeros}
1055 if (TZ > 15 && (LZ > 32 || LO > 32))
1056 return CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64,
1057 getI32Imm((Imm >> 16) & 0xffff));
1059 // Following patterns use 2 instructions to materialize the Imm.
1061 assert(LZ < 64 && "Unexpected leading zeros here.");
1062 // Count of ones follwing the leading zeros.
1063 unsigned FO = llvm::countl_one<uint64_t>(Imm << LZ);
1064 // 2-1) Patterns : {zeros}{31-bit value}
1065 // {ones}{31-bit value}
1066 if (isInt<32>(Imm)) {
1067 uint64_t ImmHi16 = (Imm >> 16) & 0xffff;
1068 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;
1069 Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16));
1070 return CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1071 getI32Imm(Imm & 0xffff));
1073 // 2-2) Patterns : {zeros}{ones}{15-bit value}{zeros}
1074 // {zeros}{15-bit value}{zeros}
1075 // {zeros}{ones}{15-bit value}
1076 // {ones}{15-bit value}{zeros}
1077 // We can take advantage of LI's sign-extension semantics to generate leading
1078 // ones, and then use RLDIC to mask off the ones in both sides after rotation.
1079 if ((LZ + FO + TZ) > 48) {
1080 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64,
1081 getI32Imm((Imm >> TZ) & 0xffff));
1082 return CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, SDValue(Result, 0),
1083 getI32Imm(TZ), getI32Imm(LZ));
1085 // 2-3) Pattern : {zeros}{15-bit value}{ones}
1086 // Shift right the Imm by (48 - LZ) bits to construct a negtive 16 bits value,
1087 // therefore we can take advantage of LI's sign-extension semantics, and then
1088 // mask them off after rotation.
1090 // +--LZ--||-15-bit-||--TO--+ +-------------|--16-bit--+
1091 // |00000001bbbbbbbbb1111111| -> |00000000000001bbbbbbbbb1|
1092 // +------------------------+ +------------------------+
1094 // Imm (Imm >> (48 - LZ) & 0xffff)
1095 // +----sext-----|--16-bit--+ +clear-|-----------------+
1096 // |11111111111111bbbbbbbbb1| -> |00000001bbbbbbbbb1111111|
1097 // +------------------------+ +------------------------+
1099 // LI8: sext many leading zeros RLDICL: rotate left (48 - LZ), clear left LZ
1100 if ((LZ + TO) > 48) {
1101 // Since the immediates with (LZ > 32) have been handled by previous
1102 // patterns, here we have (LZ <= 32) to make sure we will not shift right
1103 // the Imm by a negative value.
1104 assert(LZ <= 32 && "Unexpected shift value.");
1105 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64,
1106 getI32Imm((Imm >> (48 - LZ) & 0xffff)));
1107 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1108 getI32Imm(48 - LZ), getI32Imm(LZ));
1110 // 2-4) Patterns : {zeros}{ones}{15-bit value}{ones}
1111 // {ones}{15-bit value}{ones}
1112 // We can take advantage of LI's sign-extension semantics to generate leading
1113 // ones, and then use RLDICL to mask off the ones in left sides (if required)
1116 // +-LZ-FO||-15-bit-||--TO--+ +-------------|--16-bit--+
1117 // |00011110bbbbbbbbb1111111| -> |000000000011110bbbbbbbbb|
1118 // +------------------------+ +------------------------+
1120 // Imm (Imm >> TO) & 0xffff
1121 // +----sext-----|--16-bit--+ +LZ|---------------------+
1122 // |111111111111110bbbbbbbbb| -> |00011110bbbbbbbbb1111111|
1123 // +------------------------+ +------------------------+
1125 // LI8: sext many leading zeros RLDICL: rotate left TO, clear left LZ
1126 if ((LZ + FO + TO) > 48) {
1127 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64,
1128 getI32Imm((Imm >> TO) & 0xffff));
1129 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1130 getI32Imm(TO), getI32Imm(LZ));
1132 // 2-5) Pattern : {32 zeros}{****}{0}{15-bit value}
1133 // If Hi32 is zero and the Lo16(in Lo32) can be presented as a positive 16 bit
1134 // value, we can use LI for Lo16 without generating leading ones then add the
1136 if (LZ == 32 && ((Lo32 & 0x8000) == 0)) {
1137 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64,
1138 getI32Imm(Lo32 & 0xffff));
1139 return CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64, SDValue(Result, 0),
1140 getI32Imm(Lo32 >> 16));
1142 // 2-6) Patterns : {******}{49 zeros}{******}
1143 // {******}{49 ones}{******}
1144 // If the Imm contains 49 consecutive zeros/ones, it means that a total of 15
1145 // bits remain on both sides. Rotate right the Imm to construct an int<16>
1146 // value, use LI for int<16> value and then use RLDICL without mask to rotate
1149 // 1) findContiguousZerosAtLeast(Imm, 49)
1150 // +------|--zeros-|------+ +---ones--||---15 bit--+
1151 // |bbbbbb0000000000aaaaaa| -> |0000000000aaaaaabbbbbb|
1152 // +----------------------+ +----------------------+
1155 // 2) findContiguousZerosAtLeast(~Imm, 49)
1156 // +------|--ones--|------+ +---ones--||---15 bit--+
1157 // |bbbbbb1111111111aaaaaa| -> |1111111111aaaaaabbbbbb|
1158 // +----------------------+ +----------------------+
1160 if ((Shift = findContiguousZerosAtLeast(Imm, 49)) ||
1161 (Shift = findContiguousZerosAtLeast(~Imm, 49))) {
1162 uint64_t RotImm = APInt(64, Imm).rotr(Shift).getZExtValue();
1163 Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64,
1164 getI32Imm(RotImm & 0xffff));
1165 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1166 getI32Imm(Shift), getI32Imm(0));
1169 // Following patterns use 3 instructions to materialize the Imm.
1171 // 3-1) Patterns : {zeros}{ones}{31-bit value}{zeros}
1172 // {zeros}{31-bit value}{zeros}
1173 // {zeros}{ones}{31-bit value}
1174 // {ones}{31-bit value}{zeros}
1175 // We can take advantage of LIS's sign-extension semantics to generate leading
1176 // ones, add the remaining bits with ORI, and then use RLDIC to mask off the
1177 // ones in both sides after rotation.
1178 if ((LZ + FO + TZ) > 32) {
1179 uint64_t ImmHi16 = (Imm >> (TZ + 16)) & 0xffff;
1180 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;
1181 Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16));
1182 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1183 getI32Imm((Imm >> TZ) & 0xffff));
1184 return CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, SDValue(Result, 0),
1185 getI32Imm(TZ), getI32Imm(LZ));
1187 // 3-2) Pattern : {zeros}{31-bit value}{ones}
1188 // Shift right the Imm by (32 - LZ) bits to construct a negative 32 bits
1189 // value, therefore we can take advantage of LIS's sign-extension semantics,
1190 // add the remaining bits with ORI, and then mask them off after rotation.
1191 // This is similar to Pattern 2-3, please refer to the diagram there.
1192 if ((LZ + TO) > 32) {
1193 // Since the immediates with (LZ > 32) have been handled by previous
1194 // patterns, here we have (LZ <= 32) to make sure we will not shift right
1195 // the Imm by a negative value.
1196 assert(LZ <= 32 && "Unexpected shift value.");
1197 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64,
1198 getI32Imm((Imm >> (48 - LZ)) & 0xffff));
1199 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1200 getI32Imm((Imm >> (32 - LZ)) & 0xffff));
1201 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1202 getI32Imm(32 - LZ), getI32Imm(LZ));
1204 // 3-3) Patterns : {zeros}{ones}{31-bit value}{ones}
1205 // {ones}{31-bit value}{ones}
1206 // We can take advantage of LIS's sign-extension semantics to generate leading
1207 // ones, add the remaining bits with ORI, and then use RLDICL to mask off the
1208 // ones in left sides (if required) after rotation.
1209 // This is similar to Pattern 2-4, please refer to the diagram there.
1210 if ((LZ + FO + TO) > 32) {
1211 Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64,
1212 getI32Imm((Imm >> (TO + 16)) & 0xffff));
1213 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1214 getI32Imm((Imm >> TO) & 0xffff));
1215 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1216 getI32Imm(TO), getI32Imm(LZ));
1218 // 3-4) Patterns : High word == Low word
1220 // Handle the first 32 bits.
1221 uint64_t ImmHi16 = (Lo32 >> 16) & 0xffff;
1222 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;
1223 Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16));
1224 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1225 getI32Imm(Lo32 & 0xffff));
1226 // Use rldimi to insert the Low word into High word.
1227 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32),
1229 return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
1231 // 3-5) Patterns : {******}{33 zeros}{******}
1232 // {******}{33 ones}{******}
1233 // If the Imm contains 33 consecutive zeros/ones, it means that a total of 31
1234 // bits remain on both sides. Rotate right the Imm to construct an int<32>
1235 // value, use LIS + ORI for int<32> value and then use RLDICL without mask to
1237 // This is similar to Pattern 2-6, please refer to the diagram there.
1238 if ((Shift = findContiguousZerosAtLeast(Imm, 33)) ||
1239 (Shift = findContiguousZerosAtLeast(~Imm, 33))) {
1240 uint64_t RotImm = APInt(64, Imm).rotr(Shift).getZExtValue();
1241 uint64_t ImmHi16 = (RotImm >> 16) & 0xffff;
1242 unsigned Opcode = ImmHi16 ? PPC::LIS8 : PPC::LI8;
1243 Result = CurDAG->getMachineNode(Opcode, dl, MVT::i64, getI32Imm(ImmHi16));
1244 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1245 getI32Imm(RotImm & 0xffff));
1246 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1247 getI32Imm(Shift), getI32Imm(0));
1254 // Try to select instructions to generate a 64 bit immediate using prefix as
1255 // well as non prefix instructions. The function will return the SDNode
1256 // to materialize that constant or it will return nullptr if it does not
1257 // find one. The variable InstCnt is set to the number of instructions that
1259 static SDNode *selectI64ImmDirectPrefix(SelectionDAG *CurDAG, const SDLoc &dl,
1260 uint64_t Imm, unsigned &InstCnt) {
1261 unsigned TZ = llvm::countr_zero<uint64_t>(Imm);
1262 unsigned LZ = llvm::countl_zero<uint64_t>(Imm);
1263 unsigned TO = llvm::countr_one<uint64_t>(Imm);
1264 unsigned FO = llvm::countl_one<uint64_t>(LZ == 64 ? 0 : (Imm << LZ));
1265 unsigned Hi32 = Hi_32(Imm);
1266 unsigned Lo32 = Lo_32(Imm);
1268 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
1269 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1272 auto getI64Imm = [CurDAG, dl](uint64_t Imm) {
1273 return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
1276 // Following patterns use 1 instruction to materialize Imm.
1279 // The pli instruction can materialize up to 34 bits directly.
1280 // If a constant fits within 34-bits, emit the pli instruction here directly.
1282 return CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,
1283 CurDAG->getTargetConstant(Imm, dl, MVT::i64));
1285 // Require at least two instructions.
1287 SDNode *Result = nullptr;
1288 // Patterns : {zeros}{ones}{33-bit value}{zeros}
1289 // {zeros}{33-bit value}{zeros}
1290 // {zeros}{ones}{33-bit value}
1291 // {ones}{33-bit value}{zeros}
1292 // We can take advantage of PLI's sign-extension semantics to generate leading
1293 // ones, and then use RLDIC to mask off the ones on both sides after rotation.
1294 if ((LZ + FO + TZ) > 30) {
1295 APInt SignedInt34 = APInt(34, (Imm >> TZ) & 0x3ffffffff);
1296 APInt Extended = SignedInt34.sext(64);
1297 Result = CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,
1298 getI64Imm(*Extended.getRawData()));
1299 return CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, SDValue(Result, 0),
1300 getI32Imm(TZ), getI32Imm(LZ));
1302 // Pattern : {zeros}{33-bit value}{ones}
1303 // Shift right the Imm by (30 - LZ) bits to construct a negative 34 bit value,
1304 // therefore we can take advantage of PLI's sign-extension semantics, and then
1305 // mask them off after rotation.
1307 // +--LZ--||-33-bit-||--TO--+ +-------------|--34-bit--+
1308 // |00000001bbbbbbbbb1111111| -> |00000000000001bbbbbbbbb1|
1309 // +------------------------+ +------------------------+
1312 // +----sext-----|--34-bit--+ +clear-|-----------------+
1313 // |11111111111111bbbbbbbbb1| -> |00000001bbbbbbbbb1111111|
1314 // +------------------------+ +------------------------+
1316 if ((LZ + TO) > 30) {
1317 APInt SignedInt34 = APInt(34, (Imm >> (30 - LZ)) & 0x3ffffffff);
1318 APInt Extended = SignedInt34.sext(64);
1319 Result = CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,
1320 getI64Imm(*Extended.getRawData()));
1321 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1322 getI32Imm(30 - LZ), getI32Imm(LZ));
1324 // Patterns : {zeros}{ones}{33-bit value}{ones}
1325 // {ones}{33-bit value}{ones}
1326 // Similar to LI we can take advantage of PLI's sign-extension semantics to
1327 // generate leading ones, and then use RLDICL to mask off the ones in left
1328 // sides (if required) after rotation.
1329 if ((LZ + FO + TO) > 30) {
1330 APInt SignedInt34 = APInt(34, (Imm >> TO) & 0x3ffffffff);
1331 APInt Extended = SignedInt34.sext(64);
1332 Result = CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64,
1333 getI64Imm(*Extended.getRawData()));
1334 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, SDValue(Result, 0),
1335 getI32Imm(TO), getI32Imm(LZ));
1337 // Patterns : {******}{31 zeros}{******}
1338 // : {******}{31 ones}{******}
1339 // If Imm contains 31 consecutive zeros/ones then the remaining bit count
1340 // is 33. Rotate right the Imm to construct a int<33> value, we can use PLI
1341 // for the int<33> value and then use RLDICL without a mask to rotate it back.
1343 // +------|--ones--|------+ +---ones--||---33 bit--+
1344 // |bbbbbb1111111111aaaaaa| -> |1111111111aaaaaabbbbbb|
1345 // +----------------------+ +----------------------+
1347 for (unsigned Shift = 0; Shift < 63; ++Shift) {
1348 uint64_t RotImm = APInt(64, Imm).rotr(Shift).getZExtValue();
1349 if (isInt<34>(RotImm)) {
1351 CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64, getI64Imm(RotImm));
1352 return CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
1353 SDValue(Result, 0), getI32Imm(Shift),
1358 // Patterns : High word == Low word
1359 // This is basically a splat of a 32 bit immediate.
1361 Result = CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64, getI64Imm(Hi32));
1362 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32),
1364 return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
1369 // This pattern can form any 64 bit immediate in 3 instructions.
1371 CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64, getI64Imm(Hi32));
1373 CurDAG->getMachineNode(PPC::PLI8, dl, MVT::i64, getI64Imm(Lo32));
1374 SDValue Ops[] = {SDValue(ResultLo, 0), SDValue(ResultHi, 0), getI32Imm(32),
1376 return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
1379 static SDNode *selectI64Imm(SelectionDAG *CurDAG, const SDLoc &dl, uint64_t Imm,
1380 unsigned *InstCnt = nullptr) {
1381 unsigned InstCntDirect = 0;
1382 // No more than 3 instructions are used if we can select the i64 immediate
1384 SDNode *Result = selectI64ImmDirect(CurDAG, dl, Imm, InstCntDirect);
1386 const PPCSubtarget &Subtarget =
1387 CurDAG->getMachineFunction().getSubtarget<PPCSubtarget>();
1389 // If we have prefixed instructions and there is a chance we can
1390 // materialize the constant with fewer prefixed instructions than
1391 // non-prefixed, try that.
1392 if (Subtarget.hasPrefixInstrs() && InstCntDirect != 1) {
1393 unsigned InstCntDirectP = 0;
1394 SDNode *ResultP = selectI64ImmDirectPrefix(CurDAG, dl, Imm, InstCntDirectP);
1395 // Use the prefix case in either of two cases:
1396 // 1) We have no result from the non-prefix case to use.
1397 // 2) The non-prefix case uses more instructions than the prefix case.
1398 // If the prefix and non-prefix cases use the same number of instructions
1399 // we will prefer the non-prefix case.
1400 if (ResultP && (!Result || InstCntDirectP < InstCntDirect)) {
1402 *InstCnt = InstCntDirectP;
1409 *InstCnt = InstCntDirect;
1412 auto getI32Imm = [CurDAG, dl](unsigned Imm) {
1413 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1416 uint32_t Hi16OfLo32 = (Lo_32(Imm) >> 16) & 0xffff;
1417 uint32_t Lo16OfLo32 = Lo_32(Imm) & 0xffff;
1419 // Try to use 4 instructions to materialize the immediate which is "almost" a
1420 // splat of a 32 bit immediate.
1421 if (Hi16OfLo32 && Lo16OfLo32) {
1422 uint32_t Hi16OfHi32 = (Hi_32(Imm) >> 16) & 0xffff;
1423 uint32_t Lo16OfHi32 = Hi_32(Imm) & 0xffff;
1424 bool IsSelected = false;
1426 auto getSplat = [CurDAG, dl, getI32Imm](uint32_t Hi16, uint32_t Lo16) {
1428 CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi16));
1429 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
1430 SDValue(Result, 0), getI32Imm(Lo16));
1431 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(32),
1433 return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
1436 if (Hi16OfHi32 == Lo16OfHi32 && Lo16OfHi32 == Lo16OfLo32) {
1438 Result = getSplat(Hi16OfLo32, Lo16OfLo32);
1439 // Modify Hi16OfHi32.
1440 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(48),
1442 Result = CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
1443 } else if (Hi16OfHi32 == Hi16OfLo32 && Hi16OfLo32 == Lo16OfLo32) {
1445 Result = getSplat(Hi16OfHi32, Lo16OfHi32);
1446 // Modify Lo16OfLo32.
1447 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(16),
1448 getI32Imm(16), getI32Imm(31)};
1449 Result = CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64, Ops);
1450 } else if (Lo16OfHi32 == Lo16OfLo32 && Hi16OfLo32 == Lo16OfLo32) {
1452 Result = getSplat(Hi16OfHi32, Lo16OfHi32);
1453 // Modify Hi16OfLo32.
1454 SDValue Ops[] = {SDValue(Result, 0), SDValue(Result, 0), getI32Imm(16),
1455 getI32Imm(0), getI32Imm(15)};
1456 Result = CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64, Ops);
1458 if (IsSelected == true) {
1465 // Handle the upper 32 bit value.
1467 selectI64ImmDirect(CurDAG, dl, Imm & 0xffffffff00000000, InstCntDirect);
1468 // Add in the last bits as required.
1470 Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
1471 SDValue(Result, 0), getI32Imm(Hi16OfLo32));
1475 Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64, SDValue(Result, 0),
1476 getI32Imm(Lo16OfLo32));
1480 *InstCnt = InstCntDirect;
1484 // Select a 64-bit constant.
1485 static SDNode *selectI64Imm(SelectionDAG *CurDAG, SDNode *N) {
1488 // Get 64 bit value.
1489 int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
1490 if (unsigned MinSize = allUsesTruncate(CurDAG, N)) {
1491 uint64_t SextImm = SignExtend64(Imm, MinSize);
1492 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64);
1493 if (isInt<16>(SextImm))
1494 return CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, SDImm);
1496 return selectI64Imm(CurDAG, dl, Imm);
1501 class BitPermutationSelector {
1505 // The bit number in the value, using a convention where bit 0 is the
1506 // lowest-order bit.
1509 // ConstZero means a bit we need to mask off.
1510 // Variable is a bit comes from an input variable.
1511 // VariableKnownToBeZero is also a bit comes from an input variable,
1512 // but it is known to be already zero. So we do not need to mask them.
1516 VariableKnownToBeZero
1519 ValueBit(SDValue V, unsigned I, Kind K = Variable)
1520 : V(V), Idx(I), K(K) {}
1521 ValueBit(Kind K = Variable) : Idx(UINT32_MAX), K(K) {}
1523 bool isZero() const {
1524 return K == ConstZero || K == VariableKnownToBeZero;
1527 bool hasValue() const {
1528 return K == Variable || K == VariableKnownToBeZero;
1531 SDValue getValue() const {
1532 assert(hasValue() && "Cannot get the value of a constant bit");
1536 unsigned getValueBitIndex() const {
1537 assert(hasValue() && "Cannot get the value bit index of a constant bit");
1542 // A bit group has the same underlying value and the same rotate factor.
1546 unsigned StartIdx, EndIdx;
1548 // This rotation amount assumes that the lower 32 bits of the quantity are
1549 // replicated in the high 32 bits by the rotation operator (which is done
1550 // by rlwinm and friends in 64-bit mode).
1552 // Did converting to Repl32 == true change the rotation factor? If it did,
1553 // it decreased it by 32.
1555 // Was this group coalesced after setting Repl32 to true?
1556 bool Repl32Coalesced;
1558 BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
1559 : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
1560 Repl32Coalesced(false) {
1561 LLVM_DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R
1562 << " [" << S << ", " << E << "]\n");
1566 // Information on each (Value, RLAmt) pair (like the number of groups
1567 // associated with each) used to choose the lowering method.
1568 struct ValueRotInfo {
1570 unsigned RLAmt = std::numeric_limits<unsigned>::max();
1571 unsigned NumGroups = 0;
1572 unsigned FirstGroupStartIdx = std::numeric_limits<unsigned>::max();
1573 bool Repl32 = false;
1575 ValueRotInfo() = default;
1577 // For sorting (in reverse order) by NumGroups, and then by
1578 // FirstGroupStartIdx.
1579 bool operator < (const ValueRotInfo &Other) const {
1580 // We need to sort so that the non-Repl32 come first because, when we're
1581 // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
1582 // masking operation.
1583 if (Repl32 < Other.Repl32)
1585 else if (Repl32 > Other.Repl32)
1587 else if (NumGroups > Other.NumGroups)
1589 else if (NumGroups < Other.NumGroups)
1591 else if (RLAmt == 0 && Other.RLAmt != 0)
1593 else if (RLAmt != 0 && Other.RLAmt == 0)
1595 else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
1601 using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>;
1602 using ValueBitsMemoizer =
1603 DenseMap<SDValue, std::unique_ptr<ValueBitsMemoizedValue>>;
1604 ValueBitsMemoizer Memoizer;
1606 // Return a pair of bool and a SmallVector pointer to a memoization entry.
1607 // The bool is true if something interesting was deduced, otherwise if we're
1608 // providing only a generic representation of V (or something else likewise
1609 // uninteresting for instruction selection) through the SmallVector.
1610 std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V,
1612 auto &ValueEntry = Memoizer[V];
1614 return std::make_pair(ValueEntry->first, &ValueEntry->second);
1615 ValueEntry.reset(new ValueBitsMemoizedValue());
1616 bool &Interesting = ValueEntry->first;
1617 SmallVector<ValueBit, 64> &Bits = ValueEntry->second;
1618 Bits.resize(NumBits);
1620 switch (V.getOpcode()) {
1623 if (isa<ConstantSDNode>(V.getOperand(1))) {
1624 unsigned RotAmt = V.getConstantOperandVal(1);
1626 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1628 for (unsigned i = 0; i < NumBits; ++i)
1629 Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt];
1631 return std::make_pair(Interesting = true, &Bits);
1636 if (isa<ConstantSDNode>(V.getOperand(1))) {
1637 unsigned ShiftAmt = V.getConstantOperandVal(1);
1639 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1641 for (unsigned i = ShiftAmt; i < NumBits; ++i)
1642 Bits[i] = LHSBits[i - ShiftAmt];
1644 for (unsigned i = 0; i < ShiftAmt; ++i)
1645 Bits[i] = ValueBit(ValueBit::ConstZero);
1647 return std::make_pair(Interesting = true, &Bits);
1652 if (isa<ConstantSDNode>(V.getOperand(1))) {
1653 unsigned ShiftAmt = V.getConstantOperandVal(1);
1655 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1657 for (unsigned i = 0; i < NumBits - ShiftAmt; ++i)
1658 Bits[i] = LHSBits[i + ShiftAmt];
1660 for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i)
1661 Bits[i] = ValueBit(ValueBit::ConstZero);
1663 return std::make_pair(Interesting = true, &Bits);
1667 if (isa<ConstantSDNode>(V.getOperand(1))) {
1668 uint64_t Mask = V.getConstantOperandVal(1);
1670 const SmallVector<ValueBit, 64> *LHSBits;
1671 // Mark this as interesting, only if the LHS was also interesting. This
1672 // prevents the overall procedure from matching a single immediate 'and'
1673 // (which is non-optimal because such an and might be folded with other
1674 // things if we don't select it here).
1675 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits);
1677 for (unsigned i = 0; i < NumBits; ++i)
1678 if (((Mask >> i) & 1) == 1)
1679 Bits[i] = (*LHSBits)[i];
1681 // AND instruction masks this bit. If the input is already zero,
1682 // we have nothing to do here. Otherwise, make the bit ConstZero.
1683 if ((*LHSBits)[i].isZero())
1684 Bits[i] = (*LHSBits)[i];
1686 Bits[i] = ValueBit(ValueBit::ConstZero);
1689 return std::make_pair(Interesting, &Bits);
1693 const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1694 const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second;
1696 bool AllDisjoint = true;
1697 SDValue LastVal = SDValue();
1698 unsigned LastIdx = 0;
1699 for (unsigned i = 0; i < NumBits; ++i) {
1700 if (LHSBits[i].isZero() && RHSBits[i].isZero()) {
1701 // If both inputs are known to be zero and one is ConstZero and
1702 // another is VariableKnownToBeZero, we can select whichever
1703 // we like. To minimize the number of bit groups, we select
1704 // VariableKnownToBeZero if this bit is the next bit of the same
1705 // input variable from the previous bit. Otherwise, we select
1707 if (LHSBits[i].hasValue() && LHSBits[i].getValue() == LastVal &&
1708 LHSBits[i].getValueBitIndex() == LastIdx + 1)
1709 Bits[i] = LHSBits[i];
1710 else if (RHSBits[i].hasValue() && RHSBits[i].getValue() == LastVal &&
1711 RHSBits[i].getValueBitIndex() == LastIdx + 1)
1712 Bits[i] = RHSBits[i];
1714 Bits[i] = ValueBit(ValueBit::ConstZero);
1716 else if (LHSBits[i].isZero())
1717 Bits[i] = RHSBits[i];
1718 else if (RHSBits[i].isZero())
1719 Bits[i] = LHSBits[i];
1721 AllDisjoint = false;
1724 // We remember the value and bit index of this bit.
1725 if (Bits[i].hasValue()) {
1726 LastVal = Bits[i].getValue();
1727 LastIdx = Bits[i].getValueBitIndex();
1730 if (LastVal) LastVal = SDValue();
1738 return std::make_pair(Interesting = true, &Bits);
1740 case ISD::ZERO_EXTEND: {
1741 // We support only the case with zero extension from i32 to i64 so far.
1742 if (V.getValueType() != MVT::i64 ||
1743 V.getOperand(0).getValueType() != MVT::i32)
1746 const SmallVector<ValueBit, 64> *LHSBits;
1747 const unsigned NumOperandBits = 32;
1748 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0),
1751 for (unsigned i = 0; i < NumOperandBits; ++i)
1752 Bits[i] = (*LHSBits)[i];
1754 for (unsigned i = NumOperandBits; i < NumBits; ++i)
1755 Bits[i] = ValueBit(ValueBit::ConstZero);
1757 return std::make_pair(Interesting, &Bits);
1759 case ISD::TRUNCATE: {
1760 EVT FromType = V.getOperand(0).getValueType();
1761 EVT ToType = V.getValueType();
1762 // We support only the case with truncate from i64 to i32.
1763 if (FromType != MVT::i64 || ToType != MVT::i32)
1765 const unsigned NumAllBits = FromType.getSizeInBits();
1766 SmallVector<ValueBit, 64> *InBits;
1767 std::tie(Interesting, InBits) = getValueBits(V.getOperand(0),
1769 const unsigned NumValidBits = ToType.getSizeInBits();
1771 // A 32-bit instruction cannot touch upper 32-bit part of 64-bit value.
1772 // So, we cannot include this truncate.
1773 bool UseUpper32bit = false;
1774 for (unsigned i = 0; i < NumValidBits; ++i)
1775 if ((*InBits)[i].hasValue() && (*InBits)[i].getValueBitIndex() >= 32) {
1776 UseUpper32bit = true;
1782 for (unsigned i = 0; i < NumValidBits; ++i)
1783 Bits[i] = (*InBits)[i];
1785 return std::make_pair(Interesting, &Bits);
1787 case ISD::AssertZext: {
1788 // For AssertZext, we look through the operand and
1789 // mark the bits known to be zero.
1790 const SmallVector<ValueBit, 64> *LHSBits;
1791 std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0),
1794 EVT FromType = cast<VTSDNode>(V.getOperand(1))->getVT();
1795 const unsigned NumValidBits = FromType.getSizeInBits();
1796 for (unsigned i = 0; i < NumValidBits; ++i)
1797 Bits[i] = (*LHSBits)[i];
1799 // These bits are known to be zero but the AssertZext may be from a value
1800 // that already has some constant zero bits (i.e. from a masking and).
1801 for (unsigned i = NumValidBits; i < NumBits; ++i)
1802 Bits[i] = (*LHSBits)[i].hasValue()
1803 ? ValueBit((*LHSBits)[i].getValue(),
1804 (*LHSBits)[i].getValueBitIndex(),
1805 ValueBit::VariableKnownToBeZero)
1806 : ValueBit(ValueBit::ConstZero);
1808 return std::make_pair(Interesting, &Bits);
1811 LoadSDNode *LD = cast<LoadSDNode>(V);
1812 if (ISD::isZEXTLoad(V.getNode()) && V.getResNo() == 0) {
1813 EVT VT = LD->getMemoryVT();
1814 const unsigned NumValidBits = VT.getSizeInBits();
1816 for (unsigned i = 0; i < NumValidBits; ++i)
1817 Bits[i] = ValueBit(V, i);
1819 // These bits are known to be zero.
1820 for (unsigned i = NumValidBits; i < NumBits; ++i)
1821 Bits[i] = ValueBit(V, i, ValueBit::VariableKnownToBeZero);
1823 // Zero-extending load itself cannot be optimized. So, it is not
1824 // interesting by itself though it gives useful information.
1825 return std::make_pair(Interesting = false, &Bits);
1830 for (unsigned i = 0; i < NumBits; ++i)
1831 Bits[i] = ValueBit(V, i);
1833 return std::make_pair(Interesting = false, &Bits);
1836 // For each value (except the constant ones), compute the left-rotate amount
1837 // to get it from its original to final position.
1838 void computeRotationAmounts() {
1840 RLAmt.resize(Bits.size());
1841 for (unsigned i = 0; i < Bits.size(); ++i)
1842 if (Bits[i].hasValue()) {
1843 unsigned VBI = Bits[i].getValueBitIndex();
1847 RLAmt[i] = Bits.size() - (VBI - i);
1848 } else if (Bits[i].isZero()) {
1850 RLAmt[i] = UINT32_MAX;
1852 llvm_unreachable("Unknown value bit type");
1856 // Collect groups of consecutive bits with the same underlying value and
1857 // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1858 // they break up groups.
1859 void collectBitGroups(bool LateMask) {
1862 unsigned LastRLAmt = RLAmt[0];
1863 SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1864 unsigned LastGroupStartIdx = 0;
1865 bool IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue();
1866 for (unsigned i = 1; i < Bits.size(); ++i) {
1867 unsigned ThisRLAmt = RLAmt[i];
1868 SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1869 if (LateMask && !ThisValue) {
1870 ThisValue = LastValue;
1871 ThisRLAmt = LastRLAmt;
1872 // If we're doing late masking, then the first bit group always starts
1873 // at zero (even if the first bits were zero).
1874 if (BitGroups.empty())
1875 LastGroupStartIdx = 0;
1878 // If this bit is known to be zero and the current group is a bit group
1879 // of zeros, we do not need to terminate the current bit group even the
1880 // Value or RLAmt does not match here. Instead, we terminate this group
1881 // when the first non-zero bit appears later.
1882 if (IsGroupOfZeros && Bits[i].isZero())
1885 // If this bit has the same underlying value and the same rotate factor as
1886 // the last one, then they're part of the same group.
1887 if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1888 // We cannot continue the current group if this bits is not known to
1889 // be zero in a bit group of zeros.
1890 if (!(IsGroupOfZeros && ThisValue && !Bits[i].isZero()))
1893 if (LastValue.getNode())
1894 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1896 LastRLAmt = ThisRLAmt;
1897 LastValue = ThisValue;
1898 LastGroupStartIdx = i;
1899 IsGroupOfZeros = !Bits[LastGroupStartIdx].hasValue();
1901 if (LastValue.getNode())
1902 BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1905 if (BitGroups.empty())
1908 // We might be able to combine the first and last groups.
1909 if (BitGroups.size() > 1) {
1910 // If the first and last groups are the same, then remove the first group
1911 // in favor of the last group, making the ending index of the last group
1912 // equal to the ending index of the to-be-removed first group.
1913 if (BitGroups[0].StartIdx == 0 &&
1914 BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1915 BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1916 BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1917 LLVM_DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
1918 BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1919 BitGroups.erase(BitGroups.begin());
1924 // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1925 // associated with each. If the number of groups are same, we prefer a group
1926 // which does not require rotate, i.e. RLAmt is 0, to avoid the first rotate
1927 // instruction. If there is a degeneracy, pick the one that occurs
1928 // first (in the final value).
1929 void collectValueRotInfo() {
1932 for (auto &BG : BitGroups) {
1933 unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1934 ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1936 VRI.RLAmt = BG.RLAmt;
1937 VRI.Repl32 = BG.Repl32;
1939 VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1942 // Now that we've collected the various ValueRotInfo instances, we need to
1944 ValueRotsVec.clear();
1945 for (auto &I : ValueRots) {
1946 ValueRotsVec.push_back(I.second);
1948 llvm::sort(ValueRotsVec);
1951 // In 64-bit mode, rlwinm and friends have a rotation operator that
1952 // replicates the low-order 32 bits into the high-order 32-bits. The mask
1953 // indices of these instructions can only be in the lower 32 bits, so they
1954 // can only represent some 64-bit bit groups. However, when they can be used,
1955 // the 32-bit replication can be used to represent, as a single bit group,
1956 // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1957 // groups when possible. Returns true if any of the bit groups were
1959 void assignRepl32BitGroups() {
1960 // If we have bits like this:
1962 // Indices: 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
1963 // V bits: ... 7 6 5 4 3 2 1 0 31 30 29 28 27 26 25 24
1964 // Groups: | RLAmt = 8 | RLAmt = 40 |
1966 // But, making use of a 32-bit operation that replicates the low-order 32
1967 // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1970 auto IsAllLow32 = [this](BitGroup & BG) {
1971 if (BG.StartIdx <= BG.EndIdx) {
1972 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1973 if (!Bits[i].hasValue())
1975 if (Bits[i].getValueBitIndex() >= 32)
1979 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1980 if (!Bits[i].hasValue())
1982 if (Bits[i].getValueBitIndex() >= 32)
1985 for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1986 if (!Bits[i].hasValue())
1988 if (Bits[i].getValueBitIndex() >= 32)
1996 for (auto &BG : BitGroups) {
1997 // If this bit group has RLAmt of 0 and will not be merged with
1998 // another bit group, we don't benefit from Repl32. We don't mark
1999 // such group to give more freedom for later instruction selection.
2000 if (BG.RLAmt == 0) {
2001 auto PotentiallyMerged = [this](BitGroup & BG) {
2002 for (auto &BG2 : BitGroups)
2003 if (&BG != &BG2 && BG.V == BG2.V &&
2004 (BG2.RLAmt == 0 || BG2.RLAmt == 32))
2008 if (!PotentiallyMerged(BG))
2011 if (BG.StartIdx < 32 && BG.EndIdx < 32) {
2012 if (IsAllLow32(BG)) {
2013 if (BG.RLAmt >= 32) {
2020 LLVM_DEBUG(dbgs() << "\t32-bit replicated bit group for "
2021 << BG.V.getNode() << " RLAmt = " << BG.RLAmt << " ["
2022 << BG.StartIdx << ", " << BG.EndIdx << "]\n");
2027 // Now walk through the bit groups, consolidating where possible.
2028 for (auto I = BitGroups.begin(); I != BitGroups.end();) {
2029 // We might want to remove this bit group by merging it with the previous
2030 // group (which might be the ending group).
2031 auto IP = (I == BitGroups.begin()) ?
2032 std::prev(BitGroups.end()) : std::prev(I);
2033 if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
2034 I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
2036 LLVM_DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for "
2037 << I->V.getNode() << " RLAmt = " << I->RLAmt << " ["
2038 << I->StartIdx << ", " << I->EndIdx
2039 << "] with group with range [" << IP->StartIdx << ", "
2040 << IP->EndIdx << "]\n");
2042 IP->EndIdx = I->EndIdx;
2043 IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
2044 IP->Repl32Coalesced = true;
2045 I = BitGroups.erase(I);
2048 // There is a special case worth handling: If there is a single group
2049 // covering the entire upper 32 bits, and it can be merged with both
2050 // the next and previous groups (which might be the same group), then
2051 // do so. If it is the same group (so there will be only one group in
2052 // total), then we need to reverse the order of the range so that it
2053 // covers the entire 64 bits.
2054 if (I->StartIdx == 32 && I->EndIdx == 63) {
2055 assert(std::next(I) == BitGroups.end() &&
2056 "bit group ends at index 63 but there is another?");
2057 auto IN = BitGroups.begin();
2059 if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
2060 (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
2061 IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
2064 LLVM_DEBUG(dbgs() << "\tcombining bit group for " << I->V.getNode()
2065 << " RLAmt = " << I->RLAmt << " [" << I->StartIdx
2066 << ", " << I->EndIdx
2067 << "] with 32-bit replicated groups with ranges ["
2068 << IP->StartIdx << ", " << IP->EndIdx << "] and ["
2069 << IN->StartIdx << ", " << IN->EndIdx << "]\n");
2072 // There is only one other group; change it to cover the whole
2073 // range (backward, so that it can still be Repl32 but cover the
2074 // whole 64-bit range).
2077 IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
2078 IP->Repl32Coalesced = true;
2079 I = BitGroups.erase(I);
2081 // There are two separate groups, one before this group and one
2082 // after us (at the beginning). We're going to remove this group,
2083 // but also the group at the very beginning.
2084 IP->EndIdx = IN->EndIdx;
2085 IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
2086 IP->Repl32Coalesced = true;
2087 I = BitGroups.erase(I);
2088 BitGroups.erase(BitGroups.begin());
2091 // This must be the last group in the vector (and we might have
2092 // just invalidated the iterator above), so break here.
2102 SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
2103 return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
2106 uint64_t getZerosMask() {
2108 for (unsigned i = 0; i < Bits.size(); ++i) {
2109 if (Bits[i].hasValue())
2111 Mask |= (UINT64_C(1) << i);
2117 // This method extends an input value to 64 bit if input is 32-bit integer.
2118 // While selecting instructions in BitPermutationSelector in 64-bit mode,
2119 // an input value can be a 32-bit integer if a ZERO_EXTEND node is included.
2120 // In such case, we extend it to 64 bit to be consistent with other values.
2121 SDValue ExtendToInt64(SDValue V, const SDLoc &dl) {
2122 if (V.getValueSizeInBits() == 64)
2125 assert(V.getValueSizeInBits() == 32);
2126 SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2127 SDValue ImDef = SDValue(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl,
2129 SDValue ExtVal = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl,
2135 SDValue TruncateToInt32(SDValue V, const SDLoc &dl) {
2136 if (V.getValueSizeInBits() == 32)
2139 assert(V.getValueSizeInBits() == 64);
2140 SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
2141 SDValue SubVal = SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl,
2142 MVT::i32, V, SubRegIdx), 0);
2146 // Depending on the number of groups for a particular value, it might be
2147 // better to rotate, mask explicitly (using andi/andis), and then or the
2148 // result. Select this part of the result first.
2149 void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
2150 if (BPermRewriterNoMasking)
2153 for (ValueRotInfo &VRI : ValueRotsVec) {
2155 for (unsigned i = 0; i < Bits.size(); ++i) {
2156 if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
2158 if (RLAmt[i] != VRI.RLAmt)
2163 // Compute the masks for andi/andis that would be necessary.
2164 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
2165 assert((ANDIMask != 0 || ANDISMask != 0) &&
2166 "No set bits in mask for value bit groups");
2167 bool NeedsRotate = VRI.RLAmt != 0;
2169 // We're trying to minimize the number of instructions. If we have one
2170 // group, using one of andi/andis can break even. If we have three
2171 // groups, we can use both andi and andis and break even (to use both
2172 // andi and andis we also need to or the results together). We need four
2173 // groups if we also need to rotate. To use andi/andis we need to do more
2174 // than break even because rotate-and-mask instructions tend to be easier
2177 // FIXME: We've biased here against using andi/andis, which is right for
2178 // POWER cores, but not optimal everywhere. For example, on the A2,
2179 // andi/andis have single-cycle latency whereas the rotate-and-mask
2180 // instructions take two cycles, and it would be better to bias toward
2181 // andi/andis in break-even cases.
2183 unsigned NumAndInsts = (unsigned) NeedsRotate +
2184 (unsigned) (ANDIMask != 0) +
2185 (unsigned) (ANDISMask != 0) +
2186 (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
2187 (unsigned) (bool) Res;
2189 LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode()
2190 << " RL: " << VRI.RLAmt << ":"
2191 << "\n\t\t\tisel using masking: " << NumAndInsts
2192 << " using rotates: " << VRI.NumGroups << "\n");
2194 if (NumAndInsts >= VRI.NumGroups)
2197 LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n");
2199 if (InstCnt) *InstCnt += NumAndInsts;
2204 { TruncateToInt32(VRI.V, dl), getI32Imm(VRI.RLAmt, dl),
2205 getI32Imm(0, dl), getI32Imm(31, dl) };
2206 VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
2209 VRot = TruncateToInt32(VRI.V, dl);
2212 SDValue ANDIVal, ANDISVal;
2214 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI_rec, dl, MVT::i32,
2215 VRot, getI32Imm(ANDIMask, dl)),
2219 SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, VRot,
2220 getI32Imm(ANDISMask, dl)),
2225 TotalVal = ANDISVal;
2229 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
2230 ANDIVal, ANDISVal), 0);
2235 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
2238 // Now, remove all groups with this underlying value and rotation
2240 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
2241 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
2246 // Instruction selection for the 32-bit case.
2247 SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
2251 if (InstCnt) *InstCnt = 0;
2253 // Take care of cases that should use andi/andis first.
2254 SelectAndParts32(dl, Res, InstCnt);
2256 // If we've not yet selected a 'starting' instruction, and we have no zeros
2257 // to fill in, select the (Value, RLAmt) with the highest priority (largest
2258 // number of groups), and start with this rotated value.
2259 if ((!NeedMask || LateMask) && !Res) {
2260 ValueRotInfo &VRI = ValueRotsVec[0];
2262 if (InstCnt) *InstCnt += 1;
2264 { TruncateToInt32(VRI.V, dl), getI32Imm(VRI.RLAmt, dl),
2265 getI32Imm(0, dl), getI32Imm(31, dl) };
2266 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
2269 Res = TruncateToInt32(VRI.V, dl);
2272 // Now, remove all groups with this underlying value and rotation factor.
2273 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
2274 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
2278 if (InstCnt) *InstCnt += BitGroups.size();
2280 // Insert the other groups (one at a time).
2281 for (auto &BG : BitGroups) {
2284 { TruncateToInt32(BG.V, dl), getI32Imm(BG.RLAmt, dl),
2285 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
2286 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
2287 Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2290 { Res, TruncateToInt32(BG.V, dl), getI32Imm(BG.RLAmt, dl),
2291 getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
2292 getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
2293 Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
2298 unsigned Mask = (unsigned) getZerosMask();
2300 unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
2301 assert((ANDIMask != 0 || ANDISMask != 0) &&
2302 "No set bits in zeros mask?");
2304 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
2305 (unsigned) (ANDISMask != 0) +
2306 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2308 SDValue ANDIVal, ANDISVal;
2310 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI_rec, dl, MVT::i32,
2311 Res, getI32Imm(ANDIMask, dl)),
2315 SDValue(CurDAG->getMachineNode(PPC::ANDIS_rec, dl, MVT::i32, Res,
2316 getI32Imm(ANDISMask, dl)),
2324 Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
2325 ANDIVal, ANDISVal), 0);
2328 return Res.getNode();
2331 unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
2332 unsigned MaskStart, unsigned MaskEnd,
2334 // In the notation used by the instructions, 'start' and 'end' are reversed
2335 // because bits are counted from high to low order.
2336 unsigned InstMaskStart = 64 - MaskEnd - 1,
2337 InstMaskEnd = 64 - MaskStart - 1;
2342 if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
2343 InstMaskEnd == 63 - RLAmt)
2349 // For 64-bit values, not all combinations of rotates and masks are
2350 // available. Produce one if it is available.
2351 SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt,
2352 bool Repl32, unsigned MaskStart, unsigned MaskEnd,
2353 unsigned *InstCnt = nullptr) {
2354 // In the notation used by the instructions, 'start' and 'end' are reversed
2355 // because bits are counted from high to low order.
2356 unsigned InstMaskStart = 64 - MaskEnd - 1,
2357 InstMaskEnd = 64 - MaskStart - 1;
2359 if (InstCnt) *InstCnt += 1;
2362 // This rotation amount assumes that the lower 32 bits of the quantity
2363 // are replicated in the high 32 bits by the rotation operator (which is
2364 // done by rlwinm and friends).
2365 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
2366 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
2368 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2369 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };
2370 return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
2374 if (InstMaskEnd == 63) {
2376 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2377 getI32Imm(InstMaskStart, dl) };
2378 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
2381 if (InstMaskStart == 0) {
2383 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2384 getI32Imm(InstMaskEnd, dl) };
2385 return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
2388 if (InstMaskEnd == 63 - RLAmt) {
2390 { ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2391 getI32Imm(InstMaskStart, dl) };
2392 return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
2395 // We cannot do this with a single instruction, so we'll use two. The
2396 // problem is that we're not free to choose both a rotation amount and mask
2397 // start and end independently. We can choose an arbitrary mask start and
2398 // end, but then the rotation amount is fixed. Rotation, however, can be
2399 // inverted, and so by applying an "inverse" rotation first, we can get the
2401 if (InstCnt) *InstCnt += 1;
2403 // The rotation mask for the second instruction must be MaskStart.
2404 unsigned RLAmt2 = MaskStart;
2405 // The first instruction must rotate V so that the overall rotation amount
2407 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
2409 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
2410 return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
2413 // For 64-bit values, not all combinations of rotates and masks are
2414 // available. Produce a rotate-mask-and-insert if one is available.
2415 SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl,
2416 unsigned RLAmt, bool Repl32, unsigned MaskStart,
2417 unsigned MaskEnd, unsigned *InstCnt = nullptr) {
2418 // In the notation used by the instructions, 'start' and 'end' are reversed
2419 // because bits are counted from high to low order.
2420 unsigned InstMaskStart = 64 - MaskEnd - 1,
2421 InstMaskEnd = 64 - MaskStart - 1;
2423 if (InstCnt) *InstCnt += 1;
2426 // This rotation amount assumes that the lower 32 bits of the quantity
2427 // are replicated in the high 32 bits by the rotation operator (which is
2428 // done by rlwinm and friends).
2429 assert(InstMaskStart >= 32 && "Mask cannot start out of range");
2430 assert(InstMaskEnd >= 32 && "Mask cannot end out of range");
2432 { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2433 getI32Imm(InstMaskStart - 32, dl), getI32Imm(InstMaskEnd - 32, dl) };
2434 return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
2438 if (InstMaskEnd == 63 - RLAmt) {
2440 { ExtendToInt64(Base, dl), ExtendToInt64(V, dl), getI32Imm(RLAmt, dl),
2441 getI32Imm(InstMaskStart, dl) };
2442 return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
2445 // We cannot do this with a single instruction, so we'll use two. The
2446 // problem is that we're not free to choose both a rotation amount and mask
2447 // start and end independently. We can choose an arbitrary mask start and
2448 // end, but then the rotation amount is fixed. Rotation, however, can be
2449 // inverted, and so by applying an "inverse" rotation first, we can get the
2451 if (InstCnt) *InstCnt += 1;
2453 // The rotation mask for the second instruction must be MaskStart.
2454 unsigned RLAmt2 = MaskStart;
2455 // The first instruction must rotate V so that the overall rotation amount
2457 unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
2459 V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
2460 return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
2463 void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
2464 if (BPermRewriterNoMasking)
2467 // The idea here is the same as in the 32-bit version, but with additional
2468 // complications from the fact that Repl32 might be true. Because we
2469 // aggressively convert bit groups to Repl32 form (which, for small
2470 // rotation factors, involves no other change), and then coalesce, it might
2471 // be the case that a single 64-bit masking operation could handle both
2472 // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
2473 // form allowed coalescing, then we must use a 32-bit rotaton in order to
2474 // completely capture the new combined bit group.
2476 for (ValueRotInfo &VRI : ValueRotsVec) {
2479 // We need to add to the mask all bits from the associated bit groups.
2480 // If Repl32 is false, we need to add bits from bit groups that have
2481 // Repl32 true, but are trivially convertable to Repl32 false. Such a
2482 // group is trivially convertable if it overlaps only with the lower 32
2483 // bits, and the group has not been coalesced.
2484 auto MatchingBG = [VRI](const BitGroup &BG) {
2488 unsigned EffRLAmt = BG.RLAmt;
2489 if (!VRI.Repl32 && BG.Repl32) {
2490 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
2491 !BG.Repl32Coalesced) {
2497 } else if (VRI.Repl32 != BG.Repl32) {
2501 return VRI.RLAmt == EffRLAmt;
2504 for (auto &BG : BitGroups) {
2505 if (!MatchingBG(BG))
2508 if (BG.StartIdx <= BG.EndIdx) {
2509 for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
2510 Mask |= (UINT64_C(1) << i);
2512 for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
2513 Mask |= (UINT64_C(1) << i);
2514 for (unsigned i = 0; i <= BG.EndIdx; ++i)
2515 Mask |= (UINT64_C(1) << i);
2519 // We can use the 32-bit andi/andis technique if the mask does not
2520 // require any higher-order bits. This can save an instruction compared
2521 // to always using the general 64-bit technique.
2522 bool Use32BitInsts = isUInt<32>(Mask);
2523 // Compute the masks for andi/andis that would be necessary.
2524 unsigned ANDIMask = (Mask & UINT16_MAX),
2525 ANDISMask = (Mask >> 16) & UINT16_MAX;
2527 bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
2529 unsigned NumAndInsts = (unsigned) NeedsRotate +
2530 (unsigned) (bool) Res;
2531 unsigned NumOfSelectInsts = 0;
2532 selectI64Imm(CurDAG, dl, Mask, &NumOfSelectInsts);
2533 assert(NumOfSelectInsts > 0 && "Failed to select an i64 constant.");
2535 NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
2536 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2538 NumAndInsts += NumOfSelectInsts + /* and */ 1;
2540 unsigned NumRLInsts = 0;
2541 bool FirstBG = true;
2542 bool MoreBG = false;
2543 for (auto &BG : BitGroups) {
2544 if (!MatchingBG(BG)) {
2549 SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
2554 LLVM_DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode()
2555 << " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":")
2556 << "\n\t\t\tisel using masking: " << NumAndInsts
2557 << " using rotates: " << NumRLInsts << "\n");
2559 // When we'd use andi/andis, we bias toward using the rotates (andi only
2560 // has a record form, and is cracked on POWER cores). However, when using
2561 // general 64-bit constant formation, bias toward the constant form,
2562 // because that exposes more opportunities for CSE.
2563 if (NumAndInsts > NumRLInsts)
2565 // When merging multiple bit groups, instruction or is used.
2566 // But when rotate is used, rldimi can inert the rotated value into any
2567 // register, so instruction or can be avoided.
2568 if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts)
2571 LLVM_DEBUG(dbgs() << "\t\t\t\tusing masking\n");
2573 if (InstCnt) *InstCnt += NumAndInsts;
2576 // We actually need to generate a rotation if we have a non-zero rotation
2577 // factor or, in the Repl32 case, if we care about any of the
2578 // higher-order replicated bits. In the latter case, we generate a mask
2579 // backward so that it actually includes the entire 64 bits.
2580 if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
2581 VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
2582 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
2587 if (Use32BitInsts) {
2588 assert((ANDIMask != 0 || ANDISMask != 0) &&
2589 "No set bits in mask when using 32-bit ands for 64-bit value");
2591 SDValue ANDIVal, ANDISVal;
2593 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI8_rec, dl, MVT::i64,
2594 ExtendToInt64(VRot, dl),
2595 getI32Imm(ANDIMask, dl)),
2599 SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64,
2600 ExtendToInt64(VRot, dl),
2601 getI32Imm(ANDISMask, dl)),
2605 TotalVal = ANDISVal;
2609 TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2610 ExtendToInt64(ANDIVal, dl), ANDISVal), 0);
2612 TotalVal = SDValue(selectI64Imm(CurDAG, dl, Mask), 0);
2614 SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
2615 ExtendToInt64(VRot, dl), TotalVal),
2622 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2623 ExtendToInt64(Res, dl), TotalVal),
2626 // Now, remove all groups with this underlying value and rotation
2628 eraseMatchingBitGroups(MatchingBG);
2632 // Instruction selection for the 64-bit case.
2633 SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
2637 if (InstCnt) *InstCnt = 0;
2639 // Take care of cases that should use andi/andis first.
2640 SelectAndParts64(dl, Res, InstCnt);
2642 // If we've not yet selected a 'starting' instruction, and we have no zeros
2643 // to fill in, select the (Value, RLAmt) with the highest priority (largest
2644 // number of groups), and start with this rotated value.
2645 if ((!NeedMask || LateMask) && !Res) {
2646 // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
2647 // groups will come first, and so the VRI representing the largest number
2648 // of groups might not be first (it might be the first Repl32 groups).
2649 unsigned MaxGroupsIdx = 0;
2650 if (!ValueRotsVec[0].Repl32) {
2651 for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
2652 if (ValueRotsVec[i].Repl32) {
2653 if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
2659 ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
2660 bool NeedsRotate = false;
2663 } else if (VRI.Repl32) {
2664 for (auto &BG : BitGroups) {
2665 if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
2666 BG.Repl32 != VRI.Repl32)
2669 // We don't need a rotate if the bit group is confined to the lower
2671 if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
2680 Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
2681 VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
2686 // Now, remove all groups with this underlying value and rotation factor.
2688 eraseMatchingBitGroups([VRI](const BitGroup &BG) {
2689 return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
2690 BG.Repl32 == VRI.Repl32;
2694 // Because 64-bit rotates are more flexible than inserts, we might have a
2695 // preference regarding which one we do first (to save one instruction).
2697 for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
2698 if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
2700 SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
2702 if (I != BitGroups.begin()) {
2705 BitGroups.insert(BitGroups.begin(), BG);
2712 // Insert the other groups (one at a time).
2713 for (auto &BG : BitGroups) {
2715 Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
2716 BG.EndIdx, InstCnt);
2718 Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
2719 BG.StartIdx, BG.EndIdx, InstCnt);
2723 uint64_t Mask = getZerosMask();
2725 // We can use the 32-bit andi/andis technique if the mask does not
2726 // require any higher-order bits. This can save an instruction compared
2727 // to always using the general 64-bit technique.
2728 bool Use32BitInsts = isUInt<32>(Mask);
2729 // Compute the masks for andi/andis that would be necessary.
2730 unsigned ANDIMask = (Mask & UINT16_MAX),
2731 ANDISMask = (Mask >> 16) & UINT16_MAX;
2733 if (Use32BitInsts) {
2734 assert((ANDIMask != 0 || ANDISMask != 0) &&
2735 "No set bits in mask when using 32-bit ands for 64-bit value");
2737 if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
2738 (unsigned) (ANDISMask != 0) +
2739 (unsigned) (ANDIMask != 0 && ANDISMask != 0);
2741 SDValue ANDIVal, ANDISVal;
2743 ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDI8_rec, dl, MVT::i64,
2744 ExtendToInt64(Res, dl),
2745 getI32Imm(ANDIMask, dl)),
2749 SDValue(CurDAG->getMachineNode(PPC::ANDIS8_rec, dl, MVT::i64,
2750 ExtendToInt64(Res, dl),
2751 getI32Imm(ANDISMask, dl)),
2759 Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
2760 ExtendToInt64(ANDIVal, dl), ANDISVal), 0);
2762 unsigned NumOfSelectInsts = 0;
2764 SDValue(selectI64Imm(CurDAG, dl, Mask, &NumOfSelectInsts), 0);
2765 Res = SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
2766 ExtendToInt64(Res, dl), MaskVal),
2769 *InstCnt += NumOfSelectInsts + /* and */ 1;
2773 return Res.getNode();
2776 SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
2777 // Fill in BitGroups.
2778 collectBitGroups(LateMask);
2779 if (BitGroups.empty())
2782 // For 64-bit values, figure out when we can use 32-bit instructions.
2783 if (Bits.size() == 64)
2784 assignRepl32BitGroups();
2786 // Fill in ValueRotsVec.
2787 collectValueRotInfo();
2789 if (Bits.size() == 32) {
2790 return Select32(N, LateMask, InstCnt);
2792 assert(Bits.size() == 64 && "Not 64 bits here?");
2793 return Select64(N, LateMask, InstCnt);
2799 void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
2800 erase_if(BitGroups, F);
2803 SmallVector<ValueBit, 64> Bits;
2805 bool NeedMask = false;
2806 SmallVector<unsigned, 64> RLAmt;
2808 SmallVector<BitGroup, 16> BitGroups;
2810 DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
2811 SmallVector<ValueRotInfo, 16> ValueRotsVec;
2813 SelectionDAG *CurDAG = nullptr;
2816 BitPermutationSelector(SelectionDAG *DAG)
2819 // Here we try to match complex bit permutations into a set of
2820 // rotate-and-shift/shift/and/or instructions, using a set of heuristics
2821 // known to produce optimal code for common cases (like i32 byte swapping).
2822 SDNode *Select(SDNode *N) {
2825 getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits());
2828 Bits = std::move(*Result.second);
2830 LLVM_DEBUG(dbgs() << "Considering bit-permutation-based instruction"
2831 " selection for: ");
2832 LLVM_DEBUG(N->dump(CurDAG));
2834 // Fill it RLAmt and set NeedMask.
2835 computeRotationAmounts();
2838 return Select(N, false);
2840 // We currently have two techniques for handling results with zeros: early
2841 // masking (the default) and late masking. Late masking is sometimes more
2842 // efficient, but because the structure of the bit groups is different, it
2843 // is hard to tell without generating both and comparing the results. With
2844 // late masking, we ignore zeros in the resulting value when inserting each
2845 // set of bit groups, and then mask in the zeros at the end. With early
2846 // masking, we only insert the non-zero parts of the result at every step.
2848 unsigned InstCnt = 0, InstCntLateMask = 0;
2849 LLVM_DEBUG(dbgs() << "\tEarly masking:\n");
2850 SDNode *RN = Select(N, false, &InstCnt);
2851 LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
2853 LLVM_DEBUG(dbgs() << "\tLate masking:\n");
2854 SDNode *RNLM = Select(N, true, &InstCntLateMask);
2855 LLVM_DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask
2856 << " instructions\n");
2858 if (InstCnt <= InstCntLateMask) {
2859 LLVM_DEBUG(dbgs() << "\tUsing early-masking for isel\n");
2863 LLVM_DEBUG(dbgs() << "\tUsing late-masking for isel\n");
2868 class IntegerCompareEliminator {
2869 SelectionDAG *CurDAG;
2871 // Conversion type for interpreting results of a 32-bit instruction as
2872 // a 64-bit value or vice versa.
2873 enum ExtOrTruncConversion { Ext, Trunc };
2875 // Modifiers to guide how an ISD::SETCC node's result is to be computed
2877 // ZExtOrig - use the original condition code, zero-extend value
2878 // ZExtInvert - invert the condition code, zero-extend value
2879 // SExtOrig - use the original condition code, sign-extend value
2880 // SExtInvert - invert the condition code, sign-extend value
2881 enum SetccInGPROpts { ZExtOrig, ZExtInvert, SExtOrig, SExtInvert };
2883 // Comparisons against zero to emit GPR code sequences for. Each of these
2884 // sequences may need to be emitted for two or more equivalent patterns.
2885 // For example (a >= 0) == (a > -1). The direction of the comparison (</>)
2886 // matters as well as the extension type: sext (-1/0), zext (1/0).
2887 // GEZExt - (zext (LHS >= 0))
2888 // GESExt - (sext (LHS >= 0))
2889 // LEZExt - (zext (LHS <= 0))
2890 // LESExt - (sext (LHS <= 0))
2891 enum ZeroCompare { GEZExt, GESExt, LEZExt, LESExt };
2893 SDNode *tryEXTEND(SDNode *N);
2894 SDNode *tryLogicOpOfCompares(SDNode *N);
2895 SDValue computeLogicOpInGPR(SDValue LogicOp);
2896 SDValue signExtendInputIfNeeded(SDValue Input);
2897 SDValue zeroExtendInputIfNeeded(SDValue Input);
2898 SDValue addExtOrTrunc(SDValue NatWidthRes, ExtOrTruncConversion Conv);
2899 SDValue getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
2901 SDValue get32BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2902 int64_t RHSValue, SDLoc dl);
2903 SDValue get32BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2904 int64_t RHSValue, SDLoc dl);
2905 SDValue get64BitZExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2906 int64_t RHSValue, SDLoc dl);
2907 SDValue get64BitSExtCompare(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2908 int64_t RHSValue, SDLoc dl);
2909 SDValue getSETCCInGPR(SDValue Compare, SetccInGPROpts ConvOpts);
2912 IntegerCompareEliminator(SelectionDAG *DAG,
2913 PPCDAGToDAGISel *Sel) : CurDAG(DAG), S(Sel) {
2914 assert(CurDAG->getTargetLoweringInfo()
2915 .getPointerTy(CurDAG->getDataLayout()).getSizeInBits() == 64 &&
2916 "Only expecting to use this on 64 bit targets.");
2918 SDNode *Select(SDNode *N) {
2919 if (CmpInGPR == ICGPR_None)
2921 switch (N->getOpcode()) {
2923 case ISD::ZERO_EXTEND:
2924 if (CmpInGPR == ICGPR_Sext || CmpInGPR == ICGPR_SextI32 ||
2925 CmpInGPR == ICGPR_SextI64)
2928 case ISD::SIGN_EXTEND:
2929 if (CmpInGPR == ICGPR_Zext || CmpInGPR == ICGPR_ZextI32 ||
2930 CmpInGPR == ICGPR_ZextI64)
2932 return tryEXTEND(N);
2936 return tryLogicOpOfCompares(N);
2942 // The obvious case for wanting to keep the value in a GPR. Namely, the
2943 // result of the comparison is actually needed in a GPR.
2944 SDNode *IntegerCompareEliminator::tryEXTEND(SDNode *N) {
2945 assert((N->getOpcode() == ISD::ZERO_EXTEND ||
2946 N->getOpcode() == ISD::SIGN_EXTEND) &&
2947 "Expecting a zero/sign extend node!");
2949 // If we are zero-extending the result of a logical operation on i1
2950 // values, we can keep the values in GPRs.
2951 if (ISD::isBitwiseLogicOp(N->getOperand(0).getOpcode()) &&
2952 N->getOperand(0).getValueType() == MVT::i1 &&
2953 N->getOpcode() == ISD::ZERO_EXTEND)
2954 WideRes = computeLogicOpInGPR(N->getOperand(0));
2955 else if (N->getOperand(0).getOpcode() != ISD::SETCC)
2959 getSETCCInGPR(N->getOperand(0),
2960 N->getOpcode() == ISD::SIGN_EXTEND ?
2961 SetccInGPROpts::SExtOrig : SetccInGPROpts::ZExtOrig);
2967 bool Input32Bit = WideRes.getValueType() == MVT::i32;
2968 bool Output32Bit = N->getValueType(0) == MVT::i32;
2970 NumSextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 1 : 0;
2971 NumZextSetcc += N->getOpcode() == ISD::SIGN_EXTEND ? 0 : 1;
2973 SDValue ConvOp = WideRes;
2974 if (Input32Bit != Output32Bit)
2975 ConvOp = addExtOrTrunc(WideRes, Input32Bit ? ExtOrTruncConversion::Ext :
2976 ExtOrTruncConversion::Trunc);
2977 return ConvOp.getNode();
2980 // Attempt to perform logical operations on the results of comparisons while
2981 // keeping the values in GPRs. Without doing so, these would end up being
2982 // lowered to CR-logical operations which suffer from significant latency and
2984 SDNode *IntegerCompareEliminator::tryLogicOpOfCompares(SDNode *N) {
2985 if (N->getValueType(0) != MVT::i1)
2987 assert(ISD::isBitwiseLogicOp(N->getOpcode()) &&
2988 "Expected a logic operation on setcc results.");
2989 SDValue LoweredLogical = computeLogicOpInGPR(SDValue(N, 0));
2990 if (!LoweredLogical)
2994 bool IsBitwiseNegate = LoweredLogical.getMachineOpcode() == PPC::XORI8;
2995 unsigned SubRegToExtract = IsBitwiseNegate ? PPC::sub_eq : PPC::sub_gt;
2996 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2997 SDValue LHS = LoweredLogical.getOperand(0);
2998 SDValue RHS = LoweredLogical.getOperand(1);
3000 SDValue OpToConvToRecForm;
3002 // Look through any 32-bit to 64-bit implicit extend nodes to find the
3003 // opcode that is input to the XORI.
3004 if (IsBitwiseNegate &&
3005 LoweredLogical.getOperand(0).getMachineOpcode() == PPC::INSERT_SUBREG)
3006 OpToConvToRecForm = LoweredLogical.getOperand(0).getOperand(1);
3007 else if (IsBitwiseNegate)
3008 // If the input to the XORI isn't an extension, that's what we're after.
3009 OpToConvToRecForm = LoweredLogical.getOperand(0);
3011 // If this is not an XORI, it is a reg-reg logical op and we can convert
3012 // it to record-form.
3013 OpToConvToRecForm = LoweredLogical;
3015 // Get the record-form version of the node we're looking to use to get the
3017 uint16_t NonRecOpc = OpToConvToRecForm.getMachineOpcode();
3018 int NewOpc = PPCInstrInfo::getRecordFormOpcode(NonRecOpc);
3020 // Convert the right node to record-form. This is either the logical we're
3021 // looking at or it is the input node to the negation (if we're looking at
3022 // a bitwise negation).
3023 if (NewOpc != -1 && IsBitwiseNegate) {
3024 // The input to the XORI has a record-form. Use it.
3025 assert(LoweredLogical.getConstantOperandVal(1) == 1 &&
3026 "Expected a PPC::XORI8 only for bitwise negation.");
3027 // Emit the record-form instruction.
3028 std::vector<SDValue> Ops;
3029 for (int i = 0, e = OpToConvToRecForm.getNumOperands(); i < e; i++)
3030 Ops.push_back(OpToConvToRecForm.getOperand(i));
3033 SDValue(CurDAG->getMachineNode(NewOpc, dl,
3034 OpToConvToRecForm.getValueType(),
3035 MVT::Glue, Ops), 0);
3037 assert((NewOpc != -1 || !IsBitwiseNegate) &&
3038 "No record form available for AND8/OR8/XOR8?");
3040 SDValue(CurDAG->getMachineNode(NewOpc == -1 ? PPC::ANDI8_rec : NewOpc,
3041 dl, MVT::i64, MVT::Glue, LHS, RHS),
3045 // Select this node to a single bit from CR0 set by the record-form node
3046 // just created. For bitwise negation, use the EQ bit which is the equivalent
3047 // of negating the result (i.e. it is a bit set when the result of the
3048 // operation is zero).
3050 CurDAG->getTargetConstant(SubRegToExtract, dl, MVT::i32);
3052 SDValue(CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl,
3053 MVT::i1, CR0Reg, SRIdxVal,
3054 WideOp.getValue(1)), 0);
3055 return CRBit.getNode();
3058 // Lower a logical operation on i1 values into a GPR sequence if possible.
3059 // The result can be kept in a GPR if requested.
3060 // Three types of inputs can be handled:
3063 // - Logical operation (AND/OR/XOR)
3064 // There is also a special case that is handled (namely a complement operation
3065 // achieved with xor %a, -1).
3066 SDValue IntegerCompareEliminator::computeLogicOpInGPR(SDValue LogicOp) {
3067 assert(ISD::isBitwiseLogicOp(LogicOp.getOpcode()) &&
3068 "Can only handle logic operations here.");
3069 assert(LogicOp.getValueType() == MVT::i1 &&
3070 "Can only handle logic operations on i1 values here.");
3074 // Special case: xor %a, -1
3075 bool IsBitwiseNegation = isBitwiseNot(LogicOp);
3077 // Produces a GPR sequence for each operand of the binary logic operation.
3078 // For SETCC, it produces the respective comparison, for TRUNCATE it truncates
3079 // the value in a GPR and for logic operations, it will recursively produce
3080 // a GPR sequence for the operation.
3081 auto getLogicOperand = [&] (SDValue Operand) -> SDValue {
3082 unsigned OperandOpcode = Operand.getOpcode();
3083 if (OperandOpcode == ISD::SETCC)
3084 return getSETCCInGPR(Operand, SetccInGPROpts::ZExtOrig);
3085 else if (OperandOpcode == ISD::TRUNCATE) {
3086 SDValue InputOp = Operand.getOperand(0);
3087 EVT InVT = InputOp.getValueType();
3088 return SDValue(CurDAG->getMachineNode(InVT == MVT::i32 ? PPC::RLDICL_32 :
3089 PPC::RLDICL, dl, InVT, InputOp,
3090 S->getI64Imm(0, dl),
3091 S->getI64Imm(63, dl)), 0);
3092 } else if (ISD::isBitwiseLogicOp(OperandOpcode))
3093 return computeLogicOpInGPR(Operand);
3096 LHS = getLogicOperand(LogicOp.getOperand(0));
3097 RHS = getLogicOperand(LogicOp.getOperand(1));
3099 // If a GPR sequence can't be produced for the LHS we can't proceed.
3100 // Not producing a GPR sequence for the RHS is only a problem if this isn't
3101 // a bitwise negation operation.
3102 if (!LHS || (!RHS && !IsBitwiseNegation))
3105 NumLogicOpsOnComparison++;
3107 // We will use the inputs as 64-bit values.
3108 if (LHS.getValueType() == MVT::i32)
3109 LHS = addExtOrTrunc(LHS, ExtOrTruncConversion::Ext);
3110 if (!IsBitwiseNegation && RHS.getValueType() == MVT::i32)
3111 RHS = addExtOrTrunc(RHS, ExtOrTruncConversion::Ext);
3114 switch (LogicOp.getOpcode()) {
3115 default: llvm_unreachable("Unknown logic operation.");
3116 case ISD::AND: NewOpc = PPC::AND8; break;
3117 case ISD::OR: NewOpc = PPC::OR8; break;
3118 case ISD::XOR: NewOpc = PPC::XOR8; break;
3121 if (IsBitwiseNegation) {
3122 RHS = S->getI64Imm(1, dl);
3123 NewOpc = PPC::XORI8;
3126 return SDValue(CurDAG->getMachineNode(NewOpc, dl, MVT::i64, LHS, RHS), 0);
3130 /// If the value isn't guaranteed to be sign-extended to 64-bits, extend it.
3131 /// Otherwise just reinterpret it as a 64-bit value.
3132 /// Useful when emitting comparison code for 32-bit values without using
3133 /// the compare instruction (which only considers the lower 32-bits).
3134 SDValue IntegerCompareEliminator::signExtendInputIfNeeded(SDValue Input) {
3135 assert(Input.getValueType() == MVT::i32 &&
3136 "Can only sign-extend 32-bit values here.");
3137 unsigned Opc = Input.getOpcode();
3139 // The value was sign extended and then truncated to 32-bits. No need to
3140 // sign extend it again.
3141 if (Opc == ISD::TRUNCATE &&
3142 (Input.getOperand(0).getOpcode() == ISD::AssertSext ||
3143 Input.getOperand(0).getOpcode() == ISD::SIGN_EXTEND))
3144 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3146 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
3147 // The input is a sign-extending load. All ppc sign-extending loads
3148 // sign-extend to the full 64-bits.
3149 if (InputLoad && InputLoad->getExtensionType() == ISD::SEXTLOAD)
3150 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3152 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
3153 // We don't sign-extend constants.
3155 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3158 SignExtensionsAdded++;
3159 return SDValue(CurDAG->getMachineNode(PPC::EXTSW_32_64, dl,
3160 MVT::i64, Input), 0);
3163 /// If the value isn't guaranteed to be zero-extended to 64-bits, extend it.
3164 /// Otherwise just reinterpret it as a 64-bit value.
3165 /// Useful when emitting comparison code for 32-bit values without using
3166 /// the compare instruction (which only considers the lower 32-bits).
3167 SDValue IntegerCompareEliminator::zeroExtendInputIfNeeded(SDValue Input) {
3168 assert(Input.getValueType() == MVT::i32 &&
3169 "Can only zero-extend 32-bit values here.");
3170 unsigned Opc = Input.getOpcode();
3172 // The only condition under which we can omit the actual extend instruction:
3173 // - The value is a positive constant
3174 // - The value comes from a load that isn't a sign-extending load
3175 // An ISD::TRUNCATE needs to be zero-extended unless it is fed by a zext.
3176 bool IsTruncateOfZExt = Opc == ISD::TRUNCATE &&
3177 (Input.getOperand(0).getOpcode() == ISD::AssertZext ||
3178 Input.getOperand(0).getOpcode() == ISD::ZERO_EXTEND);
3179 if (IsTruncateOfZExt)
3180 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3182 ConstantSDNode *InputConst = dyn_cast<ConstantSDNode>(Input);
3183 if (InputConst && InputConst->getSExtValue() >= 0)
3184 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3186 LoadSDNode *InputLoad = dyn_cast<LoadSDNode>(Input);
3187 // The input is a load that doesn't sign-extend (it will be zero-extended).
3188 if (InputLoad && InputLoad->getExtensionType() != ISD::SEXTLOAD)
3189 return addExtOrTrunc(Input, ExtOrTruncConversion::Ext);
3191 // None of the above, need to zero-extend.
3193 ZeroExtensionsAdded++;
3194 return SDValue(CurDAG->getMachineNode(PPC::RLDICL_32_64, dl, MVT::i64, Input,
3195 S->getI64Imm(0, dl),
3196 S->getI64Imm(32, dl)), 0);
3199 // Handle a 32-bit value in a 64-bit register and vice-versa. These are of
3200 // course not actual zero/sign extensions that will generate machine code,
3201 // they're just a way to reinterpret a 32 bit value in a register as a
3202 // 64 bit value and vice-versa.
3203 SDValue IntegerCompareEliminator::addExtOrTrunc(SDValue NatWidthRes,
3204 ExtOrTruncConversion Conv) {
3205 SDLoc dl(NatWidthRes);
3207 // For reinterpreting 32-bit values as 64 bit values, we generate
3208 // INSERT_SUBREG IMPLICIT_DEF:i64, <input>, TargetConstant:i32<1>
3209 if (Conv == ExtOrTruncConversion::Ext) {
3210 SDValue ImDef(CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, MVT::i64), 0);
3212 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
3213 return SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, MVT::i64,
3214 ImDef, NatWidthRes, SubRegIdx), 0);
3217 assert(Conv == ExtOrTruncConversion::Trunc &&
3218 "Unknown convertion between 32 and 64 bit values.");
3219 // For reinterpreting 64-bit values as 32-bit values, we just need to
3220 // EXTRACT_SUBREG (i.e. extract the low word).
3222 CurDAG->getTargetConstant(PPC::sub_32, dl, MVT::i32);
3223 return SDValue(CurDAG->getMachineNode(PPC::EXTRACT_SUBREG, dl, MVT::i32,
3224 NatWidthRes, SubRegIdx), 0);
3227 // Produce a GPR sequence for compound comparisons (<=, >=) against zero.
3228 // Handle both zero-extensions and sign-extensions.
3230 IntegerCompareEliminator::getCompoundZeroComparisonInGPR(SDValue LHS, SDLoc dl,
3231 ZeroCompare CmpTy) {
3232 EVT InVT = LHS.getValueType();
3233 bool Is32Bit = InVT == MVT::i32;
3236 // Produce the value that needs to be either zero or sign extended.
3238 case ZeroCompare::GEZExt:
3239 case ZeroCompare::GESExt:
3240 ToExtend = SDValue(CurDAG->getMachineNode(Is32Bit ? PPC::NOR : PPC::NOR8,
3241 dl, InVT, LHS, LHS), 0);
3243 case ZeroCompare::LEZExt:
3244 case ZeroCompare::LESExt: {
3246 // Upper 32 bits cannot be undefined for this sequence.
3247 LHS = signExtendInputIfNeeded(LHS);
3249 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
3251 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3252 Neg, S->getI64Imm(1, dl),
3253 S->getI64Imm(63, dl)), 0);
3256 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3257 S->getI64Imm(~0ULL, dl)), 0);
3258 ToExtend = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
3265 // For 64-bit sequences, the extensions are the same for the GE/LE cases.
3267 (CmpTy == ZeroCompare::GEZExt || CmpTy == ZeroCompare::LEZExt))
3268 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3269 ToExtend, S->getI64Imm(1, dl),
3270 S->getI64Imm(63, dl)), 0);
3272 (CmpTy == ZeroCompare::GESExt || CmpTy == ZeroCompare::LESExt))
3273 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, ToExtend,
3274 S->getI64Imm(63, dl)), 0);
3276 assert(Is32Bit && "Should have handled the 32-bit sequences above.");
3277 // For 32-bit sequences, the extensions differ between GE/LE cases.
3279 case ZeroCompare::GEZExt: {
3280 SDValue ShiftOps[] = { ToExtend, S->getI32Imm(1, dl), S->getI32Imm(31, dl),
3281 S->getI32Imm(31, dl) };
3282 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
3285 case ZeroCompare::GESExt:
3286 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, ToExtend,
3287 S->getI32Imm(31, dl)), 0);
3288 case ZeroCompare::LEZExt:
3289 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, ToExtend,
3290 S->getI32Imm(1, dl)), 0);
3291 case ZeroCompare::LESExt:
3292 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, ToExtend,
3293 S->getI32Imm(-1, dl)), 0);
3296 // The above case covers all the enumerators so it can't have a default clause
3297 // to avoid compiler warnings.
3298 llvm_unreachable("Unknown zero-comparison type.");
3301 /// Produces a zero-extended result of comparing two 32-bit values according to
3302 /// the passed condition code.
3304 IntegerCompareEliminator::get32BitZExtCompare(SDValue LHS, SDValue RHS,
3306 int64_t RHSValue, SDLoc dl) {
3307 if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 ||
3308 CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Sext)
3310 bool IsRHSZero = RHSValue == 0;
3311 bool IsRHSOne = RHSValue == 1;
3312 bool IsRHSNegOne = RHSValue == -1LL;
3314 default: return SDValue();
3316 // (zext (setcc %a, %b, seteq)) -> (lshr (cntlzw (xor %a, %b)), 5)
3317 // (zext (setcc %a, 0, seteq)) -> (lshr (cntlzw %a), 5)
3318 SDValue Xor = IsRHSZero ? LHS :
3319 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3321 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
3322 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),
3323 S->getI32Imm(31, dl) };
3324 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
3328 // (zext (setcc %a, %b, setne)) -> (xor (lshr (cntlzw (xor %a, %b)), 5), 1)
3329 // (zext (setcc %a, 0, setne)) -> (xor (lshr (cntlzw %a), 5), 1)
3330 SDValue Xor = IsRHSZero ? LHS :
3331 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3333 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
3334 SDValue ShiftOps[] = { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl),
3335 S->getI32Imm(31, dl) };
3337 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
3338 return SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
3339 S->getI32Imm(1, dl)), 0);
3342 // (zext (setcc %a, %b, setge)) -> (xor (lshr (sub %a, %b), 63), 1)
3343 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 31)
3345 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3347 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
3348 // by swapping inputs and falling through.
3349 std::swap(LHS, RHS);
3350 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3351 IsRHSZero = RHSConst && RHSConst->isZero();
3355 if (CmpInGPR == ICGPR_NonExtIn)
3357 // (zext (setcc %a, %b, setle)) -> (xor (lshr (sub %b, %a), 63), 1)
3358 // (zext (setcc %a, 0, setle)) -> (xor (lshr (- %a), 63), 1)
3360 if (CmpInGPR == ICGPR_NonExtIn)
3362 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3365 // The upper 32-bits of the register can't be undefined for this sequence.
3366 LHS = signExtendInputIfNeeded(LHS);
3367 RHS = signExtendInputIfNeeded(RHS);
3369 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
3371 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Sub,
3372 S->getI64Imm(1, dl), S->getI64Imm(63, dl)),
3375 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl,
3376 MVT::i64, Shift, S->getI32Imm(1, dl)), 0);
3379 // (zext (setcc %a, %b, setgt)) -> (lshr (sub %b, %a), 63)
3380 // (zext (setcc %a, -1, setgt)) -> (lshr (~ %a), 31)
3381 // (zext (setcc %a, 0, setgt)) -> (lshr (- %a), 63)
3382 // Handle SETLT -1 (which is equivalent to SETGE 0).
3384 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3387 if (CmpInGPR == ICGPR_NonExtIn)
3389 // The upper 32-bits of the register can't be undefined for this sequence.
3390 LHS = signExtendInputIfNeeded(LHS);
3391 RHS = signExtendInputIfNeeded(RHS);
3393 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
3394 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3395 Neg, S->getI32Imm(1, dl), S->getI32Imm(63, dl)), 0);
3397 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as
3398 // (%b < %a) by swapping inputs and falling through.
3399 std::swap(LHS, RHS);
3400 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3401 IsRHSZero = RHSConst && RHSConst->isZero();
3402 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3406 // (zext (setcc %a, %b, setlt)) -> (lshr (sub %a, %b), 63)
3407 // (zext (setcc %a, 1, setlt)) -> (xor (lshr (- %a), 63), 1)
3408 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 31)
3409 // Handle SETLT 1 (which is equivalent to SETLE 0).
3411 if (CmpInGPR == ICGPR_NonExtIn)
3413 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3417 SDValue ShiftOps[] = { LHS, S->getI32Imm(1, dl), S->getI32Imm(31, dl),
3418 S->getI32Imm(31, dl) };
3419 return SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
3423 if (CmpInGPR == ICGPR_NonExtIn)
3425 // The upper 32-bits of the register can't be undefined for this sequence.
3426 LHS = signExtendInputIfNeeded(LHS);
3427 RHS = signExtendInputIfNeeded(RHS);
3429 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3430 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3431 SUBFNode, S->getI64Imm(1, dl),
3432 S->getI64Imm(63, dl)), 0);
3435 // (zext (setcc %a, %b, setuge)) -> (xor (lshr (sub %b, %a), 63), 1)
3436 // (zext (setcc %a, %b, setule)) -> (xor (lshr (sub %a, %b), 63), 1)
3437 std::swap(LHS, RHS);
3440 if (CmpInGPR == ICGPR_NonExtIn)
3442 // The upper 32-bits of the register can't be undefined for this sequence.
3443 LHS = zeroExtendInputIfNeeded(LHS);
3444 RHS = zeroExtendInputIfNeeded(RHS);
3446 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
3448 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3449 Subtract, S->getI64Imm(1, dl),
3450 S->getI64Imm(63, dl)), 0);
3451 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64, SrdiNode,
3452 S->getI32Imm(1, dl)), 0);
3455 // (zext (setcc %a, %b, setugt)) -> (lshr (sub %b, %a), 63)
3456 // (zext (setcc %a, %b, setult)) -> (lshr (sub %a, %b), 63)
3457 std::swap(LHS, RHS);
3460 if (CmpInGPR == ICGPR_NonExtIn)
3462 // The upper 32-bits of the register can't be undefined for this sequence.
3463 LHS = zeroExtendInputIfNeeded(LHS);
3464 RHS = zeroExtendInputIfNeeded(RHS);
3466 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3467 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3468 Subtract, S->getI64Imm(1, dl),
3469 S->getI64Imm(63, dl)), 0);
3474 /// Produces a sign-extended result of comparing two 32-bit values according to
3475 /// the passed condition code.
3477 IntegerCompareEliminator::get32BitSExtCompare(SDValue LHS, SDValue RHS,
3479 int64_t RHSValue, SDLoc dl) {
3480 if (CmpInGPR == ICGPR_I64 || CmpInGPR == ICGPR_SextI64 ||
3481 CmpInGPR == ICGPR_ZextI64 || CmpInGPR == ICGPR_Zext)
3483 bool IsRHSZero = RHSValue == 0;
3484 bool IsRHSOne = RHSValue == 1;
3485 bool IsRHSNegOne = RHSValue == -1LL;
3488 default: return SDValue();
3490 // (sext (setcc %a, %b, seteq)) ->
3491 // (ashr (shl (ctlz (xor %a, %b)), 58), 63)
3492 // (sext (setcc %a, 0, seteq)) ->
3493 // (ashr (shl (ctlz %a), 58), 63)
3494 SDValue CountInput = IsRHSZero ? LHS :
3495 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3497 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, CountInput), 0);
3498 SDValue SHLOps[] = { Cntlzw, S->getI32Imm(27, dl),
3499 S->getI32Imm(5, dl), S->getI32Imm(31, dl) };
3501 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, SHLOps), 0);
3502 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Slwi), 0);
3505 // Bitwise xor the operands, count leading zeros, shift right by 5 bits and
3506 // flip the bit, finally take 2's complement.
3507 // (sext (setcc %a, %b, setne)) ->
3508 // (neg (xor (lshr (ctlz (xor %a, %b)), 5), 1))
3509 // Same as above, but the first xor is not needed.
3510 // (sext (setcc %a, 0, setne)) ->
3511 // (neg (xor (lshr (ctlz %a), 5), 1))
3512 SDValue Xor = IsRHSZero ? LHS :
3513 SDValue(CurDAG->getMachineNode(PPC::XOR, dl, MVT::i32, LHS, RHS), 0);
3515 SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Xor), 0);
3516 SDValue ShiftOps[] =
3517 { Clz, S->getI32Imm(27, dl), S->getI32Imm(5, dl), S->getI32Imm(31, dl) };
3519 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, ShiftOps), 0);
3521 SDValue(CurDAG->getMachineNode(PPC::XORI, dl, MVT::i32, Shift,
3522 S->getI32Imm(1, dl)), 0);
3523 return SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Xori), 0);
3526 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %a, %b), 63), -1)
3527 // (sext (setcc %a, 0, setge)) -> (ashr (~ %a), 31)
3529 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3531 // Not a special case (i.e. RHS == 0). Handle (%a >= %b) as (%b <= %a)
3532 // by swapping inputs and falling through.
3533 std::swap(LHS, RHS);
3534 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3535 IsRHSZero = RHSConst && RHSConst->isZero();
3539 if (CmpInGPR == ICGPR_NonExtIn)
3541 // (sext (setcc %a, %b, setge)) -> (add (lshr (sub %b, %a), 63), -1)
3542 // (sext (setcc %a, 0, setle)) -> (add (lshr (- %a), 63), -1)
3544 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3546 // The upper 32-bits of the register can't be undefined for this sequence.
3547 LHS = signExtendInputIfNeeded(LHS);
3548 RHS = signExtendInputIfNeeded(RHS);
3550 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, MVT::Glue,
3553 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3554 SUBFNode, S->getI64Imm(1, dl),
3555 S->getI64Imm(63, dl)), 0);
3556 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Srdi,
3557 S->getI32Imm(-1, dl)), 0);
3560 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %b, %a), 63)
3561 // (sext (setcc %a, -1, setgt)) -> (ashr (~ %a), 31)
3562 // (sext (setcc %a, 0, setgt)) -> (ashr (- %a), 63)
3564 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3566 if (CmpInGPR == ICGPR_NonExtIn)
3568 // The upper 32-bits of the register can't be undefined for this sequence.
3569 LHS = signExtendInputIfNeeded(LHS);
3570 RHS = signExtendInputIfNeeded(RHS);
3572 SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, LHS), 0);
3573 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Neg,
3574 S->getI64Imm(63, dl)), 0);
3576 // Not a special case (i.e. RHS == 0 or RHS == -1). Handle (%a > %b) as
3577 // (%b < %a) by swapping inputs and falling through.
3578 std::swap(LHS, RHS);
3579 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3580 IsRHSZero = RHSConst && RHSConst->isZero();
3581 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3585 // (sext (setcc %a, %b, setgt)) -> (ashr (sub %a, %b), 63)
3586 // (sext (setcc %a, 1, setgt)) -> (add (lshr (- %a), 63), -1)
3587 // (sext (setcc %a, 0, setgt)) -> (ashr %a, 31)
3589 if (CmpInGPR == ICGPR_NonExtIn)
3591 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3594 return SDValue(CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, LHS,
3595 S->getI32Imm(31, dl)), 0);
3597 if (CmpInGPR == ICGPR_NonExtIn)
3599 // The upper 32-bits of the register can't be undefined for this sequence.
3600 LHS = signExtendInputIfNeeded(LHS);
3601 RHS = signExtendInputIfNeeded(RHS);
3603 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3604 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3605 SUBFNode, S->getI64Imm(63, dl)), 0);
3608 // (sext (setcc %a, %b, setuge)) -> (add (lshr (sub %a, %b), 63), -1)
3609 // (sext (setcc %a, %b, setule)) -> (add (lshr (sub %b, %a), 63), -1)
3610 std::swap(LHS, RHS);
3613 if (CmpInGPR == ICGPR_NonExtIn)
3615 // The upper 32-bits of the register can't be undefined for this sequence.
3616 LHS = zeroExtendInputIfNeeded(LHS);
3617 RHS = zeroExtendInputIfNeeded(RHS);
3619 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, LHS, RHS), 0);
3621 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Subtract,
3622 S->getI32Imm(1, dl), S->getI32Imm(63,dl)),
3624 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, Shift,
3625 S->getI32Imm(-1, dl)), 0);
3628 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %b, %a), 63)
3629 // (sext (setcc %a, %b, setugt)) -> (ashr (sub %a, %b), 63)
3630 std::swap(LHS, RHS);
3633 if (CmpInGPR == ICGPR_NonExtIn)
3635 // The upper 32-bits of the register can't be undefined for this sequence.
3636 LHS = zeroExtendInputIfNeeded(LHS);
3637 RHS = zeroExtendInputIfNeeded(RHS);
3639 SDValue(CurDAG->getMachineNode(PPC::SUBF8, dl, MVT::i64, RHS, LHS), 0);
3640 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3641 Subtract, S->getI64Imm(63, dl)), 0);
3646 /// Produces a zero-extended result of comparing two 64-bit values according to
3647 /// the passed condition code.
3649 IntegerCompareEliminator::get64BitZExtCompare(SDValue LHS, SDValue RHS,
3651 int64_t RHSValue, SDLoc dl) {
3652 if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 ||
3653 CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Sext)
3655 bool IsRHSZero = RHSValue == 0;
3656 bool IsRHSOne = RHSValue == 1;
3657 bool IsRHSNegOne = RHSValue == -1LL;
3659 default: return SDValue();
3661 // (zext (setcc %a, %b, seteq)) -> (lshr (ctlz (xor %a, %b)), 6)
3662 // (zext (setcc %a, 0, seteq)) -> (lshr (ctlz %a), 6)
3663 SDValue Xor = IsRHSZero ? LHS :
3664 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3666 SDValue(CurDAG->getMachineNode(PPC::CNTLZD, dl, MVT::i64, Xor), 0);
3667 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Clz,
3668 S->getI64Imm(58, dl),
3669 S->getI64Imm(63, dl)), 0);
3672 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
3673 // (zext (setcc %a, %b, setne)) -> (sube addc.reg, addc.reg, addc.CA)
3674 // {addcz.reg, addcz.CA} = (addcarry %a, -1)
3675 // (zext (setcc %a, 0, setne)) -> (sube addcz.reg, addcz.reg, addcz.CA)
3676 SDValue Xor = IsRHSZero ? LHS :
3677 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3679 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
3680 Xor, S->getI32Imm(~0U, dl)), 0);
3681 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, AC,
3682 Xor, AC.getValue(1)), 0);
3685 // {subc.reg, subc.CA} = (subcarry %a, %b)
3686 // (zext (setcc %a, %b, setge)) ->
3687 // (adde (lshr %b, 63), (ashr %a, 63), subc.CA)
3688 // (zext (setcc %a, 0, setge)) -> (lshr (~ %a), 63)
3690 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3691 std::swap(LHS, RHS);
3692 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3693 IsRHSZero = RHSConst && RHSConst->isZero();
3697 // {subc.reg, subc.CA} = (subcarry %b, %a)
3698 // (zext (setcc %a, %b, setge)) ->
3699 // (adde (lshr %a, 63), (ashr %b, 63), subc.CA)
3700 // (zext (setcc %a, 0, setge)) -> (lshr (or %a, (add %a, -1)), 63)
3702 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3704 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3705 S->getI64Imm(1, dl),
3706 S->getI64Imm(63, dl)), 0);
3708 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,
3709 S->getI64Imm(63, dl)), 0);
3710 SDValue SubtractCarry =
3711 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3713 return SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3714 ShiftR, ShiftL, SubtractCarry), 0);
3717 // {subc.reg, subc.CA} = (subcarry %b, %a)
3718 // (zext (setcc %a, %b, setgt)) ->
3719 // (xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)
3720 // (zext (setcc %a, 0, setgt)) -> (lshr (nor (add %a, -1), %a), 63)
3722 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GEZExt);
3725 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3726 S->getI64Imm(~0ULL, dl)), 0);
3728 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Addi, LHS), 0);
3729 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Nor,
3730 S->getI64Imm(1, dl),
3731 S->getI64Imm(63, dl)), 0);
3733 std::swap(LHS, RHS);
3734 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3735 IsRHSZero = RHSConst && RHSConst->isZero();
3736 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3740 // {subc.reg, subc.CA} = (subcarry %a, %b)
3741 // (zext (setcc %a, %b, setlt)) ->
3742 // (xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)
3743 // (zext (setcc %a, 0, setlt)) -> (lshr %a, 63)
3745 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LEZExt);
3747 return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3748 S->getI64Imm(1, dl),
3749 S->getI64Imm(63, dl)), 0);
3751 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3752 LHS, S->getI64Imm(63, dl)), 0);
3754 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3755 RHS, S->getI64Imm(1, dl),
3756 S->getI64Imm(63, dl)), 0);
3757 SDValue SUBFC8Carry =
3758 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3761 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3762 SRDINode, SRADINode, SUBFC8Carry), 0);
3763 return SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
3764 ADDE8Node, S->getI64Imm(1, dl)), 0);
3767 // {subc.reg, subc.CA} = (subcarry %a, %b)
3768 // (zext (setcc %a, %b, setuge)) -> (add (sube %b, %b, subc.CA), 1)
3769 std::swap(LHS, RHS);
3772 // {subc.reg, subc.CA} = (subcarry %b, %a)
3773 // (zext (setcc %a, %b, setule)) -> (add (sube %a, %a, subc.CA), 1)
3774 SDValue SUBFC8Carry =
3775 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3777 SDValue SUBFE8Node =
3778 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue,
3779 LHS, LHS, SUBFC8Carry), 0);
3780 return SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64,
3781 SUBFE8Node, S->getI64Imm(1, dl)), 0);
3784 // {subc.reg, subc.CA} = (subcarry %b, %a)
3785 // (zext (setcc %a, %b, setugt)) -> -(sube %b, %b, subc.CA)
3786 std::swap(LHS, RHS);
3789 // {subc.reg, subc.CA} = (subcarry %a, %b)
3790 // (zext (setcc %a, %b, setult)) -> -(sube %a, %a, subc.CA)
3791 SDValue SubtractCarry =
3792 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3795 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,
3796 LHS, LHS, SubtractCarry), 0);
3797 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,
3803 /// Produces a sign-extended result of comparing two 64-bit values according to
3804 /// the passed condition code.
3806 IntegerCompareEliminator::get64BitSExtCompare(SDValue LHS, SDValue RHS,
3808 int64_t RHSValue, SDLoc dl) {
3809 if (CmpInGPR == ICGPR_I32 || CmpInGPR == ICGPR_SextI32 ||
3810 CmpInGPR == ICGPR_ZextI32 || CmpInGPR == ICGPR_Zext)
3812 bool IsRHSZero = RHSValue == 0;
3813 bool IsRHSOne = RHSValue == 1;
3814 bool IsRHSNegOne = RHSValue == -1LL;
3816 default: return SDValue();
3818 // {addc.reg, addc.CA} = (addcarry (xor %a, %b), -1)
3819 // (sext (setcc %a, %b, seteq)) -> (sube addc.reg, addc.reg, addc.CA)
3820 // {addcz.reg, addcz.CA} = (addcarry %a, -1)
3821 // (sext (setcc %a, 0, seteq)) -> (sube addcz.reg, addcz.reg, addcz.CA)
3822 SDValue AddInput = IsRHSZero ? LHS :
3823 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3825 SDValue(CurDAG->getMachineNode(PPC::ADDIC8, dl, MVT::i64, MVT::Glue,
3826 AddInput, S->getI32Imm(~0U, dl)), 0);
3827 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, Addic,
3828 Addic, Addic.getValue(1)), 0);
3831 // {subfc.reg, subfc.CA} = (subcarry 0, (xor %a, %b))
3832 // (sext (setcc %a, %b, setne)) -> (sube subfc.reg, subfc.reg, subfc.CA)
3833 // {subfcz.reg, subfcz.CA} = (subcarry 0, %a)
3834 // (sext (setcc %a, 0, setne)) -> (sube subfcz.reg, subfcz.reg, subfcz.CA)
3835 SDValue Xor = IsRHSZero ? LHS :
3836 SDValue(CurDAG->getMachineNode(PPC::XOR8, dl, MVT::i64, LHS, RHS), 0);
3838 SDValue(CurDAG->getMachineNode(PPC::SUBFIC8, dl, MVT::i64, MVT::Glue,
3839 Xor, S->getI32Imm(0, dl)), 0);
3840 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, SC,
3841 SC, SC.getValue(1)), 0);
3844 // {subc.reg, subc.CA} = (subcarry %a, %b)
3845 // (zext (setcc %a, %b, setge)) ->
3846 // (- (adde (lshr %b, 63), (ashr %a, 63), subc.CA))
3847 // (zext (setcc %a, 0, setge)) -> (~ (ashr %a, 63))
3849 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3850 std::swap(LHS, RHS);
3851 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3852 IsRHSZero = RHSConst && RHSConst->isZero();
3856 // {subc.reg, subc.CA} = (subcarry %b, %a)
3857 // (zext (setcc %a, %b, setge)) ->
3858 // (- (adde (lshr %a, 63), (ashr %b, 63), subc.CA))
3859 // (zext (setcc %a, 0, setge)) -> (ashr (or %a, (add %a, -1)), 63)
3861 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3863 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, RHS,
3864 S->getI64Imm(63, dl)), 0);
3866 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, LHS,
3867 S->getI64Imm(1, dl),
3868 S->getI64Imm(63, dl)), 0);
3869 SDValue SubtractCarry =
3870 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3873 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64, MVT::Glue,
3874 ShiftR, ShiftL, SubtractCarry), 0);
3875 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64, Adde), 0);
3878 // {subc.reg, subc.CA} = (subcarry %b, %a)
3879 // (zext (setcc %a, %b, setgt)) ->
3880 // -(xor (adde (lshr %a, 63), (ashr %b, 63), subc.CA), 1)
3881 // (zext (setcc %a, 0, setgt)) -> (ashr (nor (add %a, -1), %a), 63)
3883 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::GESExt);
3886 SDValue(CurDAG->getMachineNode(PPC::ADDI8, dl, MVT::i64, LHS,
3887 S->getI64Imm(-1, dl)), 0);
3889 SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64, Add, LHS), 0);
3890 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, Nor,
3891 S->getI64Imm(63, dl)), 0);
3893 std::swap(LHS, RHS);
3894 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
3895 IsRHSZero = RHSConst && RHSConst->isZero();
3896 IsRHSOne = RHSConst && RHSConst->getSExtValue() == 1;
3900 // {subc.reg, subc.CA} = (subcarry %a, %b)
3901 // (zext (setcc %a, %b, setlt)) ->
3902 // -(xor (adde (lshr %b, 63), (ashr %a, 63), subc.CA), 1)
3903 // (zext (setcc %a, 0, setlt)) -> (ashr %a, 63)
3905 return getCompoundZeroComparisonInGPR(LHS, dl, ZeroCompare::LESExt);
3907 return SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, LHS,
3908 S->getI64Imm(63, dl)), 0);
3911 SDValue(CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64,
3912 LHS, S->getI64Imm(63, dl)), 0);
3914 SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64,
3915 RHS, S->getI64Imm(1, dl),
3916 S->getI64Imm(63, dl)), 0);
3917 SDValue SUBFC8Carry =
3918 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3921 SDValue(CurDAG->getMachineNode(PPC::ADDE8, dl, MVT::i64,
3922 SRDINode, SRADINode, SUBFC8Carry), 0);
3924 SDValue(CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
3925 ADDE8Node, S->getI64Imm(1, dl)), 0);
3926 return SDValue(CurDAG->getMachineNode(PPC::NEG8, dl, MVT::i64,
3930 // {subc.reg, subc.CA} = (subcarry %a, %b)
3931 // (sext (setcc %a, %b, setuge)) -> ~(sube %b, %b, subc.CA)
3932 std::swap(LHS, RHS);
3935 // {subc.reg, subc.CA} = (subcarry %b, %a)
3936 // (sext (setcc %a, %b, setule)) -> ~(sube %a, %a, subc.CA)
3937 SDValue SubtractCarry =
3938 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3941 SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64, MVT::Glue, LHS,
3942 LHS, SubtractCarry), 0);
3943 return SDValue(CurDAG->getMachineNode(PPC::NOR8, dl, MVT::i64,
3944 ExtSub, ExtSub), 0);
3947 // {subc.reg, subc.CA} = (subcarry %b, %a)
3948 // (sext (setcc %a, %b, setugt)) -> (sube %b, %b, subc.CA)
3949 std::swap(LHS, RHS);
3952 // {subc.reg, subc.CA} = (subcarry %a, %b)
3953 // (sext (setcc %a, %b, setult)) -> (sube %a, %a, subc.CA)
3955 SDValue(CurDAG->getMachineNode(PPC::SUBFC8, dl, MVT::i64, MVT::Glue,
3957 return SDValue(CurDAG->getMachineNode(PPC::SUBFE8, dl, MVT::i64,
3958 LHS, LHS, SubCarry), 0);
3963 /// Do all uses of this SDValue need the result in a GPR?
3964 /// This is meant to be used on values that have type i1 since
3965 /// it is somewhat meaningless to ask if values of other types
3966 /// should be kept in GPR's.
3967 static bool allUsesExtend(SDValue Compare, SelectionDAG *CurDAG) {
3968 assert(Compare.getOpcode() == ISD::SETCC &&
3969 "An ISD::SETCC node required here.");
3971 // For values that have a single use, the caller should obviously already have
3972 // checked if that use is an extending use. We check the other uses here.
3973 if (Compare.hasOneUse())
3975 // We want the value in a GPR if it is being extended, used for a select, or
3976 // used in logical operations.
3977 for (auto *CompareUse : Compare.getNode()->uses())
3978 if (CompareUse->getOpcode() != ISD::SIGN_EXTEND &&
3979 CompareUse->getOpcode() != ISD::ZERO_EXTEND &&
3980 CompareUse->getOpcode() != ISD::SELECT &&
3981 !ISD::isBitwiseLogicOp(CompareUse->getOpcode())) {
3982 OmittedForNonExtendUses++;
3988 /// Returns an equivalent of a SETCC node but with the result the same width as
3989 /// the inputs. This can also be used for SELECT_CC if either the true or false
3990 /// values is a power of two while the other is zero.
3991 SDValue IntegerCompareEliminator::getSETCCInGPR(SDValue Compare,
3992 SetccInGPROpts ConvOpts) {
3993 assert((Compare.getOpcode() == ISD::SETCC ||
3994 Compare.getOpcode() == ISD::SELECT_CC) &&
3995 "An ISD::SETCC node required here.");
3997 // Don't convert this comparison to a GPR sequence because there are uses
3998 // of the i1 result (i.e. uses that require the result in the CR).
3999 if ((Compare.getOpcode() == ISD::SETCC) && !allUsesExtend(Compare, CurDAG))
4002 SDValue LHS = Compare.getOperand(0);
4003 SDValue RHS = Compare.getOperand(1);
4005 // The condition code is operand 2 for SETCC and operand 4 for SELECT_CC.
4006 int CCOpNum = Compare.getOpcode() == ISD::SELECT_CC ? 4 : 2;
4008 cast<CondCodeSDNode>(Compare.getOperand(CCOpNum))->get();
4009 EVT InputVT = LHS.getValueType();
4010 if (InputVT != MVT::i32 && InputVT != MVT::i64)
4013 if (ConvOpts == SetccInGPROpts::ZExtInvert ||
4014 ConvOpts == SetccInGPROpts::SExtInvert)
4015 CC = ISD::getSetCCInverse(CC, InputVT);
4017 bool Inputs32Bit = InputVT == MVT::i32;
4020 ConstantSDNode *RHSConst = dyn_cast<ConstantSDNode>(RHS);
4021 int64_t RHSValue = RHSConst ? RHSConst->getSExtValue() : INT64_MAX;
4022 bool IsSext = ConvOpts == SetccInGPROpts::SExtOrig ||
4023 ConvOpts == SetccInGPROpts::SExtInvert;
4025 if (IsSext && Inputs32Bit)
4026 return get32BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
4027 else if (Inputs32Bit)
4028 return get32BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
4030 return get64BitSExtCompare(LHS, RHS, CC, RHSValue, dl);
4031 return get64BitZExtCompare(LHS, RHS, CC, RHSValue, dl);
4034 } // end anonymous namespace
4036 bool PPCDAGToDAGISel::tryIntCompareInGPR(SDNode *N) {
4037 if (N->getValueType(0) != MVT::i32 &&
4038 N->getValueType(0) != MVT::i64)
4041 // This optimization will emit code that assumes 64-bit registers
4042 // so we don't want to run it in 32-bit mode. Also don't run it
4043 // on functions that are not to be optimized.
4044 if (TM.getOptLevel() == CodeGenOpt::None || !TM.isPPC64())
4047 // For POWER10, it is more profitable to use the set boolean extension
4048 // instructions rather than the integer compare elimination codegen.
4049 // Users can override this via the command line option, `--ppc-gpr-icmps`.
4050 if (!(CmpInGPR.getNumOccurrences() > 0) && Subtarget->isISA3_1())
4053 switch (N->getOpcode()) {
4055 case ISD::ZERO_EXTEND:
4056 case ISD::SIGN_EXTEND:
4060 IntegerCompareEliminator ICmpElim(CurDAG, this);
4061 if (SDNode *New = ICmpElim.Select(N)) {
4062 ReplaceNode(N, New);
4070 bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {
4071 if (N->getValueType(0) != MVT::i32 &&
4072 N->getValueType(0) != MVT::i64)
4075 if (!UseBitPermRewriter)
4078 switch (N->getOpcode()) {
4081 // If we are on P10, we have a pattern for 32-bit (srl (bswap r), 16) that
4082 // uses the BRH instruction.
4083 if (Subtarget->isISA3_1() && N->getValueType(0) == MVT::i32 &&
4084 N->getOperand(0).getOpcode() == ISD::BSWAP) {
4085 auto &OpRight = N->getOperand(1);
4086 ConstantSDNode *SRLConst = dyn_cast<ConstantSDNode>(OpRight);
4087 if (SRLConst && SRLConst->getSExtValue() == 16)
4095 BitPermutationSelector BPS(CurDAG);
4096 if (SDNode *New = BPS.Select(N)) {
4097 ReplaceNode(N, New);
4107 /// SelectCC - Select a comparison of the specified values with the specified
4108 /// condition code, returning the CR# of the expression.
4109 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
4110 const SDLoc &dl, SDValue Chain) {
4111 // Always select the LHS.
4114 if (LHS.getValueType() == MVT::i32) {
4116 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
4117 if (isInt32Immediate(RHS, Imm)) {
4118 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
4119 if (isUInt<16>(Imm))
4120 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
4121 getI32Imm(Imm & 0xFFFF, dl)),
4123 // If this is a 16-bit signed immediate, fold it.
4124 if (isInt<16>((int)Imm))
4125 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
4126 getI32Imm(Imm & 0xFFFF, dl)),
4129 // For non-equality comparisons, the default code would materialize the
4130 // constant, then compare against it, like this:
4132 // ori r2, r2, 22136
4134 // Since we are just comparing for equality, we can emit this instead:
4135 // xoris r0,r3,0x1234
4136 // cmplwi cr0,r0,0x5678
4138 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
4139 getI32Imm(Imm >> 16, dl)), 0);
4140 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
4141 getI32Imm(Imm & 0xFFFF, dl)), 0);
4144 } else if (ISD::isUnsignedIntSetCC(CC)) {
4145 if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
4146 return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
4147 getI32Imm(Imm & 0xFFFF, dl)), 0);
4151 if (isIntS16Immediate(RHS, SImm))
4152 return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
4153 getI32Imm((int)SImm & 0xFFFF,
4158 } else if (LHS.getValueType() == MVT::i64) {
4160 if (CC == ISD::SETEQ || CC == ISD::SETNE) {
4161 if (isInt64Immediate(RHS.getNode(), Imm)) {
4162 // SETEQ/SETNE comparison with 16-bit immediate, fold it.
4163 if (isUInt<16>(Imm))
4164 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
4165 getI32Imm(Imm & 0xFFFF, dl)),
4167 // If this is a 16-bit signed immediate, fold it.
4169 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
4170 getI32Imm(Imm & 0xFFFF, dl)),
4173 // For non-equality comparisons, the default code would materialize the
4174 // constant, then compare against it, like this:
4176 // ori r2, r2, 22136
4178 // Since we are just comparing for equality, we can emit this instead:
4179 // xoris r0,r3,0x1234
4180 // cmpldi cr0,r0,0x5678
4182 if (isUInt<32>(Imm)) {
4183 SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
4184 getI64Imm(Imm >> 16, dl)), 0);
4185 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
4186 getI64Imm(Imm & 0xFFFF, dl)),
4191 } else if (ISD::isUnsignedIntSetCC(CC)) {
4192 if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
4193 return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
4194 getI64Imm(Imm & 0xFFFF, dl)), 0);
4198 if (isIntS16Immediate(RHS, SImm))
4199 return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
4200 getI64Imm(SImm & 0xFFFF, dl)),
4204 } else if (LHS.getValueType() == MVT::f32) {
4205 if (Subtarget->hasSPE()) {
4210 Opc = PPC::EFSCMPEQ;
4218 Opc = PPC::EFSCMPLT;
4226 Opc = PPC::EFSCMPGT;
4231 } else if (LHS.getValueType() == MVT::f64) {
4232 if (Subtarget->hasSPE()) {
4237 Opc = PPC::EFDCMPEQ;
4245 Opc = PPC::EFDCMPLT;
4253 Opc = PPC::EFDCMPGT;
4257 Opc = Subtarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
4259 assert(LHS.getValueType() == MVT::f128 && "Unknown vt!");
4260 assert(Subtarget->hasP9Vector() && "XSCMPUQP requires Power9 Vector");
4261 Opc = PPC::XSCMPUQP;
4265 CurDAG->getMachineNode(Opc, dl, MVT::i32, MVT::Other, LHS, RHS, Chain),
4268 return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
4271 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC, const EVT &VT,
4272 const PPCSubtarget *Subtarget) {
4273 // For SPE instructions, the result is in GT bit of the CR
4274 bool UseSPE = Subtarget->hasSPE() && VT.isFloatingPoint();
4281 llvm_unreachable("Should be lowered by legalize!");
4282 default: llvm_unreachable("Unknown condition!");
4285 return UseSPE ? PPC::PRED_GT : PPC::PRED_EQ;
4288 return UseSPE ? PPC::PRED_LE : PPC::PRED_NE;
4291 return UseSPE ? PPC::PRED_GT : PPC::PRED_LT;
4294 return PPC::PRED_LE;
4297 return PPC::PRED_GT;
4300 return UseSPE ? PPC::PRED_LE : PPC::PRED_GE;
4301 case ISD::SETO: return PPC::PRED_NU;
4302 case ISD::SETUO: return PPC::PRED_UN;
4303 // These two are invalid for floating point. Assume we have int.
4304 case ISD::SETULT: return PPC::PRED_LT;
4305 case ISD::SETUGT: return PPC::PRED_GT;
4309 /// getCRIdxForSetCC - Return the index of the condition register field
4310 /// associated with the SetCC condition, and whether or not the field is
4311 /// treated as inverted. That is, lt = 0; ge = 0 inverted.
4312 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
4315 default: llvm_unreachable("Unknown condition!");
4317 case ISD::SETLT: return 0; // Bit #0 = SETOLT
4319 case ISD::SETGT: return 1; // Bit #1 = SETOGT
4321 case ISD::SETEQ: return 2; // Bit #2 = SETOEQ
4322 case ISD::SETUO: return 3; // Bit #3 = SETUO
4324 case ISD::SETGE: Invert = true; return 0; // !Bit #0 = SETUGE
4326 case ISD::SETLE: Invert = true; return 1; // !Bit #1 = SETULE
4328 case ISD::SETNE: Invert = true; return 2; // !Bit #2 = SETUNE
4329 case ISD::SETO: Invert = true; return 3; // !Bit #3 = SETO
4334 llvm_unreachable("Invalid branch code: should be expanded by legalize");
4335 // These are invalid for floating point. Assume integer.
4336 case ISD::SETULT: return 0;
4337 case ISD::SETUGT: return 1;
4341 // getVCmpInst: return the vector compare instruction for the specified
4342 // vector type and condition code. Since this is for altivec specific code,
4343 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, v1i128,
4345 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
4346 bool HasVSX, bool &Swap, bool &Negate) {
4350 if (VecVT.isFloatingPoint()) {
4351 /* Handle some cases by swapping input operands. */
4353 case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
4354 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
4355 case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
4356 case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
4357 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
4358 case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
4361 /* Handle some cases by negating the result. */
4363 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
4364 case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
4365 case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
4366 case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
4369 /* We have instructions implementing the remaining cases. */
4373 if (VecVT == MVT::v4f32)
4374 return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
4375 else if (VecVT == MVT::v2f64)
4376 return PPC::XVCMPEQDP;
4380 if (VecVT == MVT::v4f32)
4381 return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
4382 else if (VecVT == MVT::v2f64)
4383 return PPC::XVCMPGTDP;
4387 if (VecVT == MVT::v4f32)
4388 return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
4389 else if (VecVT == MVT::v2f64)
4390 return PPC::XVCMPGEDP;
4395 llvm_unreachable("Invalid floating-point vector compare condition");
4397 /* Handle some cases by swapping input operands. */
4399 case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
4400 case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
4401 case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
4402 case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
4405 /* Handle some cases by negating the result. */
4407 case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
4408 case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
4409 case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
4410 case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
4413 /* We have instructions implementing the remaining cases. */
4417 if (VecVT == MVT::v16i8)
4418 return PPC::VCMPEQUB;
4419 else if (VecVT == MVT::v8i16)
4420 return PPC::VCMPEQUH;
4421 else if (VecVT == MVT::v4i32)
4422 return PPC::VCMPEQUW;
4423 else if (VecVT == MVT::v2i64)
4424 return PPC::VCMPEQUD;
4425 else if (VecVT == MVT::v1i128)
4426 return PPC::VCMPEQUQ;
4429 if (VecVT == MVT::v16i8)
4430 return PPC::VCMPGTSB;
4431 else if (VecVT == MVT::v8i16)
4432 return PPC::VCMPGTSH;
4433 else if (VecVT == MVT::v4i32)
4434 return PPC::VCMPGTSW;
4435 else if (VecVT == MVT::v2i64)
4436 return PPC::VCMPGTSD;
4437 else if (VecVT == MVT::v1i128)
4438 return PPC::VCMPGTSQ;
4441 if (VecVT == MVT::v16i8)
4442 return PPC::VCMPGTUB;
4443 else if (VecVT == MVT::v8i16)
4444 return PPC::VCMPGTUH;
4445 else if (VecVT == MVT::v4i32)
4446 return PPC::VCMPGTUW;
4447 else if (VecVT == MVT::v2i64)
4448 return PPC::VCMPGTUD;
4449 else if (VecVT == MVT::v1i128)
4450 return PPC::VCMPGTUQ;
4455 llvm_unreachable("Invalid integer vector compare condition");
4459 bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
4462 bool IsStrict = N->isStrictFPOpcode();
4464 cast<CondCodeSDNode>(N->getOperand(IsStrict ? 3 : 2))->get();
4466 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
4467 bool isPPC64 = (PtrVT == MVT::i64);
4468 SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
4470 SDValue LHS = N->getOperand(IsStrict ? 1 : 0);
4471 SDValue RHS = N->getOperand(IsStrict ? 2 : 1);
4473 if (!IsStrict && !Subtarget->useCRBits() && isInt32Immediate(RHS, Imm)) {
4474 // We can codegen setcc op, imm very efficiently compared to a brcond.
4475 // Check for those cases here.
4482 Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
4483 SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
4484 getI32Imm(31, dl) };
4485 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4491 SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4492 Op, getI32Imm(~0U, dl)), 0);
4493 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
4497 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
4498 getI32Imm(31, dl) };
4499 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4504 SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
4505 T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
4506 SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
4507 getI32Imm(31, dl) };
4508 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4512 } else if (Imm == ~0U) { // setcc op, -1
4518 Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4519 Op, getI32Imm(1, dl)), 0);
4520 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
4521 SDValue(CurDAG->getMachineNode(PPC::LI, dl,
4524 0), Op.getValue(1));
4528 Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
4529 SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4530 Op, getI32Imm(~0U, dl));
4531 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,
4536 SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
4537 getI32Imm(1, dl)), 0);
4538 SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
4540 SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
4541 getI32Imm(31, dl) };
4542 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4546 SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
4547 getI32Imm(31, dl) };
4548 Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
4549 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));
4556 // Altivec Vector compare instructions do not set any CR register by default and
4557 // vector compare operations return the same type as the operands.
4558 if (!IsStrict && LHS.getValueType().isVector()) {
4559 if (Subtarget->hasSPE())
4562 EVT VecVT = LHS.getValueType();
4564 unsigned int VCmpInst =
4565 getVCmpInst(VecVT.getSimpleVT(), CC, Subtarget->hasVSX(), Swap, Negate);
4567 std::swap(LHS, RHS);
4569 EVT ResVT = VecVT.changeVectorElementTypeToInteger();
4571 SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
4572 CurDAG->SelectNodeTo(N, Subtarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
4577 CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
4581 if (Subtarget->useCRBits())
4585 unsigned Idx = getCRIdxForSetCC(CC, Inv);
4586 SDValue CCReg = SelectCC(LHS, RHS, CC, dl, Chain);
4588 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 1), CCReg.getValue(1));
4591 // SPE e*cmp* instructions only set the 'gt' bit, so hard-code that
4592 // The correct compare instruction is already set by SelectCC()
4593 if (Subtarget->hasSPE() && LHS.getValueType().isFloatingPoint()) {
4597 // Force the ccreg into CR7.
4598 SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
4600 SDValue InGlue; // Null incoming flag value.
4601 CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
4602 InGlue).getValue(1);
4604 IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
4607 SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
4608 getI32Imm(31, dl), getI32Imm(31, dl) };
4610 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4614 // Get the specified bit.
4616 SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
4617 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
4621 /// Does this node represent a load/store node whose address can be represented
4622 /// with a register plus an immediate that's a multiple of \p Val:
4623 bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const {
4624 LoadSDNode *LDN = dyn_cast<LoadSDNode>(N);
4625 StoreSDNode *STN = dyn_cast<StoreSDNode>(N);
4626 MemIntrinsicSDNode *MIN = dyn_cast<MemIntrinsicSDNode>(N);
4628 if (LDN || (MIN && MIN->getOpcode() == PPCISD::LD_SPLAT))
4629 AddrOp = N->getOperand(1);
4631 AddrOp = STN->getOperand(2);
4633 // If the address points a frame object or a frame object with an offset,
4634 // we need to check the object alignment.
4636 if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(
4637 AddrOp.getOpcode() == ISD::ADD ? AddrOp.getOperand(0) :
4639 // If op0 is a frame index that is under aligned, we can't do it either,
4640 // because it is translated to r31 or r1 + slot + offset. We won't know the
4641 // slot number until the stack frame is finalized.
4642 const MachineFrameInfo &MFI = CurDAG->getMachineFunction().getFrameInfo();
4643 unsigned SlotAlign = MFI.getObjectAlign(FI->getIndex()).value();
4644 if ((SlotAlign % Val) != 0)
4647 // If we have an offset, we need further check on the offset.
4648 if (AddrOp.getOpcode() != ISD::ADD)
4652 if (AddrOp.getOpcode() == ISD::ADD)
4653 return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val);
4655 // If the address comes from the outside, the offset will be zero.
4656 return AddrOp.getOpcode() == ISD::CopyFromReg;
4659 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
4660 // Transfer memoperands.
4661 MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
4662 CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp});
4665 static bool mayUseP9Setb(SDNode *N, const ISD::CondCode &CC, SelectionDAG *DAG,
4666 bool &NeedSwapOps, bool &IsUnCmp) {
4668 assert(N->getOpcode() == ISD::SELECT_CC && "Expecting a SELECT_CC here.");
4670 SDValue LHS = N->getOperand(0);
4671 SDValue RHS = N->getOperand(1);
4672 SDValue TrueRes = N->getOperand(2);
4673 SDValue FalseRes = N->getOperand(3);
4674 ConstantSDNode *TrueConst = dyn_cast<ConstantSDNode>(TrueRes);
4675 if (!TrueConst || (N->getSimpleValueType(0) != MVT::i64 &&
4676 N->getSimpleValueType(0) != MVT::i32))
4679 // We are looking for any of:
4680 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4681 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4682 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, 1, -1, cc2), seteq)
4683 // (select_cc lhs, rhs, 0, (select_cc [lr]hs, [lr]hs, -1, 1, cc2), seteq)
4684 int64_t TrueResVal = TrueConst->getSExtValue();
4685 if ((TrueResVal < -1 || TrueResVal > 1) ||
4686 (TrueResVal == -1 && FalseRes.getOpcode() != ISD::ZERO_EXTEND) ||
4687 (TrueResVal == 1 && FalseRes.getOpcode() != ISD::SIGN_EXTEND) ||
4689 (FalseRes.getOpcode() != ISD::SELECT_CC || CC != ISD::SETEQ)))
4692 SDValue SetOrSelCC = FalseRes.getOpcode() == ISD::SELECT_CC
4694 : FalseRes.getOperand(0);
4695 bool InnerIsSel = SetOrSelCC.getOpcode() == ISD::SELECT_CC;
4696 if (SetOrSelCC.getOpcode() != ISD::SETCC &&
4697 SetOrSelCC.getOpcode() != ISD::SELECT_CC)
4700 // Without this setb optimization, the outer SELECT_CC will be manually
4701 // selected to SELECT_CC_I4/SELECT_CC_I8 Pseudo, then expand-isel-pseudos pass
4702 // transforms pseudo instruction to isel instruction. When there are more than
4703 // one use for result like zext/sext, with current optimization we only see
4704 // isel is replaced by setb but can't see any significant gain. Since
4705 // setb has longer latency than original isel, we should avoid this. Another
4706 // point is that setb requires comparison always kept, it can break the
4707 // opportunity to get the comparison away if we have in future.
4708 if (!SetOrSelCC.hasOneUse() || (!InnerIsSel && !FalseRes.hasOneUse()))
4711 SDValue InnerLHS = SetOrSelCC.getOperand(0);
4712 SDValue InnerRHS = SetOrSelCC.getOperand(1);
4713 ISD::CondCode InnerCC =
4714 cast<CondCodeSDNode>(SetOrSelCC.getOperand(InnerIsSel ? 4 : 2))->get();
4715 // If the inner comparison is a select_cc, make sure the true/false values are
4716 // 1/-1 and canonicalize it if needed.
4718 ConstantSDNode *SelCCTrueConst =
4719 dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(2));
4720 ConstantSDNode *SelCCFalseConst =
4721 dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(3));
4722 if (!SelCCTrueConst || !SelCCFalseConst)
4724 int64_t SelCCTVal = SelCCTrueConst->getSExtValue();
4725 int64_t SelCCFVal = SelCCFalseConst->getSExtValue();
4726 // The values must be -1/1 (requiring a swap) or 1/-1.
4727 if (SelCCTVal == -1 && SelCCFVal == 1) {
4728 std::swap(InnerLHS, InnerRHS);
4729 } else if (SelCCTVal != 1 || SelCCFVal != -1)
4733 // Canonicalize unsigned case
4734 if (InnerCC == ISD::SETULT || InnerCC == ISD::SETUGT) {
4736 InnerCC = (InnerCC == ISD::SETULT) ? ISD::SETLT : ISD::SETGT;
4739 bool InnerSwapped = false;
4740 if (LHS == InnerRHS && RHS == InnerLHS)
4741 InnerSwapped = true;
4742 else if (LHS != InnerLHS || RHS != InnerRHS)
4746 // (select_cc lhs, rhs, 0, \
4747 // (select_cc [lr]hs, [lr]hs, 1, -1, setlt/setgt), seteq)
4751 if (InnerCC != ISD::SETLT && InnerCC != ISD::SETGT)
4753 NeedSwapOps = (InnerCC == ISD::SETGT) ? InnerSwapped : !InnerSwapped;
4756 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4757 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setgt)), setu?lt)
4758 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setlt)), setu?lt)
4759 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4760 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setgt)), setu?lt)
4761 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setlt)), setu?lt)
4763 if (!IsUnCmp && InnerCC != ISD::SETNE)
4768 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETGT && !InnerSwapped) ||
4769 (InnerCC == ISD::SETLT && InnerSwapped))
4770 NeedSwapOps = (TrueResVal == 1);
4775 // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4776 // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setlt)), setu?gt)
4777 // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setgt)), setu?gt)
4778 // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4779 // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setlt)), setu?gt)
4780 // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setgt)), setu?gt)
4782 if (!IsUnCmp && InnerCC != ISD::SETNE)
4787 if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETLT && !InnerSwapped) ||
4788 (InnerCC == ISD::SETGT && InnerSwapped))
4789 NeedSwapOps = (TrueResVal == -1);
4798 LLVM_DEBUG(dbgs() << "Found a node that can be lowered to a SETB: ");
4799 LLVM_DEBUG(N->dump());
4804 // Return true if it's a software square-root/divide operand.
4805 static bool isSWTestOp(SDValue N) {
4806 if (N.getOpcode() == PPCISD::FTSQRT)
4808 if (N.getNumOperands() < 1 || !isa<ConstantSDNode>(N.getOperand(0)) ||
4809 N.getOpcode() != ISD::INTRINSIC_WO_CHAIN)
4811 switch (N.getConstantOperandVal(0)) {
4812 case Intrinsic::ppc_vsx_xvtdivdp:
4813 case Intrinsic::ppc_vsx_xvtdivsp:
4814 case Intrinsic::ppc_vsx_xvtsqrtdp:
4815 case Intrinsic::ppc_vsx_xvtsqrtsp:
4821 bool PPCDAGToDAGISel::tryFoldSWTestBRCC(SDNode *N) {
4822 assert(N->getOpcode() == ISD::BR_CC && "ISD::BR_CC is expected.");
4823 // We are looking for following patterns, where `truncate to i1` actually has
4824 // the same semantic with `and 1`.
4825 // (br_cc seteq, (truncateToi1 SWTestOp), 0) -> (BCC PRED_NU, SWTestOp)
4826 // (br_cc seteq, (and SWTestOp, 2), 0) -> (BCC PRED_NE, SWTestOp)
4827 // (br_cc seteq, (and SWTestOp, 4), 0) -> (BCC PRED_LE, SWTestOp)
4828 // (br_cc seteq, (and SWTestOp, 8), 0) -> (BCC PRED_GE, SWTestOp)
4829 // (br_cc setne, (truncateToi1 SWTestOp), 0) -> (BCC PRED_UN, SWTestOp)
4830 // (br_cc setne, (and SWTestOp, 2), 0) -> (BCC PRED_EQ, SWTestOp)
4831 // (br_cc setne, (and SWTestOp, 4), 0) -> (BCC PRED_GT, SWTestOp)
4832 // (br_cc setne, (and SWTestOp, 8), 0) -> (BCC PRED_LT, SWTestOp)
4833 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
4834 if (CC != ISD::SETEQ && CC != ISD::SETNE)
4837 SDValue CmpRHS = N->getOperand(3);
4838 if (!isa<ConstantSDNode>(CmpRHS) ||
4839 cast<ConstantSDNode>(CmpRHS)->getSExtValue() != 0)
4842 SDValue CmpLHS = N->getOperand(2);
4843 if (CmpLHS.getNumOperands() < 1 || !isSWTestOp(CmpLHS.getOperand(0)))
4847 bool IsCCNE = CC == ISD::SETNE;
4848 if (CmpLHS.getOpcode() == ISD::AND &&
4849 isa<ConstantSDNode>(CmpLHS.getOperand(1)))
4850 switch (CmpLHS.getConstantOperandVal(1)) {
4852 PCC = IsCCNE ? PPC::PRED_UN : PPC::PRED_NU;
4855 PCC = IsCCNE ? PPC::PRED_EQ : PPC::PRED_NE;
4858 PCC = IsCCNE ? PPC::PRED_GT : PPC::PRED_LE;
4861 PCC = IsCCNE ? PPC::PRED_LT : PPC::PRED_GE;
4866 else if (CmpLHS.getOpcode() == ISD::TRUNCATE &&
4867 CmpLHS.getValueType() == MVT::i1)
4868 PCC = IsCCNE ? PPC::PRED_UN : PPC::PRED_NU;
4872 SDValue Ops[] = {getI32Imm(PCC, dl), CmpLHS.getOperand(0), N->getOperand(4),
4874 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
4880 bool PPCDAGToDAGISel::trySelectLoopCountIntrinsic(SDNode *N) {
4881 // Sometimes the promoted value of the intrinsic is ANDed by some non-zero
4882 // value, for example when crbits is disabled. If so, select the
4883 // loop_decrement intrinsics now.
4884 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
4885 SDValue LHS = N->getOperand(2), RHS = N->getOperand(3);
4887 if (LHS.getOpcode() != ISD::AND || !isa<ConstantSDNode>(LHS.getOperand(1)) ||
4888 isNullConstant(LHS.getOperand(1)))
4891 if (LHS.getOperand(0).getOpcode() != ISD::INTRINSIC_W_CHAIN ||
4892 cast<ConstantSDNode>(LHS.getOperand(0).getOperand(1))->getZExtValue() !=
4893 Intrinsic::loop_decrement)
4896 if (!isa<ConstantSDNode>(RHS))
4899 assert((CC == ISD::SETEQ || CC == ISD::SETNE) &&
4900 "Counter decrement comparison is not EQ or NE");
4902 SDValue OldDecrement = LHS.getOperand(0);
4903 assert(OldDecrement.hasOneUse() && "loop decrement has more than one use!");
4905 SDLoc DecrementLoc(OldDecrement);
4906 SDValue ChainInput = OldDecrement.getOperand(0);
4907 SDValue DecrementOps[] = {Subtarget->isPPC64() ? getI64Imm(1, DecrementLoc)
4908 : getI32Imm(1, DecrementLoc)};
4909 unsigned DecrementOpcode =
4910 Subtarget->isPPC64() ? PPC::DecreaseCTR8loop : PPC::DecreaseCTRloop;
4911 SDNode *NewDecrement = CurDAG->getMachineNode(DecrementOpcode, DecrementLoc,
4912 MVT::i1, DecrementOps);
4914 unsigned Val = cast<ConstantSDNode>(RHS)->getZExtValue();
4915 bool IsBranchOnTrue = (CC == ISD::SETEQ && Val) || (CC == ISD::SETNE && !Val);
4916 unsigned Opcode = IsBranchOnTrue ? PPC::BC : PPC::BCn;
4918 ReplaceUses(LHS.getValue(0), LHS.getOperand(1));
4919 CurDAG->RemoveDeadNode(LHS.getNode());
4921 // Mark the old loop_decrement intrinsic as dead.
4922 ReplaceUses(OldDecrement.getValue(1), ChainInput);
4923 CurDAG->RemoveDeadNode(OldDecrement.getNode());
4925 SDValue Chain = CurDAG->getNode(ISD::TokenFactor, SDLoc(N), MVT::Other,
4926 ChainInput, N->getOperand(0));
4928 CurDAG->SelectNodeTo(N, Opcode, MVT::Other, SDValue(NewDecrement, 0),
4929 N->getOperand(4), Chain);
4933 bool PPCDAGToDAGISel::tryAsSingleRLWINM(SDNode *N) {
4934 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4936 if (!isInt32Immediate(N->getOperand(1), Imm))
4940 SDValue Val = N->getOperand(0);
4941 unsigned SH, MB, ME;
4942 // If this is an and of a value rotated between 0 and 31 bits and then and'd
4943 // with a mask, emit rlwinm
4944 if (isRotateAndMask(Val.getNode(), Imm, false, SH, MB, ME)) {
4945 Val = Val.getOperand(0);
4946 SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
4948 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4952 // If this is just a masked value where the input is not handled, and
4953 // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
4954 if (isRunOfOnes(Imm, MB, ME) && Val.getOpcode() != ISD::ROTL) {
4955 SDValue Ops[] = {Val, getI32Imm(0, dl), getI32Imm(MB, dl),
4957 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4961 // AND X, 0 -> 0, not "rlwinm 32".
4963 ReplaceUses(SDValue(N, 0), N->getOperand(1));
4970 bool PPCDAGToDAGISel::tryAsSingleRLWINM8(SDNode *N) {
4971 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4973 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64))
4977 if (isRunOfOnes64(Imm64, MB, ME) && MB >= 32 && MB <= ME) {
4979 // +----------------------+
4980 // |xxxxxxxxxxx00011111000|
4981 // +----------------------+
4983 // We can only do it if the MB is larger than 32 and MB <= ME
4984 // as RLWINM will replace the contents of [0 - 32) with [32 - 64) even
4985 // we didn't rotate it.
4987 SDValue Ops[] = {N->getOperand(0), getI64Imm(0, dl), getI64Imm(MB - 32, dl),
4988 getI64Imm(ME - 32, dl)};
4989 CurDAG->SelectNodeTo(N, PPC::RLWINM8, MVT::i64, Ops);
4996 bool PPCDAGToDAGISel::tryAsPairOfRLDICL(SDNode *N) {
4997 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4999 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64))
5002 // Do nothing if it is 16-bit imm as the pattern in the .td file handle
5003 // it well with "andi.".
5004 if (isUInt<16>(Imm64))
5008 SDValue Val = N->getOperand(0);
5010 // Optimized with two rldicl's as follows:
5011 // Add missing bits on left to the mask and check that the mask is a
5012 // wrapped run of ones, i.e.
5013 // Change pattern |0001111100000011111111|
5014 // to |1111111100000011111111|.
5015 unsigned NumOfLeadingZeros = llvm::countl_zero(Imm64);
5016 if (NumOfLeadingZeros != 0)
5017 Imm64 |= maskLeadingOnes<uint64_t>(NumOfLeadingZeros);
5020 if (!isRunOfOnes64(Imm64, MB, ME))
5024 // +----------------------+ +----------------------+
5025 // |1111111100000011111111| -> |0000001111111111111111|
5026 // +----------------------+ +----------------------+
5028 // There are ME + 1 ones on the left and (MB - ME + 63) & 63 zeros in between.
5029 unsigned OnesOnLeft = ME + 1;
5030 unsigned ZerosInBetween = (MB - ME + 63) & 63;
5031 // Rotate left by OnesOnLeft (so leading ones are now trailing ones) and clear
5032 // on the left the bits that are already zeros in the mask.
5033 Val = SDValue(CurDAG->getMachineNode(PPC::RLDICL, Loc, MVT::i64, Val,
5034 getI64Imm(OnesOnLeft, Loc),
5035 getI64Imm(ZerosInBetween, Loc)),
5038 // +----------------------+ +----------------------+
5039 // |0000001111111111111111| -> |0001111100000011111111|
5040 // +----------------------+ +----------------------+
5042 // Rotate back by 64 - OnesOnLeft to undo previous rotate. Then clear on the
5043 // left the number of ones we previously added.
5044 SDValue Ops[] = {Val, getI64Imm(64 - OnesOnLeft, Loc),
5045 getI64Imm(NumOfLeadingZeros, Loc)};
5046 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
5050 bool PPCDAGToDAGISel::tryAsSingleRLWIMI(SDNode *N) {
5051 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5053 if (!isInt32Immediate(N->getOperand(1), Imm))
5056 SDValue Val = N->getOperand(0);
5058 // ISD::OR doesn't get all the bitfield insertion fun.
5059 // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
5061 if (Val.getOpcode() != ISD::OR || !isInt32Immediate(Val.getOperand(1), Imm2))
5064 // The idea here is to check whether this is equivalent to:
5065 // (c1 & m) | (x & ~m)
5066 // where m is a run-of-ones mask. The logic here is that, for each bit in
5068 // - if both are 1, then the output will be 1.
5069 // - if both are 0, then the output will be 0.
5070 // - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
5072 // - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
5074 // If that last condition is never the case, then we can form m from the
5075 // bits that are the same between c1 and c2.
5077 if (isRunOfOnes(~(Imm ^ Imm2), MB, ME) && !(~Imm & Imm2)) {
5079 SDValue Ops[] = {Val.getOperand(0), Val.getOperand(1), getI32Imm(0, dl),
5080 getI32Imm(MB, dl), getI32Imm(ME, dl)};
5081 ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
5088 bool PPCDAGToDAGISel::tryAsSingleRLDICL(SDNode *N) {
5089 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5091 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) || !isMask_64(Imm64))
5094 // If this is a 64-bit zero-extension mask, emit rldicl.
5095 unsigned MB = 64 - llvm::countr_one(Imm64);
5098 SDValue Val = N->getOperand(0);
5101 if (Val.getOpcode() == ISD::ANY_EXTEND) {
5102 auto Op0 = Val.getOperand(0);
5103 if (Op0.getOpcode() == ISD::SRL &&
5104 isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) {
5106 auto ResultType = Val.getNode()->getValueType(0);
5107 auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, ResultType);
5108 SDValue IDVal(ImDef, 0);
5110 Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, ResultType,
5111 IDVal, Op0.getOperand(0),
5118 // If the operand is a logical right shift, we can fold it into this
5119 // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
5120 // for n <= mb. The right shift is really a left rotate followed by a
5121 // mask, and this mask is a more-restrictive sub-mask of the mask implied
5123 if (Val.getOpcode() == ISD::SRL &&
5124 isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
5125 assert(Imm < 64 && "Illegal shift amount");
5126 Val = Val.getOperand(0);
5130 SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl)};
5131 CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
5135 bool PPCDAGToDAGISel::tryAsSingleRLDICR(SDNode *N) {
5136 assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
5138 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) ||
5142 // If this is a negated 64-bit zero-extension mask,
5143 // i.e. the immediate is a sequence of ones from most significant side
5144 // and all zero for reminder, we should use rldicr.
5145 unsigned MB = 63 - llvm::countr_one(~Imm64);
5148 SDValue Ops[] = {N->getOperand(0), getI32Imm(SH, dl), getI32Imm(MB, dl)};
5149 CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);
5153 bool PPCDAGToDAGISel::tryAsSingleRLDIMI(SDNode *N) {
5154 assert(N->getOpcode() == ISD::OR && "ISD::OR SDNode expected");
5157 SDValue N0 = N->getOperand(0);
5159 // We won't get fewer instructions if the imm is 32-bit integer.
5160 // rldimi requires the imm to have consecutive ones with both sides zero.
5161 // Also, make sure the first Op has only one use, otherwise this may increase
5162 // register pressure since rldimi is destructive.
5163 if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) ||
5164 isUInt<32>(Imm64) || !isRunOfOnes64(Imm64, MB, ME) || !N0.hasOneUse())
5167 unsigned SH = 63 - ME;
5169 // Use select64Imm for making LI instr instead of directly putting Imm64
5172 SDValue(selectI64Imm(CurDAG, getI64Imm(-1, Dl).getNode()), 0),
5173 getI32Imm(SH, Dl), getI32Imm(MB, Dl)};
5174 CurDAG->SelectNodeTo(N, PPC::RLDIMI, MVT::i64, Ops);
5178 // Select - Convert the specified operand from a target-independent to a
5179 // target-specific node if it hasn't already been changed.
5180 void PPCDAGToDAGISel::Select(SDNode *N) {
5182 if (N->isMachineOpcode()) {
5184 return; // Already selected.
5187 // In case any misguided DAG-level optimizations form an ADD with a
5188 // TargetConstant operand, crash here instead of miscompiling (by selecting
5189 // an r+r add instead of some kind of r+i add).
5190 if (N->getOpcode() == ISD::ADD &&
5191 N->getOperand(1).getOpcode() == ISD::TargetConstant)
5192 llvm_unreachable("Invalid ADD with TargetConstant operand");
5194 // Try matching complex bit permutations before doing anything else.
5195 if (tryBitPermutation(N))
5198 // Try to emit integer compares as GPR-only sequences (i.e. no use of CR).
5199 if (tryIntCompareInGPR(N))
5202 switch (N->getOpcode()) {
5206 if (N->getValueType(0) == MVT::i64) {
5207 ReplaceNode(N, selectI64Imm(CurDAG, N));
5212 case ISD::INTRINSIC_VOID: {
5213 auto IntrinsicID = N->getConstantOperandVal(1);
5214 if (IntrinsicID != Intrinsic::ppc_tdw && IntrinsicID != Intrinsic::ppc_tw &&
5215 IntrinsicID != Intrinsic::ppc_trapd &&
5216 IntrinsicID != Intrinsic::ppc_trap)
5218 unsigned Opcode = (IntrinsicID == Intrinsic::ppc_tdw ||
5219 IntrinsicID == Intrinsic::ppc_trapd)
5222 SmallVector<SDValue, 4> OpsWithMD;
5224 if (IntrinsicID == Intrinsic::ppc_tdw ||
5225 IntrinsicID == Intrinsic::ppc_tw) {
5226 SDValue Ops[] = {N->getOperand(4), N->getOperand(2), N->getOperand(3)};
5227 int16_t SImmOperand2;
5228 int16_t SImmOperand3;
5229 int16_t SImmOperand4;
5230 bool isOperand2IntS16Immediate =
5231 isIntS16Immediate(N->getOperand(2), SImmOperand2);
5232 bool isOperand3IntS16Immediate =
5233 isIntS16Immediate(N->getOperand(3), SImmOperand3);
5234 // We will emit PPC::TD or PPC::TW if the 2nd and 3rd operands are reg +
5235 // reg or imm + imm. The imm + imm form will be optimized to either an
5236 // unconditional trap or a nop in a later pass.
5237 if (isOperand2IntS16Immediate == isOperand3IntS16Immediate)
5238 Opcode = IntrinsicID == Intrinsic::ppc_tdw ? PPC::TD : PPC::TW;
5239 else if (isOperand3IntS16Immediate)
5240 // The 2nd and 3rd operands are reg + imm.
5241 Ops[2] = getI32Imm(int(SImmOperand3) & 0xFFFF, dl);
5243 // The 2nd and 3rd operands are imm + reg.
5244 bool isOperand4IntS16Immediate =
5245 isIntS16Immediate(N->getOperand(4), SImmOperand4);
5246 (void)isOperand4IntS16Immediate;
5247 assert(isOperand4IntS16Immediate &&
5248 "The 4th operand is not an Immediate");
5249 // We need to flip the condition immediate TO.
5250 int16_t TO = int(SImmOperand4) & 0x1F;
5251 // We swap the first and second bit of TO if they are not same.
5252 if ((TO & 0x1) != ((TO & 0x2) >> 1))
5253 TO = (TO & 0x1) ? TO + 1 : TO - 1;
5254 // We swap the fourth and fifth bit of TO if they are not same.
5255 if ((TO & 0x8) != ((TO & 0x10) >> 1))
5256 TO = (TO & 0x8) ? TO + 8 : TO - 8;
5257 Ops[0] = getI32Imm(TO, dl);
5258 Ops[1] = N->getOperand(3);
5259 Ops[2] = getI32Imm(int(SImmOperand2) & 0xFFFF, dl);
5261 OpsWithMD = {Ops[0], Ops[1], Ops[2]};
5264 OpsWithMD = {getI32Imm(24, dl), N->getOperand(2), getI32Imm(0, dl)};
5268 if (N->getNumOperands() > MDIndex) {
5269 SDValue MDV = N->getOperand(MDIndex);
5270 const MDNode *MD = cast<MDNodeSDNode>(MDV)->getMD();
5271 assert(MD->getNumOperands() != 0 && "Empty MDNode in operands!");
5272 assert((isa<MDString>(MD->getOperand(0)) && cast<MDString>(
5273 MD->getOperand(0))->getString().equals("ppc-trap-reason"))
5274 && "Unsupported annotation data type!");
5275 for (unsigned i = 1; i < MD->getNumOperands(); i++) {
5276 assert(isa<MDString>(MD->getOperand(i)) &&
5277 "Invalid data type for annotation ppc-trap-reason!");
5278 OpsWithMD.push_back(
5279 getI32Imm(std::stoi(cast<MDString>(
5280 MD->getOperand(i))->getString().str()), dl));
5283 OpsWithMD.push_back(N->getOperand(0)); // chain
5284 CurDAG->SelectNodeTo(N, Opcode, MVT::Other, OpsWithMD);
5288 case ISD::INTRINSIC_WO_CHAIN: {
5289 // We emit the PPC::FSELS instruction here because of type conflicts with
5290 // the comparison operand. The FSELS instruction is defined to use an 8-byte
5291 // comparison like the FSELD version. The fsels intrinsic takes a 4-byte
5292 // value for the comparison. When selecting through a .td file, a type
5293 // error is raised. Must check this first so we never break on the
5294 // !Subtarget->isISA3_1() check.
5295 auto IntID = N->getConstantOperandVal(0);
5296 if (IntID == Intrinsic::ppc_fsels) {
5297 SDValue Ops[] = {N->getOperand(1), N->getOperand(2), N->getOperand(3)};
5298 CurDAG->SelectNodeTo(N, PPC::FSELS, MVT::f32, Ops);
5302 if (IntID == Intrinsic::ppc_bcdadd_p || IntID == Intrinsic::ppc_bcdsub_p) {
5303 auto Pred = N->getConstantOperandVal(1);
5305 IntID == Intrinsic::ppc_bcdadd_p ? PPC::BCDADD_rec : PPC::BCDSUB_rec;
5306 unsigned SubReg = 0;
5307 unsigned ShiftVal = 0;
5308 bool Reverse = false;
5311 SubReg = PPC::sub_eq;
5315 SubReg = PPC::sub_eq;
5320 SubReg = PPC::sub_lt;
5324 SubReg = PPC::sub_lt;
5329 SubReg = PPC::sub_gt;
5333 SubReg = PPC::sub_gt;
5338 SubReg = PPC::sub_un;
5341 SubReg = PPC::sub_un;
5346 EVT VTs[] = {MVT::v16i8, MVT::Glue};
5347 SDValue Ops[] = {N->getOperand(2), N->getOperand(3),
5348 CurDAG->getTargetConstant(0, dl, MVT::i32)};
5349 SDValue BCDOp = SDValue(CurDAG->getMachineNode(Opcode, dl, VTs, Ops), 0);
5350 SDValue CR6Reg = CurDAG->getRegister(PPC::CR6, MVT::i32);
5351 // On Power10, we can use SETBC[R]. On prior architectures, we have to use
5352 // MFOCRF and shift/negate the value.
5353 if (Subtarget->isISA3_1()) {
5354 SDValue SubRegIdx = CurDAG->getTargetConstant(SubReg, dl, MVT::i32);
5355 SDValue CRBit = SDValue(
5356 CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,
5357 CR6Reg, SubRegIdx, BCDOp.getValue(1)),
5359 CurDAG->SelectNodeTo(N, Reverse ? PPC::SETBCR : PPC::SETBC, MVT::i32,
5363 SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR6Reg,
5366 SDValue Ops[] = {Move, getI32Imm((32 - (4 + ShiftVal)) & 31, dl),
5367 getI32Imm(31, dl), getI32Imm(31, dl)};
5369 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
5371 SDValue Shift = SDValue(
5372 CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
5373 CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Shift, getI32Imm(1, dl));
5379 if (!Subtarget->isISA3_1())
5381 unsigned Opcode = 0;
5385 case Intrinsic::ppc_altivec_vstribr_p:
5386 Opcode = PPC::VSTRIBR_rec;
5388 case Intrinsic::ppc_altivec_vstribl_p:
5389 Opcode = PPC::VSTRIBL_rec;
5391 case Intrinsic::ppc_altivec_vstrihr_p:
5392 Opcode = PPC::VSTRIHR_rec;
5394 case Intrinsic::ppc_altivec_vstrihl_p:
5395 Opcode = PPC::VSTRIHL_rec;
5401 // Generate the appropriate vector string isolate intrinsic to match.
5402 EVT VTs[] = {MVT::v16i8, MVT::Glue};
5404 SDValue(CurDAG->getMachineNode(Opcode, dl, VTs, N->getOperand(2)), 0);
5405 // Vector string isolate instructions update the EQ bit of CR6.
5406 // Generate a SETBC instruction to extract the bit and place it in a GPR.
5407 SDValue SubRegIdx = CurDAG->getTargetConstant(PPC::sub_eq, dl, MVT::i32);
5408 SDValue CR6Reg = CurDAG->getRegister(PPC::CR6, MVT::i32);
5409 SDValue CRBit = SDValue(
5410 CurDAG->getMachineNode(TargetOpcode::EXTRACT_SUBREG, dl, MVT::i1,
5411 CR6Reg, SubRegIdx, VecStrOp.getValue(1)),
5413 CurDAG->SelectNodeTo(N, PPC::SETBC, MVT::i32, CRBit);
5418 case ISD::STRICT_FSETCC:
5419 case ISD::STRICT_FSETCCS:
5423 // These nodes will be transformed into GETtlsADDR32 node, which
5424 // later becomes BL_TLS __tls_get_addr(sym at tlsgd)@PLT
5425 case PPCISD::ADDI_TLSLD_L_ADDR:
5426 case PPCISD::ADDI_TLSGD_L_ADDR: {
5427 const Module *Mod = MF->getFunction().getParent();
5428 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 ||
5429 !Subtarget->isSecurePlt() || !Subtarget->isTargetELF() ||
5430 Mod->getPICLevel() == PICLevel::SmallPIC)
5432 // Attach global base pointer on GETtlsADDR32 node in order to
5433 // generate secure plt code for TLS symbols.
5436 case PPCISD::CALL: {
5437 if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 ||
5438 !TM.isPositionIndependent() || !Subtarget->isSecurePlt() ||
5439 !Subtarget->isTargetELF())
5442 SDValue Op = N->getOperand(1);
5444 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
5445 if (GA->getTargetFlags() == PPCII::MO_PLT)
5448 else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
5449 if (ES->getTargetFlags() == PPCII::MO_PLT)
5455 case PPCISD::GlobalBaseReg:
5456 ReplaceNode(N, getGlobalBaseReg());
5459 case ISD::FrameIndex:
5460 selectFrameIndex(N, N);
5463 case PPCISD::MFOCRF: {
5464 SDValue InGlue = N->getOperand(1);
5465 ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
5466 N->getOperand(0), InGlue));
5470 case PPCISD::READ_TIME_BASE:
5471 ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
5472 MVT::Other, N->getOperand(0)));
5475 case PPCISD::SRA_ADDZE: {
5476 SDValue N0 = N->getOperand(0);
5478 CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
5479 getConstantIntValue(), dl,
5480 N->getValueType(0));
5481 if (N->getValueType(0) == MVT::i64) {
5483 CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
5485 CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0),
5489 assert(N->getValueType(0) == MVT::i32 &&
5490 "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
5492 CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
5494 CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0),
5501 // Change TLS initial-exec (or TLS local-exec on AIX) D-form stores to
5503 StoreSDNode *ST = cast<StoreSDNode>(N);
5504 if (EnableTLSOpt && (Subtarget->isELFv2ABI() || Subtarget->isAIXABI()) &&
5505 ST->getAddressingMode() != ISD::PRE_INC)
5506 if (tryTLSXFormStore(ST))
5511 // Handle preincrement loads.
5512 LoadSDNode *LD = cast<LoadSDNode>(N);
5513 EVT LoadedVT = LD->getMemoryVT();
5515 // Normal loads are handled by code generated from the .td file.
5516 if (LD->getAddressingMode() != ISD::PRE_INC) {
5517 // Change TLS initial-exec (or TLS local-exec on AIX) D-form loads to
5519 if (EnableTLSOpt && (Subtarget->isELFv2ABI() || Subtarget->isAIXABI()))
5520 if (tryTLSXFormLoad(LD))
5525 SDValue Offset = LD->getOffset();
5526 if (Offset.getOpcode() == ISD::TargetConstant ||
5527 Offset.getOpcode() == ISD::TargetGlobalAddress) {
5530 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
5531 if (LD->getValueType(0) != MVT::i64) {
5532 // Handle PPC32 integer and normal FP loads.
5533 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
5534 switch (LoadedVT.getSimpleVT().SimpleTy) {
5535 default: llvm_unreachable("Invalid PPC load type!");
5536 case MVT::f64: Opcode = PPC::LFDU; break;
5537 case MVT::f32: Opcode = PPC::LFSU; break;
5538 case MVT::i32: Opcode = PPC::LWZU; break;
5539 case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
5541 case MVT::i8: Opcode = PPC::LBZU; break;
5544 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
5545 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
5546 switch (LoadedVT.getSimpleVT().SimpleTy) {
5547 default: llvm_unreachable("Invalid PPC load type!");
5548 case MVT::i64: Opcode = PPC::LDU; break;
5549 case MVT::i32: Opcode = PPC::LWZU8; break;
5550 case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
5552 case MVT::i8: Opcode = PPC::LBZU8; break;
5556 SDValue Chain = LD->getChain();
5557 SDValue Base = LD->getBasePtr();
5558 SDValue Ops[] = { Offset, Base, Chain };
5559 SDNode *MN = CurDAG->getMachineNode(
5560 Opcode, dl, LD->getValueType(0),
5561 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
5562 transferMemOperands(N, MN);
5567 bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
5568 if (LD->getValueType(0) != MVT::i64) {
5569 // Handle PPC32 integer and normal FP loads.
5570 assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
5571 switch (LoadedVT.getSimpleVT().SimpleTy) {
5572 default: llvm_unreachable("Invalid PPC load type!");
5573 case MVT::f64: Opcode = PPC::LFDUX; break;
5574 case MVT::f32: Opcode = PPC::LFSUX; break;
5575 case MVT::i32: Opcode = PPC::LWZUX; break;
5576 case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
5578 case MVT::i8: Opcode = PPC::LBZUX; break;
5581 assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
5582 assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
5583 "Invalid sext update load");
5584 switch (LoadedVT.getSimpleVT().SimpleTy) {
5585 default: llvm_unreachable("Invalid PPC load type!");
5586 case MVT::i64: Opcode = PPC::LDUX; break;
5587 case MVT::i32: Opcode = isSExt ? PPC::LWAUX : PPC::LWZUX8; break;
5588 case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
5590 case MVT::i8: Opcode = PPC::LBZUX8; break;
5594 SDValue Chain = LD->getChain();
5595 SDValue Base = LD->getBasePtr();
5596 SDValue Ops[] = { Base, Offset, Chain };
5597 SDNode *MN = CurDAG->getMachineNode(
5598 Opcode, dl, LD->getValueType(0),
5599 PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
5600 transferMemOperands(N, MN);
5607 // If this is an 'and' with a mask, try to emit rlwinm/rldicl/rldicr
5608 if (tryAsSingleRLWINM(N) || tryAsSingleRLWIMI(N) || tryAsSingleRLDICL(N) ||
5609 tryAsSingleRLDICR(N) || tryAsSingleRLWINM8(N) || tryAsPairOfRLDICL(N))
5612 // Other cases are autogenerated.
5615 if (N->getValueType(0) == MVT::i32)
5616 if (tryBitfieldInsert(N))
5620 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
5621 isIntS16Immediate(N->getOperand(1), Imm)) {
5622 KnownBits LHSKnown = CurDAG->computeKnownBits(N->getOperand(0));
5624 // If this is equivalent to an add, then we can fold it with the
5625 // FrameIndex calculation.
5626 if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {
5627 selectFrameIndex(N, N->getOperand(0).getNode(), (int64_t)Imm);
5632 // If this is 'or' against an imm with consecutive ones and both sides zero,
5633 // try to emit rldimi
5634 if (tryAsSingleRLDIMI(N))
5637 // OR with a 32-bit immediate can be handled by ori + oris
5638 // without creating an immediate in a GPR.
5640 bool IsPPC64 = Subtarget->isPPC64();
5641 if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&
5642 (Imm64 & ~0xFFFFFFFFuLL) == 0) {
5643 // If ImmHi (ImmHi) is zero, only one ori (oris) is generated later.
5644 uint64_t ImmHi = Imm64 >> 16;
5645 uint64_t ImmLo = Imm64 & 0xFFFF;
5646 if (ImmHi != 0 && ImmLo != 0) {
5647 SDNode *Lo = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
5649 getI16Imm(ImmLo, dl));
5650 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};
5651 CurDAG->SelectNodeTo(N, PPC::ORIS8, MVT::i64, Ops1);
5656 // Other cases are autogenerated.
5660 // XOR with a 32-bit immediate can be handled by xori + xoris
5661 // without creating an immediate in a GPR.
5663 bool IsPPC64 = Subtarget->isPPC64();
5664 if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&
5665 (Imm64 & ~0xFFFFFFFFuLL) == 0) {
5666 // If ImmHi (ImmHi) is zero, only one xori (xoris) is generated later.
5667 uint64_t ImmHi = Imm64 >> 16;
5668 uint64_t ImmLo = Imm64 & 0xFFFF;
5669 if (ImmHi != 0 && ImmLo != 0) {
5670 SDNode *Lo = CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
5672 getI16Imm(ImmLo, dl));
5673 SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};
5674 CurDAG->SelectNodeTo(N, PPC::XORIS8, MVT::i64, Ops1);
5683 if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
5684 isIntS16Immediate(N->getOperand(1), Imm)) {
5685 selectFrameIndex(N, N->getOperand(0).getNode(), (int64_t)Imm);
5692 unsigned Imm, SH, MB, ME;
5693 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
5694 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
5695 SDValue Ops[] = { N->getOperand(0).getOperand(0),
5696 getI32Imm(SH, dl), getI32Imm(MB, dl),
5697 getI32Imm(ME, dl) };
5698 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
5702 // Other cases are autogenerated.
5706 unsigned Imm, SH, MB, ME;
5707 if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
5708 isRotateAndMask(N, Imm, true, SH, MB, ME)) {
5709 SDValue Ops[] = { N->getOperand(0).getOperand(0),
5710 getI32Imm(SH, dl), getI32Imm(MB, dl),
5711 getI32Imm(ME, dl) };
5712 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
5716 // Other cases are autogenerated.
5720 SDValue Op1 = N->getOperand(1);
5721 if (Op1.getOpcode() != ISD::Constant ||
5722 (Op1.getValueType() != MVT::i64 && Op1.getValueType() != MVT::i32))
5725 // If the multiplier fits int16, we can handle it with mulli.
5726 int64_t Imm = cast<ConstantSDNode>(Op1)->getZExtValue();
5727 unsigned Shift = llvm::countr_zero<uint64_t>(Imm);
5728 if (isInt<16>(Imm) || !Shift)
5731 // If the shifted value fits int16, we can do this transformation:
5732 // (mul X, c1 << c2) -> (rldicr (mulli X, c1) c2). We do this in ISEL due to
5733 // DAGCombiner prefers (shl (mul X, c1), c2) -> (mul X, c1 << c2).
5734 uint64_t ImmSh = Imm >> Shift;
5735 if (!isInt<16>(ImmSh))
5738 uint64_t SextImm = SignExtend64(ImmSh & 0xFFFF, 16);
5739 if (Op1.getValueType() == MVT::i64) {
5740 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i64);
5741 SDNode *MulNode = CurDAG->getMachineNode(PPC::MULLI8, dl, MVT::i64,
5742 N->getOperand(0), SDImm);
5744 SDValue Ops[] = {SDValue(MulNode, 0), getI32Imm(Shift, dl),
5745 getI32Imm(63 - Shift, dl)};
5746 CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);
5749 SDValue SDImm = CurDAG->getTargetConstant(SextImm, dl, MVT::i32);
5750 SDNode *MulNode = CurDAG->getMachineNode(PPC::MULLI, dl, MVT::i32,
5751 N->getOperand(0), SDImm);
5753 SDValue Ops[] = {SDValue(MulNode, 0), getI32Imm(Shift, dl),
5754 getI32Imm(0, dl), getI32Imm(31 - Shift, dl)};
5755 CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
5760 // FIXME: Remove this once the ANDI glue bug is fixed:
5761 case PPCISD::ANDI_rec_1_EQ_BIT:
5762 case PPCISD::ANDI_rec_1_GT_BIT: {
5766 EVT InVT = N->getOperand(0).getValueType();
5767 assert((InVT == MVT::i64 || InVT == MVT::i32) &&
5768 "Invalid input type for ANDI_rec_1_EQ_BIT");
5770 unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDI8_rec : PPC::ANDI_rec;
5771 SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
5773 CurDAG->getTargetConstant(1, dl, InVT)),
5775 SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
5776 SDValue SRIdxVal = CurDAG->getTargetConstant(
5777 N->getOpcode() == PPCISD::ANDI_rec_1_EQ_BIT ? PPC::sub_eq : PPC::sub_gt,
5780 CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg,
5781 SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */);
5784 case ISD::SELECT_CC: {
5785 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
5787 CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
5788 bool isPPC64 = (PtrVT == MVT::i64);
5790 // If this is a select of i1 operands, we'll pattern match it.
5791 if (Subtarget->useCRBits() && N->getOperand(0).getValueType() == MVT::i1)
5794 if (Subtarget->isISA3_0() && Subtarget->isPPC64()) {
5795 bool NeedSwapOps = false;
5796 bool IsUnCmp = false;
5797 if (mayUseP9Setb(N, CC, CurDAG, NeedSwapOps, IsUnCmp)) {
5798 SDValue LHS = N->getOperand(0);
5799 SDValue RHS = N->getOperand(1);
5801 std::swap(LHS, RHS);
5803 // Make use of SelectCC to generate the comparison to set CR bits, for
5804 // equality comparisons having one literal operand, SelectCC probably
5805 // doesn't need to materialize the whole literal and just use xoris to
5806 // check it first, it leads the following comparison result can't
5807 // exactly represent GT/LT relationship. So to avoid this we specify
5808 // SETGT/SETUGT here instead of SETEQ.
5810 SelectCC(LHS, RHS, IsUnCmp ? ISD::SETUGT : ISD::SETGT, dl);
5811 CurDAG->SelectNodeTo(
5812 N, N->getSimpleValueType(0) == MVT::i64 ? PPC::SETB8 : PPC::SETB,
5813 N->getValueType(0), GenCC);
5819 // Handle the setcc cases here. select_cc lhs, 0, 1, 0, cc
5820 if (!isPPC64 && isNullConstant(N->getOperand(1)) &&
5821 isOneConstant(N->getOperand(2)) && isNullConstant(N->getOperand(3)) &&
5823 // FIXME: Implement this optzn for PPC64.
5824 N->getValueType(0) == MVT::i32) {
5826 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
5827 N->getOperand(0), getI32Imm(~0U, dl));
5828 CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0),
5829 N->getOperand(0), SDValue(Tmp, 1));
5833 SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
5835 if (N->getValueType(0) == MVT::i1) {
5836 // An i1 select is: (c & t) | (!c & f).
5838 unsigned Idx = getCRIdxForSetCC(CC, Inv);
5842 default: llvm_unreachable("Invalid CC index");
5843 case 0: SRI = PPC::sub_lt; break;
5844 case 1: SRI = PPC::sub_gt; break;
5845 case 2: SRI = PPC::sub_eq; break;
5846 case 3: SRI = PPC::sub_un; break;
5849 SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
5851 SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
5853 SDValue C = Inv ? NotCCBit : CCBit,
5854 NotC = Inv ? CCBit : NotCCBit;
5856 SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
5857 C, N->getOperand(2)), 0);
5858 SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
5859 NotC, N->getOperand(3)), 0);
5861 CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
5866 getPredicateForSetCC(CC, N->getOperand(0).getValueType(), Subtarget);
5868 unsigned SelectCCOp;
5869 if (N->getValueType(0) == MVT::i32)
5870 SelectCCOp = PPC::SELECT_CC_I4;
5871 else if (N->getValueType(0) == MVT::i64)
5872 SelectCCOp = PPC::SELECT_CC_I8;
5873 else if (N->getValueType(0) == MVT::f32) {
5874 if (Subtarget->hasP8Vector())
5875 SelectCCOp = PPC::SELECT_CC_VSSRC;
5876 else if (Subtarget->hasSPE())
5877 SelectCCOp = PPC::SELECT_CC_SPE4;
5879 SelectCCOp = PPC::SELECT_CC_F4;
5880 } else if (N->getValueType(0) == MVT::f64) {
5881 if (Subtarget->hasVSX())
5882 SelectCCOp = PPC::SELECT_CC_VSFRC;
5883 else if (Subtarget->hasSPE())
5884 SelectCCOp = PPC::SELECT_CC_SPE;
5886 SelectCCOp = PPC::SELECT_CC_F8;
5887 } else if (N->getValueType(0) == MVT::f128)
5888 SelectCCOp = PPC::SELECT_CC_F16;
5889 else if (Subtarget->hasSPE())
5890 SelectCCOp = PPC::SELECT_CC_SPE;
5891 else if (N->getValueType(0) == MVT::v2f64 ||
5892 N->getValueType(0) == MVT::v2i64)
5893 SelectCCOp = PPC::SELECT_CC_VSRC;
5895 SelectCCOp = PPC::SELECT_CC_VRRC;
5897 SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
5898 getI32Imm(BROpc, dl) };
5899 CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
5902 case ISD::VECTOR_SHUFFLE:
5903 if (Subtarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
5904 N->getValueType(0) == MVT::v2i64)) {
5905 ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
5907 SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
5908 Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
5911 for (int i = 0; i < 2; ++i)
5912 if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
5917 if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
5918 Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5919 isa<LoadSDNode>(Op1.getOperand(0))) {
5920 LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
5921 SDValue Base, Offset;
5923 if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
5924 (LD->getMemoryVT() == MVT::f64 ||
5925 LD->getMemoryVT() == MVT::i64) &&
5926 SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
5927 SDValue Chain = LD->getChain();
5928 SDValue Ops[] = { Base, Offset, Chain };
5929 MachineMemOperand *MemOp = LD->getMemOperand();
5930 SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX,
5931 N->getValueType(0), Ops);
5932 CurDAG->setNodeMemRefs(cast<MachineSDNode>(NewN), {MemOp});
5937 // For little endian, we must swap the input operands and adjust
5938 // the mask elements (reverse and invert them).
5939 if (Subtarget->isLittleEndian()) {
5940 std::swap(Op1, Op2);
5941 unsigned tmp = DM[0];
5946 SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
5948 SDValue Ops[] = { Op1, Op2, DMV };
5949 CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
5956 bool IsPPC64 = Subtarget->isPPC64();
5957 SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
5958 CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ
5959 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
5960 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
5964 case PPCISD::COND_BRANCH: {
5965 // Op #0 is the Chain.
5966 // Op #1 is the PPC::PRED_* number.
5968 // Op #3 is the Dest MBB
5969 // Op #4 is the Flag.
5970 // Prevent PPC::PRED_* from being selected into LI.
5971 unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
5972 if (EnableBranchHint)
5973 PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(3));
5975 SDValue Pred = getI32Imm(PCC, dl);
5976 SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
5977 N->getOperand(0), N->getOperand(4) };
5978 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
5982 if (tryFoldSWTestBRCC(N))
5984 if (trySelectLoopCountIntrinsic(N))
5986 ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
5988 getPredicateForSetCC(CC, N->getOperand(2).getValueType(), Subtarget);
5990 if (N->getOperand(2).getValueType() == MVT::i1) {
5994 default: llvm_unreachable("Unexpected Boolean-operand predicate");
5995 case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true; break;
5996 case PPC::PRED_LE: Opc = PPC::CRORC; Swap = true; break;
5997 case PPC::PRED_EQ: Opc = PPC::CREQV; Swap = false; break;
5998 case PPC::PRED_GE: Opc = PPC::CRORC; Swap = false; break;
5999 case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
6000 case PPC::PRED_NE: Opc = PPC::CRXOR; Swap = false; break;
6003 // A signed comparison of i1 values produces the opposite result to an
6004 // unsigned one if the condition code includes less-than or greater-than.
6005 // This is because 1 is the most negative signed i1 number and the most
6006 // positive unsigned i1 number. The CR-logical operations used for such
6007 // comparisons are non-commutative so for signed comparisons vs. unsigned
6008 // ones, the input operands just need to be swapped.
6009 if (ISD::isSignedIntSetCC(CC))
6012 SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
6013 N->getOperand(Swap ? 3 : 2),
6014 N->getOperand(Swap ? 2 : 3)), 0);
6015 CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4),
6020 if (EnableBranchHint)
6021 PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(4));
6023 SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
6024 SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
6025 N->getOperand(4), N->getOperand(0) };
6026 CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
6030 // FIXME: Should custom lower this.
6031 SDValue Chain = N->getOperand(0);
6032 SDValue Target = N->getOperand(1);
6033 unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
6034 unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
6035 Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
6037 CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
6040 case PPCISD::TOC_ENTRY: {
6041 const bool isPPC64 = Subtarget->isPPC64();
6042 const bool isELFABI = Subtarget->isSVR4ABI();
6043 const bool isAIXABI = Subtarget->isAIXABI();
6045 // PowerPC only support small, medium and large code model.
6046 const CodeModel::Model CModel = TM.getCodeModel();
6047 assert(!(CModel == CodeModel::Tiny || CModel == CodeModel::Kernel) &&
6048 "PowerPC doesn't support tiny or kernel code models.");
6050 if (isAIXABI && CModel == CodeModel::Medium)
6051 report_fatal_error("Medium code model is not supported on AIX.");
6053 // For 64-bit ELF small code model, we allow SelectCodeCommon to handle
6054 // this, selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA. For AIX
6055 // small code model, we need to check for a toc-data attribute.
6056 if (isPPC64 && !isAIXABI && CModel == CodeModel::Small)
6059 auto replaceWith = [this, &dl](unsigned OpCode, SDNode *TocEntry,
6061 SDValue GA = TocEntry->getOperand(0);
6062 SDValue TocBase = TocEntry->getOperand(1);
6063 SDNode *MN = CurDAG->getMachineNode(OpCode, dl, OperandTy, GA, TocBase);
6064 transferMemOperands(TocEntry, MN);
6065 ReplaceNode(TocEntry, MN);
6068 // Handle 32-bit small code model.
6069 if (!isPPC64 && CModel == CodeModel::Small) {
6070 // Transforms the ISD::TOC_ENTRY node to passed in Opcode, either
6071 // PPC::ADDItoc, or PPC::LWZtoc
6073 assert(TM.isPositionIndependent() &&
6074 "32-bit ELF can only have TOC entries in position independent"
6076 // 32-bit ELF always uses a small code model toc access.
6077 replaceWith(PPC::LWZtoc, N, MVT::i32);
6081 assert(isAIXABI && "ELF ABI already handled");
6083 if (hasTocDataAttr(N->getOperand(0),
6084 CurDAG->getDataLayout().getPointerSize())) {
6085 replaceWith(PPC::ADDItoc, N, MVT::i32);
6089 replaceWith(PPC::LWZtoc, N, MVT::i32);
6093 if (isPPC64 && CModel == CodeModel::Small) {
6094 assert(isAIXABI && "ELF ABI handled in common SelectCode");
6096 if (hasTocDataAttr(N->getOperand(0),
6097 CurDAG->getDataLayout().getPointerSize())) {
6098 replaceWith(PPC::ADDItoc8, N, MVT::i64);
6101 // Break if it doesn't have toc data attribute. Proceed with common
6106 assert(CModel != CodeModel::Small && "All small code models handled.");
6108 assert((isPPC64 || (isAIXABI && !isPPC64)) && "We are dealing with 64-bit"
6109 " ELF/AIX or 32-bit AIX in the following.");
6111 // Transforms the ISD::TOC_ENTRY node for 32-bit AIX large code model mode
6112 // or 64-bit medium (ELF-only) or large (ELF and AIX) code model code. We
6113 // generate two instructions as described below. The first source operand
6114 // is a symbol reference. If it must be toc-referenced according to
6115 // Subtarget, we generate:
6117 // LWZtocL(@sym, ADDIStocHA(%r2, @sym))
6119 // LDtocL(@sym, ADDIStocHA8(%x2, @sym))
6120 // Otherwise we generate:
6121 // ADDItocL(ADDIStocHA8(%x2, @sym), @sym)
6122 SDValue GA = N->getOperand(0);
6123 SDValue TOCbase = N->getOperand(1);
6125 EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
6126 SDNode *Tmp = CurDAG->getMachineNode(
6127 isPPC64 ? PPC::ADDIStocHA8 : PPC::ADDIStocHA, dl, VT, TOCbase, GA);
6129 if (PPCLowering->isAccessedAsGotIndirect(GA)) {
6130 // If it is accessed as got-indirect, we need an extra LWZ/LD to load
6132 SDNode *MN = CurDAG->getMachineNode(
6133 isPPC64 ? PPC::LDtocL : PPC::LWZtocL, dl, VT, GA, SDValue(Tmp, 0));
6135 transferMemOperands(N, MN);
6140 // Build the address relative to the TOC-pointer.
6141 ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
6142 SDValue(Tmp, 0), GA));
6145 case PPCISD::PPC32_PICGOT:
6146 // Generate a PIC-safe GOT reference.
6147 assert(Subtarget->is32BitELFABI() &&
6148 "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
6149 CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT,
6150 PPCLowering->getPointerTy(CurDAG->getDataLayout()),
6154 case PPCISD::VADD_SPLAT: {
6155 // This expands into one of three sequences, depending on whether
6156 // the first operand is odd or even, positive or negative.
6157 assert(isa<ConstantSDNode>(N->getOperand(0)) &&
6158 isa<ConstantSDNode>(N->getOperand(1)) &&
6159 "Invalid operand on VADD_SPLAT!");
6161 int Elt = N->getConstantOperandVal(0);
6162 int EltSize = N->getConstantOperandVal(1);
6163 unsigned Opc1, Opc2, Opc3;
6167 Opc1 = PPC::VSPLTISB;
6168 Opc2 = PPC::VADDUBM;
6169 Opc3 = PPC::VSUBUBM;
6171 } else if (EltSize == 2) {
6172 Opc1 = PPC::VSPLTISH;
6173 Opc2 = PPC::VADDUHM;
6174 Opc3 = PPC::VSUBUHM;
6177 assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
6178 Opc1 = PPC::VSPLTISW;
6179 Opc2 = PPC::VADDUWM;
6180 Opc3 = PPC::VSUBUWM;
6184 if ((Elt & 1) == 0) {
6185 // Elt is even, in the range [-32,-18] + [16,30].
6187 // Convert: VADD_SPLAT elt, size
6188 // Into: tmp = VSPLTIS[BHW] elt
6189 // VADDU[BHW]M tmp, tmp
6190 // Where: [BHW] = B for size = 1, H for size = 2, W for size = 4
6191 SDValue EltVal = getI32Imm(Elt >> 1, dl);
6192 SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
6193 SDValue TmpVal = SDValue(Tmp, 0);
6194 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal));
6196 } else if (Elt > 0) {
6197 // Elt is odd and positive, in the range [17,31].
6199 // Convert: VADD_SPLAT elt, size
6200 // Into: tmp1 = VSPLTIS[BHW] elt-16
6201 // tmp2 = VSPLTIS[BHW] -16
6202 // VSUBU[BHW]M tmp1, tmp2
6203 SDValue EltVal = getI32Imm(Elt - 16, dl);
6204 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
6205 EltVal = getI32Imm(-16, dl);
6206 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
6207 ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
6211 // Elt is odd and negative, in the range [-31,-17].
6213 // Convert: VADD_SPLAT elt, size
6214 // Into: tmp1 = VSPLTIS[BHW] elt+16
6215 // tmp2 = VSPLTIS[BHW] -16
6216 // VADDU[BHW]M tmp1, tmp2
6217 SDValue EltVal = getI32Imm(Elt + 16, dl);
6218 SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
6219 EltVal = getI32Imm(-16, dl);
6220 SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
6221 ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
6226 case PPCISD::LD_SPLAT: {
6227 // Here we want to handle splat load for type v16i8 and v8i16 when there is
6228 // no direct move, we don't need to use stack for this case. If target has
6229 // direct move, we should be able to get the best selection in the .td file.
6230 if (!Subtarget->hasAltivec() || Subtarget->hasDirectMove())
6233 EVT Type = N->getValueType(0);
6234 if (Type != MVT::v16i8 && Type != MVT::v8i16)
6237 // If the alignment for the load is 16 or bigger, we don't need the
6238 // permutated mask to get the required value. The value must be the 0
6239 // element in big endian target or 7/15 in little endian target in the
6240 // result vsx register of lvx instruction.
6241 // Select the instruction in the .td file.
6242 if (cast<MemIntrinsicSDNode>(N)->getAlign() >= Align(16) &&
6243 isOffsetMultipleOf(N, 16))
6247 CurDAG->getRegister(Subtarget->isPPC64() ? PPC::ZERO8 : PPC::ZERO,
6248 Subtarget->isPPC64() ? MVT::i64 : MVT::i32);
6249 unsigned LIOpcode = Subtarget->isPPC64() ? PPC::LI8 : PPC::LI;
6250 // v16i8 LD_SPLAT addr
6252 // Mask = LVSR/LVSL 0, addr
6253 // LoadLow = LVX 0, addr
6254 // Perm = VPERM LoadLow, LoadLow, Mask
6255 // Splat = VSPLTB 15/0, Perm
6257 // v8i16 LD_SPLAT addr
6259 // Mask = LVSR/LVSL 0, addr
6260 // LoadLow = LVX 0, addr
6261 // LoadHigh = LVX (LI, 1), addr
6262 // Perm = VPERM LoadLow, LoadHigh, Mask
6263 // Splat = VSPLTH 7/0, Perm
6264 unsigned SplatOp = (Type == MVT::v16i8) ? PPC::VSPLTB : PPC::VSPLTH;
6265 unsigned SplatElemIndex =
6266 Subtarget->isLittleEndian() ? ((Type == MVT::v16i8) ? 15 : 7) : 0;
6268 SDNode *Mask = CurDAG->getMachineNode(
6269 Subtarget->isLittleEndian() ? PPC::LVSR : PPC::LVSL, dl, Type, ZeroReg,
6273 CurDAG->getMachineNode(PPC::LVX, dl, MVT::v16i8, MVT::Other,
6274 {ZeroReg, N->getOperand(1), N->getOperand(0)});
6276 SDNode *LoadHigh = LoadLow;
6277 if (Type == MVT::v8i16) {
6278 LoadHigh = CurDAG->getMachineNode(
6279 PPC::LVX, dl, MVT::v16i8, MVT::Other,
6280 {SDValue(CurDAG->getMachineNode(
6281 LIOpcode, dl, MVT::i32,
6282 CurDAG->getTargetConstant(1, dl, MVT::i8)),
6284 N->getOperand(1), SDValue(LoadLow, 1)});
6287 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 1), SDValue(LoadHigh, 1));
6288 transferMemOperands(N, LoadHigh);
6291 CurDAG->getMachineNode(PPC::VPERM, dl, Type, SDValue(LoadLow, 0),
6292 SDValue(LoadHigh, 0), SDValue(Mask, 0));
6293 CurDAG->SelectNodeTo(N, SplatOp, Type,
6294 CurDAG->getTargetConstant(SplatElemIndex, dl, MVT::i8),
6303 // If the target supports the cmpb instruction, do the idiom recognition here.
6304 // We don't do this as a DAG combine because we don't want to do it as nodes
6305 // are being combined (because we might miss part of the eventual idiom). We
6306 // don't want to do it during instruction selection because we want to reuse
6307 // the logic for lowering the masking operations already part of the
6308 // instruction selector.
6309 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
6312 assert(N->getOpcode() == ISD::OR &&
6313 "Only OR nodes are supported for CMPB");
6316 if (!Subtarget->hasCMPB())
6319 if (N->getValueType(0) != MVT::i32 &&
6320 N->getValueType(0) != MVT::i64)
6323 EVT VT = N->getValueType(0);
6326 bool BytesFound[8] = {false, false, false, false, false, false, false, false};
6327 uint64_t Mask = 0, Alt = 0;
6329 auto IsByteSelectCC = [this](SDValue O, unsigned &b,
6330 uint64_t &Mask, uint64_t &Alt,
6331 SDValue &LHS, SDValue &RHS) {
6332 if (O.getOpcode() != ISD::SELECT_CC)
6334 ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
6336 if (!isa<ConstantSDNode>(O.getOperand(2)) ||
6337 !isa<ConstantSDNode>(O.getOperand(3)))
6340 uint64_t PM = O.getConstantOperandVal(2);
6341 uint64_t PAlt = O.getConstantOperandVal(3);
6342 for (b = 0; b < 8; ++b) {
6343 uint64_t Mask = UINT64_C(0xFF) << (8*b);
6344 if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
6353 if (!isa<ConstantSDNode>(O.getOperand(1)) ||
6354 O.getConstantOperandVal(1) != 0) {
6355 SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
6356 if (Op0.getOpcode() == ISD::TRUNCATE)
6357 Op0 = Op0.getOperand(0);
6358 if (Op1.getOpcode() == ISD::TRUNCATE)
6359 Op1 = Op1.getOperand(0);
6361 if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
6362 Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
6363 isa<ConstantSDNode>(Op0.getOperand(1))) {
6365 unsigned Bits = Op0.getValueSizeInBits();
6368 if (Op0.getConstantOperandVal(1) != Bits-8)
6371 LHS = Op0.getOperand(0);
6372 RHS = Op1.getOperand(0);
6376 // When we have small integers (i16 to be specific), the form present
6377 // post-legalization uses SETULT in the SELECT_CC for the
6378 // higher-order byte, depending on the fact that the
6379 // even-higher-order bytes are known to all be zero, for example:
6380 // select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
6381 // (so when the second byte is the same, because all higher-order
6382 // bits from bytes 3 and 4 are known to be zero, the result of the
6383 // xor can be at most 255)
6384 if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
6385 isa<ConstantSDNode>(O.getOperand(1))) {
6387 uint64_t ULim = O.getConstantOperandVal(1);
6388 if (ULim != (UINT64_C(1) << b*8))
6391 // Now we need to make sure that the upper bytes are known to be
6393 unsigned Bits = Op0.getValueSizeInBits();
6394 if (!CurDAG->MaskedValueIsZero(
6395 Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8)))
6398 LHS = Op0.getOperand(0);
6399 RHS = Op0.getOperand(1);
6406 if (CC != ISD::SETEQ)
6409 SDValue Op = O.getOperand(0);
6410 if (Op.getOpcode() == ISD::AND) {
6411 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6413 if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
6416 SDValue XOR = Op.getOperand(0);
6417 if (XOR.getOpcode() == ISD::TRUNCATE)
6418 XOR = XOR.getOperand(0);
6419 if (XOR.getOpcode() != ISD::XOR)
6422 LHS = XOR.getOperand(0);
6423 RHS = XOR.getOperand(1);
6425 } else if (Op.getOpcode() == ISD::SRL) {
6426 if (!isa<ConstantSDNode>(Op.getOperand(1)))
6428 unsigned Bits = Op.getValueSizeInBits();
6431 if (Op.getConstantOperandVal(1) != Bits-8)
6434 SDValue XOR = Op.getOperand(0);
6435 if (XOR.getOpcode() == ISD::TRUNCATE)
6436 XOR = XOR.getOperand(0);
6437 if (XOR.getOpcode() != ISD::XOR)
6440 LHS = XOR.getOperand(0);
6441 RHS = XOR.getOperand(1);
6448 SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
6449 while (!Queue.empty()) {
6450 SDValue V = Queue.pop_back_val();
6452 for (const SDValue &O : V.getNode()->ops()) {
6454 uint64_t M = 0, A = 0;
6456 if (O.getOpcode() == ISD::OR) {
6458 } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
6462 BytesFound[b] = true;
6465 } else if ((LHS == ORHS && RHS == OLHS) ||
6466 (RHS == ORHS && LHS == OLHS)) {
6467 BytesFound[b] = true;
6479 unsigned LastB = 0, BCnt = 0;
6480 for (unsigned i = 0; i < 8; ++i)
6481 if (BytesFound[LastB]) {
6486 if (!LastB || BCnt < 2)
6489 // Because we'll be zero-extending the output anyway if don't have a specific
6490 // value for each input byte (via the Mask), we can 'anyext' the inputs.
6491 if (LHS.getValueType() != VT) {
6492 LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
6493 RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
6496 Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
6498 bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
6499 if (NonTrivialMask && !Alt) {
6500 // Res = Mask & CMPB
6501 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
6502 CurDAG->getConstant(Mask, dl, VT));
6504 // Res = (CMPB & Mask) | (~CMPB & Alt)
6505 // Which, as suggested here:
6506 // https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
6507 // can be written as:
6508 // Res = Alt ^ ((Alt ^ Mask) & CMPB)
6509 // useful because the (Alt ^ Mask) can be pre-computed.
6510 Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
6511 CurDAG->getConstant(Mask ^ Alt, dl, VT));
6512 Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
6513 CurDAG->getConstant(Alt, dl, VT));
6519 // When CR bit registers are enabled, an extension of an i1 variable to a i32
6520 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
6521 // involves constant materialization of a 0 or a 1 or both. If the result of
6522 // the extension is then operated upon by some operator that can be constant
6523 // folded with a constant 0 or 1, and that constant can be materialized using
6524 // only one instruction (like a zero or one), then we should fold in those
6525 // operations with the select.
6526 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
6527 if (!Subtarget->useCRBits())
6530 if (N->getOpcode() != ISD::ZERO_EXTEND &&
6531 N->getOpcode() != ISD::SIGN_EXTEND &&
6532 N->getOpcode() != ISD::ANY_EXTEND)
6535 if (N->getOperand(0).getValueType() != MVT::i1)
6538 if (!N->hasOneUse())
6542 EVT VT = N->getValueType(0);
6543 SDValue Cond = N->getOperand(0);
6545 CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
6546 SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
6549 SDNode *User = *N->use_begin();
6550 if (User->getNumOperands() != 2)
6553 auto TryFold = [this, N, User, dl](SDValue Val) {
6554 SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
6555 SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
6556 SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
6558 return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
6559 User->getValueType(0), {O0, O1});
6562 // FIXME: When the semantics of the interaction between select and undef
6563 // are clearly defined, it may turn out to be unnecessary to break here.
6564 SDValue TrueRes = TryFold(ConstTrue);
6565 if (!TrueRes || TrueRes.isUndef())
6567 SDValue FalseRes = TryFold(ConstFalse);
6568 if (!FalseRes || FalseRes.isUndef())
6571 // For us to materialize these using one instruction, we must be able to
6572 // represent them as signed 16-bit integers.
6573 uint64_t True = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
6574 False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
6575 if (!isInt<16>(True) || !isInt<16>(False))
6578 // We can replace User with a new SELECT node, and try again to see if we
6579 // can fold the select with its user.
6580 Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
6582 ConstTrue = TrueRes;
6583 ConstFalse = FalseRes;
6584 } while (N->hasOneUse());
6587 void PPCDAGToDAGISel::PreprocessISelDAG() {
6588 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
6590 bool MadeChange = false;
6591 while (Position != CurDAG->allnodes_begin()) {
6592 SDNode *N = &*--Position;
6597 switch (N->getOpcode()) {
6600 Res = combineToCMPB(N);
6605 foldBoolExts(Res, N);
6608 LLVM_DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld: ");
6609 LLVM_DEBUG(N->dump(CurDAG));
6610 LLVM_DEBUG(dbgs() << "\nNew: ");
6611 LLVM_DEBUG(Res.getNode()->dump(CurDAG));
6612 LLVM_DEBUG(dbgs() << "\n");
6614 CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
6620 CurDAG->RemoveDeadNodes();
6623 /// PostprocessISelDAG - Perform some late peephole optimizations
6624 /// on the DAG representation.
6625 void PPCDAGToDAGISel::PostprocessISelDAG() {
6626 // Skip peepholes at -O0.
6627 if (TM.getOptLevel() == CodeGenOpt::None)
6632 PeepholePPC64ZExt();
6635 // Check if all users of this node will become isel where the second operand
6636 // is the constant zero. If this is so, and if we can negate the condition,
6637 // then we can flip the true and false operands. This will allow the zero to
6638 // be folded with the isel so that we don't need to materialize a register
6640 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
6641 for (const SDNode *User : N->uses()) {
6642 if (!User->isMachineOpcode())
6644 if (User->getMachineOpcode() != PPC::SELECT_I4 &&
6645 User->getMachineOpcode() != PPC::SELECT_I8)
6648 SDNode *Op1 = User->getOperand(1).getNode();
6649 SDNode *Op2 = User->getOperand(2).getNode();
6650 // If we have a degenerate select with two equal operands, swapping will
6651 // not do anything, and we may run into an infinite loop.
6655 if (!Op2->isMachineOpcode())
6658 if (Op2->getMachineOpcode() != PPC::LI &&
6659 Op2->getMachineOpcode() != PPC::LI8)
6662 ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
6673 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
6674 SmallVector<SDNode *, 4> ToReplace;
6675 for (SDNode *User : N->uses()) {
6676 assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
6677 User->getMachineOpcode() == PPC::SELECT_I8) &&
6678 "Must have all select users");
6679 ToReplace.push_back(User);
6682 for (SDNode *User : ToReplace) {
6684 CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
6685 User->getValueType(0), User->getOperand(0),
6686 User->getOperand(2),
6687 User->getOperand(1));
6689 LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
6690 LLVM_DEBUG(User->dump(CurDAG));
6691 LLVM_DEBUG(dbgs() << "\nNew: ");
6692 LLVM_DEBUG(ResNode->dump(CurDAG));
6693 LLVM_DEBUG(dbgs() << "\n");
6695 ReplaceUses(User, ResNode);
6699 void PPCDAGToDAGISel::PeepholeCROps() {
6703 for (SDNode &Node : CurDAG->allnodes()) {
6704 MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
6705 if (!MachineNode || MachineNode->use_empty())
6707 SDNode *ResNode = MachineNode;
6709 bool Op1Set = false, Op1Unset = false,
6711 Op2Set = false, Op2Unset = false,
6714 unsigned Opcode = MachineNode->getMachineOpcode();
6725 SDValue Op = MachineNode->getOperand(1);
6726 if (Op.isMachineOpcode()) {
6727 if (Op.getMachineOpcode() == PPC::CRSET)
6729 else if (Op.getMachineOpcode() == PPC::CRUNSET)
6731 else if ((Op.getMachineOpcode() == PPC::CRNOR &&
6732 Op.getOperand(0) == Op.getOperand(1)) ||
6733 Op.getMachineOpcode() == PPC::CRNOT)
6740 case PPC::SELECT_I4:
6741 case PPC::SELECT_I8:
6742 case PPC::SELECT_F4:
6743 case PPC::SELECT_F8:
6744 case PPC::SELECT_SPE:
6745 case PPC::SELECT_SPE4:
6746 case PPC::SELECT_VRRC:
6747 case PPC::SELECT_VSFRC:
6748 case PPC::SELECT_VSSRC:
6749 case PPC::SELECT_VSRC: {
6750 SDValue Op = MachineNode->getOperand(0);
6751 if (Op.isMachineOpcode()) {
6752 if (Op.getMachineOpcode() == PPC::CRSET)
6754 else if (Op.getMachineOpcode() == PPC::CRUNSET)
6756 else if ((Op.getMachineOpcode() == PPC::CRNOR &&
6757 Op.getOperand(0) == Op.getOperand(1)) ||
6758 Op.getMachineOpcode() == PPC::CRNOT)
6765 bool SelectSwap = false;
6769 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6771 ResNode = MachineNode->getOperand(0).getNode();
6774 ResNode = MachineNode->getOperand(1).getNode();
6777 ResNode = MachineNode->getOperand(0).getNode();
6778 else if (Op1Unset || Op2Unset)
6779 // x & 0 = 0 & y = 0
6780 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6783 // ~x & y = andc(y, x)
6784 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6785 MVT::i1, MachineNode->getOperand(1),
6786 MachineNode->getOperand(0).
6789 // x & ~y = andc(x, y)
6790 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6791 MVT::i1, MachineNode->getOperand(0),
6792 MachineNode->getOperand(1).
6794 else if (AllUsersSelectZero(MachineNode)) {
6795 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
6796 MVT::i1, MachineNode->getOperand(0),
6797 MachineNode->getOperand(1));
6802 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6803 // nand(x, x) -> nor(x, x)
6804 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6805 MVT::i1, MachineNode->getOperand(0),
6806 MachineNode->getOperand(0));
6808 // nand(1, y) -> nor(y, y)
6809 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6810 MVT::i1, MachineNode->getOperand(1),
6811 MachineNode->getOperand(1));
6813 // nand(x, 1) -> nor(x, x)
6814 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6815 MVT::i1, MachineNode->getOperand(0),
6816 MachineNode->getOperand(0));
6817 else if (Op1Unset || Op2Unset)
6818 // nand(x, 0) = nand(0, y) = 1
6819 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
6822 // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
6823 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
6824 MVT::i1, MachineNode->getOperand(0).
6826 MachineNode->getOperand(1));
6828 // nand(x, ~y) = ~x | y = orc(y, x)
6829 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
6830 MVT::i1, MachineNode->getOperand(1).
6832 MachineNode->getOperand(0));
6833 else if (AllUsersSelectZero(MachineNode)) {
6834 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
6835 MVT::i1, MachineNode->getOperand(0),
6836 MachineNode->getOperand(1));
6841 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6843 ResNode = MachineNode->getOperand(0).getNode();
6844 else if (Op1Set || Op2Set)
6845 // x | 1 = 1 | y = 1
6846 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
6850 ResNode = MachineNode->getOperand(1).getNode();
6853 ResNode = MachineNode->getOperand(0).getNode();
6855 // ~x | y = orc(y, x)
6856 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
6857 MVT::i1, MachineNode->getOperand(1),
6858 MachineNode->getOperand(0).
6861 // x | ~y = orc(x, y)
6862 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
6863 MVT::i1, MachineNode->getOperand(0),
6864 MachineNode->getOperand(1).
6866 else if (AllUsersSelectZero(MachineNode)) {
6867 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6868 MVT::i1, MachineNode->getOperand(0),
6869 MachineNode->getOperand(1));
6874 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6876 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6879 // xor(1, y) -> nor(y, y)
6880 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6881 MVT::i1, MachineNode->getOperand(1),
6882 MachineNode->getOperand(1));
6884 // xor(x, 1) -> nor(x, x)
6885 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6886 MVT::i1, MachineNode->getOperand(0),
6887 MachineNode->getOperand(0));
6890 ResNode = MachineNode->getOperand(1).getNode();
6893 ResNode = MachineNode->getOperand(0).getNode();
6895 // xor(~x, y) = eqv(x, y)
6896 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
6897 MVT::i1, MachineNode->getOperand(0).
6899 MachineNode->getOperand(1));
6901 // xor(x, ~y) = eqv(x, y)
6902 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
6903 MVT::i1, MachineNode->getOperand(0),
6904 MachineNode->getOperand(1).
6906 else if (AllUsersSelectZero(MachineNode)) {
6907 ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
6908 MVT::i1, MachineNode->getOperand(0),
6909 MachineNode->getOperand(1));
6914 if (Op1Set || Op2Set)
6916 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6919 // nor(0, y) = ~y -> nor(y, y)
6920 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6921 MVT::i1, MachineNode->getOperand(1),
6922 MachineNode->getOperand(1));
6925 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6926 MVT::i1, MachineNode->getOperand(0),
6927 MachineNode->getOperand(0));
6929 // nor(~x, y) = andc(x, y)
6930 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6931 MVT::i1, MachineNode->getOperand(0).
6933 MachineNode->getOperand(1));
6935 // nor(x, ~y) = andc(y, x)
6936 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6937 MVT::i1, MachineNode->getOperand(1).
6939 MachineNode->getOperand(0));
6940 else if (AllUsersSelectZero(MachineNode)) {
6941 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
6942 MVT::i1, MachineNode->getOperand(0),
6943 MachineNode->getOperand(1));
6948 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6950 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
6954 ResNode = MachineNode->getOperand(1).getNode();
6957 ResNode = MachineNode->getOperand(0).getNode();
6959 // eqv(0, y) = ~y -> nor(y, y)
6960 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6961 MVT::i1, MachineNode->getOperand(1),
6962 MachineNode->getOperand(1));
6965 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6966 MVT::i1, MachineNode->getOperand(0),
6967 MachineNode->getOperand(0));
6969 // eqv(~x, y) = xor(x, y)
6970 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
6971 MVT::i1, MachineNode->getOperand(0).
6973 MachineNode->getOperand(1));
6975 // eqv(x, ~y) = xor(x, y)
6976 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
6977 MVT::i1, MachineNode->getOperand(0),
6978 MachineNode->getOperand(1).
6980 else if (AllUsersSelectZero(MachineNode)) {
6981 ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
6982 MVT::i1, MachineNode->getOperand(0),
6983 MachineNode->getOperand(1));
6988 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6990 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6994 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6995 MVT::i1, MachineNode->getOperand(1),
6996 MachineNode->getOperand(1));
6997 else if (Op1Unset || Op2Set)
6998 // andc(0, y) = andc(x, 1) = 0
6999 ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
7003 ResNode = MachineNode->getOperand(0).getNode();
7005 // andc(~x, y) = ~(x | y) = nor(x, y)
7006 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
7007 MVT::i1, MachineNode->getOperand(0).
7009 MachineNode->getOperand(1));
7011 // andc(x, ~y) = x & y
7012 ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
7013 MVT::i1, MachineNode->getOperand(0),
7014 MachineNode->getOperand(1).
7016 else if (AllUsersSelectZero(MachineNode)) {
7017 ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
7018 MVT::i1, MachineNode->getOperand(1),
7019 MachineNode->getOperand(0));
7024 if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
7026 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
7028 else if (Op1Set || Op2Unset)
7029 // orc(1, y) = orc(x, 0) = 1
7030 ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
7034 ResNode = MachineNode->getOperand(0).getNode();
7037 ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
7038 MVT::i1, MachineNode->getOperand(1),
7039 MachineNode->getOperand(1));
7041 // orc(~x, y) = ~(x & y) = nand(x, y)
7042 ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
7043 MVT::i1, MachineNode->getOperand(0).
7045 MachineNode->getOperand(1));
7047 // orc(x, ~y) = x | y
7048 ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
7049 MVT::i1, MachineNode->getOperand(0),
7050 MachineNode->getOperand(1).
7052 else if (AllUsersSelectZero(MachineNode)) {
7053 ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
7054 MVT::i1, MachineNode->getOperand(1),
7055 MachineNode->getOperand(0));
7059 case PPC::SELECT_I4:
7060 case PPC::SELECT_I8:
7061 case PPC::SELECT_F4:
7062 case PPC::SELECT_F8:
7063 case PPC::SELECT_SPE:
7064 case PPC::SELECT_SPE4:
7065 case PPC::SELECT_VRRC:
7066 case PPC::SELECT_VSFRC:
7067 case PPC::SELECT_VSSRC:
7068 case PPC::SELECT_VSRC:
7070 ResNode = MachineNode->getOperand(1).getNode();
7072 ResNode = MachineNode->getOperand(2).getNode();
7074 ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
7076 MachineNode->getValueType(0),
7077 MachineNode->getOperand(0).
7079 MachineNode->getOperand(2),
7080 MachineNode->getOperand(1));
7085 ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
7089 MachineNode->getOperand(0).
7091 MachineNode->getOperand(1),
7092 MachineNode->getOperand(2));
7093 // FIXME: Handle Op1Set, Op1Unset here too.
7097 // If we're inverting this node because it is used only by selects that
7098 // we'd like to swap, then swap the selects before the node replacement.
7100 SwapAllSelectUsers(MachineNode);
7102 if (ResNode != MachineNode) {
7103 LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld: ");
7104 LLVM_DEBUG(MachineNode->dump(CurDAG));
7105 LLVM_DEBUG(dbgs() << "\nNew: ");
7106 LLVM_DEBUG(ResNode->dump(CurDAG));
7107 LLVM_DEBUG(dbgs() << "\n");
7109 ReplaceUses(MachineNode, ResNode);
7114 CurDAG->RemoveDeadNodes();
7115 } while (IsModified);
7118 // Gather the set of 32-bit operations that are known to have their
7119 // higher-order 32 bits zero, where ToPromote contains all such operations.
7120 static bool PeepholePPC64ZExtGather(SDValue Op32,
7121 SmallPtrSetImpl<SDNode *> &ToPromote) {
7122 if (!Op32.isMachineOpcode())
7125 // First, check for the "frontier" instructions (those that will clear the
7126 // higher-order 32 bits.
7128 // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
7129 // around. If it does not, then these instructions will clear the
7130 // higher-order bits.
7131 if ((Op32.getMachineOpcode() == PPC::RLWINM ||
7132 Op32.getMachineOpcode() == PPC::RLWNM) &&
7133 Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
7134 ToPromote.insert(Op32.getNode());
7138 // SLW and SRW always clear the higher-order bits.
7139 if (Op32.getMachineOpcode() == PPC::SLW ||
7140 Op32.getMachineOpcode() == PPC::SRW) {
7141 ToPromote.insert(Op32.getNode());
7145 // For LI and LIS, we need the immediate to be positive (so that it is not
7147 if (Op32.getMachineOpcode() == PPC::LI ||
7148 Op32.getMachineOpcode() == PPC::LIS) {
7149 if (!isUInt<15>(Op32.getConstantOperandVal(0)))
7152 ToPromote.insert(Op32.getNode());
7156 // LHBRX and LWBRX always clear the higher-order bits.
7157 if (Op32.getMachineOpcode() == PPC::LHBRX ||
7158 Op32.getMachineOpcode() == PPC::LWBRX) {
7159 ToPromote.insert(Op32.getNode());
7163 // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended.
7164 if (Op32.getMachineOpcode() == PPC::CNTLZW ||
7165 Op32.getMachineOpcode() == PPC::CNTTZW) {
7166 ToPromote.insert(Op32.getNode());
7170 // Next, check for those instructions we can look through.
7172 // Assuming the mask does not wrap around, then the higher-order bits are
7173 // taken directly from the first operand.
7174 if (Op32.getMachineOpcode() == PPC::RLWIMI &&
7175 Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
7176 SmallPtrSet<SDNode *, 16> ToPromote1;
7177 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
7180 ToPromote.insert(Op32.getNode());
7181 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
7185 // For OR, the higher-order bits are zero if that is true for both operands.
7186 // For SELECT_I4, the same is true (but the relevant operand numbers are
7188 if (Op32.getMachineOpcode() == PPC::OR ||
7189 Op32.getMachineOpcode() == PPC::SELECT_I4) {
7190 unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
7191 SmallPtrSet<SDNode *, 16> ToPromote1;
7192 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
7194 if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
7197 ToPromote.insert(Op32.getNode());
7198 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
7202 // For ORI and ORIS, we need the higher-order bits of the first operand to be
7203 // zero, and also for the constant to be positive (so that it is not sign
7205 if (Op32.getMachineOpcode() == PPC::ORI ||
7206 Op32.getMachineOpcode() == PPC::ORIS) {
7207 SmallPtrSet<SDNode *, 16> ToPromote1;
7208 if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
7210 if (!isUInt<15>(Op32.getConstantOperandVal(1)))
7213 ToPromote.insert(Op32.getNode());
7214 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
7218 // The higher-order bits of AND are zero if that is true for at least one of
7220 if (Op32.getMachineOpcode() == PPC::AND) {
7221 SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
7223 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
7225 PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
7226 if (!Op0OK && !Op1OK)
7229 ToPromote.insert(Op32.getNode());
7232 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
7235 ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
7240 // For ANDI and ANDIS, the higher-order bits are zero if either that is true
7241 // of the first operand, or if the second operand is positive (so that it is
7242 // not sign extended).
7243 if (Op32.getMachineOpcode() == PPC::ANDI_rec ||
7244 Op32.getMachineOpcode() == PPC::ANDIS_rec) {
7245 SmallPtrSet<SDNode *, 16> ToPromote1;
7247 PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
7248 bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
7249 if (!Op0OK && !Op1OK)
7252 ToPromote.insert(Op32.getNode());
7255 ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
7263 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
7264 if (!Subtarget->isPPC64())
7267 // When we zero-extend from i32 to i64, we use a pattern like this:
7268 // def : Pat<(i64 (zext i32:$in)),
7269 // (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
7271 // There are several 32-bit shift/rotate instructions, however, that will
7272 // clear the higher-order bits of their output, rendering the RLDICL
7273 // unnecessary. When that happens, we remove it here, and redefine the
7274 // relevant 32-bit operation to be a 64-bit operation.
7276 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
7278 bool MadeChange = false;
7279 while (Position != CurDAG->allnodes_begin()) {
7280 SDNode *N = &*--Position;
7281 // Skip dead nodes and any non-machine opcodes.
7282 if (N->use_empty() || !N->isMachineOpcode())
7285 if (N->getMachineOpcode() != PPC::RLDICL)
7288 if (N->getConstantOperandVal(1) != 0 ||
7289 N->getConstantOperandVal(2) != 32)
7292 SDValue ISR = N->getOperand(0);
7293 if (!ISR.isMachineOpcode() ||
7294 ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
7297 if (!ISR.hasOneUse())
7300 if (ISR.getConstantOperandVal(2) != PPC::sub_32)
7303 SDValue IDef = ISR.getOperand(0);
7304 if (!IDef.isMachineOpcode() ||
7305 IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
7308 // We now know that we're looking at a canonical i32 -> i64 zext. See if we
7309 // can get rid of it.
7311 SDValue Op32 = ISR->getOperand(1);
7312 if (!Op32.isMachineOpcode())
7315 // There are some 32-bit instructions that always clear the high-order 32
7316 // bits, there are also some instructions (like AND) that we can look
7318 SmallPtrSet<SDNode *, 16> ToPromote;
7319 if (!PeepholePPC64ZExtGather(Op32, ToPromote))
7322 // If the ToPromote set contains nodes that have uses outside of the set
7323 // (except for the original INSERT_SUBREG), then abort the transformation.
7324 bool OutsideUse = false;
7325 for (SDNode *PN : ToPromote) {
7326 for (SDNode *UN : PN->uses()) {
7327 if (!ToPromote.count(UN) && UN != ISR.getNode()) {
7341 // We now know that this zero extension can be removed by promoting to
7342 // nodes in ToPromote to 64-bit operations, where for operations in the
7343 // frontier of the set, we need to insert INSERT_SUBREGs for their
7345 for (SDNode *PN : ToPromote) {
7347 switch (PN->getMachineOpcode()) {
7349 llvm_unreachable("Don't know the 64-bit variant of this instruction");
7350 case PPC::RLWINM: NewOpcode = PPC::RLWINM8; break;
7351 case PPC::RLWNM: NewOpcode = PPC::RLWNM8; break;
7352 case PPC::SLW: NewOpcode = PPC::SLW8; break;
7353 case PPC::SRW: NewOpcode = PPC::SRW8; break;
7354 case PPC::LI: NewOpcode = PPC::LI8; break;
7355 case PPC::LIS: NewOpcode = PPC::LIS8; break;
7356 case PPC::LHBRX: NewOpcode = PPC::LHBRX8; break;
7357 case PPC::LWBRX: NewOpcode = PPC::LWBRX8; break;
7358 case PPC::CNTLZW: NewOpcode = PPC::CNTLZW8; break;
7359 case PPC::CNTTZW: NewOpcode = PPC::CNTTZW8; break;
7360 case PPC::RLWIMI: NewOpcode = PPC::RLWIMI8; break;
7361 case PPC::OR: NewOpcode = PPC::OR8; break;
7362 case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
7363 case PPC::ORI: NewOpcode = PPC::ORI8; break;
7364 case PPC::ORIS: NewOpcode = PPC::ORIS8; break;
7365 case PPC::AND: NewOpcode = PPC::AND8; break;
7367 NewOpcode = PPC::ANDI8_rec;
7369 case PPC::ANDIS_rec:
7370 NewOpcode = PPC::ANDIS8_rec;
7374 // Note: During the replacement process, the nodes will be in an
7375 // inconsistent state (some instructions will have operands with values
7376 // of the wrong type). Once done, however, everything should be right
7379 SmallVector<SDValue, 4> Ops;
7380 for (const SDValue &V : PN->ops()) {
7381 if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
7382 !isa<ConstantSDNode>(V)) {
7383 SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
7385 CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
7386 ISR.getNode()->getVTList(), ReplOpOps);
7387 Ops.push_back(SDValue(ReplOp, 0));
7393 // Because all to-be-promoted nodes only have users that are other
7394 // promoted nodes (or the original INSERT_SUBREG), we can safely replace
7395 // the i32 result value type with i64.
7397 SmallVector<EVT, 2> NewVTs;
7398 SDVTList VTs = PN->getVTList();
7399 for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
7400 if (VTs.VTs[i] == MVT::i32)
7401 NewVTs.push_back(MVT::i64);
7403 NewVTs.push_back(VTs.VTs[i]);
7405 LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld: ");
7406 LLVM_DEBUG(PN->dump(CurDAG));
7408 CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
7410 LLVM_DEBUG(dbgs() << "\nNew: ");
7411 LLVM_DEBUG(PN->dump(CurDAG));
7412 LLVM_DEBUG(dbgs() << "\n");
7415 // Now we replace the original zero extend and its associated INSERT_SUBREG
7416 // with the value feeding the INSERT_SUBREG (which has now been promoted to
7419 LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld: ");
7420 LLVM_DEBUG(N->dump(CurDAG));
7421 LLVM_DEBUG(dbgs() << "\nNew: ");
7422 LLVM_DEBUG(Op32.getNode()->dump(CurDAG));
7423 LLVM_DEBUG(dbgs() << "\n");
7425 ReplaceUses(N, Op32.getNode());
7429 CurDAG->RemoveDeadNodes();
7432 static bool isVSXSwap(SDValue N) {
7433 if (!N->isMachineOpcode())
7435 unsigned Opc = N->getMachineOpcode();
7437 // Single-operand XXPERMDI or the regular XXPERMDI/XXSLDWI where the immediate
7439 if (Opc == PPC::XXPERMDIs) {
7440 return isa<ConstantSDNode>(N->getOperand(1)) &&
7441 N->getConstantOperandVal(1) == 2;
7442 } else if (Opc == PPC::XXPERMDI || Opc == PPC::XXSLDWI) {
7443 return N->getOperand(0) == N->getOperand(1) &&
7444 isa<ConstantSDNode>(N->getOperand(2)) &&
7445 N->getConstantOperandVal(2) == 2;
7451 // TODO: Make this complete and replace with a table-gen bit.
7452 static bool isLaneInsensitive(SDValue N) {
7453 if (!N->isMachineOpcode())
7455 unsigned Opc = N->getMachineOpcode();
7499 // Try to simplify (xxswap (vec-op (xxswap) (xxswap))) where vec-op is
7500 // lane-insensitive.
7501 static void reduceVSXSwap(SDNode *N, SelectionDAG *DAG) {
7502 // Our desired xxswap might be source of COPY_TO_REGCLASS.
7503 // TODO: Can we put this a common method for DAG?
7504 auto SkipRCCopy = [](SDValue V) {
7505 while (V->isMachineOpcode() &&
7506 V->getMachineOpcode() == TargetOpcode::COPY_TO_REGCLASS) {
7507 // All values in the chain should have single use.
7508 if (V->use_empty() || !V->use_begin()->isOnlyUserOf(V.getNode()))
7510 V = V->getOperand(0);
7512 return V.hasOneUse() ? V : SDValue();
7515 SDValue VecOp = SkipRCCopy(N->getOperand(0));
7516 if (!VecOp || !isLaneInsensitive(VecOp))
7519 SDValue LHS = SkipRCCopy(VecOp.getOperand(0)),
7520 RHS = SkipRCCopy(VecOp.getOperand(1));
7521 if (!LHS || !RHS || !isVSXSwap(LHS) || !isVSXSwap(RHS))
7524 // These swaps may still have chain-uses here, count on dead code elimination
7525 // in following passes to remove them.
7526 DAG->ReplaceAllUsesOfValueWith(LHS, LHS.getOperand(0));
7527 DAG->ReplaceAllUsesOfValueWith(RHS, RHS.getOperand(0));
7528 DAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), N->getOperand(0));
7531 void PPCDAGToDAGISel::PeepholePPC64() {
7532 SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
7534 while (Position != CurDAG->allnodes_begin()) {
7535 SDNode *N = &*--Position;
7536 // Skip dead nodes and any non-machine opcodes.
7537 if (N->use_empty() || !N->isMachineOpcode())
7540 if (isVSXSwap(SDValue(N, 0)))
7541 reduceVSXSwap(N, CurDAG);
7544 unsigned StorageOpcode = N->getMachineOpcode();
7545 bool RequiresMod4Offset = false;
7547 switch (StorageOpcode) {
7552 case PPC::DFLOADf64:
7553 case PPC::DFLOADf32:
7554 RequiresMod4Offset = true;
7570 case PPC::DFSTOREf64:
7571 case PPC::DFSTOREf32:
7572 RequiresMod4Offset = true;
7586 // If this is a load or store with a zero offset, or within the alignment,
7587 // we may be able to fold an add-immediate into the memory operation.
7588 // The check against alignment is below, as it can't occur until we check
7589 // the arguments to N
7590 if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
7593 SDValue Base = N->getOperand(FirstOp + 1);
7594 if (!Base.isMachineOpcode())
7598 bool ReplaceFlags = true;
7600 // When the feeding operation is an add-immediate of some sort,
7601 // determine whether we need to add relocation information to the
7602 // target flags on the immediate operand when we fold it into the
7603 // load instruction.
7605 // For something like ADDItocL, the relocation information is
7606 // inferred from the opcode; when we process it in the AsmPrinter,
7607 // we add the necessary relocation there. A load, though, can receive
7608 // relocation from various flavors of ADDIxxx, so we need to carry
7609 // the relocation information in the target flags.
7610 switch (Base.getMachineOpcode()) {
7615 // In some cases (such as TLS) the relocation information
7616 // is already in place on the operand, so copying the operand
7618 ReplaceFlags = false;
7619 // For these cases, the immediate may not be divisible by 4, in
7620 // which case the fold is illegal for DS-form instructions. (The
7621 // other cases provide aligned addresses and are always safe.)
7622 if (RequiresMod4Offset &&
7623 (!isa<ConstantSDNode>(Base.getOperand(1)) ||
7624 Base.getConstantOperandVal(1) % 4 != 0))
7627 case PPC::ADDIdtprelL:
7628 Flags = PPCII::MO_DTPREL_LO;
7630 case PPC::ADDItlsldL:
7631 Flags = PPCII::MO_TLSLD_LO;
7634 Flags = PPCII::MO_TOC_LO;
7638 if (RequiresMod4Offset) {
7639 if (GlobalAddressSDNode *GA =
7640 dyn_cast<GlobalAddressSDNode>(Base.getOperand(0))) {
7641 const GlobalValue *GV = GA->getGlobal();
7642 Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout());
7643 // XMC_TD global that is underaligned being accessed with a DS form
7652 SDValue ImmOpnd = Base.getOperand(1);
7654 // On PPC64, the TOC base pointer is guaranteed by the ABI only to have
7655 // 8-byte alignment, and so we can only use offsets less than 8 (otherwise,
7656 // we might have needed different @ha relocation values for the offset
7658 int MaxDisplacement = 7;
7659 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
7660 const GlobalValue *GV = GA->getGlobal();
7661 Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout());
7662 MaxDisplacement = std::min((int)Alignment.value() - 1, MaxDisplacement);
7665 bool UpdateHBase = false;
7666 SDValue HBase = Base.getOperand(0);
7668 int Offset = N->getConstantOperandVal(FirstOp);
7670 if (Offset < 0 || Offset > MaxDisplacement) {
7671 // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only
7672 // one use, then we can do this for any offset, we just need to also
7673 // update the offset (i.e. the symbol addend) on the addis also.
7674 if (Base.getMachineOpcode() != PPC::ADDItocL)
7677 if (!HBase.isMachineOpcode() ||
7678 HBase.getMachineOpcode() != PPC::ADDIStocHA8)
7681 if (!Base.hasOneUse() || !HBase.hasOneUse())
7684 SDValue HImmOpnd = HBase.getOperand(1);
7685 if (HImmOpnd != ImmOpnd)
7691 // If we're directly folding the addend from an addi instruction, then:
7692 // 1. In general, the offset on the memory access must be zero.
7693 // 2. If the addend is a constant, then it can be combined with a
7694 // non-zero offset, but only if the result meets the encoding
7696 if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) {
7697 Offset += C->getSExtValue();
7699 if (RequiresMod4Offset && (Offset % 4) != 0)
7702 if (!isInt<16>(Offset))
7705 ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd),
7706 ImmOpnd.getValueType());
7707 } else if (Offset != 0) {
7712 // We found an opportunity. Reverse the operands from the add
7713 // immediate and substitute them into the load or store. If
7714 // needed, update the target flags for the immediate operand to
7715 // reflect the necessary relocation information.
7716 LLVM_DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase: ");
7717 LLVM_DEBUG(Base->dump(CurDAG));
7718 LLVM_DEBUG(dbgs() << "\nN: ");
7719 LLVM_DEBUG(N->dump(CurDAG));
7720 LLVM_DEBUG(dbgs() << "\n");
7722 // If the relocation information isn't already present on the
7723 // immediate operand, add it now.
7725 if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
7727 const GlobalValue *GV = GA->getGlobal();
7728 Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout());
7729 // We can't perform this optimization for data whose alignment
7730 // is insufficient for the instruction encoding.
7731 if (Alignment < 4 && (RequiresMod4Offset || (Offset % 4) != 0)) {
7732 LLVM_DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
7735 ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
7736 } else if (ConstantPoolSDNode *CP =
7737 dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
7738 const Constant *C = CP->getConstVal();
7739 ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64, CP->getAlign(),
7744 const unsigned BaseOpcode = Base.getMachineOpcode();
7745 // ADDItoc and ADDItoc8 are pseudos used exclusively by AIX small code
7746 // model when a global is defined in the TOC.
7747 const bool OpcodeIsAIXTocData =
7748 BaseOpcode == PPC::ADDItoc || BaseOpcode == PPC::ADDItoc8;
7750 if (FirstOp == 1) // Store
7751 if (OpcodeIsAIXTocData)
7752 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0),
7753 Base.getOperand(0), Base.getOperand(1),
7756 (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
7757 Base.getOperand(0), N->getOperand(3));
7759 if (OpcodeIsAIXTocData)
7760 (void)CurDAG->UpdateNodeOperands(N, Base.getOperand(0),
7761 Base.getOperand(1), N->getOperand(2));
7763 (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
7767 (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0),
7770 // The add-immediate may now be dead, in which case remove it.
7771 if (Base.getNode()->use_empty())
7772 CurDAG->RemoveDeadNode(Base.getNode());
7776 /// createPPCISelDag - This pass converts a legalized DAG into a
7777 /// PowerPC-specific DAG, ready for instruction scheduling.
7779 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM,
7780 CodeGenOpt::Level OptLevel) {
7781 return new PPCDAGToDAGISel(TM, OptLevel);