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