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