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