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