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