1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines a pattern matching instruction selector for PowerPC,
10 // converting from a legalized dag to a PPC dag.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MCTargetDesc/PPCMCTargetDesc.h"
15 #include "MCTargetDesc/PPCPredicates.h"
16 #include "PPC.h"
17 #include "PPCISelLowering.h"
18 #include "PPCMachineFunctionInfo.h"
19 #include "PPCSubtarget.h"
20 #include "PPCTargetMachine.h"
21 #include "llvm/ADT/APInt.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallPtrSet.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/ADT/Statistic.h"
27 #include "llvm/Analysis/BranchProbabilityInfo.h"
28 #include "llvm/CodeGen/FunctionLoweringInfo.h"
29 #include "llvm/CodeGen/ISDOpcodes.h"
30 #include "llvm/CodeGen/MachineBasicBlock.h"
31 #include "llvm/CodeGen/MachineFunction.h"
32 #include "llvm/CodeGen/MachineInstrBuilder.h"
33 #include "llvm/CodeGen/MachineRegisterInfo.h"
34 #include "llvm/CodeGen/SelectionDAG.h"
35 #include "llvm/CodeGen/SelectionDAGISel.h"
36 #include "llvm/CodeGen/SelectionDAGNodes.h"
37 #include "llvm/CodeGen/TargetInstrInfo.h"
38 #include "llvm/CodeGen/TargetRegisterInfo.h"
39 #include "llvm/CodeGen/ValueTypes.h"
40 #include "llvm/IR/BasicBlock.h"
41 #include "llvm/IR/DebugLoc.h"
42 #include "llvm/IR/Function.h"
43 #include "llvm/IR/GlobalValue.h"
44 #include "llvm/IR/InlineAsm.h"
45 #include "llvm/IR/InstrTypes.h"
46 #include "llvm/IR/Module.h"
47 #include "llvm/Support/Casting.h"
48 #include "llvm/Support/CodeGen.h"
49 #include "llvm/Support/CommandLine.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/ErrorHandling.h"
53 #include "llvm/Support/KnownBits.h"
54 #include "llvm/Support/MachineValueType.h"
55 #include "llvm/Support/MathExtras.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include <algorithm>
58 #include <cassert>
59 #include <cstdint>
60 #include <iterator>
61 #include <limits>
62 #include <memory>
63 #include <new>
64 #include <tuple>
65 #include <utility>
66 
67 using namespace llvm;
68 
69 #define DEBUG_TYPE "ppc-codegen"
70 
71 STATISTIC(NumSextSetcc,
72           "Number of (sext(setcc)) nodes expanded into GPR sequence.");
73 STATISTIC(NumZextSetcc,
74           "Number of (zext(setcc)) nodes expanded into GPR sequence.");
75 STATISTIC(SignExtensionsAdded,
76           "Number of sign extensions for compare inputs added.");
77 STATISTIC(ZeroExtensionsAdded,
78           "Number of zero extensions for compare inputs added.");
79 STATISTIC(NumLogicOpsOnComparison,
80           "Number of logical ops on i1 values calculated in GPR.");
81 STATISTIC(OmittedForNonExtendUses,
82           "Number of compares not eliminated as they have non-extending uses.");
83 STATISTIC(NumP9Setb,
84           "Number of compares lowered to setb.");
85 
86 // FIXME: Remove this once the bug has been fixed!
87 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
88 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
89 
90 static cl::opt<bool>
91     UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
92                        cl::desc("use aggressive ppc isel for bit permutations"),
93                        cl::Hidden);
94 static cl::opt<bool> BPermRewriterNoMasking(
95     "ppc-bit-perm-rewriter-stress-rotates",
96     cl::desc("stress rotate selection in aggressive ppc isel for "
97              "bit permutations"),
98     cl::Hidden);
99 
100 static cl::opt<bool> EnableBranchHint(
101   "ppc-use-branch-hint", cl::init(true),
102     cl::desc("Enable static hinting of branches on ppc"),
103     cl::Hidden);
104 
105 static cl::opt<bool> EnableTLSOpt(
106   "ppc-tls-opt", cl::init(true),
107     cl::desc("Enable tls optimization peephole"),
108     cl::Hidden);
109 
110 enum ICmpInGPRType { ICGPR_All, ICGPR_None, ICGPR_I32, ICGPR_I64,
111   ICGPR_NonExtIn, ICGPR_Zext, ICGPR_Sext, ICGPR_ZextI32,
112   ICGPR_SextI32, ICGPR_ZextI64, ICGPR_SextI64 };
113 
114 static cl::opt<ICmpInGPRType> CmpInGPR(
115   "ppc-gpr-icmps", cl::Hidden, cl::init(ICGPR_All),
116   cl::desc("Specify the types of comparisons to emit GPR-only code for."),
117   cl::values(clEnumValN(ICGPR_None, "none", "Do not modify integer comparisons."),
118              clEnumValN(ICGPR_All, "all", "All possible int comparisons in GPRs."),
119              clEnumValN(ICGPR_I32, "i32", "Only i32 comparisons in GPRs."),
120              clEnumValN(ICGPR_I64, "i64", "Only i64 comparisons in GPRs."),
121              clEnumValN(ICGPR_NonExtIn, "nonextin",
122                         "Only comparisons where inputs don't need [sz]ext."),
123              clEnumValN(ICGPR_Zext, "zext", "Only comparisons with zext result."),
124              clEnumValN(ICGPR_ZextI32, "zexti32",
125                         "Only i32 comparisons with zext result."),
126              clEnumValN(ICGPR_ZextI64, "zexti64",
127                         "Only i64 comparisons with zext result."),
128              clEnumValN(ICGPR_Sext, "sext", "Only comparisons with sext result."),
129              clEnumValN(ICGPR_SextI32, "sexti32",
130                         "Only i32 comparisons with sext result."),
131              clEnumValN(ICGPR_SextI64, "sexti64",
132                         "Only i64 comparisons with sext result.")));
133 namespace {
134 
135   //===--------------------------------------------------------------------===//
136   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
137   /// instructions for SelectionDAG operations.
138   ///
139   class PPCDAGToDAGISel : public SelectionDAGISel {
140     const PPCTargetMachine &TM;
141     const PPCSubtarget *PPCSubTarget = nullptr;
142     const PPCSubtarget *Subtarget = nullptr;
143     const PPCTargetLowering *PPCLowering = nullptr;
144     unsigned GlobalBaseReg = 0;
145 
146   public:
147     explicit PPCDAGToDAGISel(PPCTargetMachine &tm, CodeGenOpt::Level OptLevel)
148         : SelectionDAGISel(tm, OptLevel), TM(tm) {}
149 
150     bool runOnMachineFunction(MachineFunction &MF) override {
151       // Make sure we re-emit a set of the global base reg if necessary
152       GlobalBaseReg = 0;
153       PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
154       Subtarget = &MF.getSubtarget<PPCSubtarget>();
155       PPCLowering = Subtarget->getTargetLowering();
156       SelectionDAGISel::runOnMachineFunction(MF);
157 
158       if (!Subtarget->isSVR4ABI())
159         InsertVRSaveCode(MF);
160 
161       return true;
162     }
163 
164     void PreprocessISelDAG() override;
165     void PostprocessISelDAG() override;
166 
167     /// getI16Imm - Return a target constant with the specified value, of type
168     /// i16.
169     inline SDValue getI16Imm(unsigned Imm, const SDLoc &dl) {
170       return CurDAG->getTargetConstant(Imm, dl, MVT::i16);
171     }
172 
173     /// getI32Imm - Return a target constant with the specified value, of type
174     /// i32.
175     inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
176       return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
177     }
178 
179     /// getI64Imm - Return a target constant with the specified value, of type
180     /// i64.
181     inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) {
182       return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
183     }
184 
185     /// getSmallIPtrImm - Return a target constant of pointer type.
186     inline SDValue getSmallIPtrImm(unsigned Imm, const SDLoc &dl) {
187       return CurDAG->getTargetConstant(
188           Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));
189     }
190 
191     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
192     /// rotate and mask opcode and mask operation.
193     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
194                                 unsigned &SH, unsigned &MB, unsigned &ME);
195 
196     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
197     /// base register.  Return the virtual register that holds this value.
198     SDNode *getGlobalBaseReg();
199 
200     void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
201 
202     // Select - Convert the specified operand from a target-independent to a
203     // target-specific node if it hasn't already been changed.
204     void Select(SDNode *N) override;
205 
206     bool tryBitfieldInsert(SDNode *N);
207     bool tryBitPermutation(SDNode *N);
208     bool tryIntCompareInGPR(SDNode *N);
209 
210     // tryTLSXFormLoad - Convert an ISD::LOAD fed by a PPCISD::ADD_TLS into
211     // an X-Form load instruction with the offset being a relocation coming from
212     // the PPCISD::ADD_TLS.
213     bool tryTLSXFormLoad(LoadSDNode *N);
214     // tryTLSXFormStore - Convert an ISD::STORE fed by a PPCISD::ADD_TLS into
215     // an X-Form store instruction with the offset being a relocation coming from
216     // the PPCISD::ADD_TLS.
217     bool tryTLSXFormStore(StoreSDNode *N);
218     /// SelectCC - Select a comparison of the specified values with the
219     /// specified condition code, returning the CR# of the expression.
220     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
221                      const SDLoc &dl, SDValue Chain = SDValue());
222 
223     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
224     /// immediate field.  Note that the operand at this point is already the
225     /// result of a prior SelectAddressRegImm call.
226     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
227       if (N.getOpcode() == ISD::TargetConstant ||
228           N.getOpcode() == ISD::TargetGlobalAddress) {
229         Out = N;
230         return true;
231       }
232 
233       return false;
234     }
235 
236     /// SelectAddrIdx - Given the specified address, check to see if it can be
237     /// represented as an indexed [r+r] operation.
238     /// This is for xform instructions whose associated displacement form is D.
239     /// The last parameter \p 0 means associated D form has no requirment for 16
240     /// bit signed displacement.
241     /// Returns false if it can be represented by [r+imm], which are preferred.
242     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
243       return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG, None);
244     }
245 
246     /// SelectAddrIdx4 - Given the specified address, check to see if it can be
247     /// represented as an indexed [r+r] operation.
248     /// This is for xform instructions whose associated displacement form is DS.
249     /// The last parameter \p 4 means associated DS form 16 bit signed
250     /// displacement must be a multiple of 4.
251     /// Returns false if it can be represented by [r+imm], which are preferred.
252     bool SelectAddrIdxX4(SDValue N, SDValue &Base, SDValue &Index) {
253       return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG,
254                                               Align(4));
255     }
256 
257     /// SelectAddrIdx16 - Given the specified address, check to see if it can be
258     /// represented as an indexed [r+r] operation.
259     /// This is for xform instructions whose associated displacement form is DQ.
260     /// The last parameter \p 16 means associated DQ form 16 bit signed
261     /// displacement must be a multiple of 16.
262     /// Returns false if it can be represented by [r+imm], which are preferred.
263     bool SelectAddrIdxX16(SDValue N, SDValue &Base, SDValue &Index) {
264       return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG,
265                                               Align(16));
266     }
267 
268     /// SelectAddrIdxOnly - Given the specified address, force it to be
269     /// represented as an indexed [r+r] operation.
270     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
271       return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
272     }
273 
274     /// SelectAddrImm - Returns true if the address N can be represented by
275     /// a base register plus a signed 16-bit displacement [r+imm].
276     /// The last parameter \p 0 means D form has no requirment for 16 bit signed
277     /// displacement.
278     bool SelectAddrImm(SDValue N, SDValue &Disp,
279                        SDValue &Base) {
280       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, None);
281     }
282 
283     /// SelectAddrImmX4 - Returns true if the address N can be represented by
284     /// a base register plus a signed 16-bit displacement that is a multiple of
285     /// 4 (last parameter). Suitable for use by STD and friends.
286     bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
287       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, Align(4));
288     }
289 
290     /// SelectAddrImmX16 - Returns true if the address N can be represented by
291     /// a base register plus a signed 16-bit displacement that is a multiple of
292     /// 16(last parameter). Suitable for use by STXV and friends.
293     bool SelectAddrImmX16(SDValue N, SDValue &Disp, SDValue &Base) {
294       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG,
295                                               Align(16));
296     }
297 
298     // Select an address into a single register.
299     bool SelectAddr(SDValue N, SDValue &Base) {
300       Base = N;
301       return true;
302     }
303 
304     bool SelectAddrPCRel(SDValue N, SDValue &Base) {
305       return PPCLowering->SelectAddressPCRel(N, Base);
306     }
307 
308     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
309     /// inline asm expressions.  It is always correct to compute the value into
310     /// a register.  The case of adding a (possibly relocatable) constant to a
311     /// register can be improved, but it is wrong to substitute Reg+Reg for
312     /// Reg in an asm, because the load or store opcode would have to change.
313     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
314                                       unsigned ConstraintID,
315                                       std::vector<SDValue> &OutOps) override {
316       switch(ConstraintID) {
317       default:
318         errs() << "ConstraintID: " << ConstraintID << "\n";
319         llvm_unreachable("Unexpected asm memory constraint");
320       case InlineAsm::Constraint_es:
321       case InlineAsm::Constraint_m:
322       case InlineAsm::Constraint_o:
323       case InlineAsm::Constraint_Q:
324       case InlineAsm::Constraint_Z:
325       case InlineAsm::Constraint_Zy:
326         // We need to make sure that this one operand does not end up in r0
327         // (because we might end up lowering this as 0(%op)).
328         const TargetRegisterInfo *TRI = Subtarget->getRegisterInfo();
329         const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
330         SDLoc dl(Op);
331         SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
332         SDValue NewOp =
333           SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
334                                          dl, Op.getValueType(),
335                                          Op, RC), 0);
336 
337         OutOps.push_back(NewOp);
338         return false;
339       }
340       return true;
341     }
342 
343     void InsertVRSaveCode(MachineFunction &MF);
344 
345     StringRef getPassName() const override {
346       return "PowerPC DAG->DAG Pattern Instruction Selection";
347     }
348 
349 // Include the pieces autogenerated from the target description.
350 #include "PPCGenDAGISel.inc"
351 
352 private:
353     bool trySETCC(SDNode *N);
354     bool tryAsSingleRLDICL(SDNode *N);
355     bool tryAsSingleRLDICR(SDNode *N);
356     bool tryAsSingleRLWINM(SDNode *N);
357     bool tryAsSingleRLWINM8(SDNode *N);
358     bool tryAsSingleRLWIMI(SDNode *N);
359     bool tryAsPairOfRLDICL(SDNode *N);
360     bool tryAsSingleRLDIMI(SDNode *N);
361 
362     void PeepholePPC64();
363     void PeepholePPC64ZExt();
364     void PeepholeCROps();
365 
366     SDValue combineToCMPB(SDNode *N);
367     void foldBoolExts(SDValue &Res, SDNode *&N);
368 
369     bool AllUsersSelectZero(SDNode *N);
370     void SwapAllSelectUsers(SDNode *N);
371 
372     bool isOffsetMultipleOf(SDNode *N, unsigned Val) const;
373     void transferMemOperands(SDNode *N, SDNode *Result);
374   };
375 
376 } // end anonymous namespace
377 
378 /// InsertVRSaveCode - Once the entire function has been instruction selected,
379 /// all virtual registers are created and all machine instructions are built,
380 /// check to see if we need to save/restore VRSAVE.  If so, do it.
381 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
382   // Check to see if this function uses vector registers, which means we have to
383   // save and restore the VRSAVE register and update it with the regs we use.
384   //
385   // In this case, there will be virtual registers of vector type created
386   // by the scheduler.  Detect them now.
387   bool HasVectorVReg = false;
388   for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
389     unsigned Reg = Register::index2VirtReg(i);
390     if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
391       HasVectorVReg = true;
392       break;
393     }
394   }
395   if (!HasVectorVReg) return;  // nothing to do.
396 
397   // If we have a vector register, we want to emit code into the entry and exit
398   // blocks to save and restore the VRSAVE register.  We do this here (instead
399   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
400   //
401   // 1. This (trivially) reduces the load on the register allocator, by not
402   //    having to represent the live range of the VRSAVE register.
403   // 2. This (more significantly) allows us to create a temporary virtual
404   //    register to hold the saved VRSAVE value, allowing this temporary to be
405   //    register allocated, instead of forcing it to be spilled to the stack.
406 
407   // Create two vregs - one to hold the VRSAVE register that is live-in to the
408   // function and one for the value after having bits or'd into it.
409   Register InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
410   Register UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
411 
412   const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
413   MachineBasicBlock &EntryBB = *Fn.begin();
414   DebugLoc dl;
415   // Emit the following code into the entry block:
416   // InVRSAVE = MFVRSAVE
417   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
418   // MTVRSAVE UpdatedVRSAVE
419   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
420   BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
421   BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
422           UpdatedVRSAVE).addReg(InVRSAVE);
423   BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
424 
425   // Find all return blocks, outputting a restore in each epilog.
426   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
427     if (BB->isReturnBlock()) {
428       IP = BB->end(); --IP;
429 
430       // Skip over all terminator instructions, which are part of the return
431       // sequence.
432       MachineBasicBlock::iterator I2 = IP;
433       while (I2 != BB->begin() && (--I2)->isTerminator())
434         IP = I2;
435 
436       // Emit: MTVRSAVE InVRSave
437       BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
438     }
439   }
440 }
441 
442 /// getGlobalBaseReg - Output the instructions required to put the
443 /// base address to use for accessing globals into a register.
444 ///
445 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
446   if (!GlobalBaseReg) {
447     const TargetInstrInfo &TII = *Subtarget->getInstrInfo();
448     // Insert the set of GlobalBaseReg into the first MBB of the function
449     MachineBasicBlock &FirstMBB = MF->front();
450     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
451     const Module *M = MF->getFunction().getParent();
452     DebugLoc dl;
453 
454     if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
455       if (Subtarget->isTargetELF()) {
456         GlobalBaseReg = PPC::R30;
457         if (!Subtarget->isSecurePlt() &&
458             M->getPICLevel() == PICLevel::SmallPIC) {
459           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
460           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
461           MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
462         } else {
463           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
464           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
465           Register TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
466           BuildMI(FirstMBB, MBBI, dl,
467                   TII.get(PPC::UpdateGBR), GlobalBaseReg)
468                   .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
469           MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
470         }
471       } else {
472         GlobalBaseReg =
473           RegInfo->createVirtualRegister(&PPC::GPRC_and_GPRC_NOR0RegClass);
474         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
475         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
476       }
477     } else {
478       // We must ensure that this sequence is dominated by the prologue.
479       // FIXME: This is a bit of a big hammer since we don't get the benefits
480       // of shrink-wrapping whenever we emit this instruction. Considering
481       // this is used in any function where we emit a jump table, this may be
482       // a significant limitation. We should consider inserting this in the
483       // block where it is used and then commoning this sequence up if it
484       // appears in multiple places.
485       // Note: on ISA 3.0 cores, we can use lnia (addpcis) instead of
486       // MovePCtoLR8.
487       MF->getInfo<PPCFunctionInfo>()->setShrinkWrapDisabled(true);
488       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_and_G8RC_NOX0RegClass);
489       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
490       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
491     }
492   }
493   return CurDAG->getRegister(GlobalBaseReg,
494                              PPCLowering->getPointerTy(CurDAG->getDataLayout()))
495       .getNode();
496 }
497 
498 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
499 /// operand. If so Imm will receive the 32-bit value.
500 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
501   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
502     Imm = cast<ConstantSDNode>(N)->getZExtValue();
503     return true;
504   }
505   return false;
506 }
507 
508 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
509 /// operand.  If so Imm will receive the 64-bit value.
510 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
511   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
512     Imm = cast<ConstantSDNode>(N)->getZExtValue();
513     return true;
514   }
515   return false;
516 }
517 
518 // isInt32Immediate - This method tests to see if a constant operand.
519 // If so Imm will receive the 32 bit value.
520 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
521   return isInt32Immediate(N.getNode(), Imm);
522 }
523 
524 /// isInt64Immediate - This method tests to see if the value is a 64-bit
525 /// constant operand. If so Imm will receive the 64-bit value.
526 static bool isInt64Immediate(SDValue N, uint64_t &Imm) {
527   return isInt64Immediate(N.getNode(), Imm);
528 }
529 
530 static unsigned getBranchHint(unsigned PCC,
531                               const FunctionLoweringInfo &FuncInfo,
532                               const SDValue &DestMBB) {
533   assert(isa<BasicBlockSDNode>(DestMBB));
534 
535   if (!FuncInfo.BPI) return PPC::BR_NO_HINT;
536 
537   const BasicBlock *BB = FuncInfo.MBB->getBasicBlock();
538   const Instruction *BBTerm = BB->getTerminator();
539 
540   if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;
541 
542   const BasicBlock *TBB = BBTerm->getSuccessor(0);
543   const BasicBlock *FBB = BBTerm->getSuccessor(1);
544 
545   auto TProb = FuncInfo.BPI->getEdgeProbability(BB, TBB);
546   auto FProb = FuncInfo.BPI->getEdgeProbability(BB, FBB);
547 
548   // We only want to handle cases which are easy to predict at static time, e.g.
549   // C++ throw statement, that is very likely not taken, or calling never
550   // returned function, e.g. stdlib exit(). So we set Threshold to filter
551   // unwanted cases.
552   //
553   // Below is LLVM branch weight table, we only want to handle case 1, 2
554   //
555   // Case                  Taken:Nontaken  Example
556   // 1. Unreachable        1048575:1       C++ throw, stdlib exit(),
557   // 2. Invoke-terminating 1:1048575
558   // 3. Coldblock          4:64            __builtin_expect
559   // 4. Loop Branch        124:4           For loop
560   // 5. PH/ZH/FPH          20:12
561   const uint32_t Threshold = 10000;
562 
563   if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))
564     return PPC::BR_NO_HINT;
565 
566   LLVM_DEBUG(dbgs() << "Use branch hint for '" << FuncInfo.Fn->getName()
567                     << "::" << BB->getName() << "'\n"
568                     << " -> " << TBB->getName() << ": " << TProb << "\n"
569                     << " -> " << FBB->getName() << ": " << FProb << "\n");
570 
571   const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB);
572 
573   // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
574   // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
575   if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
576     std::swap(TProb, FProb);
577 
578   return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
579 }
580 
581 // isOpcWithIntImmediate - This method tests to see if the node is a specific
582 // opcode and that it has a immediate integer right operand.
583 // If so Imm will receive the 32 bit value.
584 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
585   return N->getOpcode() == Opc
586          && isInt32Immediate(N->getOperand(1).getNode(), Imm);
587 }
588 
589 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
590   SDLoc dl(SN);
591   int FI = cast<FrameIndexSDNode>(N)->getIndex();
592   SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
593   unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
594   if (SN->hasOneUse())
595     CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
596                          getSmallIPtrImm(Offset, dl));
597   else
598     ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
599                                            getSmallIPtrImm(Offset, dl)));
600 }
601 
602 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
603                                       bool isShiftMask, unsigned &SH,
604                                       unsigned &MB, unsigned &ME) {
605   // Don't even go down this path for i64, since different logic will be
606   // necessary for rldicl/rldicr/rldimi.
607   if (N->getValueType(0) != MVT::i32)
608     return false;
609 
610   unsigned Shift  = 32;
611   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
612   unsigned Opcode = N->getOpcode();
613   if (N->getNumOperands() != 2 ||
614       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
615     return false;
616 
617   if (Opcode == ISD::SHL) {
618     // apply shift left to mask if it comes first
619     if (isShiftMask) Mask = Mask << Shift;
620     // determine which bits are made indeterminant by shift
621     Indeterminant = ~(0xFFFFFFFFu << Shift);
622   } else if (Opcode == ISD::SRL) {
623     // apply shift right to mask if it comes first
624     if (isShiftMask) Mask = Mask >> Shift;
625     // determine which bits are made indeterminant by shift
626     Indeterminant = ~(0xFFFFFFFFu >> Shift);
627     // adjust for the left rotate
628     Shift = 32 - Shift;
629   } else if (Opcode == ISD::ROTL) {
630     Indeterminant = 0;
631   } else {
632     return false;
633   }
634 
635   // if the mask doesn't intersect any Indeterminant bits
636   if (Mask && !(Mask & Indeterminant)) {
637     SH = Shift & 31;
638     // make sure the mask is still a mask (wrap arounds may not be)
639     return isRunOfOnes(Mask, MB, ME);
640   }
641   return false;
642 }
643 
644 bool PPCDAGToDAGISel::tryTLSXFormStore(StoreSDNode *ST) {
645   SDValue Base = ST->getBasePtr();
646   if (Base.getOpcode() != PPCISD::ADD_TLS)
647     return false;
648   SDValue Offset = ST->getOffset();
649   if (!Offset.isUndef())
650     return false;
651 
652   SDLoc dl(ST);
653   EVT MemVT = ST->getMemoryVT();
654   EVT RegVT = ST->getValue().getValueType();
655 
656   unsigned Opcode;
657   switch (MemVT.getSimpleVT().SimpleTy) {
658     default:
659       return false;
660     case MVT::i8: {
661       Opcode = (RegVT == MVT::i32) ? PPC::STBXTLS_32 : PPC::STBXTLS;
662       break;
663     }
664     case MVT::i16: {
665       Opcode = (RegVT == MVT::i32) ? PPC::STHXTLS_32 : PPC::STHXTLS;
666       break;
667     }
668     case MVT::i32: {
669       Opcode = (RegVT == MVT::i32) ? PPC::STWXTLS_32 : PPC::STWXTLS;
670       break;
671     }
672     case MVT::i64: {
673       Opcode = PPC::STDXTLS;
674       break;
675     }
676   }
677   SDValue Chain = ST->getChain();
678   SDVTList VTs = ST->getVTList();
679   SDValue Ops[] = {ST->getValue(), Base.getOperand(0), Base.getOperand(1),
680                    Chain};
681   SDNode *MN = CurDAG->getMachineNode(Opcode, dl, VTs, Ops);
682   transferMemOperands(ST, MN);
683   ReplaceNode(ST, MN);
684   return true;
685 }
686 
687 bool PPCDAGToDAGISel::tryTLSXFormLoad(LoadSDNode *LD) {
688   SDValue Base = LD->getBasePtr();
689   if (Base.getOpcode() != PPCISD::ADD_TLS)
690     return false;
691   SDValue Offset = LD->getOffset();
692   if (!Offset.isUndef())
693     return false;
694 
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, SDValue Chain) {
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   if (Chain)
3867     return SDValue(
3868         CurDAG->getMachineNode(Opc, dl, MVT::i32, MVT::Other, LHS, RHS, Chain),
3869         0);
3870   else
3871     return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
3872 }
3873 
3874 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC, const EVT &VT,
3875                                            const PPCSubtarget *Subtarget) {
3876   // For SPE instructions, the result is in GT bit of the CR
3877   bool UseSPE = Subtarget->hasSPE() && VT.isFloatingPoint();
3878 
3879   switch (CC) {
3880   case ISD::SETUEQ:
3881   case ISD::SETONE:
3882   case ISD::SETOLE:
3883   case ISD::SETOGE:
3884     llvm_unreachable("Should be lowered by legalize!");
3885   default: llvm_unreachable("Unknown condition!");
3886   case ISD::SETOEQ:
3887   case ISD::SETEQ:
3888     return UseSPE ? PPC::PRED_GT : PPC::PRED_EQ;
3889   case ISD::SETUNE:
3890   case ISD::SETNE:
3891     return UseSPE ? PPC::PRED_LE : PPC::PRED_NE;
3892   case ISD::SETOLT:
3893   case ISD::SETLT:
3894     return UseSPE ? PPC::PRED_GT : PPC::PRED_LT;
3895   case ISD::SETULE:
3896   case ISD::SETLE:
3897     return PPC::PRED_LE;
3898   case ISD::SETOGT:
3899   case ISD::SETGT:
3900     return PPC::PRED_GT;
3901   case ISD::SETUGE:
3902   case ISD::SETGE:
3903     return UseSPE ? PPC::PRED_LE : PPC::PRED_GE;
3904   case ISD::SETO:   return PPC::PRED_NU;
3905   case ISD::SETUO:  return PPC::PRED_UN;
3906     // These two are invalid for floating point.  Assume we have int.
3907   case ISD::SETULT: return PPC::PRED_LT;
3908   case ISD::SETUGT: return PPC::PRED_GT;
3909   }
3910 }
3911 
3912 /// getCRIdxForSetCC - Return the index of the condition register field
3913 /// associated with the SetCC condition, and whether or not the field is
3914 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
3915 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
3916   Invert = false;
3917   switch (CC) {
3918   default: llvm_unreachable("Unknown condition!");
3919   case ISD::SETOLT:
3920   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
3921   case ISD::SETOGT:
3922   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
3923   case ISD::SETOEQ:
3924   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
3925   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
3926   case ISD::SETUGE:
3927   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
3928   case ISD::SETULE:
3929   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
3930   case ISD::SETUNE:
3931   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
3932   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
3933   case ISD::SETUEQ:
3934   case ISD::SETOGE:
3935   case ISD::SETOLE:
3936   case ISD::SETONE:
3937     llvm_unreachable("Invalid branch code: should be expanded by legalize");
3938   // These are invalid for floating point.  Assume integer.
3939   case ISD::SETULT: return 0;
3940   case ISD::SETUGT: return 1;
3941   }
3942 }
3943 
3944 // getVCmpInst: return the vector compare instruction for the specified
3945 // vector type and condition code. Since this is for altivec specific code,
3946 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
3947 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
3948                                 bool HasVSX, bool &Swap, bool &Negate) {
3949   Swap = false;
3950   Negate = false;
3951 
3952   if (VecVT.isFloatingPoint()) {
3953     /* Handle some cases by swapping input operands.  */
3954     switch (CC) {
3955       case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
3956       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
3957       case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
3958       case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
3959       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
3960       case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
3961       default: break;
3962     }
3963     /* Handle some cases by negating the result.  */
3964     switch (CC) {
3965       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
3966       case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
3967       case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
3968       case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
3969       default: break;
3970     }
3971     /* We have instructions implementing the remaining cases.  */
3972     switch (CC) {
3973       case ISD::SETEQ:
3974       case ISD::SETOEQ:
3975         if (VecVT == MVT::v4f32)
3976           return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
3977         else if (VecVT == MVT::v2f64)
3978           return PPC::XVCMPEQDP;
3979         break;
3980       case ISD::SETGT:
3981       case ISD::SETOGT:
3982         if (VecVT == MVT::v4f32)
3983           return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
3984         else if (VecVT == MVT::v2f64)
3985           return PPC::XVCMPGTDP;
3986         break;
3987       case ISD::SETGE:
3988       case ISD::SETOGE:
3989         if (VecVT == MVT::v4f32)
3990           return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
3991         else if (VecVT == MVT::v2f64)
3992           return PPC::XVCMPGEDP;
3993         break;
3994       default:
3995         break;
3996     }
3997     llvm_unreachable("Invalid floating-point vector compare condition");
3998   } else {
3999     /* Handle some cases by swapping input operands.  */
4000     switch (CC) {
4001       case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
4002       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
4003       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
4004       case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
4005       default: break;
4006     }
4007     /* Handle some cases by negating the result.  */
4008     switch (CC) {
4009       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
4010       case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
4011       case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
4012       case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
4013       default: break;
4014     }
4015     /* We have instructions implementing the remaining cases.  */
4016     switch (CC) {
4017       case ISD::SETEQ:
4018       case ISD::SETUEQ:
4019         if (VecVT == MVT::v16i8)
4020           return PPC::VCMPEQUB;
4021         else if (VecVT == MVT::v8i16)
4022           return PPC::VCMPEQUH;
4023         else if (VecVT == MVT::v4i32)
4024           return PPC::VCMPEQUW;
4025         else if (VecVT == MVT::v2i64)
4026           return PPC::VCMPEQUD;
4027         break;
4028       case ISD::SETGT:
4029         if (VecVT == MVT::v16i8)
4030           return PPC::VCMPGTSB;
4031         else if (VecVT == MVT::v8i16)
4032           return PPC::VCMPGTSH;
4033         else if (VecVT == MVT::v4i32)
4034           return PPC::VCMPGTSW;
4035         else if (VecVT == MVT::v2i64)
4036           return PPC::VCMPGTSD;
4037         break;
4038       case ISD::SETUGT:
4039         if (VecVT == MVT::v16i8)
4040           return PPC::VCMPGTUB;
4041         else if (VecVT == MVT::v8i16)
4042           return PPC::VCMPGTUH;
4043         else if (VecVT == MVT::v4i32)
4044           return PPC::VCMPGTUW;
4045         else if (VecVT == MVT::v2i64)
4046           return PPC::VCMPGTUD;
4047         break;
4048       default:
4049         break;
4050     }
4051     llvm_unreachable("Invalid integer vector compare condition");
4052   }
4053 }
4054 
4055 bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
4056   SDLoc dl(N);
4057   unsigned Imm;
4058   bool IsStrict = N->isStrictFPOpcode();
4059   ISD::CondCode CC =
4060       cast<CondCodeSDNode>(N->getOperand(IsStrict ? 3 : 2))->get();
4061   EVT PtrVT =
4062       CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
4063   bool isPPC64 = (PtrVT == MVT::i64);
4064   SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
4065 
4066   SDValue LHS = N->getOperand(IsStrict ? 1 : 0);
4067   SDValue RHS = N->getOperand(IsStrict ? 2 : 1);
4068 
4069   if (!IsStrict && !Subtarget->useCRBits() && isInt32Immediate(RHS, Imm)) {
4070     // We can codegen setcc op, imm very efficiently compared to a brcond.
4071     // Check for those cases here.
4072     // setcc op, 0
4073     if (Imm == 0) {
4074       SDValue Op = LHS;
4075       switch (CC) {
4076       default: break;
4077       case ISD::SETEQ: {
4078         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
4079         SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
4080                           getI32Imm(31, dl) };
4081         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4082         return true;
4083       }
4084       case ISD::SETNE: {
4085         if (isPPC64) break;
4086         SDValue AD =
4087           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4088                                          Op, getI32Imm(~0U, dl)), 0);
4089         CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
4090         return true;
4091       }
4092       case ISD::SETLT: {
4093         SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
4094                           getI32Imm(31, dl) };
4095         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4096         return true;
4097       }
4098       case ISD::SETGT: {
4099         SDValue T =
4100           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
4101         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
4102         SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
4103                           getI32Imm(31, dl) };
4104         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4105         return true;
4106       }
4107       }
4108     } else if (Imm == ~0U) {        // setcc op, -1
4109       SDValue Op = LHS;
4110       switch (CC) {
4111       default: break;
4112       case ISD::SETEQ:
4113         if (isPPC64) break;
4114         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4115                                             Op, getI32Imm(1, dl)), 0);
4116         CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
4117                              SDValue(CurDAG->getMachineNode(PPC::LI, dl,
4118                                                             MVT::i32,
4119                                                             getI32Imm(0, dl)),
4120                                      0), Op.getValue(1));
4121         return true;
4122       case ISD::SETNE: {
4123         if (isPPC64) break;
4124         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
4125         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
4126                                             Op, getI32Imm(~0U, dl));
4127         CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,
4128                              SDValue(AD, 1));
4129         return true;
4130       }
4131       case ISD::SETLT: {
4132         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
4133                                                     getI32Imm(1, dl)), 0);
4134         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
4135                                                     Op), 0);
4136         SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
4137                           getI32Imm(31, dl) };
4138         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4139         return true;
4140       }
4141       case ISD::SETGT: {
4142         SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
4143                           getI32Imm(31, dl) };
4144         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
4145         CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));
4146         return true;
4147       }
4148       }
4149     }
4150   }
4151 
4152   // Altivec Vector compare instructions do not set any CR register by default and
4153   // vector compare operations return the same type as the operands.
4154   if (!IsStrict && LHS.getValueType().isVector()) {
4155     if (Subtarget->hasSPE())
4156       return false;
4157 
4158     EVT VecVT = LHS.getValueType();
4159     bool Swap, Negate;
4160     unsigned int VCmpInst =
4161         getVCmpInst(VecVT.getSimpleVT(), CC, Subtarget->hasVSX(), Swap, Negate);
4162     if (Swap)
4163       std::swap(LHS, RHS);
4164 
4165     EVT ResVT = VecVT.changeVectorElementTypeToInteger();
4166     if (Negate) {
4167       SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
4168       CurDAG->SelectNodeTo(N, Subtarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
4169                            ResVT, VCmp, VCmp);
4170       return true;
4171     }
4172 
4173     CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
4174     return true;
4175   }
4176 
4177   if (Subtarget->useCRBits())
4178     return false;
4179 
4180   bool Inv;
4181   unsigned Idx = getCRIdxForSetCC(CC, Inv);
4182   SDValue CCReg = SelectCC(LHS, RHS, CC, dl, Chain);
4183   if (IsStrict)
4184     CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 1), CCReg.getValue(1));
4185   SDValue IntCR;
4186 
4187   // SPE e*cmp* instructions only set the 'gt' bit, so hard-code that
4188   // The correct compare instruction is already set by SelectCC()
4189   if (Subtarget->hasSPE() && LHS.getValueType().isFloatingPoint()) {
4190     Idx = 1;
4191   }
4192 
4193   // Force the ccreg into CR7.
4194   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
4195 
4196   SDValue InFlag(nullptr, 0);  // Null incoming flag value.
4197   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
4198                                InFlag).getValue(1);
4199 
4200   IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
4201                                          CCReg), 0);
4202 
4203   SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
4204                       getI32Imm(31, dl), getI32Imm(31, dl) };
4205   if (!Inv) {
4206     CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4207     return true;
4208   }
4209 
4210   // Get the specified bit.
4211   SDValue Tmp =
4212     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
4213   CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
4214   return true;
4215 }
4216 
4217 /// Does this node represent a load/store node whose address can be represented
4218 /// with a register plus an immediate that's a multiple of \p Val:
4219 bool PPCDAGToDAGISel::isOffsetMultipleOf(SDNode *N, unsigned Val) const {
4220   LoadSDNode *LDN = dyn_cast<LoadSDNode>(N);
4221   StoreSDNode *STN = dyn_cast<StoreSDNode>(N);
4222   SDValue AddrOp;
4223   if (LDN)
4224     AddrOp = LDN->getOperand(1);
4225   else if (STN)
4226     AddrOp = STN->getOperand(2);
4227 
4228   // If the address points a frame object or a frame object with an offset,
4229   // we need to check the object alignment.
4230   short Imm = 0;
4231   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(
4232           AddrOp.getOpcode() == ISD::ADD ? AddrOp.getOperand(0) :
4233                                            AddrOp)) {
4234     // If op0 is a frame index that is under aligned, we can't do it either,
4235     // because it is translated to r31 or r1 + slot + offset. We won't know the
4236     // slot number until the stack frame is finalized.
4237     const MachineFrameInfo &MFI = CurDAG->getMachineFunction().getFrameInfo();
4238     unsigned SlotAlign = MFI.getObjectAlign(FI->getIndex()).value();
4239     if ((SlotAlign % Val) != 0)
4240       return false;
4241 
4242     // If we have an offset, we need further check on the offset.
4243     if (AddrOp.getOpcode() != ISD::ADD)
4244       return true;
4245   }
4246 
4247   if (AddrOp.getOpcode() == ISD::ADD)
4248     return isIntS16Immediate(AddrOp.getOperand(1), Imm) && !(Imm % Val);
4249 
4250   // If the address comes from the outside, the offset will be zero.
4251   return AddrOp.getOpcode() == ISD::CopyFromReg;
4252 }
4253 
4254 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
4255   // Transfer memoperands.
4256   MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
4257   CurDAG->setNodeMemRefs(cast<MachineSDNode>(Result), {MemOp});
4258 }
4259 
4260 static bool mayUseP9Setb(SDNode *N, const ISD::CondCode &CC, SelectionDAG *DAG,
4261                          bool &NeedSwapOps, bool &IsUnCmp) {
4262 
4263   assert(N->getOpcode() == ISD::SELECT_CC && "Expecting a SELECT_CC here.");
4264 
4265   SDValue LHS = N->getOperand(0);
4266   SDValue RHS = N->getOperand(1);
4267   SDValue TrueRes = N->getOperand(2);
4268   SDValue FalseRes = N->getOperand(3);
4269   ConstantSDNode *TrueConst = dyn_cast<ConstantSDNode>(TrueRes);
4270   if (!TrueConst || (N->getSimpleValueType(0) != MVT::i64 &&
4271                      N->getSimpleValueType(0) != MVT::i32))
4272     return false;
4273 
4274   // We are looking for any of:
4275   // (select_cc lhs, rhs,  1, (sext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4276   // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, cc2)), cc1)
4277   // (select_cc lhs, rhs,  0, (select_cc [lr]hs, [lr]hs,  1, -1, cc2), seteq)
4278   // (select_cc lhs, rhs,  0, (select_cc [lr]hs, [lr]hs, -1,  1, cc2), seteq)
4279   int64_t TrueResVal = TrueConst->getSExtValue();
4280   if ((TrueResVal < -1 || TrueResVal > 1) ||
4281       (TrueResVal == -1 && FalseRes.getOpcode() != ISD::ZERO_EXTEND) ||
4282       (TrueResVal == 1 && FalseRes.getOpcode() != ISD::SIGN_EXTEND) ||
4283       (TrueResVal == 0 &&
4284        (FalseRes.getOpcode() != ISD::SELECT_CC || CC != ISD::SETEQ)))
4285     return false;
4286 
4287   bool InnerIsSel = FalseRes.getOpcode() == ISD::SELECT_CC;
4288   SDValue SetOrSelCC = InnerIsSel ? FalseRes : FalseRes.getOperand(0);
4289   if (SetOrSelCC.getOpcode() != ISD::SETCC &&
4290       SetOrSelCC.getOpcode() != ISD::SELECT_CC)
4291     return false;
4292 
4293   // Without this setb optimization, the outer SELECT_CC will be manually
4294   // selected to SELECT_CC_I4/SELECT_CC_I8 Pseudo, then expand-isel-pseudos pass
4295   // transforms pseudo instruction to isel instruction. When there are more than
4296   // one use for result like zext/sext, with current optimization we only see
4297   // isel is replaced by setb but can't see any significant gain. Since
4298   // setb has longer latency than original isel, we should avoid this. Another
4299   // point is that setb requires comparison always kept, it can break the
4300   // opportunity to get the comparison away if we have in future.
4301   if (!SetOrSelCC.hasOneUse() || (!InnerIsSel && !FalseRes.hasOneUse()))
4302     return false;
4303 
4304   SDValue InnerLHS = SetOrSelCC.getOperand(0);
4305   SDValue InnerRHS = SetOrSelCC.getOperand(1);
4306   ISD::CondCode InnerCC =
4307       cast<CondCodeSDNode>(SetOrSelCC.getOperand(InnerIsSel ? 4 : 2))->get();
4308   // If the inner comparison is a select_cc, make sure the true/false values are
4309   // 1/-1 and canonicalize it if needed.
4310   if (InnerIsSel) {
4311     ConstantSDNode *SelCCTrueConst =
4312         dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(2));
4313     ConstantSDNode *SelCCFalseConst =
4314         dyn_cast<ConstantSDNode>(SetOrSelCC.getOperand(3));
4315     if (!SelCCTrueConst || !SelCCFalseConst)
4316       return false;
4317     int64_t SelCCTVal = SelCCTrueConst->getSExtValue();
4318     int64_t SelCCFVal = SelCCFalseConst->getSExtValue();
4319     // The values must be -1/1 (requiring a swap) or 1/-1.
4320     if (SelCCTVal == -1 && SelCCFVal == 1) {
4321       std::swap(InnerLHS, InnerRHS);
4322     } else if (SelCCTVal != 1 || SelCCFVal != -1)
4323       return false;
4324   }
4325 
4326   // Canonicalize unsigned case
4327   if (InnerCC == ISD::SETULT || InnerCC == ISD::SETUGT) {
4328     IsUnCmp = true;
4329     InnerCC = (InnerCC == ISD::SETULT) ? ISD::SETLT : ISD::SETGT;
4330   }
4331 
4332   bool InnerSwapped = false;
4333   if (LHS == InnerRHS && RHS == InnerLHS)
4334     InnerSwapped = true;
4335   else if (LHS != InnerLHS || RHS != InnerRHS)
4336     return false;
4337 
4338   switch (CC) {
4339   // (select_cc lhs, rhs,  0, \
4340   //     (select_cc [lr]hs, [lr]hs, 1, -1, setlt/setgt), seteq)
4341   case ISD::SETEQ:
4342     if (!InnerIsSel)
4343       return false;
4344     if (InnerCC != ISD::SETLT && InnerCC != ISD::SETGT)
4345       return false;
4346     NeedSwapOps = (InnerCC == ISD::SETGT) ? InnerSwapped : !InnerSwapped;
4347     break;
4348 
4349   // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4350   // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setgt)), setu?lt)
4351   // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setlt)), setu?lt)
4352   // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?lt)
4353   // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setgt)), setu?lt)
4354   // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setlt)), setu?lt)
4355   case ISD::SETULT:
4356     if (!IsUnCmp && InnerCC != ISD::SETNE)
4357       return false;
4358     IsUnCmp = true;
4359     LLVM_FALLTHROUGH;
4360   case ISD::SETLT:
4361     if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETGT && !InnerSwapped) ||
4362         (InnerCC == ISD::SETLT && InnerSwapped))
4363       NeedSwapOps = (TrueResVal == 1);
4364     else
4365       return false;
4366     break;
4367 
4368   // (select_cc lhs, rhs, 1, (sext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4369   // (select_cc lhs, rhs, 1, (sext (setcc lhs, rhs, setlt)), setu?gt)
4370   // (select_cc lhs, rhs, 1, (sext (setcc rhs, lhs, setgt)), setu?gt)
4371   // (select_cc lhs, rhs, -1, (zext (setcc [lr]hs, [lr]hs, setne)), setu?gt)
4372   // (select_cc lhs, rhs, -1, (zext (setcc lhs, rhs, setlt)), setu?gt)
4373   // (select_cc lhs, rhs, -1, (zext (setcc rhs, lhs, setgt)), setu?gt)
4374   case ISD::SETUGT:
4375     if (!IsUnCmp && InnerCC != ISD::SETNE)
4376       return false;
4377     IsUnCmp = true;
4378     LLVM_FALLTHROUGH;
4379   case ISD::SETGT:
4380     if (InnerCC == ISD::SETNE || (InnerCC == ISD::SETLT && !InnerSwapped) ||
4381         (InnerCC == ISD::SETGT && InnerSwapped))
4382       NeedSwapOps = (TrueResVal == -1);
4383     else
4384       return false;
4385     break;
4386 
4387   default:
4388     return false;
4389   }
4390 
4391   LLVM_DEBUG(dbgs() << "Found a node that can be lowered to a SETB: ");
4392   LLVM_DEBUG(N->dump());
4393 
4394   return true;
4395 }
4396 
4397 bool PPCDAGToDAGISel::tryAsSingleRLWINM(SDNode *N) {
4398   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4399   unsigned Imm;
4400   if (!isInt32Immediate(N->getOperand(1), Imm))
4401     return false;
4402 
4403   SDLoc dl(N);
4404   SDValue Val = N->getOperand(0);
4405   unsigned SH, MB, ME;
4406   // If this is an and of a value rotated between 0 and 31 bits and then and'd
4407   // with a mask, emit rlwinm
4408   if (isRotateAndMask(Val.getNode(), Imm, false, SH, MB, ME)) {
4409     Val = Val.getOperand(0);
4410     SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
4411                      getI32Imm(ME, dl)};
4412     CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4413     return true;
4414   }
4415 
4416   // If this is just a masked value where the input is not handled, and
4417   // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
4418   if (isRunOfOnes(Imm, MB, ME) && Val.getOpcode() != ISD::ROTL) {
4419     SDValue Ops[] = {Val, getI32Imm(0, dl), getI32Imm(MB, dl),
4420                      getI32Imm(ME, dl)};
4421     CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4422     return true;
4423   }
4424 
4425   // AND X, 0 -> 0, not "rlwinm 32".
4426   if (Imm == 0) {
4427     ReplaceUses(SDValue(N, 0), N->getOperand(1));
4428     return true;
4429   }
4430 
4431   return false;
4432 }
4433 
4434 bool PPCDAGToDAGISel::tryAsSingleRLWINM8(SDNode *N) {
4435   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4436   uint64_t Imm64;
4437   if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64))
4438     return false;
4439 
4440   unsigned MB, ME;
4441   if (isRunOfOnes64(Imm64, MB, ME) && MB >= 32 && MB <= ME) {
4442     //                MB  ME
4443     // +----------------------+
4444     // |xxxxxxxxxxx00011111000|
4445     // +----------------------+
4446     //  0         32         64
4447     // We can only do it if the MB is larger than 32 and MB <= ME
4448     // as RLWINM will replace the contents of [0 - 32) with [32 - 64) even
4449     // we didn't rotate it.
4450     SDLoc dl(N);
4451     SDValue Ops[] = {N->getOperand(0), getI64Imm(0, dl), getI64Imm(MB - 32, dl),
4452                      getI64Imm(ME - 32, dl)};
4453     CurDAG->SelectNodeTo(N, PPC::RLWINM8, MVT::i64, Ops);
4454     return true;
4455   }
4456 
4457   return false;
4458 }
4459 
4460 bool PPCDAGToDAGISel::tryAsPairOfRLDICL(SDNode *N) {
4461   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4462   uint64_t Imm64;
4463   if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64))
4464     return false;
4465 
4466   // Do nothing if it is 16-bit imm as the pattern in the .td file handle
4467   // it well with "andi.".
4468   if (isUInt<16>(Imm64))
4469     return false;
4470 
4471   SDLoc Loc(N);
4472   SDValue Val = N->getOperand(0);
4473 
4474   // Optimized with two rldicl's as follows:
4475   // Add missing bits on left to the mask and check that the mask is a
4476   // wrapped run of ones, i.e.
4477   // Change pattern |0001111100000011111111|
4478   //             to |1111111100000011111111|.
4479   unsigned NumOfLeadingZeros = countLeadingZeros(Imm64);
4480   if (NumOfLeadingZeros != 0)
4481     Imm64 |= maskLeadingOnes<uint64_t>(NumOfLeadingZeros);
4482 
4483   unsigned MB, ME;
4484   if (!isRunOfOnes64(Imm64, MB, ME))
4485     return false;
4486 
4487   //         ME     MB                   MB-ME+63
4488   // +----------------------+     +----------------------+
4489   // |1111111100000011111111| ->  |0000001111111111111111|
4490   // +----------------------+     +----------------------+
4491   //  0                    63      0                    63
4492   // There are ME + 1 ones on the left and (MB - ME + 63) & 63 zeros in between.
4493   unsigned OnesOnLeft = ME + 1;
4494   unsigned ZerosInBetween = (MB - ME + 63) & 63;
4495   // Rotate left by OnesOnLeft (so leading ones are now trailing ones) and clear
4496   // on the left the bits that are already zeros in the mask.
4497   Val = SDValue(CurDAG->getMachineNode(PPC::RLDICL, Loc, MVT::i64, Val,
4498                                        getI64Imm(OnesOnLeft, Loc),
4499                                        getI64Imm(ZerosInBetween, Loc)),
4500                 0);
4501   //        MB-ME+63                      ME     MB
4502   // +----------------------+     +----------------------+
4503   // |0000001111111111111111| ->  |0001111100000011111111|
4504   // +----------------------+     +----------------------+
4505   //  0                    63      0                    63
4506   // Rotate back by 64 - OnesOnLeft to undo previous rotate. Then clear on the
4507   // left the number of ones we previously added.
4508   SDValue Ops[] = {Val, getI64Imm(64 - OnesOnLeft, Loc),
4509                    getI64Imm(NumOfLeadingZeros, Loc)};
4510   CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
4511   return true;
4512 }
4513 
4514 bool PPCDAGToDAGISel::tryAsSingleRLWIMI(SDNode *N) {
4515   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4516   unsigned Imm;
4517   if (!isInt32Immediate(N->getOperand(1), Imm))
4518     return false;
4519 
4520   SDValue Val = N->getOperand(0);
4521   unsigned Imm2;
4522   // ISD::OR doesn't get all the bitfield insertion fun.
4523   // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
4524   // bitfield insert.
4525   if (Val.getOpcode() != ISD::OR || !isInt32Immediate(Val.getOperand(1), Imm2))
4526     return false;
4527 
4528   // The idea here is to check whether this is equivalent to:
4529   //   (c1 & m) | (x & ~m)
4530   // where m is a run-of-ones mask. The logic here is that, for each bit in
4531   // c1 and c2:
4532   //  - if both are 1, then the output will be 1.
4533   //  - if both are 0, then the output will be 0.
4534   //  - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
4535   //    come from x.
4536   //  - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
4537   //    be 0.
4538   //  If that last condition is never the case, then we can form m from the
4539   //  bits that are the same between c1 and c2.
4540   unsigned MB, ME;
4541   if (isRunOfOnes(~(Imm ^ Imm2), MB, ME) && !(~Imm & Imm2)) {
4542     SDLoc dl(N);
4543     SDValue Ops[] = {Val.getOperand(0), Val.getOperand(1), getI32Imm(0, dl),
4544                      getI32Imm(MB, dl), getI32Imm(ME, dl)};
4545     ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
4546     return true;
4547   }
4548 
4549   return false;
4550 }
4551 
4552 bool PPCDAGToDAGISel::tryAsSingleRLDICL(SDNode *N) {
4553   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4554   uint64_t Imm64;
4555   if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) || !isMask_64(Imm64))
4556     return false;
4557 
4558   // If this is a 64-bit zero-extension mask, emit rldicl.
4559   unsigned MB = 64 - countTrailingOnes(Imm64);
4560   unsigned SH = 0;
4561   unsigned Imm;
4562   SDValue Val = N->getOperand(0);
4563   SDLoc dl(N);
4564 
4565   if (Val.getOpcode() == ISD::ANY_EXTEND) {
4566     auto Op0 = Val.getOperand(0);
4567     if (Op0.getOpcode() == ISD::SRL &&
4568         isInt32Immediate(Op0.getOperand(1).getNode(), Imm) && Imm <= MB) {
4569 
4570       auto ResultType = Val.getNode()->getValueType(0);
4571       auto ImDef = CurDAG->getMachineNode(PPC::IMPLICIT_DEF, dl, ResultType);
4572       SDValue IDVal(ImDef, 0);
4573 
4574       Val = SDValue(CurDAG->getMachineNode(PPC::INSERT_SUBREG, dl, ResultType,
4575                                            IDVal, Op0.getOperand(0),
4576                                            getI32Imm(1, dl)),
4577                     0);
4578       SH = 64 - Imm;
4579     }
4580   }
4581 
4582   // If the operand is a logical right shift, we can fold it into this
4583   // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
4584   // for n <= mb. The right shift is really a left rotate followed by a
4585   // mask, and this mask is a more-restrictive sub-mask of the mask implied
4586   // by the shift.
4587   if (Val.getOpcode() == ISD::SRL &&
4588       isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
4589     assert(Imm < 64 && "Illegal shift amount");
4590     Val = Val.getOperand(0);
4591     SH = 64 - Imm;
4592   }
4593 
4594   SDValue Ops[] = {Val, getI32Imm(SH, dl), getI32Imm(MB, dl)};
4595   CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
4596   return true;
4597 }
4598 
4599 bool PPCDAGToDAGISel::tryAsSingleRLDICR(SDNode *N) {
4600   assert(N->getOpcode() == ISD::AND && "ISD::AND SDNode expected");
4601   uint64_t Imm64;
4602   if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) ||
4603       !isMask_64(~Imm64))
4604     return false;
4605 
4606   // If this is a negated 64-bit zero-extension mask,
4607   // i.e. the immediate is a sequence of ones from most significant side
4608   // and all zero for reminder, we should use rldicr.
4609   unsigned MB = 63 - countTrailingOnes(~Imm64);
4610   unsigned SH = 0;
4611   SDLoc dl(N);
4612   SDValue Ops[] = {N->getOperand(0), getI32Imm(SH, dl), getI32Imm(MB, dl)};
4613   CurDAG->SelectNodeTo(N, PPC::RLDICR, MVT::i64, Ops);
4614   return true;
4615 }
4616 
4617 bool PPCDAGToDAGISel::tryAsSingleRLDIMI(SDNode *N) {
4618   assert(N->getOpcode() == ISD::OR && "ISD::OR SDNode expected");
4619   uint64_t Imm64;
4620   unsigned MB, ME;
4621   SDValue N0 = N->getOperand(0);
4622 
4623   // We won't get fewer instructions if the imm is 32-bit integer.
4624   // rldimi requires the imm to have consecutive ones with both sides zero.
4625   // Also, make sure the first Op has only one use, otherwise this may increase
4626   // register pressure since rldimi is destructive.
4627   if (!isInt64Immediate(N->getOperand(1).getNode(), Imm64) ||
4628       isUInt<32>(Imm64) || !isRunOfOnes64(Imm64, MB, ME) || !N0.hasOneUse())
4629     return false;
4630 
4631   unsigned SH = 63 - ME;
4632   SDLoc Dl(N);
4633   // Use select64Imm for making LI instr instead of directly putting Imm64
4634   SDValue Ops[] = {
4635       N->getOperand(0),
4636       SDValue(selectI64Imm(CurDAG, getI64Imm(-1, Dl).getNode()), 0),
4637       getI32Imm(SH, Dl), getI32Imm(MB, Dl)};
4638   CurDAG->SelectNodeTo(N, PPC::RLDIMI, MVT::i64, Ops);
4639   return true;
4640 }
4641 
4642 // Select - Convert the specified operand from a target-independent to a
4643 // target-specific node if it hasn't already been changed.
4644 void PPCDAGToDAGISel::Select(SDNode *N) {
4645   SDLoc dl(N);
4646   if (N->isMachineOpcode()) {
4647     N->setNodeId(-1);
4648     return;   // Already selected.
4649   }
4650 
4651   // In case any misguided DAG-level optimizations form an ADD with a
4652   // TargetConstant operand, crash here instead of miscompiling (by selecting
4653   // an r+r add instead of some kind of r+i add).
4654   if (N->getOpcode() == ISD::ADD &&
4655       N->getOperand(1).getOpcode() == ISD::TargetConstant)
4656     llvm_unreachable("Invalid ADD with TargetConstant operand");
4657 
4658   // Try matching complex bit permutations before doing anything else.
4659   if (tryBitPermutation(N))
4660     return;
4661 
4662   // Try to emit integer compares as GPR-only sequences (i.e. no use of CR).
4663   if (tryIntCompareInGPR(N))
4664     return;
4665 
4666   switch (N->getOpcode()) {
4667   default: break;
4668 
4669   case ISD::Constant:
4670     if (N->getValueType(0) == MVT::i64) {
4671       ReplaceNode(N, selectI64Imm(CurDAG, N));
4672       return;
4673     }
4674     break;
4675 
4676   case ISD::SETCC:
4677   case ISD::STRICT_FSETCC:
4678   case ISD::STRICT_FSETCCS:
4679     if (trySETCC(N))
4680       return;
4681     break;
4682   // These nodes will be transformed into GETtlsADDR32 node, which
4683   // later becomes BL_TLS __tls_get_addr(sym at tlsgd)@PLT
4684   case PPCISD::ADDI_TLSLD_L_ADDR:
4685   case PPCISD::ADDI_TLSGD_L_ADDR: {
4686     const Module *Mod = MF->getFunction().getParent();
4687     if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 ||
4688         !Subtarget->isSecurePlt() || !Subtarget->isTargetELF() ||
4689         Mod->getPICLevel() == PICLevel::SmallPIC)
4690       break;
4691     // Attach global base pointer on GETtlsADDR32 node in order to
4692     // generate secure plt code for TLS symbols.
4693     getGlobalBaseReg();
4694   } break;
4695   case PPCISD::CALL: {
4696     if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) != MVT::i32 ||
4697         !TM.isPositionIndependent() || !Subtarget->isSecurePlt() ||
4698         !Subtarget->isTargetELF())
4699       break;
4700 
4701     SDValue Op = N->getOperand(1);
4702 
4703     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
4704       if (GA->getTargetFlags() == PPCII::MO_PLT)
4705         getGlobalBaseReg();
4706     }
4707     else if (ExternalSymbolSDNode *ES = dyn_cast<ExternalSymbolSDNode>(Op)) {
4708       if (ES->getTargetFlags() == PPCII::MO_PLT)
4709         getGlobalBaseReg();
4710     }
4711   }
4712     break;
4713 
4714   case PPCISD::GlobalBaseReg:
4715     ReplaceNode(N, getGlobalBaseReg());
4716     return;
4717 
4718   case ISD::FrameIndex:
4719     selectFrameIndex(N, N);
4720     return;
4721 
4722   case PPCISD::MFOCRF: {
4723     SDValue InFlag = N->getOperand(1);
4724     ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
4725                                           N->getOperand(0), InFlag));
4726     return;
4727   }
4728 
4729   case PPCISD::READ_TIME_BASE:
4730     ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
4731                                           MVT::Other, N->getOperand(0)));
4732     return;
4733 
4734   case PPCISD::SRA_ADDZE: {
4735     SDValue N0 = N->getOperand(0);
4736     SDValue ShiftAmt =
4737       CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
4738                                   getConstantIntValue(), dl,
4739                                   N->getValueType(0));
4740     if (N->getValueType(0) == MVT::i64) {
4741       SDNode *Op =
4742         CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
4743                                N0, ShiftAmt);
4744       CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0),
4745                            SDValue(Op, 1));
4746       return;
4747     } else {
4748       assert(N->getValueType(0) == MVT::i32 &&
4749              "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
4750       SDNode *Op =
4751         CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
4752                                N0, ShiftAmt);
4753       CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0),
4754                            SDValue(Op, 1));
4755       return;
4756     }
4757   }
4758 
4759   case ISD::STORE: {
4760     // Change TLS initial-exec D-form stores to X-form stores.
4761     StoreSDNode *ST = cast<StoreSDNode>(N);
4762     if (EnableTLSOpt && Subtarget->isELFv2ABI() &&
4763         ST->getAddressingMode() != ISD::PRE_INC)
4764       if (tryTLSXFormStore(ST))
4765         return;
4766     break;
4767   }
4768   case ISD::LOAD: {
4769     // Handle preincrement loads.
4770     LoadSDNode *LD = cast<LoadSDNode>(N);
4771     EVT LoadedVT = LD->getMemoryVT();
4772 
4773     // Normal loads are handled by code generated from the .td file.
4774     if (LD->getAddressingMode() != ISD::PRE_INC) {
4775       // Change TLS initial-exec D-form loads to X-form loads.
4776       if (EnableTLSOpt && Subtarget->isELFv2ABI())
4777         if (tryTLSXFormLoad(LD))
4778           return;
4779       break;
4780     }
4781 
4782     SDValue Offset = LD->getOffset();
4783     if (Offset.getOpcode() == ISD::TargetConstant ||
4784         Offset.getOpcode() == ISD::TargetGlobalAddress) {
4785 
4786       unsigned Opcode;
4787       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
4788       if (LD->getValueType(0) != MVT::i64) {
4789         // Handle PPC32 integer and normal FP loads.
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::f64: Opcode = PPC::LFDU; break;
4794           case MVT::f32: Opcode = PPC::LFSU; break;
4795           case MVT::i32: Opcode = PPC::LWZU; break;
4796           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
4797           case MVT::i1:
4798           case MVT::i8:  Opcode = PPC::LBZU; break;
4799         }
4800       } else {
4801         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
4802         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
4803         switch (LoadedVT.getSimpleVT().SimpleTy) {
4804           default: llvm_unreachable("Invalid PPC load type!");
4805           case MVT::i64: Opcode = PPC::LDU; break;
4806           case MVT::i32: Opcode = PPC::LWZU8; break;
4807           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
4808           case MVT::i1:
4809           case MVT::i8:  Opcode = PPC::LBZU8; break;
4810         }
4811       }
4812 
4813       SDValue Chain = LD->getChain();
4814       SDValue Base = LD->getBasePtr();
4815       SDValue Ops[] = { Offset, Base, Chain };
4816       SDNode *MN = CurDAG->getMachineNode(
4817           Opcode, dl, LD->getValueType(0),
4818           PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
4819       transferMemOperands(N, MN);
4820       ReplaceNode(N, MN);
4821       return;
4822     } else {
4823       unsigned Opcode;
4824       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
4825       if (LD->getValueType(0) != MVT::i64) {
4826         // Handle PPC32 integer and normal FP loads.
4827         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
4828         switch (LoadedVT.getSimpleVT().SimpleTy) {
4829           default: llvm_unreachable("Invalid PPC load type!");
4830           case MVT::f64: Opcode = PPC::LFDUX; break;
4831           case MVT::f32: Opcode = PPC::LFSUX; break;
4832           case MVT::i32: Opcode = PPC::LWZUX; break;
4833           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
4834           case MVT::i1:
4835           case MVT::i8:  Opcode = PPC::LBZUX; break;
4836         }
4837       } else {
4838         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
4839         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
4840                "Invalid sext update load");
4841         switch (LoadedVT.getSimpleVT().SimpleTy) {
4842           default: llvm_unreachable("Invalid PPC load type!");
4843           case MVT::i64: Opcode = PPC::LDUX; break;
4844           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
4845           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
4846           case MVT::i1:
4847           case MVT::i8:  Opcode = PPC::LBZUX8; break;
4848         }
4849       }
4850 
4851       SDValue Chain = LD->getChain();
4852       SDValue Base = LD->getBasePtr();
4853       SDValue Ops[] = { Base, Offset, Chain };
4854       SDNode *MN = CurDAG->getMachineNode(
4855           Opcode, dl, LD->getValueType(0),
4856           PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
4857       transferMemOperands(N, MN);
4858       ReplaceNode(N, MN);
4859       return;
4860     }
4861   }
4862 
4863   case ISD::AND:
4864     // If this is an 'and' with a mask, try to emit rlwinm/rldicl/rldicr
4865     if (tryAsSingleRLWINM(N) || tryAsSingleRLWIMI(N) || tryAsSingleRLDICL(N) ||
4866         tryAsSingleRLDICR(N) || tryAsSingleRLWINM8(N) || tryAsPairOfRLDICL(N))
4867       return;
4868 
4869     // Other cases are autogenerated.
4870     break;
4871   case ISD::OR: {
4872     if (N->getValueType(0) == MVT::i32)
4873       if (tryBitfieldInsert(N))
4874         return;
4875 
4876     int16_t Imm;
4877     if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
4878         isIntS16Immediate(N->getOperand(1), Imm)) {
4879       KnownBits LHSKnown = CurDAG->computeKnownBits(N->getOperand(0));
4880 
4881       // If this is equivalent to an add, then we can fold it with the
4882       // FrameIndex calculation.
4883       if ((LHSKnown.Zero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {
4884         selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
4885         return;
4886       }
4887     }
4888 
4889     // If this is 'or' against an imm with consecutive ones and both sides zero,
4890     // try to emit rldimi
4891     if (tryAsSingleRLDIMI(N))
4892       return;
4893 
4894     // OR with a 32-bit immediate can be handled by ori + oris
4895     // without creating an immediate in a GPR.
4896     uint64_t Imm64 = 0;
4897     bool IsPPC64 = Subtarget->isPPC64();
4898     if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&
4899         (Imm64 & ~0xFFFFFFFFuLL) == 0) {
4900       // If ImmHi (ImmHi) is zero, only one ori (oris) is generated later.
4901       uint64_t ImmHi = Imm64 >> 16;
4902       uint64_t ImmLo = Imm64 & 0xFFFF;
4903       if (ImmHi != 0 && ImmLo != 0) {
4904         SDNode *Lo = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
4905                                             N->getOperand(0),
4906                                             getI16Imm(ImmLo, dl));
4907         SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};
4908         CurDAG->SelectNodeTo(N, PPC::ORIS8, MVT::i64, Ops1);
4909         return;
4910       }
4911     }
4912 
4913     // Other cases are autogenerated.
4914     break;
4915   }
4916   case ISD::XOR: {
4917     // XOR with a 32-bit immediate can be handled by xori + xoris
4918     // without creating an immediate in a GPR.
4919     uint64_t Imm64 = 0;
4920     bool IsPPC64 = Subtarget->isPPC64();
4921     if (IsPPC64 && isInt64Immediate(N->getOperand(1), Imm64) &&
4922         (Imm64 & ~0xFFFFFFFFuLL) == 0) {
4923       // If ImmHi (ImmHi) is zero, only one xori (xoris) is generated later.
4924       uint64_t ImmHi = Imm64 >> 16;
4925       uint64_t ImmLo = Imm64 & 0xFFFF;
4926       if (ImmHi != 0 && ImmLo != 0) {
4927         SDNode *Lo = CurDAG->getMachineNode(PPC::XORI8, dl, MVT::i64,
4928                                             N->getOperand(0),
4929                                             getI16Imm(ImmLo, dl));
4930         SDValue Ops1[] = { SDValue(Lo, 0), getI16Imm(ImmHi, dl)};
4931         CurDAG->SelectNodeTo(N, PPC::XORIS8, MVT::i64, Ops1);
4932         return;
4933       }
4934     }
4935 
4936     break;
4937   }
4938   case ISD::ADD: {
4939     int16_t Imm;
4940     if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
4941         isIntS16Immediate(N->getOperand(1), Imm)) {
4942       selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
4943       return;
4944     }
4945 
4946     break;
4947   }
4948   case ISD::SHL: {
4949     unsigned Imm, SH, MB, ME;
4950     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
4951         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
4952       SDValue Ops[] = { N->getOperand(0).getOperand(0),
4953                           getI32Imm(SH, dl), getI32Imm(MB, dl),
4954                           getI32Imm(ME, dl) };
4955       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4956       return;
4957     }
4958 
4959     // Other cases are autogenerated.
4960     break;
4961   }
4962   case ISD::SRL: {
4963     unsigned Imm, SH, MB, ME;
4964     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
4965         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
4966       SDValue Ops[] = { N->getOperand(0).getOperand(0),
4967                           getI32Imm(SH, dl), getI32Imm(MB, dl),
4968                           getI32Imm(ME, dl) };
4969       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
4970       return;
4971     }
4972 
4973     // Other cases are autogenerated.
4974     break;
4975   }
4976   // FIXME: Remove this once the ANDI glue bug is fixed:
4977   case PPCISD::ANDI_rec_1_EQ_BIT:
4978   case PPCISD::ANDI_rec_1_GT_BIT: {
4979     if (!ANDIGlueBug)
4980       break;
4981 
4982     EVT InVT = N->getOperand(0).getValueType();
4983     assert((InVT == MVT::i64 || InVT == MVT::i32) &&
4984            "Invalid input type for ANDI_rec_1_EQ_BIT");
4985 
4986     unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDI8_rec : PPC::ANDI_rec;
4987     SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
4988                                         N->getOperand(0),
4989                                         CurDAG->getTargetConstant(1, dl, InVT)),
4990                  0);
4991     SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
4992     SDValue SRIdxVal = CurDAG->getTargetConstant(
4993         N->getOpcode() == PPCISD::ANDI_rec_1_EQ_BIT ? PPC::sub_eq : PPC::sub_gt,
4994         dl, MVT::i32);
4995 
4996     CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg,
4997                          SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */);
4998     return;
4999   }
5000   case ISD::SELECT_CC: {
5001     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
5002     EVT PtrVT =
5003         CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
5004     bool isPPC64 = (PtrVT == MVT::i64);
5005 
5006     // If this is a select of i1 operands, we'll pattern match it.
5007     if (Subtarget->useCRBits() && N->getOperand(0).getValueType() == MVT::i1)
5008       break;
5009 
5010     if (Subtarget->isISA3_0() && Subtarget->isPPC64()) {
5011       bool NeedSwapOps = false;
5012       bool IsUnCmp = false;
5013       if (mayUseP9Setb(N, CC, CurDAG, NeedSwapOps, IsUnCmp)) {
5014         SDValue LHS = N->getOperand(0);
5015         SDValue RHS = N->getOperand(1);
5016         if (NeedSwapOps)
5017           std::swap(LHS, RHS);
5018 
5019         // Make use of SelectCC to generate the comparison to set CR bits, for
5020         // equality comparisons having one literal operand, SelectCC probably
5021         // doesn't need to materialize the whole literal and just use xoris to
5022         // check it first, it leads the following comparison result can't
5023         // exactly represent GT/LT relationship. So to avoid this we specify
5024         // SETGT/SETUGT here instead of SETEQ.
5025         SDValue GenCC =
5026             SelectCC(LHS, RHS, IsUnCmp ? ISD::SETUGT : ISD::SETGT, dl);
5027         CurDAG->SelectNodeTo(
5028             N, N->getSimpleValueType(0) == MVT::i64 ? PPC::SETB8 : PPC::SETB,
5029             N->getValueType(0), GenCC);
5030         NumP9Setb++;
5031         return;
5032       }
5033     }
5034 
5035     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
5036     if (!isPPC64)
5037       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
5038         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
5039           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
5040             if (N1C->isNullValue() && N3C->isNullValue() &&
5041                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
5042                 // FIXME: Implement this optzn for PPC64.
5043                 N->getValueType(0) == MVT::i32) {
5044               SDNode *Tmp =
5045                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
5046                                        N->getOperand(0), getI32Imm(~0U, dl));
5047               CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0),
5048                                    N->getOperand(0), SDValue(Tmp, 1));
5049               return;
5050             }
5051 
5052     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
5053 
5054     if (N->getValueType(0) == MVT::i1) {
5055       // An i1 select is: (c & t) | (!c & f).
5056       bool Inv;
5057       unsigned Idx = getCRIdxForSetCC(CC, Inv);
5058 
5059       unsigned SRI;
5060       switch (Idx) {
5061       default: llvm_unreachable("Invalid CC index");
5062       case 0: SRI = PPC::sub_lt; break;
5063       case 1: SRI = PPC::sub_gt; break;
5064       case 2: SRI = PPC::sub_eq; break;
5065       case 3: SRI = PPC::sub_un; break;
5066       }
5067 
5068       SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
5069 
5070       SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
5071                                               CCBit, CCBit), 0);
5072       SDValue C =    Inv ? NotCCBit : CCBit,
5073               NotC = Inv ? CCBit    : NotCCBit;
5074 
5075       SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
5076                                            C, N->getOperand(2)), 0);
5077       SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
5078                                               NotC, N->getOperand(3)), 0);
5079 
5080       CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
5081       return;
5082     }
5083 
5084     unsigned BROpc =
5085         getPredicateForSetCC(CC, N->getOperand(0).getValueType(), Subtarget);
5086 
5087     unsigned SelectCCOp;
5088     if (N->getValueType(0) == MVT::i32)
5089       SelectCCOp = PPC::SELECT_CC_I4;
5090     else if (N->getValueType(0) == MVT::i64)
5091       SelectCCOp = PPC::SELECT_CC_I8;
5092     else if (N->getValueType(0) == MVT::f32) {
5093       if (Subtarget->hasP8Vector())
5094         SelectCCOp = PPC::SELECT_CC_VSSRC;
5095       else if (Subtarget->hasSPE())
5096         SelectCCOp = PPC::SELECT_CC_SPE4;
5097       else
5098         SelectCCOp = PPC::SELECT_CC_F4;
5099     } else if (N->getValueType(0) == MVT::f64) {
5100       if (Subtarget->hasVSX())
5101         SelectCCOp = PPC::SELECT_CC_VSFRC;
5102       else if (Subtarget->hasSPE())
5103         SelectCCOp = PPC::SELECT_CC_SPE;
5104       else
5105         SelectCCOp = PPC::SELECT_CC_F8;
5106     } else if (N->getValueType(0) == MVT::f128)
5107       SelectCCOp = PPC::SELECT_CC_F16;
5108     else if (Subtarget->hasSPE())
5109       SelectCCOp = PPC::SELECT_CC_SPE;
5110     else if (N->getValueType(0) == MVT::v2f64 ||
5111              N->getValueType(0) == MVT::v2i64)
5112       SelectCCOp = PPC::SELECT_CC_VSRC;
5113     else
5114       SelectCCOp = PPC::SELECT_CC_VRRC;
5115 
5116     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
5117                         getI32Imm(BROpc, dl) };
5118     CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
5119     return;
5120   }
5121   case ISD::VECTOR_SHUFFLE:
5122     if (Subtarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
5123                                 N->getValueType(0) == MVT::v2i64)) {
5124       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
5125 
5126       SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
5127               Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
5128       unsigned DM[2];
5129 
5130       for (int i = 0; i < 2; ++i)
5131         if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
5132           DM[i] = 0;
5133         else
5134           DM[i] = 1;
5135 
5136       if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
5137           Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
5138           isa<LoadSDNode>(Op1.getOperand(0))) {
5139         LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
5140         SDValue Base, Offset;
5141 
5142         if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
5143             (LD->getMemoryVT() == MVT::f64 ||
5144              LD->getMemoryVT() == MVT::i64) &&
5145             SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
5146           SDValue Chain = LD->getChain();
5147           SDValue Ops[] = { Base, Offset, Chain };
5148           MachineMemOperand *MemOp = LD->getMemOperand();
5149           SDNode *NewN = CurDAG->SelectNodeTo(N, PPC::LXVDSX,
5150                                               N->getValueType(0), Ops);
5151           CurDAG->setNodeMemRefs(cast<MachineSDNode>(NewN), {MemOp});
5152           return;
5153         }
5154       }
5155 
5156       // For little endian, we must swap the input operands and adjust
5157       // the mask elements (reverse and invert them).
5158       if (Subtarget->isLittleEndian()) {
5159         std::swap(Op1, Op2);
5160         unsigned tmp = DM[0];
5161         DM[0] = 1 - DM[1];
5162         DM[1] = 1 - tmp;
5163       }
5164 
5165       SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
5166                                               MVT::i32);
5167       SDValue Ops[] = { Op1, Op2, DMV };
5168       CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
5169       return;
5170     }
5171 
5172     break;
5173   case PPCISD::BDNZ:
5174   case PPCISD::BDZ: {
5175     bool IsPPC64 = Subtarget->isPPC64();
5176     SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
5177     CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ
5178                                 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
5179                                 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
5180                          MVT::Other, Ops);
5181     return;
5182   }
5183   case PPCISD::COND_BRANCH: {
5184     // Op #0 is the Chain.
5185     // Op #1 is the PPC::PRED_* number.
5186     // Op #2 is the CR#
5187     // Op #3 is the Dest MBB
5188     // Op #4 is the Flag.
5189     // Prevent PPC::PRED_* from being selected into LI.
5190     unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
5191     if (EnableBranchHint)
5192       PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(3));
5193 
5194     SDValue Pred = getI32Imm(PCC, dl);
5195     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
5196       N->getOperand(0), N->getOperand(4) };
5197     CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
5198     return;
5199   }
5200   case ISD::BR_CC: {
5201     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
5202     unsigned PCC =
5203         getPredicateForSetCC(CC, N->getOperand(2).getValueType(), Subtarget);
5204 
5205     if (N->getOperand(2).getValueType() == MVT::i1) {
5206       unsigned Opc;
5207       bool Swap;
5208       switch (PCC) {
5209       default: llvm_unreachable("Unexpected Boolean-operand predicate");
5210       case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true;  break;
5211       case PPC::PRED_LE: Opc = PPC::CRORC;  Swap = true;  break;
5212       case PPC::PRED_EQ: Opc = PPC::CREQV;  Swap = false; break;
5213       case PPC::PRED_GE: Opc = PPC::CRORC;  Swap = false; break;
5214       case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
5215       case PPC::PRED_NE: Opc = PPC::CRXOR;  Swap = false; break;
5216       }
5217 
5218       // A signed comparison of i1 values produces the opposite result to an
5219       // unsigned one if the condition code includes less-than or greater-than.
5220       // This is because 1 is the most negative signed i1 number and the most
5221       // positive unsigned i1 number. The CR-logical operations used for such
5222       // comparisons are non-commutative so for signed comparisons vs. unsigned
5223       // ones, the input operands just need to be swapped.
5224       if (ISD::isSignedIntSetCC(CC))
5225         Swap = !Swap;
5226 
5227       SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
5228                                              N->getOperand(Swap ? 3 : 2),
5229                                              N->getOperand(Swap ? 2 : 3)), 0);
5230       CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4),
5231                            N->getOperand(0));
5232       return;
5233     }
5234 
5235     if (EnableBranchHint)
5236       PCC |= getBranchHint(PCC, *FuncInfo, N->getOperand(4));
5237 
5238     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
5239     SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
5240                         N->getOperand(4), N->getOperand(0) };
5241     CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
5242     return;
5243   }
5244   case ISD::BRIND: {
5245     // FIXME: Should custom lower this.
5246     SDValue Chain = N->getOperand(0);
5247     SDValue Target = N->getOperand(1);
5248     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
5249     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
5250     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
5251                                            Chain), 0);
5252     CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
5253     return;
5254   }
5255   case PPCISD::TOC_ENTRY: {
5256     const bool isPPC64 = Subtarget->isPPC64();
5257     const bool isELFABI = Subtarget->isSVR4ABI();
5258     const bool isAIXABI = Subtarget->isAIXABI();
5259 
5260     // PowerPC only support small, medium and large code model.
5261     const CodeModel::Model CModel = TM.getCodeModel();
5262     assert(!(CModel == CodeModel::Tiny || CModel == CodeModel::Kernel) &&
5263            "PowerPC doesn't support tiny or kernel code models.");
5264 
5265     if (isAIXABI && CModel == CodeModel::Medium)
5266       report_fatal_error("Medium code model is not supported on AIX.");
5267 
5268     // For 64-bit small code model, we allow SelectCodeCommon to handle this,
5269     // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
5270     if (isPPC64 && CModel == CodeModel::Small)
5271       break;
5272 
5273     // Handle 32-bit small code model.
5274     if (!isPPC64) {
5275       // Transforms the ISD::TOC_ENTRY node to a PPCISD::LWZtoc.
5276       auto replaceWithLWZtoc = [this, &dl](SDNode *TocEntry) {
5277         SDValue GA = TocEntry->getOperand(0);
5278         SDValue TocBase = TocEntry->getOperand(1);
5279         SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
5280                                             TocBase);
5281         transferMemOperands(TocEntry, MN);
5282         ReplaceNode(TocEntry, MN);
5283       };
5284 
5285       if (isELFABI) {
5286         assert(TM.isPositionIndependent() &&
5287                "32-bit ELF can only have TOC entries in position independent"
5288                " code.");
5289         // 32-bit ELF always uses a small code model toc access.
5290         replaceWithLWZtoc(N);
5291         return;
5292       }
5293 
5294       if (isAIXABI && CModel == CodeModel::Small) {
5295         replaceWithLWZtoc(N);
5296         return;
5297       }
5298     }
5299 
5300     assert(CModel != CodeModel::Small && "All small code models handled.");
5301 
5302     assert((isPPC64 || (isAIXABI && !isPPC64)) && "We are dealing with 64-bit"
5303            " ELF/AIX or 32-bit AIX in the following.");
5304 
5305     // Transforms the ISD::TOC_ENTRY node for 32-bit AIX large code model mode
5306     // or 64-bit medium (ELF-only) or large (ELF and AIX) code model code. We
5307     // generate two instructions as described below. The first source operand
5308     // is a symbol reference. If it must be toc-referenced according to
5309     // Subtarget, we generate:
5310     // [32-bit AIX]
5311     //   LWZtocL(@sym, ADDIStocHA(%r2, @sym))
5312     // [64-bit ELF/AIX]
5313     //   LDtocL(@sym, ADDIStocHA8(%x2, @sym))
5314     // Otherwise we generate:
5315     //   ADDItocL(ADDIStocHA8(%x2, @sym), @sym)
5316     SDValue GA = N->getOperand(0);
5317     SDValue TOCbase = N->getOperand(1);
5318 
5319     EVT VT = isPPC64 ? MVT::i64 : MVT::i32;
5320     SDNode *Tmp = CurDAG->getMachineNode(
5321         isPPC64 ? PPC::ADDIStocHA8 : PPC::ADDIStocHA, dl, VT, TOCbase, GA);
5322 
5323     if (PPCLowering->isAccessedAsGotIndirect(GA)) {
5324       // If it is accessed as got-indirect, we need an extra LWZ/LD to load
5325       // the address.
5326       SDNode *MN = CurDAG->getMachineNode(
5327           isPPC64 ? PPC::LDtocL : PPC::LWZtocL, dl, VT, GA, SDValue(Tmp, 0));
5328 
5329       transferMemOperands(N, MN);
5330       ReplaceNode(N, MN);
5331       return;
5332     }
5333 
5334     // Build the address relative to the TOC-pointer.
5335     ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
5336                                           SDValue(Tmp, 0), GA));
5337     return;
5338   }
5339   case PPCISD::PPC32_PICGOT:
5340     // Generate a PIC-safe GOT reference.
5341     assert(Subtarget->is32BitELFABI() &&
5342            "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
5343     CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT,
5344                          PPCLowering->getPointerTy(CurDAG->getDataLayout()),
5345                          MVT::i32);
5346     return;
5347 
5348   case PPCISD::VADD_SPLAT: {
5349     // This expands into one of three sequences, depending on whether
5350     // the first operand is odd or even, positive or negative.
5351     assert(isa<ConstantSDNode>(N->getOperand(0)) &&
5352            isa<ConstantSDNode>(N->getOperand(1)) &&
5353            "Invalid operand on VADD_SPLAT!");
5354 
5355     int Elt     = N->getConstantOperandVal(0);
5356     int EltSize = N->getConstantOperandVal(1);
5357     unsigned Opc1, Opc2, Opc3;
5358     EVT VT;
5359 
5360     if (EltSize == 1) {
5361       Opc1 = PPC::VSPLTISB;
5362       Opc2 = PPC::VADDUBM;
5363       Opc3 = PPC::VSUBUBM;
5364       VT = MVT::v16i8;
5365     } else if (EltSize == 2) {
5366       Opc1 = PPC::VSPLTISH;
5367       Opc2 = PPC::VADDUHM;
5368       Opc3 = PPC::VSUBUHM;
5369       VT = MVT::v8i16;
5370     } else {
5371       assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
5372       Opc1 = PPC::VSPLTISW;
5373       Opc2 = PPC::VADDUWM;
5374       Opc3 = PPC::VSUBUWM;
5375       VT = MVT::v4i32;
5376     }
5377 
5378     if ((Elt & 1) == 0) {
5379       // Elt is even, in the range [-32,-18] + [16,30].
5380       //
5381       // Convert: VADD_SPLAT elt, size
5382       // Into:    tmp = VSPLTIS[BHW] elt
5383       //          VADDU[BHW]M tmp, tmp
5384       // Where:   [BHW] = B for size = 1, H for size = 2, W for size = 4
5385       SDValue EltVal = getI32Imm(Elt >> 1, dl);
5386       SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
5387       SDValue TmpVal = SDValue(Tmp, 0);
5388       ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal));
5389       return;
5390     } else if (Elt > 0) {
5391       // Elt is odd and positive, in the range [17,31].
5392       //
5393       // Convert: VADD_SPLAT elt, size
5394       // Into:    tmp1 = VSPLTIS[BHW] elt-16
5395       //          tmp2 = VSPLTIS[BHW] -16
5396       //          VSUBU[BHW]M tmp1, tmp2
5397       SDValue EltVal = getI32Imm(Elt - 16, dl);
5398       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
5399       EltVal = getI32Imm(-16, dl);
5400       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
5401       ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
5402                                             SDValue(Tmp2, 0)));
5403       return;
5404     } else {
5405       // Elt is odd and negative, in the range [-31,-17].
5406       //
5407       // Convert: VADD_SPLAT elt, size
5408       // Into:    tmp1 = VSPLTIS[BHW] elt+16
5409       //          tmp2 = VSPLTIS[BHW] -16
5410       //          VADDU[BHW]M tmp1, tmp2
5411       SDValue EltVal = getI32Imm(Elt + 16, dl);
5412       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
5413       EltVal = getI32Imm(-16, dl);
5414       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
5415       ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
5416                                             SDValue(Tmp2, 0)));
5417       return;
5418     }
5419   }
5420   }
5421 
5422   SelectCode(N);
5423 }
5424 
5425 // If the target supports the cmpb instruction, do the idiom recognition here.
5426 // We don't do this as a DAG combine because we don't want to do it as nodes
5427 // are being combined (because we might miss part of the eventual idiom). We
5428 // don't want to do it during instruction selection because we want to reuse
5429 // the logic for lowering the masking operations already part of the
5430 // instruction selector.
5431 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
5432   SDLoc dl(N);
5433 
5434   assert(N->getOpcode() == ISD::OR &&
5435          "Only OR nodes are supported for CMPB");
5436 
5437   SDValue Res;
5438   if (!Subtarget->hasCMPB())
5439     return Res;
5440 
5441   if (N->getValueType(0) != MVT::i32 &&
5442       N->getValueType(0) != MVT::i64)
5443     return Res;
5444 
5445   EVT VT = N->getValueType(0);
5446 
5447   SDValue RHS, LHS;
5448   bool BytesFound[8] = {false, false, false, false, false, false, false, false};
5449   uint64_t Mask = 0, Alt = 0;
5450 
5451   auto IsByteSelectCC = [this](SDValue O, unsigned &b,
5452                                uint64_t &Mask, uint64_t &Alt,
5453                                SDValue &LHS, SDValue &RHS) {
5454     if (O.getOpcode() != ISD::SELECT_CC)
5455       return false;
5456     ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
5457 
5458     if (!isa<ConstantSDNode>(O.getOperand(2)) ||
5459         !isa<ConstantSDNode>(O.getOperand(3)))
5460       return false;
5461 
5462     uint64_t PM = O.getConstantOperandVal(2);
5463     uint64_t PAlt = O.getConstantOperandVal(3);
5464     for (b = 0; b < 8; ++b) {
5465       uint64_t Mask = UINT64_C(0xFF) << (8*b);
5466       if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
5467         break;
5468     }
5469 
5470     if (b == 8)
5471       return false;
5472     Mask |= PM;
5473     Alt  |= PAlt;
5474 
5475     if (!isa<ConstantSDNode>(O.getOperand(1)) ||
5476         O.getConstantOperandVal(1) != 0) {
5477       SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
5478       if (Op0.getOpcode() == ISD::TRUNCATE)
5479         Op0 = Op0.getOperand(0);
5480       if (Op1.getOpcode() == ISD::TRUNCATE)
5481         Op1 = Op1.getOperand(0);
5482 
5483       if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
5484           Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
5485           isa<ConstantSDNode>(Op0.getOperand(1))) {
5486 
5487         unsigned Bits = Op0.getValueSizeInBits();
5488         if (b != Bits/8-1)
5489           return false;
5490         if (Op0.getConstantOperandVal(1) != Bits-8)
5491           return false;
5492 
5493         LHS = Op0.getOperand(0);
5494         RHS = Op1.getOperand(0);
5495         return true;
5496       }
5497 
5498       // When we have small integers (i16 to be specific), the form present
5499       // post-legalization uses SETULT in the SELECT_CC for the
5500       // higher-order byte, depending on the fact that the
5501       // even-higher-order bytes are known to all be zero, for example:
5502       //   select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
5503       // (so when the second byte is the same, because all higher-order
5504       // bits from bytes 3 and 4 are known to be zero, the result of the
5505       // xor can be at most 255)
5506       if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
5507           isa<ConstantSDNode>(O.getOperand(1))) {
5508 
5509         uint64_t ULim = O.getConstantOperandVal(1);
5510         if (ULim != (UINT64_C(1) << b*8))
5511           return false;
5512 
5513         // Now we need to make sure that the upper bytes are known to be
5514         // zero.
5515         unsigned Bits = Op0.getValueSizeInBits();
5516         if (!CurDAG->MaskedValueIsZero(
5517                 Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8)))
5518           return false;
5519 
5520         LHS = Op0.getOperand(0);
5521         RHS = Op0.getOperand(1);
5522         return true;
5523       }
5524 
5525       return false;
5526     }
5527 
5528     if (CC != ISD::SETEQ)
5529       return false;
5530 
5531     SDValue Op = O.getOperand(0);
5532     if (Op.getOpcode() == ISD::AND) {
5533       if (!isa<ConstantSDNode>(Op.getOperand(1)))
5534         return false;
5535       if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
5536         return false;
5537 
5538       SDValue XOR = Op.getOperand(0);
5539       if (XOR.getOpcode() == ISD::TRUNCATE)
5540         XOR = XOR.getOperand(0);
5541       if (XOR.getOpcode() != ISD::XOR)
5542         return false;
5543 
5544       LHS = XOR.getOperand(0);
5545       RHS = XOR.getOperand(1);
5546       return true;
5547     } else if (Op.getOpcode() == ISD::SRL) {
5548       if (!isa<ConstantSDNode>(Op.getOperand(1)))
5549         return false;
5550       unsigned Bits = Op.getValueSizeInBits();
5551       if (b != Bits/8-1)
5552         return false;
5553       if (Op.getConstantOperandVal(1) != Bits-8)
5554         return false;
5555 
5556       SDValue XOR = Op.getOperand(0);
5557       if (XOR.getOpcode() == ISD::TRUNCATE)
5558         XOR = XOR.getOperand(0);
5559       if (XOR.getOpcode() != ISD::XOR)
5560         return false;
5561 
5562       LHS = XOR.getOperand(0);
5563       RHS = XOR.getOperand(1);
5564       return true;
5565     }
5566 
5567     return false;
5568   };
5569 
5570   SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
5571   while (!Queue.empty()) {
5572     SDValue V = Queue.pop_back_val();
5573 
5574     for (const SDValue &O : V.getNode()->ops()) {
5575       unsigned b = 0;
5576       uint64_t M = 0, A = 0;
5577       SDValue OLHS, ORHS;
5578       if (O.getOpcode() == ISD::OR) {
5579         Queue.push_back(O);
5580       } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
5581         if (!LHS) {
5582           LHS = OLHS;
5583           RHS = ORHS;
5584           BytesFound[b] = true;
5585           Mask |= M;
5586           Alt  |= A;
5587         } else if ((LHS == ORHS && RHS == OLHS) ||
5588                    (RHS == ORHS && LHS == OLHS)) {
5589           BytesFound[b] = true;
5590           Mask |= M;
5591           Alt  |= A;
5592         } else {
5593           return Res;
5594         }
5595       } else {
5596         return Res;
5597       }
5598     }
5599   }
5600 
5601   unsigned LastB = 0, BCnt = 0;
5602   for (unsigned i = 0; i < 8; ++i)
5603     if (BytesFound[LastB]) {
5604       ++BCnt;
5605       LastB = i;
5606     }
5607 
5608   if (!LastB || BCnt < 2)
5609     return Res;
5610 
5611   // Because we'll be zero-extending the output anyway if don't have a specific
5612   // value for each input byte (via the Mask), we can 'anyext' the inputs.
5613   if (LHS.getValueType() != VT) {
5614     LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
5615     RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
5616   }
5617 
5618   Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
5619 
5620   bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
5621   if (NonTrivialMask && !Alt) {
5622     // Res = Mask & CMPB
5623     Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
5624                           CurDAG->getConstant(Mask, dl, VT));
5625   } else if (Alt) {
5626     // Res = (CMPB & Mask) | (~CMPB & Alt)
5627     // Which, as suggested here:
5628     //   https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
5629     // can be written as:
5630     // Res = Alt ^ ((Alt ^ Mask) & CMPB)
5631     // useful because the (Alt ^ Mask) can be pre-computed.
5632     Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
5633                           CurDAG->getConstant(Mask ^ Alt, dl, VT));
5634     Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
5635                           CurDAG->getConstant(Alt, dl, VT));
5636   }
5637 
5638   return Res;
5639 }
5640 
5641 // When CR bit registers are enabled, an extension of an i1 variable to a i32
5642 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
5643 // involves constant materialization of a 0 or a 1 or both. If the result of
5644 // the extension is then operated upon by some operator that can be constant
5645 // folded with a constant 0 or 1, and that constant can be materialized using
5646 // only one instruction (like a zero or one), then we should fold in those
5647 // operations with the select.
5648 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
5649   if (!Subtarget->useCRBits())
5650     return;
5651 
5652   if (N->getOpcode() != ISD::ZERO_EXTEND &&
5653       N->getOpcode() != ISD::SIGN_EXTEND &&
5654       N->getOpcode() != ISD::ANY_EXTEND)
5655     return;
5656 
5657   if (N->getOperand(0).getValueType() != MVT::i1)
5658     return;
5659 
5660   if (!N->hasOneUse())
5661     return;
5662 
5663   SDLoc dl(N);
5664   EVT VT = N->getValueType(0);
5665   SDValue Cond = N->getOperand(0);
5666   SDValue ConstTrue =
5667     CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
5668   SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
5669 
5670   do {
5671     SDNode *User = *N->use_begin();
5672     if (User->getNumOperands() != 2)
5673       break;
5674 
5675     auto TryFold = [this, N, User, dl](SDValue Val) {
5676       SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
5677       SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
5678       SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
5679 
5680       return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
5681                                             User->getValueType(0), {O0, O1});
5682     };
5683 
5684     // FIXME: When the semantics of the interaction between select and undef
5685     // are clearly defined, it may turn out to be unnecessary to break here.
5686     SDValue TrueRes = TryFold(ConstTrue);
5687     if (!TrueRes || TrueRes.isUndef())
5688       break;
5689     SDValue FalseRes = TryFold(ConstFalse);
5690     if (!FalseRes || FalseRes.isUndef())
5691       break;
5692 
5693     // For us to materialize these using one instruction, we must be able to
5694     // represent them as signed 16-bit integers.
5695     uint64_t True  = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
5696              False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
5697     if (!isInt<16>(True) || !isInt<16>(False))
5698       break;
5699 
5700     // We can replace User with a new SELECT node, and try again to see if we
5701     // can fold the select with its user.
5702     Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
5703     N = User;
5704     ConstTrue = TrueRes;
5705     ConstFalse = FalseRes;
5706   } while (N->hasOneUse());
5707 }
5708 
5709 void PPCDAGToDAGISel::PreprocessISelDAG() {
5710   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
5711 
5712   bool MadeChange = false;
5713   while (Position != CurDAG->allnodes_begin()) {
5714     SDNode *N = &*--Position;
5715     if (N->use_empty())
5716       continue;
5717 
5718     SDValue Res;
5719     switch (N->getOpcode()) {
5720     default: break;
5721     case ISD::OR:
5722       Res = combineToCMPB(N);
5723       break;
5724     }
5725 
5726     if (!Res)
5727       foldBoolExts(Res, N);
5728 
5729     if (Res) {
5730       LLVM_DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld:    ");
5731       LLVM_DEBUG(N->dump(CurDAG));
5732       LLVM_DEBUG(dbgs() << "\nNew: ");
5733       LLVM_DEBUG(Res.getNode()->dump(CurDAG));
5734       LLVM_DEBUG(dbgs() << "\n");
5735 
5736       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
5737       MadeChange = true;
5738     }
5739   }
5740 
5741   if (MadeChange)
5742     CurDAG->RemoveDeadNodes();
5743 }
5744 
5745 /// PostprocessISelDAG - Perform some late peephole optimizations
5746 /// on the DAG representation.
5747 void PPCDAGToDAGISel::PostprocessISelDAG() {
5748   // Skip peepholes at -O0.
5749   if (TM.getOptLevel() == CodeGenOpt::None)
5750     return;
5751 
5752   PeepholePPC64();
5753   PeepholeCROps();
5754   PeepholePPC64ZExt();
5755 }
5756 
5757 // Check if all users of this node will become isel where the second operand
5758 // is the constant zero. If this is so, and if we can negate the condition,
5759 // then we can flip the true and false operands. This will allow the zero to
5760 // be folded with the isel so that we don't need to materialize a register
5761 // containing zero.
5762 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
5763   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5764        UI != UE; ++UI) {
5765     SDNode *User = *UI;
5766     if (!User->isMachineOpcode())
5767       return false;
5768     if (User->getMachineOpcode() != PPC::SELECT_I4 &&
5769         User->getMachineOpcode() != PPC::SELECT_I8)
5770       return false;
5771 
5772     SDNode *Op2 = User->getOperand(2).getNode();
5773     if (!Op2->isMachineOpcode())
5774       return false;
5775 
5776     if (Op2->getMachineOpcode() != PPC::LI &&
5777         Op2->getMachineOpcode() != PPC::LI8)
5778       return false;
5779 
5780     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
5781     if (!C)
5782       return false;
5783 
5784     if (!C->isNullValue())
5785       return false;
5786   }
5787 
5788   return true;
5789 }
5790 
5791 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
5792   SmallVector<SDNode *, 4> ToReplace;
5793   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
5794        UI != UE; ++UI) {
5795     SDNode *User = *UI;
5796     assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
5797             User->getMachineOpcode() == PPC::SELECT_I8) &&
5798            "Must have all select users");
5799     ToReplace.push_back(User);
5800   }
5801 
5802   for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
5803        UE = ToReplace.end(); UI != UE; ++UI) {
5804     SDNode *User = *UI;
5805     SDNode *ResNode =
5806       CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
5807                              User->getValueType(0), User->getOperand(0),
5808                              User->getOperand(2),
5809                              User->getOperand(1));
5810 
5811     LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
5812     LLVM_DEBUG(User->dump(CurDAG));
5813     LLVM_DEBUG(dbgs() << "\nNew: ");
5814     LLVM_DEBUG(ResNode->dump(CurDAG));
5815     LLVM_DEBUG(dbgs() << "\n");
5816 
5817     ReplaceUses(User, ResNode);
5818   }
5819 }
5820 
5821 void PPCDAGToDAGISel::PeepholeCROps() {
5822   bool IsModified;
5823   do {
5824     IsModified = false;
5825     for (SDNode &Node : CurDAG->allnodes()) {
5826       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
5827       if (!MachineNode || MachineNode->use_empty())
5828         continue;
5829       SDNode *ResNode = MachineNode;
5830 
5831       bool Op1Set   = false, Op1Unset = false,
5832            Op1Not   = false,
5833            Op2Set   = false, Op2Unset = false,
5834            Op2Not   = false;
5835 
5836       unsigned Opcode = MachineNode->getMachineOpcode();
5837       switch (Opcode) {
5838       default: break;
5839       case PPC::CRAND:
5840       case PPC::CRNAND:
5841       case PPC::CROR:
5842       case PPC::CRXOR:
5843       case PPC::CRNOR:
5844       case PPC::CREQV:
5845       case PPC::CRANDC:
5846       case PPC::CRORC: {
5847         SDValue Op = MachineNode->getOperand(1);
5848         if (Op.isMachineOpcode()) {
5849           if (Op.getMachineOpcode() == PPC::CRSET)
5850             Op2Set = true;
5851           else if (Op.getMachineOpcode() == PPC::CRUNSET)
5852             Op2Unset = true;
5853           else if (Op.getMachineOpcode() == PPC::CRNOR &&
5854                    Op.getOperand(0) == Op.getOperand(1))
5855             Op2Not = true;
5856         }
5857         LLVM_FALLTHROUGH;
5858       }
5859       case PPC::BC:
5860       case PPC::BCn:
5861       case PPC::SELECT_I4:
5862       case PPC::SELECT_I8:
5863       case PPC::SELECT_F4:
5864       case PPC::SELECT_F8:
5865       case PPC::SELECT_SPE:
5866       case PPC::SELECT_SPE4:
5867       case PPC::SELECT_VRRC:
5868       case PPC::SELECT_VSFRC:
5869       case PPC::SELECT_VSSRC:
5870       case PPC::SELECT_VSRC: {
5871         SDValue Op = MachineNode->getOperand(0);
5872         if (Op.isMachineOpcode()) {
5873           if (Op.getMachineOpcode() == PPC::CRSET)
5874             Op1Set = true;
5875           else if (Op.getMachineOpcode() == PPC::CRUNSET)
5876             Op1Unset = true;
5877           else if (Op.getMachineOpcode() == PPC::CRNOR &&
5878                    Op.getOperand(0) == Op.getOperand(1))
5879             Op1Not = true;
5880         }
5881         }
5882         break;
5883       }
5884 
5885       bool SelectSwap = false;
5886       switch (Opcode) {
5887       default: break;
5888       case PPC::CRAND:
5889         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5890           // x & x = x
5891           ResNode = MachineNode->getOperand(0).getNode();
5892         else if (Op1Set)
5893           // 1 & y = y
5894           ResNode = MachineNode->getOperand(1).getNode();
5895         else if (Op2Set)
5896           // x & 1 = x
5897           ResNode = MachineNode->getOperand(0).getNode();
5898         else if (Op1Unset || Op2Unset)
5899           // x & 0 = 0 & y = 0
5900           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
5901                                            MVT::i1);
5902         else if (Op1Not)
5903           // ~x & y = andc(y, x)
5904           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
5905                                            MVT::i1, MachineNode->getOperand(1),
5906                                            MachineNode->getOperand(0).
5907                                              getOperand(0));
5908         else if (Op2Not)
5909           // x & ~y = andc(x, y)
5910           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
5911                                            MVT::i1, MachineNode->getOperand(0),
5912                                            MachineNode->getOperand(1).
5913                                              getOperand(0));
5914         else if (AllUsersSelectZero(MachineNode)) {
5915           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
5916                                            MVT::i1, MachineNode->getOperand(0),
5917                                            MachineNode->getOperand(1));
5918           SelectSwap = true;
5919         }
5920         break;
5921       case PPC::CRNAND:
5922         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5923           // nand(x, x) -> nor(x, x)
5924           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5925                                            MVT::i1, MachineNode->getOperand(0),
5926                                            MachineNode->getOperand(0));
5927         else if (Op1Set)
5928           // nand(1, y) -> nor(y, y)
5929           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5930                                            MVT::i1, MachineNode->getOperand(1),
5931                                            MachineNode->getOperand(1));
5932         else if (Op2Set)
5933           // nand(x, 1) -> nor(x, x)
5934           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5935                                            MVT::i1, MachineNode->getOperand(0),
5936                                            MachineNode->getOperand(0));
5937         else if (Op1Unset || Op2Unset)
5938           // nand(x, 0) = nand(0, y) = 1
5939           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
5940                                            MVT::i1);
5941         else if (Op1Not)
5942           // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
5943           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5944                                            MVT::i1, MachineNode->getOperand(0).
5945                                                       getOperand(0),
5946                                            MachineNode->getOperand(1));
5947         else if (Op2Not)
5948           // nand(x, ~y) = ~x | y = orc(y, x)
5949           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5950                                            MVT::i1, MachineNode->getOperand(1).
5951                                                       getOperand(0),
5952                                            MachineNode->getOperand(0));
5953         else if (AllUsersSelectZero(MachineNode)) {
5954           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
5955                                            MVT::i1, MachineNode->getOperand(0),
5956                                            MachineNode->getOperand(1));
5957           SelectSwap = true;
5958         }
5959         break;
5960       case PPC::CROR:
5961         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5962           // x | x = x
5963           ResNode = MachineNode->getOperand(0).getNode();
5964         else if (Op1Set || Op2Set)
5965           // x | 1 = 1 | y = 1
5966           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
5967                                            MVT::i1);
5968         else if (Op1Unset)
5969           // 0 | y = y
5970           ResNode = MachineNode->getOperand(1).getNode();
5971         else if (Op2Unset)
5972           // x | 0 = x
5973           ResNode = MachineNode->getOperand(0).getNode();
5974         else if (Op1Not)
5975           // ~x | y = orc(y, x)
5976           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5977                                            MVT::i1, MachineNode->getOperand(1),
5978                                            MachineNode->getOperand(0).
5979                                              getOperand(0));
5980         else if (Op2Not)
5981           // x | ~y = orc(x, y)
5982           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
5983                                            MVT::i1, MachineNode->getOperand(0),
5984                                            MachineNode->getOperand(1).
5985                                              getOperand(0));
5986         else if (AllUsersSelectZero(MachineNode)) {
5987           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
5988                                            MVT::i1, MachineNode->getOperand(0),
5989                                            MachineNode->getOperand(1));
5990           SelectSwap = true;
5991         }
5992         break;
5993       case PPC::CRXOR:
5994         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
5995           // xor(x, x) = 0
5996           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
5997                                            MVT::i1);
5998         else if (Op1Set)
5999           // xor(1, y) -> nor(y, y)
6000           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6001                                            MVT::i1, MachineNode->getOperand(1),
6002                                            MachineNode->getOperand(1));
6003         else if (Op2Set)
6004           // xor(x, 1) -> nor(x, x)
6005           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6006                                            MVT::i1, MachineNode->getOperand(0),
6007                                            MachineNode->getOperand(0));
6008         else if (Op1Unset)
6009           // xor(0, y) = y
6010           ResNode = MachineNode->getOperand(1).getNode();
6011         else if (Op2Unset)
6012           // xor(x, 0) = x
6013           ResNode = MachineNode->getOperand(0).getNode();
6014         else if (Op1Not)
6015           // xor(~x, y) = eqv(x, y)
6016           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
6017                                            MVT::i1, MachineNode->getOperand(0).
6018                                                       getOperand(0),
6019                                            MachineNode->getOperand(1));
6020         else if (Op2Not)
6021           // xor(x, ~y) = eqv(x, y)
6022           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
6023                                            MVT::i1, MachineNode->getOperand(0),
6024                                            MachineNode->getOperand(1).
6025                                              getOperand(0));
6026         else if (AllUsersSelectZero(MachineNode)) {
6027           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
6028                                            MVT::i1, MachineNode->getOperand(0),
6029                                            MachineNode->getOperand(1));
6030           SelectSwap = true;
6031         }
6032         break;
6033       case PPC::CRNOR:
6034         if (Op1Set || Op2Set)
6035           // nor(1, y) -> 0
6036           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6037                                            MVT::i1);
6038         else if (Op1Unset)
6039           // nor(0, y) = ~y -> nor(y, y)
6040           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6041                                            MVT::i1, MachineNode->getOperand(1),
6042                                            MachineNode->getOperand(1));
6043         else if (Op2Unset)
6044           // nor(x, 0) = ~x
6045           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6046                                            MVT::i1, MachineNode->getOperand(0),
6047                                            MachineNode->getOperand(0));
6048         else if (Op1Not)
6049           // nor(~x, y) = andc(x, y)
6050           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6051                                            MVT::i1, MachineNode->getOperand(0).
6052                                                       getOperand(0),
6053                                            MachineNode->getOperand(1));
6054         else if (Op2Not)
6055           // nor(x, ~y) = andc(y, x)
6056           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6057                                            MVT::i1, MachineNode->getOperand(1).
6058                                                       getOperand(0),
6059                                            MachineNode->getOperand(0));
6060         else if (AllUsersSelectZero(MachineNode)) {
6061           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
6062                                            MVT::i1, MachineNode->getOperand(0),
6063                                            MachineNode->getOperand(1));
6064           SelectSwap = true;
6065         }
6066         break;
6067       case PPC::CREQV:
6068         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6069           // eqv(x, x) = 1
6070           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
6071                                            MVT::i1);
6072         else if (Op1Set)
6073           // eqv(1, y) = y
6074           ResNode = MachineNode->getOperand(1).getNode();
6075         else if (Op2Set)
6076           // eqv(x, 1) = x
6077           ResNode = MachineNode->getOperand(0).getNode();
6078         else if (Op1Unset)
6079           // eqv(0, y) = ~y -> nor(y, y)
6080           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6081                                            MVT::i1, MachineNode->getOperand(1),
6082                                            MachineNode->getOperand(1));
6083         else if (Op2Unset)
6084           // eqv(x, 0) = ~x
6085           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6086                                            MVT::i1, MachineNode->getOperand(0),
6087                                            MachineNode->getOperand(0));
6088         else if (Op1Not)
6089           // eqv(~x, y) = xor(x, y)
6090           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
6091                                            MVT::i1, MachineNode->getOperand(0).
6092                                                       getOperand(0),
6093                                            MachineNode->getOperand(1));
6094         else if (Op2Not)
6095           // eqv(x, ~y) = xor(x, y)
6096           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
6097                                            MVT::i1, MachineNode->getOperand(0),
6098                                            MachineNode->getOperand(1).
6099                                              getOperand(0));
6100         else if (AllUsersSelectZero(MachineNode)) {
6101           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
6102                                            MVT::i1, MachineNode->getOperand(0),
6103                                            MachineNode->getOperand(1));
6104           SelectSwap = true;
6105         }
6106         break;
6107       case PPC::CRANDC:
6108         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6109           // andc(x, x) = 0
6110           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6111                                            MVT::i1);
6112         else if (Op1Set)
6113           // andc(1, y) = ~y
6114           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6115                                            MVT::i1, MachineNode->getOperand(1),
6116                                            MachineNode->getOperand(1));
6117         else if (Op1Unset || Op2Set)
6118           // andc(0, y) = andc(x, 1) = 0
6119           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
6120                                            MVT::i1);
6121         else if (Op2Unset)
6122           // andc(x, 0) = x
6123           ResNode = MachineNode->getOperand(0).getNode();
6124         else if (Op1Not)
6125           // andc(~x, y) = ~(x | y) = nor(x, y)
6126           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6127                                            MVT::i1, MachineNode->getOperand(0).
6128                                                       getOperand(0),
6129                                            MachineNode->getOperand(1));
6130         else if (Op2Not)
6131           // andc(x, ~y) = x & y
6132           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
6133                                            MVT::i1, MachineNode->getOperand(0),
6134                                            MachineNode->getOperand(1).
6135                                              getOperand(0));
6136         else if (AllUsersSelectZero(MachineNode)) {
6137           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
6138                                            MVT::i1, MachineNode->getOperand(1),
6139                                            MachineNode->getOperand(0));
6140           SelectSwap = true;
6141         }
6142         break;
6143       case PPC::CRORC:
6144         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
6145           // orc(x, x) = 1
6146           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
6147                                            MVT::i1);
6148         else if (Op1Set || Op2Unset)
6149           // orc(1, y) = orc(x, 0) = 1
6150           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
6151                                            MVT::i1);
6152         else if (Op2Set)
6153           // orc(x, 1) = x
6154           ResNode = MachineNode->getOperand(0).getNode();
6155         else if (Op1Unset)
6156           // orc(0, y) = ~y
6157           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
6158                                            MVT::i1, MachineNode->getOperand(1),
6159                                            MachineNode->getOperand(1));
6160         else if (Op1Not)
6161           // orc(~x, y) = ~(x & y) = nand(x, y)
6162           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
6163                                            MVT::i1, MachineNode->getOperand(0).
6164                                                       getOperand(0),
6165                                            MachineNode->getOperand(1));
6166         else if (Op2Not)
6167           // orc(x, ~y) = x | y
6168           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
6169                                            MVT::i1, MachineNode->getOperand(0),
6170                                            MachineNode->getOperand(1).
6171                                              getOperand(0));
6172         else if (AllUsersSelectZero(MachineNode)) {
6173           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
6174                                            MVT::i1, MachineNode->getOperand(1),
6175                                            MachineNode->getOperand(0));
6176           SelectSwap = true;
6177         }
6178         break;
6179       case PPC::SELECT_I4:
6180       case PPC::SELECT_I8:
6181       case PPC::SELECT_F4:
6182       case PPC::SELECT_F8:
6183       case PPC::SELECT_SPE:
6184       case PPC::SELECT_SPE4:
6185       case PPC::SELECT_VRRC:
6186       case PPC::SELECT_VSFRC:
6187       case PPC::SELECT_VSSRC:
6188       case PPC::SELECT_VSRC:
6189         if (Op1Set)
6190           ResNode = MachineNode->getOperand(1).getNode();
6191         else if (Op1Unset)
6192           ResNode = MachineNode->getOperand(2).getNode();
6193         else if (Op1Not)
6194           ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
6195                                            SDLoc(MachineNode),
6196                                            MachineNode->getValueType(0),
6197                                            MachineNode->getOperand(0).
6198                                              getOperand(0),
6199                                            MachineNode->getOperand(2),
6200                                            MachineNode->getOperand(1));
6201         break;
6202       case PPC::BC:
6203       case PPC::BCn:
6204         if (Op1Not)
6205           ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
6206                                                                PPC::BC,
6207                                            SDLoc(MachineNode),
6208                                            MVT::Other,
6209                                            MachineNode->getOperand(0).
6210                                              getOperand(0),
6211                                            MachineNode->getOperand(1),
6212                                            MachineNode->getOperand(2));
6213         // FIXME: Handle Op1Set, Op1Unset here too.
6214         break;
6215       }
6216 
6217       // If we're inverting this node because it is used only by selects that
6218       // we'd like to swap, then swap the selects before the node replacement.
6219       if (SelectSwap)
6220         SwapAllSelectUsers(MachineNode);
6221 
6222       if (ResNode != MachineNode) {
6223         LLVM_DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
6224         LLVM_DEBUG(MachineNode->dump(CurDAG));
6225         LLVM_DEBUG(dbgs() << "\nNew: ");
6226         LLVM_DEBUG(ResNode->dump(CurDAG));
6227         LLVM_DEBUG(dbgs() << "\n");
6228 
6229         ReplaceUses(MachineNode, ResNode);
6230         IsModified = true;
6231       }
6232     }
6233     if (IsModified)
6234       CurDAG->RemoveDeadNodes();
6235   } while (IsModified);
6236 }
6237 
6238 // Gather the set of 32-bit operations that are known to have their
6239 // higher-order 32 bits zero, where ToPromote contains all such operations.
6240 static bool PeepholePPC64ZExtGather(SDValue Op32,
6241                                     SmallPtrSetImpl<SDNode *> &ToPromote) {
6242   if (!Op32.isMachineOpcode())
6243     return false;
6244 
6245   // First, check for the "frontier" instructions (those that will clear the
6246   // higher-order 32 bits.
6247 
6248   // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
6249   // around. If it does not, then these instructions will clear the
6250   // higher-order bits.
6251   if ((Op32.getMachineOpcode() == PPC::RLWINM ||
6252        Op32.getMachineOpcode() == PPC::RLWNM) &&
6253       Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
6254     ToPromote.insert(Op32.getNode());
6255     return true;
6256   }
6257 
6258   // SLW and SRW always clear the higher-order bits.
6259   if (Op32.getMachineOpcode() == PPC::SLW ||
6260       Op32.getMachineOpcode() == PPC::SRW) {
6261     ToPromote.insert(Op32.getNode());
6262     return true;
6263   }
6264 
6265   // For LI and LIS, we need the immediate to be positive (so that it is not
6266   // sign extended).
6267   if (Op32.getMachineOpcode() == PPC::LI ||
6268       Op32.getMachineOpcode() == PPC::LIS) {
6269     if (!isUInt<15>(Op32.getConstantOperandVal(0)))
6270       return false;
6271 
6272     ToPromote.insert(Op32.getNode());
6273     return true;
6274   }
6275 
6276   // LHBRX and LWBRX always clear the higher-order bits.
6277   if (Op32.getMachineOpcode() == PPC::LHBRX ||
6278       Op32.getMachineOpcode() == PPC::LWBRX) {
6279     ToPromote.insert(Op32.getNode());
6280     return true;
6281   }
6282 
6283   // CNT[LT]ZW always produce a 64-bit value in [0,32], and so is zero extended.
6284   if (Op32.getMachineOpcode() == PPC::CNTLZW ||
6285       Op32.getMachineOpcode() == PPC::CNTTZW) {
6286     ToPromote.insert(Op32.getNode());
6287     return true;
6288   }
6289 
6290   // Next, check for those instructions we can look through.
6291 
6292   // Assuming the mask does not wrap around, then the higher-order bits are
6293   // taken directly from the first operand.
6294   if (Op32.getMachineOpcode() == PPC::RLWIMI &&
6295       Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
6296     SmallPtrSet<SDNode *, 16> ToPromote1;
6297     if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
6298       return false;
6299 
6300     ToPromote.insert(Op32.getNode());
6301     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
6302     return true;
6303   }
6304 
6305   // For OR, the higher-order bits are zero if that is true for both operands.
6306   // For SELECT_I4, the same is true (but the relevant operand numbers are
6307   // shifted by 1).
6308   if (Op32.getMachineOpcode() == PPC::OR ||
6309       Op32.getMachineOpcode() == PPC::SELECT_I4) {
6310     unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
6311     SmallPtrSet<SDNode *, 16> ToPromote1;
6312     if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
6313       return false;
6314     if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
6315       return false;
6316 
6317     ToPromote.insert(Op32.getNode());
6318     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
6319     return true;
6320   }
6321 
6322   // For ORI and ORIS, we need the higher-order bits of the first operand to be
6323   // zero, and also for the constant to be positive (so that it is not sign
6324   // extended).
6325   if (Op32.getMachineOpcode() == PPC::ORI ||
6326       Op32.getMachineOpcode() == PPC::ORIS) {
6327     SmallPtrSet<SDNode *, 16> ToPromote1;
6328     if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
6329       return false;
6330     if (!isUInt<15>(Op32.getConstantOperandVal(1)))
6331       return false;
6332 
6333     ToPromote.insert(Op32.getNode());
6334     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
6335     return true;
6336   }
6337 
6338   // The higher-order bits of AND are zero if that is true for at least one of
6339   // the operands.
6340   if (Op32.getMachineOpcode() == PPC::AND) {
6341     SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
6342     bool Op0OK =
6343       PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
6344     bool Op1OK =
6345       PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
6346     if (!Op0OK && !Op1OK)
6347       return false;
6348 
6349     ToPromote.insert(Op32.getNode());
6350 
6351     if (Op0OK)
6352       ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
6353 
6354     if (Op1OK)
6355       ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
6356 
6357     return true;
6358   }
6359 
6360   // For ANDI and ANDIS, the higher-order bits are zero if either that is true
6361   // of the first operand, or if the second operand is positive (so that it is
6362   // not sign extended).
6363   if (Op32.getMachineOpcode() == PPC::ANDI_rec ||
6364       Op32.getMachineOpcode() == PPC::ANDIS_rec) {
6365     SmallPtrSet<SDNode *, 16> ToPromote1;
6366     bool Op0OK =
6367       PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
6368     bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
6369     if (!Op0OK && !Op1OK)
6370       return false;
6371 
6372     ToPromote.insert(Op32.getNode());
6373 
6374     if (Op0OK)
6375       ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
6376 
6377     return true;
6378   }
6379 
6380   return false;
6381 }
6382 
6383 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
6384   if (!Subtarget->isPPC64())
6385     return;
6386 
6387   // When we zero-extend from i32 to i64, we use a pattern like this:
6388   // def : Pat<(i64 (zext i32:$in)),
6389   //           (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
6390   //                   0, 32)>;
6391   // There are several 32-bit shift/rotate instructions, however, that will
6392   // clear the higher-order bits of their output, rendering the RLDICL
6393   // unnecessary. When that happens, we remove it here, and redefine the
6394   // relevant 32-bit operation to be a 64-bit operation.
6395 
6396   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
6397 
6398   bool MadeChange = false;
6399   while (Position != CurDAG->allnodes_begin()) {
6400     SDNode *N = &*--Position;
6401     // Skip dead nodes and any non-machine opcodes.
6402     if (N->use_empty() || !N->isMachineOpcode())
6403       continue;
6404 
6405     if (N->getMachineOpcode() != PPC::RLDICL)
6406       continue;
6407 
6408     if (N->getConstantOperandVal(1) != 0 ||
6409         N->getConstantOperandVal(2) != 32)
6410       continue;
6411 
6412     SDValue ISR = N->getOperand(0);
6413     if (!ISR.isMachineOpcode() ||
6414         ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
6415       continue;
6416 
6417     if (!ISR.hasOneUse())
6418       continue;
6419 
6420     if (ISR.getConstantOperandVal(2) != PPC::sub_32)
6421       continue;
6422 
6423     SDValue IDef = ISR.getOperand(0);
6424     if (!IDef.isMachineOpcode() ||
6425         IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
6426       continue;
6427 
6428     // We now know that we're looking at a canonical i32 -> i64 zext. See if we
6429     // can get rid of it.
6430 
6431     SDValue Op32 = ISR->getOperand(1);
6432     if (!Op32.isMachineOpcode())
6433       continue;
6434 
6435     // There are some 32-bit instructions that always clear the high-order 32
6436     // bits, there are also some instructions (like AND) that we can look
6437     // through.
6438     SmallPtrSet<SDNode *, 16> ToPromote;
6439     if (!PeepholePPC64ZExtGather(Op32, ToPromote))
6440       continue;
6441 
6442     // If the ToPromote set contains nodes that have uses outside of the set
6443     // (except for the original INSERT_SUBREG), then abort the transformation.
6444     bool OutsideUse = false;
6445     for (SDNode *PN : ToPromote) {
6446       for (SDNode *UN : PN->uses()) {
6447         if (!ToPromote.count(UN) && UN != ISR.getNode()) {
6448           OutsideUse = true;
6449           break;
6450         }
6451       }
6452 
6453       if (OutsideUse)
6454         break;
6455     }
6456     if (OutsideUse)
6457       continue;
6458 
6459     MadeChange = true;
6460 
6461     // We now know that this zero extension can be removed by promoting to
6462     // nodes in ToPromote to 64-bit operations, where for operations in the
6463     // frontier of the set, we need to insert INSERT_SUBREGs for their
6464     // operands.
6465     for (SDNode *PN : ToPromote) {
6466       unsigned NewOpcode;
6467       switch (PN->getMachineOpcode()) {
6468       default:
6469         llvm_unreachable("Don't know the 64-bit variant of this instruction");
6470       case PPC::RLWINM:    NewOpcode = PPC::RLWINM8; break;
6471       case PPC::RLWNM:     NewOpcode = PPC::RLWNM8; break;
6472       case PPC::SLW:       NewOpcode = PPC::SLW8; break;
6473       case PPC::SRW:       NewOpcode = PPC::SRW8; break;
6474       case PPC::LI:        NewOpcode = PPC::LI8; break;
6475       case PPC::LIS:       NewOpcode = PPC::LIS8; break;
6476       case PPC::LHBRX:     NewOpcode = PPC::LHBRX8; break;
6477       case PPC::LWBRX:     NewOpcode = PPC::LWBRX8; break;
6478       case PPC::CNTLZW:    NewOpcode = PPC::CNTLZW8; break;
6479       case PPC::CNTTZW:    NewOpcode = PPC::CNTTZW8; break;
6480       case PPC::RLWIMI:    NewOpcode = PPC::RLWIMI8; break;
6481       case PPC::OR:        NewOpcode = PPC::OR8; break;
6482       case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
6483       case PPC::ORI:       NewOpcode = PPC::ORI8; break;
6484       case PPC::ORIS:      NewOpcode = PPC::ORIS8; break;
6485       case PPC::AND:       NewOpcode = PPC::AND8; break;
6486       case PPC::ANDI_rec:
6487         NewOpcode = PPC::ANDI8_rec;
6488         break;
6489       case PPC::ANDIS_rec:
6490         NewOpcode = PPC::ANDIS8_rec;
6491         break;
6492       }
6493 
6494       // Note: During the replacement process, the nodes will be in an
6495       // inconsistent state (some instructions will have operands with values
6496       // of the wrong type). Once done, however, everything should be right
6497       // again.
6498 
6499       SmallVector<SDValue, 4> Ops;
6500       for (const SDValue &V : PN->ops()) {
6501         if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
6502             !isa<ConstantSDNode>(V)) {
6503           SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
6504           SDNode *ReplOp =
6505             CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
6506                                    ISR.getNode()->getVTList(), ReplOpOps);
6507           Ops.push_back(SDValue(ReplOp, 0));
6508         } else {
6509           Ops.push_back(V);
6510         }
6511       }
6512 
6513       // Because all to-be-promoted nodes only have users that are other
6514       // promoted nodes (or the original INSERT_SUBREG), we can safely replace
6515       // the i32 result value type with i64.
6516 
6517       SmallVector<EVT, 2> NewVTs;
6518       SDVTList VTs = PN->getVTList();
6519       for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
6520         if (VTs.VTs[i] == MVT::i32)
6521           NewVTs.push_back(MVT::i64);
6522         else
6523           NewVTs.push_back(VTs.VTs[i]);
6524 
6525       LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld:    ");
6526       LLVM_DEBUG(PN->dump(CurDAG));
6527 
6528       CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
6529 
6530       LLVM_DEBUG(dbgs() << "\nNew: ");
6531       LLVM_DEBUG(PN->dump(CurDAG));
6532       LLVM_DEBUG(dbgs() << "\n");
6533     }
6534 
6535     // Now we replace the original zero extend and its associated INSERT_SUBREG
6536     // with the value feeding the INSERT_SUBREG (which has now been promoted to
6537     // return an i64).
6538 
6539     LLVM_DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld:    ");
6540     LLVM_DEBUG(N->dump(CurDAG));
6541     LLVM_DEBUG(dbgs() << "\nNew: ");
6542     LLVM_DEBUG(Op32.getNode()->dump(CurDAG));
6543     LLVM_DEBUG(dbgs() << "\n");
6544 
6545     ReplaceUses(N, Op32.getNode());
6546   }
6547 
6548   if (MadeChange)
6549     CurDAG->RemoveDeadNodes();
6550 }
6551 
6552 void PPCDAGToDAGISel::PeepholePPC64() {
6553   SelectionDAG::allnodes_iterator Position = CurDAG->allnodes_end();
6554 
6555   while (Position != CurDAG->allnodes_begin()) {
6556     SDNode *N = &*--Position;
6557     // Skip dead nodes and any non-machine opcodes.
6558     if (N->use_empty() || !N->isMachineOpcode())
6559       continue;
6560 
6561     unsigned FirstOp;
6562     unsigned StorageOpcode = N->getMachineOpcode();
6563     bool RequiresMod4Offset = false;
6564 
6565     switch (StorageOpcode) {
6566     default: continue;
6567 
6568     case PPC::LWA:
6569     case PPC::LD:
6570     case PPC::DFLOADf64:
6571     case PPC::DFLOADf32:
6572       RequiresMod4Offset = true;
6573       LLVM_FALLTHROUGH;
6574     case PPC::LBZ:
6575     case PPC::LBZ8:
6576     case PPC::LFD:
6577     case PPC::LFS:
6578     case PPC::LHA:
6579     case PPC::LHA8:
6580     case PPC::LHZ:
6581     case PPC::LHZ8:
6582     case PPC::LWZ:
6583     case PPC::LWZ8:
6584       FirstOp = 0;
6585       break;
6586 
6587     case PPC::STD:
6588     case PPC::DFSTOREf64:
6589     case PPC::DFSTOREf32:
6590       RequiresMod4Offset = true;
6591       LLVM_FALLTHROUGH;
6592     case PPC::STB:
6593     case PPC::STB8:
6594     case PPC::STFD:
6595     case PPC::STFS:
6596     case PPC::STH:
6597     case PPC::STH8:
6598     case PPC::STW:
6599     case PPC::STW8:
6600       FirstOp = 1;
6601       break;
6602     }
6603 
6604     // If this is a load or store with a zero offset, or within the alignment,
6605     // we may be able to fold an add-immediate into the memory operation.
6606     // The check against alignment is below, as it can't occur until we check
6607     // the arguments to N
6608     if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
6609       continue;
6610 
6611     SDValue Base = N->getOperand(FirstOp + 1);
6612     if (!Base.isMachineOpcode())
6613       continue;
6614 
6615     unsigned Flags = 0;
6616     bool ReplaceFlags = true;
6617 
6618     // When the feeding operation is an add-immediate of some sort,
6619     // determine whether we need to add relocation information to the
6620     // target flags on the immediate operand when we fold it into the
6621     // load instruction.
6622     //
6623     // For something like ADDItocL, the relocation information is
6624     // inferred from the opcode; when we process it in the AsmPrinter,
6625     // we add the necessary relocation there.  A load, though, can receive
6626     // relocation from various flavors of ADDIxxx, so we need to carry
6627     // the relocation information in the target flags.
6628     switch (Base.getMachineOpcode()) {
6629     default: continue;
6630 
6631     case PPC::ADDI8:
6632     case PPC::ADDI:
6633       // In some cases (such as TLS) the relocation information
6634       // is already in place on the operand, so copying the operand
6635       // is sufficient.
6636       ReplaceFlags = false;
6637       // For these cases, the immediate may not be divisible by 4, in
6638       // which case the fold is illegal for DS-form instructions.  (The
6639       // other cases provide aligned addresses and are always safe.)
6640       if (RequiresMod4Offset &&
6641           (!isa<ConstantSDNode>(Base.getOperand(1)) ||
6642            Base.getConstantOperandVal(1) % 4 != 0))
6643         continue;
6644       break;
6645     case PPC::ADDIdtprelL:
6646       Flags = PPCII::MO_DTPREL_LO;
6647       break;
6648     case PPC::ADDItlsldL:
6649       Flags = PPCII::MO_TLSLD_LO;
6650       break;
6651     case PPC::ADDItocL:
6652       Flags = PPCII::MO_TOC_LO;
6653       break;
6654     }
6655 
6656     SDValue ImmOpnd = Base.getOperand(1);
6657 
6658     // On PPC64, the TOC base pointer is guaranteed by the ABI only to have
6659     // 8-byte alignment, and so we can only use offsets less than 8 (otherwise,
6660     // we might have needed different @ha relocation values for the offset
6661     // pointers).
6662     int MaxDisplacement = 7;
6663     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
6664       const GlobalValue *GV = GA->getGlobal();
6665       Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout());
6666       MaxDisplacement = std::min((int)Alignment.value() - 1, MaxDisplacement);
6667     }
6668 
6669     bool UpdateHBase = false;
6670     SDValue HBase = Base.getOperand(0);
6671 
6672     int Offset = N->getConstantOperandVal(FirstOp);
6673     if (ReplaceFlags) {
6674       if (Offset < 0 || Offset > MaxDisplacement) {
6675         // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only
6676         // one use, then we can do this for any offset, we just need to also
6677         // update the offset (i.e. the symbol addend) on the addis also.
6678         if (Base.getMachineOpcode() != PPC::ADDItocL)
6679           continue;
6680 
6681         if (!HBase.isMachineOpcode() ||
6682             HBase.getMachineOpcode() != PPC::ADDIStocHA8)
6683           continue;
6684 
6685         if (!Base.hasOneUse() || !HBase.hasOneUse())
6686           continue;
6687 
6688         SDValue HImmOpnd = HBase.getOperand(1);
6689         if (HImmOpnd != ImmOpnd)
6690           continue;
6691 
6692         UpdateHBase = true;
6693       }
6694     } else {
6695       // If we're directly folding the addend from an addi instruction, then:
6696       //  1. In general, the offset on the memory access must be zero.
6697       //  2. If the addend is a constant, then it can be combined with a
6698       //     non-zero offset, but only if the result meets the encoding
6699       //     requirements.
6700       if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) {
6701         Offset += C->getSExtValue();
6702 
6703         if (RequiresMod4Offset && (Offset % 4) != 0)
6704           continue;
6705 
6706         if (!isInt<16>(Offset))
6707           continue;
6708 
6709         ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd),
6710                                             ImmOpnd.getValueType());
6711       } else if (Offset != 0) {
6712         continue;
6713       }
6714     }
6715 
6716     // We found an opportunity.  Reverse the operands from the add
6717     // immediate and substitute them into the load or store.  If
6718     // needed, update the target flags for the immediate operand to
6719     // reflect the necessary relocation information.
6720     LLVM_DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
6721     LLVM_DEBUG(Base->dump(CurDAG));
6722     LLVM_DEBUG(dbgs() << "\nN: ");
6723     LLVM_DEBUG(N->dump(CurDAG));
6724     LLVM_DEBUG(dbgs() << "\n");
6725 
6726     // If the relocation information isn't already present on the
6727     // immediate operand, add it now.
6728     if (ReplaceFlags) {
6729       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
6730         SDLoc dl(GA);
6731         const GlobalValue *GV = GA->getGlobal();
6732         Align Alignment = GV->getPointerAlignment(CurDAG->getDataLayout());
6733         // We can't perform this optimization for data whose alignment
6734         // is insufficient for the instruction encoding.
6735         if (Alignment < 4 && (RequiresMod4Offset || (Offset % 4) != 0)) {
6736           LLVM_DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
6737           continue;
6738         }
6739         ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
6740       } else if (ConstantPoolSDNode *CP =
6741                  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
6742         const Constant *C = CP->getConstVal();
6743         ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64, CP->getAlign(),
6744                                                 Offset, Flags);
6745       }
6746     }
6747 
6748     if (FirstOp == 1) // Store
6749       (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
6750                                        Base.getOperand(0), N->getOperand(3));
6751     else // Load
6752       (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
6753                                        N->getOperand(2));
6754 
6755     if (UpdateHBase)
6756       (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0),
6757                                        ImmOpnd);
6758 
6759     // The add-immediate may now be dead, in which case remove it.
6760     if (Base.getNode()->use_empty())
6761       CurDAG->RemoveDeadNode(Base.getNode());
6762   }
6763 }
6764 
6765 /// createPPCISelDag - This pass converts a legalized DAG into a
6766 /// PowerPC-specific DAG, ready for instruction scheduling.
6767 ///
6768 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM,
6769                                      CodeGenOpt::Level OptLevel) {
6770   return new PPCDAGToDAGISel(TM, OptLevel);
6771 }
6772