1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "PPC.h"
16 #include "MCTargetDesc/PPCPredicates.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCTargetMachine.h"
19 #include "llvm/Analysis/BranchProbabilityInfo.h"
20 #include "llvm/CodeGen/FunctionLoweringInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/CodeGen/SelectionDAGISel.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/Function.h"
28 #include "llvm/IR/GlobalAlias.h"
29 #include "llvm/IR/GlobalValue.h"
30 #include "llvm/IR/GlobalVariable.h"
31 #include "llvm/IR/Intrinsics.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/MathExtras.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Target/TargetOptions.h"
39 using namespace llvm;
40 
41 #define DEBUG_TYPE "ppc-codegen"
42 
43 // FIXME: Remove this once the bug has been fixed!
44 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
45 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
46 
47 static cl::opt<bool>
48     UseBitPermRewriter("ppc-use-bit-perm-rewriter", cl::init(true),
49                        cl::desc("use aggressive ppc isel for bit permutations"),
50                        cl::Hidden);
51 static cl::opt<bool> BPermRewriterNoMasking(
52     "ppc-bit-perm-rewriter-stress-rotates",
53     cl::desc("stress rotate selection in aggressive ppc isel for "
54              "bit permutations"),
55     cl::Hidden);
56 
57 static cl::opt<bool> EnableBranchHint(
58   "ppc-use-branch-hint", cl::init(true),
59     cl::desc("Enable static hinting of branches on ppc"),
60     cl::Hidden);
61 
62 namespace {
63   //===--------------------------------------------------------------------===//
64   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
65   /// instructions for SelectionDAG operations.
66   ///
67   class PPCDAGToDAGISel : public SelectionDAGISel {
68     const PPCTargetMachine &TM;
69     const PPCSubtarget *PPCSubTarget;
70     const PPCTargetLowering *PPCLowering;
71     unsigned GlobalBaseReg;
72   public:
73     explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
74         : SelectionDAGISel(tm), TM(tm) {}
75 
76     bool runOnMachineFunction(MachineFunction &MF) override {
77       // Make sure we re-emit a set of the global base reg if necessary
78       GlobalBaseReg = 0;
79       PPCSubTarget = &MF.getSubtarget<PPCSubtarget>();
80       PPCLowering = PPCSubTarget->getTargetLowering();
81       SelectionDAGISel::runOnMachineFunction(MF);
82 
83       if (!PPCSubTarget->isSVR4ABI())
84         InsertVRSaveCode(MF);
85 
86       return true;
87     }
88 
89     void PreprocessISelDAG() override;
90     void PostprocessISelDAG() override;
91 
92     /// getI32Imm - Return a target constant with the specified value, of type
93     /// i32.
94     inline SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
95       return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
96     }
97 
98     /// getI64Imm - Return a target constant with the specified value, of type
99     /// i64.
100     inline SDValue getI64Imm(uint64_t Imm, const SDLoc &dl) {
101       return CurDAG->getTargetConstant(Imm, dl, MVT::i64);
102     }
103 
104     /// getSmallIPtrImm - Return a target constant of pointer type.
105     inline SDValue getSmallIPtrImm(unsigned Imm, const SDLoc &dl) {
106       return CurDAG->getTargetConstant(
107           Imm, dl, PPCLowering->getPointerTy(CurDAG->getDataLayout()));
108     }
109 
110     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
111     /// rotate and mask opcode and mask operation.
112     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
113                                 unsigned &SH, unsigned &MB, unsigned &ME);
114 
115     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
116     /// base register.  Return the virtual register that holds this value.
117     SDNode *getGlobalBaseReg();
118 
119     void selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset = 0);
120 
121     // Select - Convert the specified operand from a target-independent to a
122     // target-specific node if it hasn't already been changed.
123     void Select(SDNode *N) override;
124 
125     bool tryBitfieldInsert(SDNode *N);
126     bool tryBitPermutation(SDNode *N);
127 
128     /// SelectCC - Select a comparison of the specified values with the
129     /// specified condition code, returning the CR# of the expression.
130     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
131                      const SDLoc &dl);
132 
133     /// SelectAddrImm - Returns true if the address N can be represented by
134     /// a base register plus a signed 16-bit displacement [r+imm].
135     bool SelectAddrImm(SDValue N, SDValue &Disp,
136                        SDValue &Base) {
137       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
138     }
139 
140     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
141     /// immediate field.  Note that the operand at this point is already the
142     /// result of a prior SelectAddressRegImm call.
143     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
144       if (N.getOpcode() == ISD::TargetConstant ||
145           N.getOpcode() == ISD::TargetGlobalAddress) {
146         Out = N;
147         return true;
148       }
149 
150       return false;
151     }
152 
153     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
154     /// represented as an indexed [r+r] operation.  Returns false if it can
155     /// be represented by [r+imm], which are preferred.
156     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
157       return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
158     }
159 
160     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
161     /// represented as an indexed [r+r] operation.
162     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
163       return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
164     }
165 
166     /// SelectAddrImmX4 - Returns true if the address N can be represented by
167     /// a base register plus a signed 16-bit displacement that is a multiple of 4.
168     /// Suitable for use by STD and friends.
169     bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
170       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
171     }
172 
173     // Select an address into a single register.
174     bool SelectAddr(SDValue N, SDValue &Base) {
175       Base = N;
176       return true;
177     }
178 
179     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
180     /// inline asm expressions.  It is always correct to compute the value into
181     /// a register.  The case of adding a (possibly relocatable) constant to a
182     /// register can be improved, but it is wrong to substitute Reg+Reg for
183     /// Reg in an asm, because the load or store opcode would have to change.
184     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
185                                       unsigned ConstraintID,
186                                       std::vector<SDValue> &OutOps) override {
187 
188       switch(ConstraintID) {
189       default:
190         errs() << "ConstraintID: " << ConstraintID << "\n";
191         llvm_unreachable("Unexpected asm memory constraint");
192       case InlineAsm::Constraint_es:
193       case InlineAsm::Constraint_i:
194       case InlineAsm::Constraint_m:
195       case InlineAsm::Constraint_o:
196       case InlineAsm::Constraint_Q:
197       case InlineAsm::Constraint_Z:
198       case InlineAsm::Constraint_Zy:
199         // We need to make sure that this one operand does not end up in r0
200         // (because we might end up lowering this as 0(%op)).
201         const TargetRegisterInfo *TRI = PPCSubTarget->getRegisterInfo();
202         const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
203         SDLoc dl(Op);
204         SDValue RC = CurDAG->getTargetConstant(TRC->getID(), dl, MVT::i32);
205         SDValue NewOp =
206           SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
207                                          dl, Op.getValueType(),
208                                          Op, RC), 0);
209 
210         OutOps.push_back(NewOp);
211         return false;
212       }
213       return true;
214     }
215 
216     void InsertVRSaveCode(MachineFunction &MF);
217 
218     StringRef getPassName() const override {
219       return "PowerPC DAG->DAG Pattern Instruction Selection";
220     }
221 
222 // Include the pieces autogenerated from the target description.
223 #include "PPCGenDAGISel.inc"
224 
225 private:
226     bool trySETCC(SDNode *N);
227 
228     void PeepholePPC64();
229     void PeepholePPC64ZExt();
230     void PeepholeCROps();
231 
232     SDValue combineToCMPB(SDNode *N);
233     void foldBoolExts(SDValue &Res, SDNode *&N);
234 
235     bool AllUsersSelectZero(SDNode *N);
236     void SwapAllSelectUsers(SDNode *N);
237 
238     void transferMemOperands(SDNode *N, SDNode *Result);
239   };
240 }
241 
242 /// InsertVRSaveCode - Once the entire function has been instruction selected,
243 /// all virtual registers are created and all machine instructions are built,
244 /// check to see if we need to save/restore VRSAVE.  If so, do it.
245 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
246   // Check to see if this function uses vector registers, which means we have to
247   // save and restore the VRSAVE register and update it with the regs we use.
248   //
249   // In this case, there will be virtual registers of vector type created
250   // by the scheduler.  Detect them now.
251   bool HasVectorVReg = false;
252   for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
253     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
254     if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
255       HasVectorVReg = true;
256       break;
257     }
258   }
259   if (!HasVectorVReg) return;  // nothing to do.
260 
261   // If we have a vector register, we want to emit code into the entry and exit
262   // blocks to save and restore the VRSAVE register.  We do this here (instead
263   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
264   //
265   // 1. This (trivially) reduces the load on the register allocator, by not
266   //    having to represent the live range of the VRSAVE register.
267   // 2. This (more significantly) allows us to create a temporary virtual
268   //    register to hold the saved VRSAVE value, allowing this temporary to be
269   //    register allocated, instead of forcing it to be spilled to the stack.
270 
271   // Create two vregs - one to hold the VRSAVE register that is live-in to the
272   // function and one for the value after having bits or'd into it.
273   unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
274   unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
275 
276   const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
277   MachineBasicBlock &EntryBB = *Fn.begin();
278   DebugLoc dl;
279   // Emit the following code into the entry block:
280   // InVRSAVE = MFVRSAVE
281   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
282   // MTVRSAVE UpdatedVRSAVE
283   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
284   BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
285   BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
286           UpdatedVRSAVE).addReg(InVRSAVE);
287   BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
288 
289   // Find all return blocks, outputting a restore in each epilog.
290   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
291     if (BB->isReturnBlock()) {
292       IP = BB->end(); --IP;
293 
294       // Skip over all terminator instructions, which are part of the return
295       // sequence.
296       MachineBasicBlock::iterator I2 = IP;
297       while (I2 != BB->begin() && (--I2)->isTerminator())
298         IP = I2;
299 
300       // Emit: MTVRSAVE InVRSave
301       BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
302     }
303   }
304 }
305 
306 
307 /// getGlobalBaseReg - Output the instructions required to put the
308 /// base address to use for accessing globals into a register.
309 ///
310 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
311   if (!GlobalBaseReg) {
312     const TargetInstrInfo &TII = *PPCSubTarget->getInstrInfo();
313     // Insert the set of GlobalBaseReg into the first MBB of the function
314     MachineBasicBlock &FirstMBB = MF->front();
315     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
316     const Module *M = MF->getFunction()->getParent();
317     DebugLoc dl;
318 
319     if (PPCLowering->getPointerTy(CurDAG->getDataLayout()) == MVT::i32) {
320       if (PPCSubTarget->isTargetELF()) {
321         GlobalBaseReg = PPC::R30;
322         if (M->getPICLevel() == PICLevel::SmallPIC) {
323           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
324           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
325           MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
326         } else {
327           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
328           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
329           unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
330           BuildMI(FirstMBB, MBBI, dl,
331                   TII.get(PPC::UpdateGBR), GlobalBaseReg)
332                   .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
333           MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
334         }
335       } else {
336         GlobalBaseReg =
337           RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
338         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
339         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
340       }
341     } else {
342       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
343       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
344       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
345     }
346   }
347   return CurDAG->getRegister(GlobalBaseReg,
348                              PPCLowering->getPointerTy(CurDAG->getDataLayout()))
349       .getNode();
350 }
351 
352 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
353 /// or 64-bit immediate, and if the value can be accurately represented as a
354 /// sign extension from a 16-bit value.  If so, this returns true and the
355 /// immediate.
356 static bool isIntS16Immediate(SDNode *N, short &Imm) {
357   if (N->getOpcode() != ISD::Constant)
358     return false;
359 
360   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
361   if (N->getValueType(0) == MVT::i32)
362     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
363   else
364     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
365 }
366 
367 static bool isIntS16Immediate(SDValue Op, short &Imm) {
368   return isIntS16Immediate(Op.getNode(), Imm);
369 }
370 
371 
372 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
373 /// operand. If so Imm will receive the 32-bit value.
374 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
375   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
376     Imm = cast<ConstantSDNode>(N)->getZExtValue();
377     return true;
378   }
379   return false;
380 }
381 
382 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
383 /// operand.  If so Imm will receive the 64-bit value.
384 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
385   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
386     Imm = cast<ConstantSDNode>(N)->getZExtValue();
387     return true;
388   }
389   return false;
390 }
391 
392 // isInt32Immediate - This method tests to see if a constant operand.
393 // If so Imm will receive the 32 bit value.
394 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
395   return isInt32Immediate(N.getNode(), Imm);
396 }
397 
398 static unsigned getBranchHint(unsigned PCC, FunctionLoweringInfo *FuncInfo,
399                               const SDValue &DestMBB) {
400   assert(isa<BasicBlockSDNode>(DestMBB));
401 
402   if (!FuncInfo->BPI) return PPC::BR_NO_HINT;
403 
404   const BasicBlock *BB = FuncInfo->MBB->getBasicBlock();
405   const TerminatorInst *BBTerm = BB->getTerminator();
406 
407   if (BBTerm->getNumSuccessors() != 2) return PPC::BR_NO_HINT;
408 
409   const BasicBlock *TBB = BBTerm->getSuccessor(0);
410   const BasicBlock *FBB = BBTerm->getSuccessor(1);
411 
412   auto TProb = FuncInfo->BPI->getEdgeProbability(BB, TBB);
413   auto FProb = FuncInfo->BPI->getEdgeProbability(BB, FBB);
414 
415   // We only want to handle cases which are easy to predict at static time, e.g.
416   // C++ throw statement, that is very likely not taken, or calling never
417   // returned function, e.g. stdlib exit(). So we set Threshold to filter
418   // unwanted cases.
419   //
420   // Below is LLVM branch weight table, we only want to handle case 1, 2
421   //
422   // Case                  Taken:Nontaken  Example
423   // 1. Unreachable        1048575:1       C++ throw, stdlib exit(),
424   // 2. Invoke-terminating 1:1048575
425   // 3. Coldblock          4:64            __builtin_expect
426   // 4. Loop Branch        124:4           For loop
427   // 5. PH/ZH/FPH          20:12
428   const uint32_t Threshold = 10000;
429 
430   if (std::max(TProb, FProb) / Threshold < std::min(TProb, FProb))
431     return PPC::BR_NO_HINT;
432 
433   DEBUG(dbgs() << "Use branch hint for '" << FuncInfo->Fn->getName() << "::"
434                << BB->getName() << "'\n"
435                << " -> " << TBB->getName() << ": " << TProb << "\n"
436                << " -> " << FBB->getName() << ": " << FProb << "\n");
437 
438   const BasicBlockSDNode *BBDN = cast<BasicBlockSDNode>(DestMBB);
439 
440   // If Dest BasicBlock is False-BasicBlock (FBB), swap branch probabilities,
441   // because we want 'TProb' stands for 'branch probability' to Dest BasicBlock
442   if (BBDN->getBasicBlock()->getBasicBlock() != TBB)
443     std::swap(TProb, FProb);
444 
445   return (TProb > FProb) ? PPC::BR_TAKEN_HINT : PPC::BR_NONTAKEN_HINT;
446 }
447 
448 // isOpcWithIntImmediate - This method tests to see if the node is a specific
449 // opcode and that it has a immediate integer right operand.
450 // If so Imm will receive the 32 bit value.
451 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
452   return N->getOpcode() == Opc
453          && isInt32Immediate(N->getOperand(1).getNode(), Imm);
454 }
455 
456 void PPCDAGToDAGISel::selectFrameIndex(SDNode *SN, SDNode *N, unsigned Offset) {
457   SDLoc dl(SN);
458   int FI = cast<FrameIndexSDNode>(N)->getIndex();
459   SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
460   unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
461   if (SN->hasOneUse())
462     CurDAG->SelectNodeTo(SN, Opc, N->getValueType(0), TFI,
463                          getSmallIPtrImm(Offset, dl));
464   else
465     ReplaceNode(SN, CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
466                                            getSmallIPtrImm(Offset, dl)));
467 }
468 
469 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
470                                       bool isShiftMask, unsigned &SH,
471                                       unsigned &MB, unsigned &ME) {
472   // Don't even go down this path for i64, since different logic will be
473   // necessary for rldicl/rldicr/rldimi.
474   if (N->getValueType(0) != MVT::i32)
475     return false;
476 
477   unsigned Shift  = 32;
478   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
479   unsigned Opcode = N->getOpcode();
480   if (N->getNumOperands() != 2 ||
481       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
482     return false;
483 
484   if (Opcode == ISD::SHL) {
485     // apply shift left to mask if it comes first
486     if (isShiftMask) Mask = Mask << Shift;
487     // determine which bits are made indeterminant by shift
488     Indeterminant = ~(0xFFFFFFFFu << Shift);
489   } else if (Opcode == ISD::SRL) {
490     // apply shift right to mask if it comes first
491     if (isShiftMask) Mask = Mask >> Shift;
492     // determine which bits are made indeterminant by shift
493     Indeterminant = ~(0xFFFFFFFFu >> Shift);
494     // adjust for the left rotate
495     Shift = 32 - Shift;
496   } else if (Opcode == ISD::ROTL) {
497     Indeterminant = 0;
498   } else {
499     return false;
500   }
501 
502   // if the mask doesn't intersect any Indeterminant bits
503   if (Mask && !(Mask & Indeterminant)) {
504     SH = Shift & 31;
505     // make sure the mask is still a mask (wrap arounds may not be)
506     return isRunOfOnes(Mask, MB, ME);
507   }
508   return false;
509 }
510 
511 /// Turn an or of two masked values into the rotate left word immediate then
512 /// mask insert (rlwimi) instruction.
513 bool PPCDAGToDAGISel::tryBitfieldInsert(SDNode *N) {
514   SDValue Op0 = N->getOperand(0);
515   SDValue Op1 = N->getOperand(1);
516   SDLoc dl(N);
517 
518   APInt LKZ, LKO, RKZ, RKO;
519   CurDAG->computeKnownBits(Op0, LKZ, LKO);
520   CurDAG->computeKnownBits(Op1, RKZ, RKO);
521 
522   unsigned TargetMask = LKZ.getZExtValue();
523   unsigned InsertMask = RKZ.getZExtValue();
524 
525   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
526     unsigned Op0Opc = Op0.getOpcode();
527     unsigned Op1Opc = Op1.getOpcode();
528     unsigned Value, SH = 0;
529     TargetMask = ~TargetMask;
530     InsertMask = ~InsertMask;
531 
532     // If the LHS has a foldable shift and the RHS does not, then swap it to the
533     // RHS so that we can fold the shift into the insert.
534     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
535       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
536           Op0.getOperand(0).getOpcode() == ISD::SRL) {
537         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
538             Op1.getOperand(0).getOpcode() != ISD::SRL) {
539           std::swap(Op0, Op1);
540           std::swap(Op0Opc, Op1Opc);
541           std::swap(TargetMask, InsertMask);
542         }
543       }
544     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
545       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
546           Op1.getOperand(0).getOpcode() != ISD::SRL) {
547         std::swap(Op0, Op1);
548         std::swap(Op0Opc, Op1Opc);
549         std::swap(TargetMask, InsertMask);
550       }
551     }
552 
553     unsigned MB, ME;
554     if (isRunOfOnes(InsertMask, MB, ME)) {
555       SDValue Tmp1, Tmp2;
556 
557       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
558           isInt32Immediate(Op1.getOperand(1), Value)) {
559         Op1 = Op1.getOperand(0);
560         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
561       }
562       if (Op1Opc == ISD::AND) {
563        // The AND mask might not be a constant, and we need to make sure that
564        // if we're going to fold the masking with the insert, all bits not
565        // know to be zero in the mask are known to be one.
566         APInt MKZ, MKO;
567         CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
568         bool CanFoldMask = InsertMask == MKO.getZExtValue();
569 
570         unsigned SHOpc = Op1.getOperand(0).getOpcode();
571         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
572             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
573           // Note that Value must be in range here (less than 32) because
574           // otherwise there would not be any bits set in InsertMask.
575           Op1 = Op1.getOperand(0).getOperand(0);
576           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
577         }
578       }
579 
580       SH &= 31;
581       SDValue Ops[] = { Op0, Op1, getI32Imm(SH, dl), getI32Imm(MB, dl),
582                           getI32Imm(ME, dl) };
583       ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
584       return true;
585     }
586   }
587   return false;
588 }
589 
590 // Predict the number of instructions that would be generated by calling
591 // getInt64(N).
592 static unsigned getInt64CountDirect(int64_t Imm) {
593   // Assume no remaining bits.
594   unsigned Remainder = 0;
595   // Assume no shift required.
596   unsigned Shift = 0;
597 
598   // If it can't be represented as a 32 bit value.
599   if (!isInt<32>(Imm)) {
600     Shift = countTrailingZeros<uint64_t>(Imm);
601     int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
602 
603     // If the shifted value fits 32 bits.
604     if (isInt<32>(ImmSh)) {
605       // Go with the shifted value.
606       Imm = ImmSh;
607     } else {
608       // Still stuck with a 64 bit value.
609       Remainder = Imm;
610       Shift = 32;
611       Imm >>= 32;
612     }
613   }
614 
615   // Intermediate operand.
616   unsigned Result = 0;
617 
618   // Handle first 32 bits.
619   unsigned Lo = Imm & 0xFFFF;
620 
621   // Simple value.
622   if (isInt<16>(Imm)) {
623     // Just the Lo bits.
624     ++Result;
625   } else if (Lo) {
626     // Handle the Hi bits and Lo bits.
627     Result += 2;
628   } else {
629     // Just the Hi bits.
630     ++Result;
631   }
632 
633   // If no shift, we're done.
634   if (!Shift) return Result;
635 
636   // If Hi word == Lo word,
637   // we can use rldimi to insert the Lo word into Hi word.
638   if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
639     ++Result;
640     return Result;
641   }
642 
643   // Shift for next step if the upper 32-bits were not zero.
644   if (Imm)
645     ++Result;
646 
647   // Add in the last bits as required.
648   if ((Remainder >> 16) & 0xFFFF)
649     ++Result;
650   if (Remainder & 0xFFFF)
651     ++Result;
652 
653   return Result;
654 }
655 
656 static uint64_t Rot64(uint64_t Imm, unsigned R) {
657   return (Imm << R) | (Imm >> (64 - R));
658 }
659 
660 static unsigned getInt64Count(int64_t Imm) {
661   unsigned Count = getInt64CountDirect(Imm);
662   if (Count == 1)
663     return Count;
664 
665   for (unsigned r = 1; r < 63; ++r) {
666     uint64_t RImm = Rot64(Imm, r);
667     unsigned RCount = getInt64CountDirect(RImm) + 1;
668     Count = std::min(Count, RCount);
669 
670     // See comments in getInt64 for an explanation of the logic below.
671     unsigned LS = findLastSet(RImm);
672     if (LS != r-1)
673       continue;
674 
675     uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
676     uint64_t RImmWithOnes = RImm | OnesMask;
677 
678     RCount = getInt64CountDirect(RImmWithOnes) + 1;
679     Count = std::min(Count, RCount);
680   }
681 
682   return Count;
683 }
684 
685 // Select a 64-bit constant. For cost-modeling purposes, getInt64Count
686 // (above) needs to be kept in sync with this function.
687 static SDNode *getInt64Direct(SelectionDAG *CurDAG, const SDLoc &dl,
688                               int64_t Imm) {
689   // Assume no remaining bits.
690   unsigned Remainder = 0;
691   // Assume no shift required.
692   unsigned Shift = 0;
693 
694   // If it can't be represented as a 32 bit value.
695   if (!isInt<32>(Imm)) {
696     Shift = countTrailingZeros<uint64_t>(Imm);
697     int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
698 
699     // If the shifted value fits 32 bits.
700     if (isInt<32>(ImmSh)) {
701       // Go with the shifted value.
702       Imm = ImmSh;
703     } else {
704       // Still stuck with a 64 bit value.
705       Remainder = Imm;
706       Shift = 32;
707       Imm >>= 32;
708     }
709   }
710 
711   // Intermediate operand.
712   SDNode *Result;
713 
714   // Handle first 32 bits.
715   unsigned Lo = Imm & 0xFFFF;
716   unsigned Hi = (Imm >> 16) & 0xFFFF;
717 
718   auto getI32Imm = [CurDAG, dl](unsigned Imm) {
719       return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
720   };
721 
722   // Simple value.
723   if (isInt<16>(Imm)) {
724     // Just the Lo bits.
725     Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
726   } else if (Lo) {
727     // Handle the Hi bits.
728     unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
729     Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
730     // And Lo bits.
731     Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
732                                     SDValue(Result, 0), getI32Imm(Lo));
733   } else {
734     // Just the Hi bits.
735     Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
736   }
737 
738   // If no shift, we're done.
739   if (!Shift) return Result;
740 
741   // If Hi word == Lo word,
742   // we can use rldimi to insert the Lo word into Hi word.
743   if ((unsigned)(Imm & 0xFFFFFFFF) == Remainder) {
744     SDValue Ops[] =
745       { SDValue(Result, 0), SDValue(Result, 0), getI32Imm(Shift), getI32Imm(0)};
746     return CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops);
747   }
748 
749   // Shift for next step if the upper 32-bits were not zero.
750   if (Imm) {
751     Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
752                                     SDValue(Result, 0),
753                                     getI32Imm(Shift),
754                                     getI32Imm(63 - Shift));
755   }
756 
757   // Add in the last bits as required.
758   if ((Hi = (Remainder >> 16) & 0xFFFF)) {
759     Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
760                                     SDValue(Result, 0), getI32Imm(Hi));
761   }
762   if ((Lo = Remainder & 0xFFFF)) {
763     Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
764                                     SDValue(Result, 0), getI32Imm(Lo));
765   }
766 
767   return Result;
768 }
769 
770 static SDNode *getInt64(SelectionDAG *CurDAG, const SDLoc &dl, int64_t Imm) {
771   unsigned Count = getInt64CountDirect(Imm);
772   if (Count == 1)
773     return getInt64Direct(CurDAG, dl, Imm);
774 
775   unsigned RMin = 0;
776 
777   int64_t MatImm;
778   unsigned MaskEnd;
779 
780   for (unsigned r = 1; r < 63; ++r) {
781     uint64_t RImm = Rot64(Imm, r);
782     unsigned RCount = getInt64CountDirect(RImm) + 1;
783     if (RCount < Count) {
784       Count = RCount;
785       RMin = r;
786       MatImm = RImm;
787       MaskEnd = 63;
788     }
789 
790     // If the immediate to generate has many trailing zeros, it might be
791     // worthwhile to generate a rotated value with too many leading ones
792     // (because that's free with li/lis's sign-extension semantics), and then
793     // mask them off after rotation.
794 
795     unsigned LS = findLastSet(RImm);
796     // We're adding (63-LS) higher-order ones, and we expect to mask them off
797     // after performing the inverse rotation by (64-r). So we need that:
798     //   63-LS == 64-r => LS == r-1
799     if (LS != r-1)
800       continue;
801 
802     uint64_t OnesMask = -(int64_t) (UINT64_C(1) << (LS+1));
803     uint64_t RImmWithOnes = RImm | OnesMask;
804 
805     RCount = getInt64CountDirect(RImmWithOnes) + 1;
806     if (RCount < Count) {
807       Count = RCount;
808       RMin = r;
809       MatImm = RImmWithOnes;
810       MaskEnd = LS;
811     }
812   }
813 
814   if (!RMin)
815     return getInt64Direct(CurDAG, dl, Imm);
816 
817   auto getI32Imm = [CurDAG, dl](unsigned Imm) {
818       return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
819   };
820 
821   SDValue Val = SDValue(getInt64Direct(CurDAG, dl, MatImm), 0);
822   return CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Val,
823                                 getI32Imm(64 - RMin), getI32Imm(MaskEnd));
824 }
825 
826 // Select a 64-bit constant.
827 static SDNode *getInt64(SelectionDAG *CurDAG, SDNode *N) {
828   SDLoc dl(N);
829 
830   // Get 64 bit value.
831   int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
832   return getInt64(CurDAG, dl, Imm);
833 }
834 
835 namespace {
836 class BitPermutationSelector {
837   struct ValueBit {
838     SDValue V;
839 
840     // The bit number in the value, using a convention where bit 0 is the
841     // lowest-order bit.
842     unsigned Idx;
843 
844     enum Kind {
845       ConstZero,
846       Variable
847     } K;
848 
849     ValueBit(SDValue V, unsigned I, Kind K = Variable)
850       : V(V), Idx(I), K(K) {}
851     ValueBit(Kind K = Variable)
852       : V(SDValue(nullptr, 0)), Idx(UINT32_MAX), K(K) {}
853 
854     bool isZero() const {
855       return K == ConstZero;
856     }
857 
858     bool hasValue() const {
859       return K == Variable;
860     }
861 
862     SDValue getValue() const {
863       assert(hasValue() && "Cannot get the value of a constant bit");
864       return V;
865     }
866 
867     unsigned getValueBitIndex() const {
868       assert(hasValue() && "Cannot get the value bit index of a constant bit");
869       return Idx;
870     }
871   };
872 
873   // A bit group has the same underlying value and the same rotate factor.
874   struct BitGroup {
875     SDValue V;
876     unsigned RLAmt;
877     unsigned StartIdx, EndIdx;
878 
879     // This rotation amount assumes that the lower 32 bits of the quantity are
880     // replicated in the high 32 bits by the rotation operator (which is done
881     // by rlwinm and friends in 64-bit mode).
882     bool Repl32;
883     // Did converting to Repl32 == true change the rotation factor? If it did,
884     // it decreased it by 32.
885     bool Repl32CR;
886     // Was this group coalesced after setting Repl32 to true?
887     bool Repl32Coalesced;
888 
889     BitGroup(SDValue V, unsigned R, unsigned S, unsigned E)
890       : V(V), RLAmt(R), StartIdx(S), EndIdx(E), Repl32(false), Repl32CR(false),
891         Repl32Coalesced(false) {
892       DEBUG(dbgs() << "\tbit group for " << V.getNode() << " RLAmt = " << R <<
893                       " [" << S << ", " << E << "]\n");
894     }
895   };
896 
897   // Information on each (Value, RLAmt) pair (like the number of groups
898   // associated with each) used to choose the lowering method.
899   struct ValueRotInfo {
900     SDValue V;
901     unsigned RLAmt;
902     unsigned NumGroups;
903     unsigned FirstGroupStartIdx;
904     bool Repl32;
905 
906     ValueRotInfo()
907       : RLAmt(UINT32_MAX), NumGroups(0), FirstGroupStartIdx(UINT32_MAX),
908         Repl32(false) {}
909 
910     // For sorting (in reverse order) by NumGroups, and then by
911     // FirstGroupStartIdx.
912     bool operator < (const ValueRotInfo &Other) const {
913       // We need to sort so that the non-Repl32 come first because, when we're
914       // doing masking, the Repl32 bit groups might be subsumed into the 64-bit
915       // masking operation.
916       if (Repl32 < Other.Repl32)
917         return true;
918       else if (Repl32 > Other.Repl32)
919         return false;
920       else if (NumGroups > Other.NumGroups)
921         return true;
922       else if (NumGroups < Other.NumGroups)
923         return false;
924       else if (FirstGroupStartIdx < Other.FirstGroupStartIdx)
925         return true;
926       return false;
927     }
928   };
929 
930   using ValueBitsMemoizedValue = std::pair<bool, SmallVector<ValueBit, 64>>;
931   using ValueBitsMemoizer =
932       DenseMap<SDValue, std::unique_ptr<ValueBitsMemoizedValue>>;
933   ValueBitsMemoizer Memoizer;
934 
935   // Return a pair of bool and a SmallVector pointer to a memoization entry.
936   // The bool is true if something interesting was deduced, otherwise if we're
937   // providing only a generic representation of V (or something else likewise
938   // uninteresting for instruction selection) through the SmallVector.
939   std::pair<bool, SmallVector<ValueBit, 64> *> getValueBits(SDValue V,
940                                                             unsigned NumBits) {
941     auto &ValueEntry = Memoizer[V];
942     if (ValueEntry)
943       return std::make_pair(ValueEntry->first, &ValueEntry->second);
944     ValueEntry.reset(new ValueBitsMemoizedValue());
945     bool &Interesting = ValueEntry->first;
946     SmallVector<ValueBit, 64> &Bits = ValueEntry->second;
947     Bits.resize(NumBits);
948 
949     switch (V.getOpcode()) {
950     default: break;
951     case ISD::ROTL:
952       if (isa<ConstantSDNode>(V.getOperand(1))) {
953         unsigned RotAmt = V.getConstantOperandVal(1);
954 
955         const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
956 
957         for (unsigned i = 0; i < NumBits; ++i)
958           Bits[i] = LHSBits[i < RotAmt ? i + (NumBits - RotAmt) : i - RotAmt];
959 
960         return std::make_pair(Interesting = true, &Bits);
961       }
962       break;
963     case ISD::SHL:
964       if (isa<ConstantSDNode>(V.getOperand(1))) {
965         unsigned ShiftAmt = V.getConstantOperandVal(1);
966 
967         const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
968 
969         for (unsigned i = ShiftAmt; i < NumBits; ++i)
970           Bits[i] = LHSBits[i - ShiftAmt];
971 
972         for (unsigned i = 0; i < ShiftAmt; ++i)
973           Bits[i] = ValueBit(ValueBit::ConstZero);
974 
975         return std::make_pair(Interesting = true, &Bits);
976       }
977       break;
978     case ISD::SRL:
979       if (isa<ConstantSDNode>(V.getOperand(1))) {
980         unsigned ShiftAmt = V.getConstantOperandVal(1);
981 
982         const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
983 
984         for (unsigned i = 0; i < NumBits - ShiftAmt; ++i)
985           Bits[i] = LHSBits[i + ShiftAmt];
986 
987         for (unsigned i = NumBits - ShiftAmt; i < NumBits; ++i)
988           Bits[i] = ValueBit(ValueBit::ConstZero);
989 
990         return std::make_pair(Interesting = true, &Bits);
991       }
992       break;
993     case ISD::AND:
994       if (isa<ConstantSDNode>(V.getOperand(1))) {
995         uint64_t Mask = V.getConstantOperandVal(1);
996 
997         const SmallVector<ValueBit, 64> *LHSBits;
998         // Mark this as interesting, only if the LHS was also interesting. This
999         // prevents the overall procedure from matching a single immediate 'and'
1000         // (which is non-optimal because such an and might be folded with other
1001         // things if we don't select it here).
1002         std::tie(Interesting, LHSBits) = getValueBits(V.getOperand(0), NumBits);
1003 
1004         for (unsigned i = 0; i < NumBits; ++i)
1005           if (((Mask >> i) & 1) == 1)
1006             Bits[i] = (*LHSBits)[i];
1007           else
1008             Bits[i] = ValueBit(ValueBit::ConstZero);
1009 
1010         return std::make_pair(Interesting, &Bits);
1011       }
1012       break;
1013     case ISD::OR: {
1014       const auto &LHSBits = *getValueBits(V.getOperand(0), NumBits).second;
1015       const auto &RHSBits = *getValueBits(V.getOperand(1), NumBits).second;
1016 
1017       bool AllDisjoint = true;
1018       for (unsigned i = 0; i < NumBits; ++i)
1019         if (LHSBits[i].isZero())
1020           Bits[i] = RHSBits[i];
1021         else if (RHSBits[i].isZero())
1022           Bits[i] = LHSBits[i];
1023         else {
1024           AllDisjoint = false;
1025           break;
1026         }
1027 
1028       if (!AllDisjoint)
1029         break;
1030 
1031       return std::make_pair(Interesting = true, &Bits);
1032     }
1033     }
1034 
1035     for (unsigned i = 0; i < NumBits; ++i)
1036       Bits[i] = ValueBit(V, i);
1037 
1038     return std::make_pair(Interesting = false, &Bits);
1039   }
1040 
1041   // For each value (except the constant ones), compute the left-rotate amount
1042   // to get it from its original to final position.
1043   void computeRotationAmounts() {
1044     HasZeros = false;
1045     RLAmt.resize(Bits.size());
1046     for (unsigned i = 0; i < Bits.size(); ++i)
1047       if (Bits[i].hasValue()) {
1048         unsigned VBI = Bits[i].getValueBitIndex();
1049         if (i >= VBI)
1050           RLAmt[i] = i - VBI;
1051         else
1052           RLAmt[i] = Bits.size() - (VBI - i);
1053       } else if (Bits[i].isZero()) {
1054         HasZeros = true;
1055         RLAmt[i] = UINT32_MAX;
1056       } else {
1057         llvm_unreachable("Unknown value bit type");
1058       }
1059   }
1060 
1061   // Collect groups of consecutive bits with the same underlying value and
1062   // rotation factor. If we're doing late masking, we ignore zeros, otherwise
1063   // they break up groups.
1064   void collectBitGroups(bool LateMask) {
1065     BitGroups.clear();
1066 
1067     unsigned LastRLAmt = RLAmt[0];
1068     SDValue LastValue = Bits[0].hasValue() ? Bits[0].getValue() : SDValue();
1069     unsigned LastGroupStartIdx = 0;
1070     for (unsigned i = 1; i < Bits.size(); ++i) {
1071       unsigned ThisRLAmt = RLAmt[i];
1072       SDValue ThisValue = Bits[i].hasValue() ? Bits[i].getValue() : SDValue();
1073       if (LateMask && !ThisValue) {
1074         ThisValue = LastValue;
1075         ThisRLAmt = LastRLAmt;
1076         // If we're doing late masking, then the first bit group always starts
1077         // at zero (even if the first bits were zero).
1078         if (BitGroups.empty())
1079           LastGroupStartIdx = 0;
1080       }
1081 
1082       // If this bit has the same underlying value and the same rotate factor as
1083       // the last one, then they're part of the same group.
1084       if (ThisRLAmt == LastRLAmt && ThisValue == LastValue)
1085         continue;
1086 
1087       if (LastValue.getNode())
1088         BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1089                                      i-1));
1090       LastRLAmt = ThisRLAmt;
1091       LastValue = ThisValue;
1092       LastGroupStartIdx = i;
1093     }
1094     if (LastValue.getNode())
1095       BitGroups.push_back(BitGroup(LastValue, LastRLAmt, LastGroupStartIdx,
1096                                    Bits.size()-1));
1097 
1098     if (BitGroups.empty())
1099       return;
1100 
1101     // We might be able to combine the first and last groups.
1102     if (BitGroups.size() > 1) {
1103       // If the first and last groups are the same, then remove the first group
1104       // in favor of the last group, making the ending index of the last group
1105       // equal to the ending index of the to-be-removed first group.
1106       if (BitGroups[0].StartIdx == 0 &&
1107           BitGroups[BitGroups.size()-1].EndIdx == Bits.size()-1 &&
1108           BitGroups[0].V == BitGroups[BitGroups.size()-1].V &&
1109           BitGroups[0].RLAmt == BitGroups[BitGroups.size()-1].RLAmt) {
1110         DEBUG(dbgs() << "\tcombining final bit group with initial one\n");
1111         BitGroups[BitGroups.size()-1].EndIdx = BitGroups[0].EndIdx;
1112         BitGroups.erase(BitGroups.begin());
1113       }
1114     }
1115   }
1116 
1117   // Take all (SDValue, RLAmt) pairs and sort them by the number of groups
1118   // associated with each. If there is a degeneracy, pick the one that occurs
1119   // first (in the final value).
1120   void collectValueRotInfo() {
1121     ValueRots.clear();
1122 
1123     for (auto &BG : BitGroups) {
1124       unsigned RLAmtKey = BG.RLAmt + (BG.Repl32 ? 64 : 0);
1125       ValueRotInfo &VRI = ValueRots[std::make_pair(BG.V, RLAmtKey)];
1126       VRI.V = BG.V;
1127       VRI.RLAmt = BG.RLAmt;
1128       VRI.Repl32 = BG.Repl32;
1129       VRI.NumGroups += 1;
1130       VRI.FirstGroupStartIdx = std::min(VRI.FirstGroupStartIdx, BG.StartIdx);
1131     }
1132 
1133     // Now that we've collected the various ValueRotInfo instances, we need to
1134     // sort them.
1135     ValueRotsVec.clear();
1136     for (auto &I : ValueRots) {
1137       ValueRotsVec.push_back(I.second);
1138     }
1139     std::sort(ValueRotsVec.begin(), ValueRotsVec.end());
1140   }
1141 
1142   // In 64-bit mode, rlwinm and friends have a rotation operator that
1143   // replicates the low-order 32 bits into the high-order 32-bits. The mask
1144   // indices of these instructions can only be in the lower 32 bits, so they
1145   // can only represent some 64-bit bit groups. However, when they can be used,
1146   // the 32-bit replication can be used to represent, as a single bit group,
1147   // otherwise separate bit groups. We'll convert to replicated-32-bit bit
1148   // groups when possible. Returns true if any of the bit groups were
1149   // converted.
1150   void assignRepl32BitGroups() {
1151     // If we have bits like this:
1152     //
1153     // Indices:    15 14 13 12 11 10 9 8  7  6  5  4  3  2  1  0
1154     // V bits: ... 7  6  5  4  3  2  1 0 31 30 29 28 27 26 25 24
1155     // Groups:    |      RLAmt = 8      |      RLAmt = 40       |
1156     //
1157     // But, making use of a 32-bit operation that replicates the low-order 32
1158     // bits into the high-order 32 bits, this can be one bit group with a RLAmt
1159     // of 8.
1160 
1161     auto IsAllLow32 = [this](BitGroup & BG) {
1162       if (BG.StartIdx <= BG.EndIdx) {
1163         for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i) {
1164           if (!Bits[i].hasValue())
1165             continue;
1166           if (Bits[i].getValueBitIndex() >= 32)
1167             return false;
1168         }
1169       } else {
1170         for (unsigned i = BG.StartIdx; i < Bits.size(); ++i) {
1171           if (!Bits[i].hasValue())
1172             continue;
1173           if (Bits[i].getValueBitIndex() >= 32)
1174             return false;
1175         }
1176         for (unsigned i = 0; i <= BG.EndIdx; ++i) {
1177           if (!Bits[i].hasValue())
1178             continue;
1179           if (Bits[i].getValueBitIndex() >= 32)
1180             return false;
1181         }
1182       }
1183 
1184       return true;
1185     };
1186 
1187     for (auto &BG : BitGroups) {
1188       if (BG.StartIdx < 32 && BG.EndIdx < 32) {
1189         if (IsAllLow32(BG)) {
1190           if (BG.RLAmt >= 32) {
1191             BG.RLAmt -= 32;
1192             BG.Repl32CR = true;
1193           }
1194 
1195           BG.Repl32 = true;
1196 
1197           DEBUG(dbgs() << "\t32-bit replicated bit group for " <<
1198                           BG.V.getNode() << " RLAmt = " << BG.RLAmt <<
1199                           " [" << BG.StartIdx << ", " << BG.EndIdx << "]\n");
1200         }
1201       }
1202     }
1203 
1204     // Now walk through the bit groups, consolidating where possible.
1205     for (auto I = BitGroups.begin(); I != BitGroups.end();) {
1206       // We might want to remove this bit group by merging it with the previous
1207       // group (which might be the ending group).
1208       auto IP = (I == BitGroups.begin()) ?
1209                 std::prev(BitGroups.end()) : std::prev(I);
1210       if (I->Repl32 && IP->Repl32 && I->V == IP->V && I->RLAmt == IP->RLAmt &&
1211           I->StartIdx == (IP->EndIdx + 1) % 64 && I != IP) {
1212 
1213         DEBUG(dbgs() << "\tcombining 32-bit replicated bit group for " <<
1214                         I->V.getNode() << " RLAmt = " << I->RLAmt <<
1215                         " [" << I->StartIdx << ", " << I->EndIdx <<
1216                         "] with group with range [" <<
1217                         IP->StartIdx << ", " << IP->EndIdx << "]\n");
1218 
1219         IP->EndIdx = I->EndIdx;
1220         IP->Repl32CR = IP->Repl32CR || I->Repl32CR;
1221         IP->Repl32Coalesced = true;
1222         I = BitGroups.erase(I);
1223         continue;
1224       } else {
1225         // There is a special case worth handling: If there is a single group
1226         // covering the entire upper 32 bits, and it can be merged with both
1227         // the next and previous groups (which might be the same group), then
1228         // do so. If it is the same group (so there will be only one group in
1229         // total), then we need to reverse the order of the range so that it
1230         // covers the entire 64 bits.
1231         if (I->StartIdx == 32 && I->EndIdx == 63) {
1232           assert(std::next(I) == BitGroups.end() &&
1233                  "bit group ends at index 63 but there is another?");
1234           auto IN = BitGroups.begin();
1235 
1236           if (IP->Repl32 && IN->Repl32 && I->V == IP->V && I->V == IN->V &&
1237               (I->RLAmt % 32) == IP->RLAmt && (I->RLAmt % 32) == IN->RLAmt &&
1238               IP->EndIdx == 31 && IN->StartIdx == 0 && I != IP &&
1239               IsAllLow32(*I)) {
1240 
1241             DEBUG(dbgs() << "\tcombining bit group for " <<
1242                             I->V.getNode() << " RLAmt = " << I->RLAmt <<
1243                             " [" << I->StartIdx << ", " << I->EndIdx <<
1244                             "] with 32-bit replicated groups with ranges [" <<
1245                             IP->StartIdx << ", " << IP->EndIdx << "] and [" <<
1246                             IN->StartIdx << ", " << IN->EndIdx << "]\n");
1247 
1248             if (IP == IN) {
1249               // There is only one other group; change it to cover the whole
1250               // range (backward, so that it can still be Repl32 but cover the
1251               // whole 64-bit range).
1252               IP->StartIdx = 31;
1253               IP->EndIdx = 30;
1254               IP->Repl32CR = IP->Repl32CR || I->RLAmt >= 32;
1255               IP->Repl32Coalesced = true;
1256               I = BitGroups.erase(I);
1257             } else {
1258               // There are two separate groups, one before this group and one
1259               // after us (at the beginning). We're going to remove this group,
1260               // but also the group at the very beginning.
1261               IP->EndIdx = IN->EndIdx;
1262               IP->Repl32CR = IP->Repl32CR || IN->Repl32CR || I->RLAmt >= 32;
1263               IP->Repl32Coalesced = true;
1264               I = BitGroups.erase(I);
1265               BitGroups.erase(BitGroups.begin());
1266             }
1267 
1268             // This must be the last group in the vector (and we might have
1269             // just invalidated the iterator above), so break here.
1270             break;
1271           }
1272         }
1273       }
1274 
1275       ++I;
1276     }
1277   }
1278 
1279   SDValue getI32Imm(unsigned Imm, const SDLoc &dl) {
1280     return CurDAG->getTargetConstant(Imm, dl, MVT::i32);
1281   }
1282 
1283   uint64_t getZerosMask() {
1284     uint64_t Mask = 0;
1285     for (unsigned i = 0; i < Bits.size(); ++i) {
1286       if (Bits[i].hasValue())
1287         continue;
1288       Mask |= (UINT64_C(1) << i);
1289     }
1290 
1291     return ~Mask;
1292   }
1293 
1294   // Depending on the number of groups for a particular value, it might be
1295   // better to rotate, mask explicitly (using andi/andis), and then or the
1296   // result. Select this part of the result first.
1297   void SelectAndParts32(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
1298     if (BPermRewriterNoMasking)
1299       return;
1300 
1301     for (ValueRotInfo &VRI : ValueRotsVec) {
1302       unsigned Mask = 0;
1303       for (unsigned i = 0; i < Bits.size(); ++i) {
1304         if (!Bits[i].hasValue() || Bits[i].getValue() != VRI.V)
1305           continue;
1306         if (RLAmt[i] != VRI.RLAmt)
1307           continue;
1308         Mask |= (1u << i);
1309       }
1310 
1311       // Compute the masks for andi/andis that would be necessary.
1312       unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1313       assert((ANDIMask != 0 || ANDISMask != 0) &&
1314              "No set bits in mask for value bit groups");
1315       bool NeedsRotate = VRI.RLAmt != 0;
1316 
1317       // We're trying to minimize the number of instructions. If we have one
1318       // group, using one of andi/andis can break even.  If we have three
1319       // groups, we can use both andi and andis and break even (to use both
1320       // andi and andis we also need to or the results together). We need four
1321       // groups if we also need to rotate. To use andi/andis we need to do more
1322       // than break even because rotate-and-mask instructions tend to be easier
1323       // to schedule.
1324 
1325       // FIXME: We've biased here against using andi/andis, which is right for
1326       // POWER cores, but not optimal everywhere. For example, on the A2,
1327       // andi/andis have single-cycle latency whereas the rotate-and-mask
1328       // instructions take two cycles, and it would be better to bias toward
1329       // andi/andis in break-even cases.
1330 
1331       unsigned NumAndInsts = (unsigned) NeedsRotate +
1332                              (unsigned) (ANDIMask != 0) +
1333                              (unsigned) (ANDISMask != 0) +
1334                              (unsigned) (ANDIMask != 0 && ANDISMask != 0) +
1335                              (unsigned) (bool) Res;
1336 
1337       DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1338                       " RL: " << VRI.RLAmt << ":" <<
1339                       "\n\t\t\tisel using masking: " << NumAndInsts <<
1340                       " using rotates: " << VRI.NumGroups << "\n");
1341 
1342       if (NumAndInsts >= VRI.NumGroups)
1343         continue;
1344 
1345       DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1346 
1347       if (InstCnt) *InstCnt += NumAndInsts;
1348 
1349       SDValue VRot;
1350       if (VRI.RLAmt) {
1351         SDValue Ops[] =
1352           { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1353             getI32Imm(31, dl) };
1354         VRot = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32,
1355                                               Ops), 0);
1356       } else {
1357         VRot = VRI.V;
1358       }
1359 
1360       SDValue ANDIVal, ANDISVal;
1361       if (ANDIMask != 0)
1362         ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1363                             VRot, getI32Imm(ANDIMask, dl)), 0);
1364       if (ANDISMask != 0)
1365         ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1366                              VRot, getI32Imm(ANDISMask, dl)), 0);
1367 
1368       SDValue TotalVal;
1369       if (!ANDIVal)
1370         TotalVal = ANDISVal;
1371       else if (!ANDISVal)
1372         TotalVal = ANDIVal;
1373       else
1374         TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1375                              ANDIVal, ANDISVal), 0);
1376 
1377       if (!Res)
1378         Res = TotalVal;
1379       else
1380         Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1381                         Res, TotalVal), 0);
1382 
1383       // Now, remove all groups with this underlying value and rotation
1384       // factor.
1385       eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1386         return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1387       });
1388     }
1389   }
1390 
1391   // Instruction selection for the 32-bit case.
1392   SDNode *Select32(SDNode *N, bool LateMask, unsigned *InstCnt) {
1393     SDLoc dl(N);
1394     SDValue Res;
1395 
1396     if (InstCnt) *InstCnt = 0;
1397 
1398     // Take care of cases that should use andi/andis first.
1399     SelectAndParts32(dl, Res, InstCnt);
1400 
1401     // If we've not yet selected a 'starting' instruction, and we have no zeros
1402     // to fill in, select the (Value, RLAmt) with the highest priority (largest
1403     // number of groups), and start with this rotated value.
1404     if ((!HasZeros || LateMask) && !Res) {
1405       ValueRotInfo &VRI = ValueRotsVec[0];
1406       if (VRI.RLAmt) {
1407         if (InstCnt) *InstCnt += 1;
1408         SDValue Ops[] =
1409           { VRI.V, getI32Imm(VRI.RLAmt, dl), getI32Imm(0, dl),
1410             getI32Imm(31, dl) };
1411         Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
1412                       0);
1413       } else {
1414         Res = VRI.V;
1415       }
1416 
1417       // Now, remove all groups with this underlying value and rotation factor.
1418       eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1419         return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt;
1420       });
1421     }
1422 
1423     if (InstCnt) *InstCnt += BitGroups.size();
1424 
1425     // Insert the other groups (one at a time).
1426     for (auto &BG : BitGroups) {
1427       if (!Res) {
1428         SDValue Ops[] =
1429           { BG.V, getI32Imm(BG.RLAmt, dl),
1430             getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1431             getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1432         Res = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
1433       } else {
1434         SDValue Ops[] =
1435           { Res, BG.V, getI32Imm(BG.RLAmt, dl),
1436               getI32Imm(Bits.size() - BG.EndIdx - 1, dl),
1437             getI32Imm(Bits.size() - BG.StartIdx - 1, dl) };
1438         Res = SDValue(CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops), 0);
1439       }
1440     }
1441 
1442     if (LateMask) {
1443       unsigned Mask = (unsigned) getZerosMask();
1444 
1445       unsigned ANDIMask = (Mask & UINT16_MAX), ANDISMask = Mask >> 16;
1446       assert((ANDIMask != 0 || ANDISMask != 0) &&
1447              "No set bits in zeros mask?");
1448 
1449       if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1450                                (unsigned) (ANDISMask != 0) +
1451                                (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1452 
1453       SDValue ANDIVal, ANDISVal;
1454       if (ANDIMask != 0)
1455         ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo, dl, MVT::i32,
1456                             Res, getI32Imm(ANDIMask, dl)), 0);
1457       if (ANDISMask != 0)
1458         ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo, dl, MVT::i32,
1459                              Res, getI32Imm(ANDISMask, dl)), 0);
1460 
1461       if (!ANDIVal)
1462         Res = ANDISVal;
1463       else if (!ANDISVal)
1464         Res = ANDIVal;
1465       else
1466         Res = SDValue(CurDAG->getMachineNode(PPC::OR, dl, MVT::i32,
1467                         ANDIVal, ANDISVal), 0);
1468     }
1469 
1470     return Res.getNode();
1471   }
1472 
1473   unsigned SelectRotMask64Count(unsigned RLAmt, bool Repl32,
1474                                 unsigned MaskStart, unsigned MaskEnd,
1475                                 bool IsIns) {
1476     // In the notation used by the instructions, 'start' and 'end' are reversed
1477     // because bits are counted from high to low order.
1478     unsigned InstMaskStart = 64 - MaskEnd - 1,
1479              InstMaskEnd   = 64 - MaskStart - 1;
1480 
1481     if (Repl32)
1482       return 1;
1483 
1484     if ((!IsIns && (InstMaskEnd == 63 || InstMaskStart == 0)) ||
1485         InstMaskEnd == 63 - RLAmt)
1486       return 1;
1487 
1488     return 2;
1489   }
1490 
1491   // For 64-bit values, not all combinations of rotates and masks are
1492   // available. Produce one if it is available.
1493   SDValue SelectRotMask64(SDValue V, const SDLoc &dl, unsigned RLAmt,
1494                           bool Repl32, unsigned MaskStart, unsigned MaskEnd,
1495                           unsigned *InstCnt = nullptr) {
1496     // In the notation used by the instructions, 'start' and 'end' are reversed
1497     // because bits are counted from high to low order.
1498     unsigned InstMaskStart = 64 - MaskEnd - 1,
1499              InstMaskEnd   = 64 - MaskStart - 1;
1500 
1501     if (InstCnt) *InstCnt += 1;
1502 
1503     if (Repl32) {
1504       // This rotation amount assumes that the lower 32 bits of the quantity
1505       // are replicated in the high 32 bits by the rotation operator (which is
1506       // done by rlwinm and friends).
1507       assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1508       assert(InstMaskEnd   >= 32 && "Mask cannot end out of range");
1509       SDValue Ops[] =
1510         { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1511           getI32Imm(InstMaskEnd - 32, dl) };
1512       return SDValue(CurDAG->getMachineNode(PPC::RLWINM8, dl, MVT::i64,
1513                                             Ops), 0);
1514     }
1515 
1516     if (InstMaskEnd == 63) {
1517       SDValue Ops[] =
1518         { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1519       return SDValue(CurDAG->getMachineNode(PPC::RLDICL, dl, MVT::i64, Ops), 0);
1520     }
1521 
1522     if (InstMaskStart == 0) {
1523       SDValue Ops[] =
1524         { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskEnd, dl) };
1525       return SDValue(CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64, Ops), 0);
1526     }
1527 
1528     if (InstMaskEnd == 63 - RLAmt) {
1529       SDValue Ops[] =
1530         { V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1531       return SDValue(CurDAG->getMachineNode(PPC::RLDIC, dl, MVT::i64, Ops), 0);
1532     }
1533 
1534     // We cannot do this with a single instruction, so we'll use two. The
1535     // problem is that we're not free to choose both a rotation amount and mask
1536     // start and end independently. We can choose an arbitrary mask start and
1537     // end, but then the rotation amount is fixed. Rotation, however, can be
1538     // inverted, and so by applying an "inverse" rotation first, we can get the
1539     // desired result.
1540     if (InstCnt) *InstCnt += 1;
1541 
1542     // The rotation mask for the second instruction must be MaskStart.
1543     unsigned RLAmt2 = MaskStart;
1544     // The first instruction must rotate V so that the overall rotation amount
1545     // is RLAmt.
1546     unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1547     if (RLAmt1)
1548       V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1549     return SelectRotMask64(V, dl, RLAmt2, false, MaskStart, MaskEnd);
1550   }
1551 
1552   // For 64-bit values, not all combinations of rotates and masks are
1553   // available. Produce a rotate-mask-and-insert if one is available.
1554   SDValue SelectRotMaskIns64(SDValue Base, SDValue V, const SDLoc &dl,
1555                              unsigned RLAmt, bool Repl32, unsigned MaskStart,
1556                              unsigned MaskEnd, unsigned *InstCnt = nullptr) {
1557     // In the notation used by the instructions, 'start' and 'end' are reversed
1558     // because bits are counted from high to low order.
1559     unsigned InstMaskStart = 64 - MaskEnd - 1,
1560              InstMaskEnd   = 64 - MaskStart - 1;
1561 
1562     if (InstCnt) *InstCnt += 1;
1563 
1564     if (Repl32) {
1565       // This rotation amount assumes that the lower 32 bits of the quantity
1566       // are replicated in the high 32 bits by the rotation operator (which is
1567       // done by rlwinm and friends).
1568       assert(InstMaskStart >= 32 && "Mask cannot start out of range");
1569       assert(InstMaskEnd   >= 32 && "Mask cannot end out of range");
1570       SDValue Ops[] =
1571         { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart - 32, dl),
1572           getI32Imm(InstMaskEnd - 32, dl) };
1573       return SDValue(CurDAG->getMachineNode(PPC::RLWIMI8, dl, MVT::i64,
1574                                             Ops), 0);
1575     }
1576 
1577     if (InstMaskEnd == 63 - RLAmt) {
1578       SDValue Ops[] =
1579         { Base, V, getI32Imm(RLAmt, dl), getI32Imm(InstMaskStart, dl) };
1580       return SDValue(CurDAG->getMachineNode(PPC::RLDIMI, dl, MVT::i64, Ops), 0);
1581     }
1582 
1583     // We cannot do this with a single instruction, so we'll use two. The
1584     // problem is that we're not free to choose both a rotation amount and mask
1585     // start and end independently. We can choose an arbitrary mask start and
1586     // end, but then the rotation amount is fixed. Rotation, however, can be
1587     // inverted, and so by applying an "inverse" rotation first, we can get the
1588     // desired result.
1589     if (InstCnt) *InstCnt += 1;
1590 
1591     // The rotation mask for the second instruction must be MaskStart.
1592     unsigned RLAmt2 = MaskStart;
1593     // The first instruction must rotate V so that the overall rotation amount
1594     // is RLAmt.
1595     unsigned RLAmt1 = (64 + RLAmt - RLAmt2) % 64;
1596     if (RLAmt1)
1597       V = SelectRotMask64(V, dl, RLAmt1, false, 0, 63);
1598     return SelectRotMaskIns64(Base, V, dl, RLAmt2, false, MaskStart, MaskEnd);
1599   }
1600 
1601   void SelectAndParts64(const SDLoc &dl, SDValue &Res, unsigned *InstCnt) {
1602     if (BPermRewriterNoMasking)
1603       return;
1604 
1605     // The idea here is the same as in the 32-bit version, but with additional
1606     // complications from the fact that Repl32 might be true. Because we
1607     // aggressively convert bit groups to Repl32 form (which, for small
1608     // rotation factors, involves no other change), and then coalesce, it might
1609     // be the case that a single 64-bit masking operation could handle both
1610     // some Repl32 groups and some non-Repl32 groups. If converting to Repl32
1611     // form allowed coalescing, then we must use a 32-bit rotaton in order to
1612     // completely capture the new combined bit group.
1613 
1614     for (ValueRotInfo &VRI : ValueRotsVec) {
1615       uint64_t Mask = 0;
1616 
1617       // We need to add to the mask all bits from the associated bit groups.
1618       // If Repl32 is false, we need to add bits from bit groups that have
1619       // Repl32 true, but are trivially convertable to Repl32 false. Such a
1620       // group is trivially convertable if it overlaps only with the lower 32
1621       // bits, and the group has not been coalesced.
1622       auto MatchingBG = [VRI](const BitGroup &BG) {
1623         if (VRI.V != BG.V)
1624           return false;
1625 
1626         unsigned EffRLAmt = BG.RLAmt;
1627         if (!VRI.Repl32 && BG.Repl32) {
1628           if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx <= BG.EndIdx &&
1629               !BG.Repl32Coalesced) {
1630             if (BG.Repl32CR)
1631               EffRLAmt += 32;
1632           } else {
1633             return false;
1634           }
1635         } else if (VRI.Repl32 != BG.Repl32) {
1636           return false;
1637         }
1638 
1639         return VRI.RLAmt == EffRLAmt;
1640       };
1641 
1642       for (auto &BG : BitGroups) {
1643         if (!MatchingBG(BG))
1644           continue;
1645 
1646         if (BG.StartIdx <= BG.EndIdx) {
1647           for (unsigned i = BG.StartIdx; i <= BG.EndIdx; ++i)
1648             Mask |= (UINT64_C(1) << i);
1649         } else {
1650           for (unsigned i = BG.StartIdx; i < Bits.size(); ++i)
1651             Mask |= (UINT64_C(1) << i);
1652           for (unsigned i = 0; i <= BG.EndIdx; ++i)
1653             Mask |= (UINT64_C(1) << i);
1654         }
1655       }
1656 
1657       // We can use the 32-bit andi/andis technique if the mask does not
1658       // require any higher-order bits. This can save an instruction compared
1659       // to always using the general 64-bit technique.
1660       bool Use32BitInsts = isUInt<32>(Mask);
1661       // Compute the masks for andi/andis that would be necessary.
1662       unsigned ANDIMask = (Mask & UINT16_MAX),
1663                ANDISMask = (Mask >> 16) & UINT16_MAX;
1664 
1665       bool NeedsRotate = VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask));
1666 
1667       unsigned NumAndInsts = (unsigned) NeedsRotate +
1668                              (unsigned) (bool) Res;
1669       if (Use32BitInsts)
1670         NumAndInsts += (unsigned) (ANDIMask != 0) + (unsigned) (ANDISMask != 0) +
1671                        (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1672       else
1673         NumAndInsts += getInt64Count(Mask) + /* and */ 1;
1674 
1675       unsigned NumRLInsts = 0;
1676       bool FirstBG = true;
1677       bool MoreBG = false;
1678       for (auto &BG : BitGroups) {
1679         if (!MatchingBG(BG)) {
1680           MoreBG = true;
1681           continue;
1682         }
1683         NumRLInsts +=
1684           SelectRotMask64Count(BG.RLAmt, BG.Repl32, BG.StartIdx, BG.EndIdx,
1685                                !FirstBG);
1686         FirstBG = false;
1687       }
1688 
1689       DEBUG(dbgs() << "\t\trotation groups for " << VRI.V.getNode() <<
1690                       " RL: " << VRI.RLAmt << (VRI.Repl32 ? " (32):" : ":") <<
1691                       "\n\t\t\tisel using masking: " << NumAndInsts <<
1692                       " using rotates: " << NumRLInsts << "\n");
1693 
1694       // When we'd use andi/andis, we bias toward using the rotates (andi only
1695       // has a record form, and is cracked on POWER cores). However, when using
1696       // general 64-bit constant formation, bias toward the constant form,
1697       // because that exposes more opportunities for CSE.
1698       if (NumAndInsts > NumRLInsts)
1699         continue;
1700       // When merging multiple bit groups, instruction or is used.
1701       // But when rotate is used, rldimi can inert the rotated value into any
1702       // register, so instruction or can be avoided.
1703       if ((Use32BitInsts || MoreBG) && NumAndInsts == NumRLInsts)
1704         continue;
1705 
1706       DEBUG(dbgs() << "\t\t\t\tusing masking\n");
1707 
1708       if (InstCnt) *InstCnt += NumAndInsts;
1709 
1710       SDValue VRot;
1711       // We actually need to generate a rotation if we have a non-zero rotation
1712       // factor or, in the Repl32 case, if we care about any of the
1713       // higher-order replicated bits. In the latter case, we generate a mask
1714       // backward so that it actually includes the entire 64 bits.
1715       if (VRI.RLAmt || (VRI.Repl32 && !isUInt<32>(Mask)))
1716         VRot = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1717                                VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63);
1718       else
1719         VRot = VRI.V;
1720 
1721       SDValue TotalVal;
1722       if (Use32BitInsts) {
1723         assert((ANDIMask != 0 || ANDISMask != 0) &&
1724                "No set bits in mask when using 32-bit ands for 64-bit value");
1725 
1726         SDValue ANDIVal, ANDISVal;
1727         if (ANDIMask != 0)
1728           ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1729                               VRot, getI32Imm(ANDIMask, dl)), 0);
1730         if (ANDISMask != 0)
1731           ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1732                                VRot, getI32Imm(ANDISMask, dl)), 0);
1733 
1734         if (!ANDIVal)
1735           TotalVal = ANDISVal;
1736         else if (!ANDISVal)
1737           TotalVal = ANDIVal;
1738         else
1739           TotalVal = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1740                                ANDIVal, ANDISVal), 0);
1741       } else {
1742         TotalVal = SDValue(getInt64(CurDAG, dl, Mask), 0);
1743         TotalVal =
1744           SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1745                                          VRot, TotalVal), 0);
1746      }
1747 
1748       if (!Res)
1749         Res = TotalVal;
1750       else
1751         Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1752                                              Res, TotalVal), 0);
1753 
1754       // Now, remove all groups with this underlying value and rotation
1755       // factor.
1756       eraseMatchingBitGroups(MatchingBG);
1757     }
1758   }
1759 
1760   // Instruction selection for the 64-bit case.
1761   SDNode *Select64(SDNode *N, bool LateMask, unsigned *InstCnt) {
1762     SDLoc dl(N);
1763     SDValue Res;
1764 
1765     if (InstCnt) *InstCnt = 0;
1766 
1767     // Take care of cases that should use andi/andis first.
1768     SelectAndParts64(dl, Res, InstCnt);
1769 
1770     // If we've not yet selected a 'starting' instruction, and we have no zeros
1771     // to fill in, select the (Value, RLAmt) with the highest priority (largest
1772     // number of groups), and start with this rotated value.
1773     if ((!HasZeros || LateMask) && !Res) {
1774       // If we have both Repl32 groups and non-Repl32 groups, the non-Repl32
1775       // groups will come first, and so the VRI representing the largest number
1776       // of groups might not be first (it might be the first Repl32 groups).
1777       unsigned MaxGroupsIdx = 0;
1778       if (!ValueRotsVec[0].Repl32) {
1779         for (unsigned i = 0, ie = ValueRotsVec.size(); i < ie; ++i)
1780           if (ValueRotsVec[i].Repl32) {
1781             if (ValueRotsVec[i].NumGroups > ValueRotsVec[0].NumGroups)
1782               MaxGroupsIdx = i;
1783             break;
1784           }
1785       }
1786 
1787       ValueRotInfo &VRI = ValueRotsVec[MaxGroupsIdx];
1788       bool NeedsRotate = false;
1789       if (VRI.RLAmt) {
1790         NeedsRotate = true;
1791       } else if (VRI.Repl32) {
1792         for (auto &BG : BitGroups) {
1793           if (BG.V != VRI.V || BG.RLAmt != VRI.RLAmt ||
1794               BG.Repl32 != VRI.Repl32)
1795             continue;
1796 
1797           // We don't need a rotate if the bit group is confined to the lower
1798           // 32 bits.
1799           if (BG.StartIdx < 32 && BG.EndIdx < 32 && BG.StartIdx < BG.EndIdx)
1800             continue;
1801 
1802           NeedsRotate = true;
1803           break;
1804         }
1805       }
1806 
1807       if (NeedsRotate)
1808         Res = SelectRotMask64(VRI.V, dl, VRI.RLAmt, VRI.Repl32,
1809                               VRI.Repl32 ? 31 : 0, VRI.Repl32 ? 30 : 63,
1810                               InstCnt);
1811       else
1812         Res = VRI.V;
1813 
1814       // Now, remove all groups with this underlying value and rotation factor.
1815       if (Res)
1816         eraseMatchingBitGroups([VRI](const BitGroup &BG) {
1817           return BG.V == VRI.V && BG.RLAmt == VRI.RLAmt &&
1818                  BG.Repl32 == VRI.Repl32;
1819         });
1820     }
1821 
1822     // Because 64-bit rotates are more flexible than inserts, we might have a
1823     // preference regarding which one we do first (to save one instruction).
1824     if (!Res)
1825       for (auto I = BitGroups.begin(), IE = BitGroups.end(); I != IE; ++I) {
1826         if (SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1827                                 false) <
1828             SelectRotMask64Count(I->RLAmt, I->Repl32, I->StartIdx, I->EndIdx,
1829                                 true)) {
1830           if (I != BitGroups.begin()) {
1831             BitGroup BG = *I;
1832             BitGroups.erase(I);
1833             BitGroups.insert(BitGroups.begin(), BG);
1834           }
1835 
1836           break;
1837         }
1838       }
1839 
1840     // Insert the other groups (one at a time).
1841     for (auto &BG : BitGroups) {
1842       if (!Res)
1843         Res = SelectRotMask64(BG.V, dl, BG.RLAmt, BG.Repl32, BG.StartIdx,
1844                               BG.EndIdx, InstCnt);
1845       else
1846         Res = SelectRotMaskIns64(Res, BG.V, dl, BG.RLAmt, BG.Repl32,
1847                                  BG.StartIdx, BG.EndIdx, InstCnt);
1848     }
1849 
1850     if (LateMask) {
1851       uint64_t Mask = getZerosMask();
1852 
1853       // We can use the 32-bit andi/andis technique if the mask does not
1854       // require any higher-order bits. This can save an instruction compared
1855       // to always using the general 64-bit technique.
1856       bool Use32BitInsts = isUInt<32>(Mask);
1857       // Compute the masks for andi/andis that would be necessary.
1858       unsigned ANDIMask = (Mask & UINT16_MAX),
1859                ANDISMask = (Mask >> 16) & UINT16_MAX;
1860 
1861       if (Use32BitInsts) {
1862         assert((ANDIMask != 0 || ANDISMask != 0) &&
1863                "No set bits in mask when using 32-bit ands for 64-bit value");
1864 
1865         if (InstCnt) *InstCnt += (unsigned) (ANDIMask != 0) +
1866                                  (unsigned) (ANDISMask != 0) +
1867                                  (unsigned) (ANDIMask != 0 && ANDISMask != 0);
1868 
1869         SDValue ANDIVal, ANDISVal;
1870         if (ANDIMask != 0)
1871           ANDIVal = SDValue(CurDAG->getMachineNode(PPC::ANDIo8, dl, MVT::i64,
1872                               Res, getI32Imm(ANDIMask, dl)), 0);
1873         if (ANDISMask != 0)
1874           ANDISVal = SDValue(CurDAG->getMachineNode(PPC::ANDISo8, dl, MVT::i64,
1875                                Res, getI32Imm(ANDISMask, dl)), 0);
1876 
1877         if (!ANDIVal)
1878           Res = ANDISVal;
1879         else if (!ANDISVal)
1880           Res = ANDIVal;
1881         else
1882           Res = SDValue(CurDAG->getMachineNode(PPC::OR8, dl, MVT::i64,
1883                           ANDIVal, ANDISVal), 0);
1884       } else {
1885         if (InstCnt) *InstCnt += getInt64Count(Mask) + /* and */ 1;
1886 
1887         SDValue MaskVal = SDValue(getInt64(CurDAG, dl, Mask), 0);
1888         Res =
1889           SDValue(CurDAG->getMachineNode(PPC::AND8, dl, MVT::i64,
1890                                          Res, MaskVal), 0);
1891       }
1892     }
1893 
1894     return Res.getNode();
1895   }
1896 
1897   SDNode *Select(SDNode *N, bool LateMask, unsigned *InstCnt = nullptr) {
1898     // Fill in BitGroups.
1899     collectBitGroups(LateMask);
1900     if (BitGroups.empty())
1901       return nullptr;
1902 
1903     // For 64-bit values, figure out when we can use 32-bit instructions.
1904     if (Bits.size() == 64)
1905       assignRepl32BitGroups();
1906 
1907     // Fill in ValueRotsVec.
1908     collectValueRotInfo();
1909 
1910     if (Bits.size() == 32) {
1911       return Select32(N, LateMask, InstCnt);
1912     } else {
1913       assert(Bits.size() == 64 && "Not 64 bits here?");
1914       return Select64(N, LateMask, InstCnt);
1915     }
1916 
1917     return nullptr;
1918   }
1919 
1920   void eraseMatchingBitGroups(function_ref<bool(const BitGroup &)> F) {
1921     BitGroups.erase(remove_if(BitGroups, F), BitGroups.end());
1922   }
1923 
1924   SmallVector<ValueBit, 64> Bits;
1925 
1926   bool HasZeros;
1927   SmallVector<unsigned, 64> RLAmt;
1928 
1929   SmallVector<BitGroup, 16> BitGroups;
1930 
1931   DenseMap<std::pair<SDValue, unsigned>, ValueRotInfo> ValueRots;
1932   SmallVector<ValueRotInfo, 16> ValueRotsVec;
1933 
1934   SelectionDAG *CurDAG;
1935 
1936 public:
1937   BitPermutationSelector(SelectionDAG *DAG)
1938     : CurDAG(DAG) {}
1939 
1940   // Here we try to match complex bit permutations into a set of
1941   // rotate-and-shift/shift/and/or instructions, using a set of heuristics
1942   // known to produce optimial code for common cases (like i32 byte swapping).
1943   SDNode *Select(SDNode *N) {
1944     Memoizer.clear();
1945     auto Result =
1946         getValueBits(SDValue(N, 0), N->getValueType(0).getSizeInBits());
1947     if (!Result.first)
1948       return nullptr;
1949     Bits = std::move(*Result.second);
1950 
1951     DEBUG(dbgs() << "Considering bit-permutation-based instruction"
1952                     " selection for:    ");
1953     DEBUG(N->dump(CurDAG));
1954 
1955     // Fill it RLAmt and set HasZeros.
1956     computeRotationAmounts();
1957 
1958     if (!HasZeros)
1959       return Select(N, false);
1960 
1961     // We currently have two techniques for handling results with zeros: early
1962     // masking (the default) and late masking. Late masking is sometimes more
1963     // efficient, but because the structure of the bit groups is different, it
1964     // is hard to tell without generating both and comparing the results. With
1965     // late masking, we ignore zeros in the resulting value when inserting each
1966     // set of bit groups, and then mask in the zeros at the end. With early
1967     // masking, we only insert the non-zero parts of the result at every step.
1968 
1969     unsigned InstCnt, InstCntLateMask;
1970     DEBUG(dbgs() << "\tEarly masking:\n");
1971     SDNode *RN = Select(N, false, &InstCnt);
1972     DEBUG(dbgs() << "\t\tisel would use " << InstCnt << " instructions\n");
1973 
1974     DEBUG(dbgs() << "\tLate masking:\n");
1975     SDNode *RNLM = Select(N, true, &InstCntLateMask);
1976     DEBUG(dbgs() << "\t\tisel would use " << InstCntLateMask <<
1977                     " instructions\n");
1978 
1979     if (InstCnt <= InstCntLateMask) {
1980       DEBUG(dbgs() << "\tUsing early-masking for isel\n");
1981       return RN;
1982     }
1983 
1984     DEBUG(dbgs() << "\tUsing late-masking for isel\n");
1985     return RNLM;
1986   }
1987 };
1988 } // anonymous namespace
1989 
1990 bool PPCDAGToDAGISel::tryBitPermutation(SDNode *N) {
1991   if (N->getValueType(0) != MVT::i32 &&
1992       N->getValueType(0) != MVT::i64)
1993     return false;
1994 
1995   if (!UseBitPermRewriter)
1996     return false;
1997 
1998   switch (N->getOpcode()) {
1999   default: break;
2000   case ISD::ROTL:
2001   case ISD::SHL:
2002   case ISD::SRL:
2003   case ISD::AND:
2004   case ISD::OR: {
2005     BitPermutationSelector BPS(CurDAG);
2006     if (SDNode *New = BPS.Select(N)) {
2007       ReplaceNode(N, New);
2008       return true;
2009     }
2010     return false;
2011   }
2012   }
2013 
2014   return false;
2015 }
2016 
2017 /// SelectCC - Select a comparison of the specified values with the specified
2018 /// condition code, returning the CR# of the expression.
2019 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC,
2020                                   const SDLoc &dl) {
2021   // Always select the LHS.
2022   unsigned Opc;
2023 
2024   if (LHS.getValueType() == MVT::i32) {
2025     unsigned Imm;
2026     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2027       if (isInt32Immediate(RHS, Imm)) {
2028         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2029         if (isUInt<16>(Imm))
2030           return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2031                                                 getI32Imm(Imm & 0xFFFF, dl)),
2032                          0);
2033         // If this is a 16-bit signed immediate, fold it.
2034         if (isInt<16>((int)Imm))
2035           return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2036                                                 getI32Imm(Imm & 0xFFFF, dl)),
2037                          0);
2038 
2039         // For non-equality comparisons, the default code would materialize the
2040         // constant, then compare against it, like this:
2041         //   lis r2, 4660
2042         //   ori r2, r2, 22136
2043         //   cmpw cr0, r3, r2
2044         // Since we are just comparing for equality, we can emit this instead:
2045         //   xoris r0,r3,0x1234
2046         //   cmplwi cr0,r0,0x5678
2047         //   beq cr0,L6
2048         SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
2049                                            getI32Imm(Imm >> 16, dl)), 0);
2050         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
2051                                               getI32Imm(Imm & 0xFFFF, dl)), 0);
2052       }
2053       Opc = PPC::CMPLW;
2054     } else if (ISD::isUnsignedIntSetCC(CC)) {
2055       if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
2056         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
2057                                               getI32Imm(Imm & 0xFFFF, dl)), 0);
2058       Opc = PPC::CMPLW;
2059     } else {
2060       short SImm;
2061       if (isIntS16Immediate(RHS, SImm))
2062         return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
2063                                               getI32Imm((int)SImm & 0xFFFF,
2064                                                         dl)),
2065                          0);
2066       Opc = PPC::CMPW;
2067     }
2068   } else if (LHS.getValueType() == MVT::i64) {
2069     uint64_t Imm;
2070     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
2071       if (isInt64Immediate(RHS.getNode(), Imm)) {
2072         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
2073         if (isUInt<16>(Imm))
2074           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2075                                                 getI32Imm(Imm & 0xFFFF, dl)),
2076                          0);
2077         // If this is a 16-bit signed immediate, fold it.
2078         if (isInt<16>(Imm))
2079           return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2080                                                 getI32Imm(Imm & 0xFFFF, dl)),
2081                          0);
2082 
2083         // For non-equality comparisons, the default code would materialize the
2084         // constant, then compare against it, like this:
2085         //   lis r2, 4660
2086         //   ori r2, r2, 22136
2087         //   cmpd cr0, r3, r2
2088         // Since we are just comparing for equality, we can emit this instead:
2089         //   xoris r0,r3,0x1234
2090         //   cmpldi cr0,r0,0x5678
2091         //   beq cr0,L6
2092         if (isUInt<32>(Imm)) {
2093           SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
2094                                              getI64Imm(Imm >> 16, dl)), 0);
2095           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
2096                                                 getI64Imm(Imm & 0xFFFF, dl)),
2097                          0);
2098         }
2099       }
2100       Opc = PPC::CMPLD;
2101     } else if (ISD::isUnsignedIntSetCC(CC)) {
2102       if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
2103         return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
2104                                               getI64Imm(Imm & 0xFFFF, dl)), 0);
2105       Opc = PPC::CMPLD;
2106     } else {
2107       short SImm;
2108       if (isIntS16Immediate(RHS, SImm))
2109         return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
2110                                               getI64Imm(SImm & 0xFFFF, dl)),
2111                          0);
2112       Opc = PPC::CMPD;
2113     }
2114   } else if (LHS.getValueType() == MVT::f32) {
2115     Opc = PPC::FCMPUS;
2116   } else {
2117     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
2118     Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
2119   }
2120   return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
2121 }
2122 
2123 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
2124   switch (CC) {
2125   case ISD::SETUEQ:
2126   case ISD::SETONE:
2127   case ISD::SETOLE:
2128   case ISD::SETOGE:
2129     llvm_unreachable("Should be lowered by legalize!");
2130   default: llvm_unreachable("Unknown condition!");
2131   case ISD::SETOEQ:
2132   case ISD::SETEQ:  return PPC::PRED_EQ;
2133   case ISD::SETUNE:
2134   case ISD::SETNE:  return PPC::PRED_NE;
2135   case ISD::SETOLT:
2136   case ISD::SETLT:  return PPC::PRED_LT;
2137   case ISD::SETULE:
2138   case ISD::SETLE:  return PPC::PRED_LE;
2139   case ISD::SETOGT:
2140   case ISD::SETGT:  return PPC::PRED_GT;
2141   case ISD::SETUGE:
2142   case ISD::SETGE:  return PPC::PRED_GE;
2143   case ISD::SETO:   return PPC::PRED_NU;
2144   case ISD::SETUO:  return PPC::PRED_UN;
2145     // These two are invalid for floating point.  Assume we have int.
2146   case ISD::SETULT: return PPC::PRED_LT;
2147   case ISD::SETUGT: return PPC::PRED_GT;
2148   }
2149 }
2150 
2151 /// getCRIdxForSetCC - Return the index of the condition register field
2152 /// associated with the SetCC condition, and whether or not the field is
2153 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
2154 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
2155   Invert = false;
2156   switch (CC) {
2157   default: llvm_unreachable("Unknown condition!");
2158   case ISD::SETOLT:
2159   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
2160   case ISD::SETOGT:
2161   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
2162   case ISD::SETOEQ:
2163   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
2164   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
2165   case ISD::SETUGE:
2166   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
2167   case ISD::SETULE:
2168   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
2169   case ISD::SETUNE:
2170   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
2171   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
2172   case ISD::SETUEQ:
2173   case ISD::SETOGE:
2174   case ISD::SETOLE:
2175   case ISD::SETONE:
2176     llvm_unreachable("Invalid branch code: should be expanded by legalize");
2177   // These are invalid for floating point.  Assume integer.
2178   case ISD::SETULT: return 0;
2179   case ISD::SETUGT: return 1;
2180   }
2181 }
2182 
2183 // getVCmpInst: return the vector compare instruction for the specified
2184 // vector type and condition code. Since this is for altivec specific code,
2185 // only support the altivec types (v16i8, v8i16, v4i32, v2i64, and v4f32).
2186 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
2187                                 bool HasVSX, bool &Swap, bool &Negate) {
2188   Swap = false;
2189   Negate = false;
2190 
2191   if (VecVT.isFloatingPoint()) {
2192     /* Handle some cases by swapping input operands.  */
2193     switch (CC) {
2194       case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
2195       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2196       case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
2197       case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
2198       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2199       case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
2200       default: break;
2201     }
2202     /* Handle some cases by negating the result.  */
2203     switch (CC) {
2204       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2205       case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
2206       case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
2207       case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
2208       default: break;
2209     }
2210     /* We have instructions implementing the remaining cases.  */
2211     switch (CC) {
2212       case ISD::SETEQ:
2213       case ISD::SETOEQ:
2214         if (VecVT == MVT::v4f32)
2215           return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
2216         else if (VecVT == MVT::v2f64)
2217           return PPC::XVCMPEQDP;
2218         break;
2219       case ISD::SETGT:
2220       case ISD::SETOGT:
2221         if (VecVT == MVT::v4f32)
2222           return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
2223         else if (VecVT == MVT::v2f64)
2224           return PPC::XVCMPGTDP;
2225         break;
2226       case ISD::SETGE:
2227       case ISD::SETOGE:
2228         if (VecVT == MVT::v4f32)
2229           return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
2230         else if (VecVT == MVT::v2f64)
2231           return PPC::XVCMPGEDP;
2232         break;
2233       default:
2234         break;
2235     }
2236     llvm_unreachable("Invalid floating-point vector compare condition");
2237   } else {
2238     /* Handle some cases by swapping input operands.  */
2239     switch (CC) {
2240       case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
2241       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
2242       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
2243       case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
2244       default: break;
2245     }
2246     /* Handle some cases by negating the result.  */
2247     switch (CC) {
2248       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
2249       case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
2250       case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
2251       case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
2252       default: break;
2253     }
2254     /* We have instructions implementing the remaining cases.  */
2255     switch (CC) {
2256       case ISD::SETEQ:
2257       case ISD::SETUEQ:
2258         if (VecVT == MVT::v16i8)
2259           return PPC::VCMPEQUB;
2260         else if (VecVT == MVT::v8i16)
2261           return PPC::VCMPEQUH;
2262         else if (VecVT == MVT::v4i32)
2263           return PPC::VCMPEQUW;
2264         else if (VecVT == MVT::v2i64)
2265           return PPC::VCMPEQUD;
2266         break;
2267       case ISD::SETGT:
2268         if (VecVT == MVT::v16i8)
2269           return PPC::VCMPGTSB;
2270         else if (VecVT == MVT::v8i16)
2271           return PPC::VCMPGTSH;
2272         else if (VecVT == MVT::v4i32)
2273           return PPC::VCMPGTSW;
2274         else if (VecVT == MVT::v2i64)
2275           return PPC::VCMPGTSD;
2276         break;
2277       case ISD::SETUGT:
2278         if (VecVT == MVT::v16i8)
2279           return PPC::VCMPGTUB;
2280         else if (VecVT == MVT::v8i16)
2281           return PPC::VCMPGTUH;
2282         else if (VecVT == MVT::v4i32)
2283           return PPC::VCMPGTUW;
2284         else if (VecVT == MVT::v2i64)
2285           return PPC::VCMPGTUD;
2286         break;
2287       default:
2288         break;
2289     }
2290     llvm_unreachable("Invalid integer vector compare condition");
2291   }
2292 }
2293 
2294 bool PPCDAGToDAGISel::trySETCC(SDNode *N) {
2295   SDLoc dl(N);
2296   unsigned Imm;
2297   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
2298   EVT PtrVT =
2299       CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2300   bool isPPC64 = (PtrVT == MVT::i64);
2301 
2302   if (!PPCSubTarget->useCRBits() &&
2303       isInt32Immediate(N->getOperand(1), Imm)) {
2304     // We can codegen setcc op, imm very efficiently compared to a brcond.
2305     // Check for those cases here.
2306     // setcc op, 0
2307     if (Imm == 0) {
2308       SDValue Op = N->getOperand(0);
2309       switch (CC) {
2310       default: break;
2311       case ISD::SETEQ: {
2312         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
2313         SDValue Ops[] = { Op, getI32Imm(27, dl), getI32Imm(5, dl),
2314                           getI32Imm(31, dl) };
2315         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2316         return true;
2317       }
2318       case ISD::SETNE: {
2319         if (isPPC64) break;
2320         SDValue AD =
2321           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2322                                          Op, getI32Imm(~0U, dl)), 0);
2323         CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
2324         return true;
2325       }
2326       case ISD::SETLT: {
2327         SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2328                           getI32Imm(31, dl) };
2329         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2330         return true;
2331       }
2332       case ISD::SETGT: {
2333         SDValue T =
2334           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
2335         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
2336         SDValue Ops[] = { T, getI32Imm(1, dl), getI32Imm(31, dl),
2337                           getI32Imm(31, dl) };
2338         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2339         return true;
2340       }
2341       }
2342     } else if (Imm == ~0U) {        // setcc op, -1
2343       SDValue Op = N->getOperand(0);
2344       switch (CC) {
2345       default: break;
2346       case ISD::SETEQ:
2347         if (isPPC64) break;
2348         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2349                                             Op, getI32Imm(1, dl)), 0);
2350         CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
2351                              SDValue(CurDAG->getMachineNode(PPC::LI, dl,
2352                                                             MVT::i32,
2353                                                             getI32Imm(0, dl)),
2354                                      0), Op.getValue(1));
2355         return true;
2356       case ISD::SETNE: {
2357         if (isPPC64) break;
2358         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
2359         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2360                                             Op, getI32Imm(~0U, dl));
2361         CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0), Op,
2362                              SDValue(AD, 1));
2363         return true;
2364       }
2365       case ISD::SETLT: {
2366         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
2367                                                     getI32Imm(1, dl)), 0);
2368         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
2369                                                     Op), 0);
2370         SDValue Ops[] = { AN, getI32Imm(1, dl), getI32Imm(31, dl),
2371                           getI32Imm(31, dl) };
2372         CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2373         return true;
2374       }
2375       case ISD::SETGT: {
2376         SDValue Ops[] = { Op, getI32Imm(1, dl), getI32Imm(31, dl),
2377                           getI32Imm(31, dl) };
2378         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2379         CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1, dl));
2380         return true;
2381       }
2382       }
2383     }
2384   }
2385 
2386   SDValue LHS = N->getOperand(0);
2387   SDValue RHS = N->getOperand(1);
2388 
2389   // Altivec Vector compare instructions do not set any CR register by default and
2390   // vector compare operations return the same type as the operands.
2391   if (LHS.getValueType().isVector()) {
2392     if (PPCSubTarget->hasQPX())
2393       return false;
2394 
2395     EVT VecVT = LHS.getValueType();
2396     bool Swap, Negate;
2397     unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
2398                                         PPCSubTarget->hasVSX(), Swap, Negate);
2399     if (Swap)
2400       std::swap(LHS, RHS);
2401 
2402     EVT ResVT = VecVT.changeVectorElementTypeToInteger();
2403     if (Negate) {
2404       SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, ResVT, LHS, RHS), 0);
2405       CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR : PPC::VNOR,
2406                            ResVT, VCmp, VCmp);
2407       return true;
2408     }
2409 
2410     CurDAG->SelectNodeTo(N, VCmpInst, ResVT, LHS, RHS);
2411     return true;
2412   }
2413 
2414   if (PPCSubTarget->useCRBits())
2415     return false;
2416 
2417   bool Inv;
2418   unsigned Idx = getCRIdxForSetCC(CC, Inv);
2419   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
2420   SDValue IntCR;
2421 
2422   // Force the ccreg into CR7.
2423   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
2424 
2425   SDValue InFlag(nullptr, 0);  // Null incoming flag value.
2426   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
2427                                InFlag).getValue(1);
2428 
2429   IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
2430                                          CCReg), 0);
2431 
2432   SDValue Ops[] = { IntCR, getI32Imm((32 - (3 - Idx)) & 31, dl),
2433                       getI32Imm(31, dl), getI32Imm(31, dl) };
2434   if (!Inv) {
2435     CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2436     return true;
2437   }
2438 
2439   // Get the specified bit.
2440   SDValue Tmp =
2441     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
2442   CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1, dl));
2443   return true;
2444 }
2445 
2446 void PPCDAGToDAGISel::transferMemOperands(SDNode *N, SDNode *Result) {
2447   // Transfer memoperands.
2448   MachineSDNode::mmo_iterator MemOp = MF->allocateMemRefsArray(1);
2449   MemOp[0] = cast<MemSDNode>(N)->getMemOperand();
2450   cast<MachineSDNode>(Result)->setMemRefs(MemOp, MemOp + 1);
2451 }
2452 
2453 
2454 // Select - Convert the specified operand from a target-independent to a
2455 // target-specific node if it hasn't already been changed.
2456 void PPCDAGToDAGISel::Select(SDNode *N) {
2457   SDLoc dl(N);
2458   if (N->isMachineOpcode()) {
2459     N->setNodeId(-1);
2460     return;   // Already selected.
2461   }
2462 
2463   // In case any misguided DAG-level optimizations form an ADD with a
2464   // TargetConstant operand, crash here instead of miscompiling (by selecting
2465   // an r+r add instead of some kind of r+i add).
2466   if (N->getOpcode() == ISD::ADD &&
2467       N->getOperand(1).getOpcode() == ISD::TargetConstant)
2468     llvm_unreachable("Invalid ADD with TargetConstant operand");
2469 
2470   // Try matching complex bit permutations before doing anything else.
2471   if (tryBitPermutation(N))
2472     return;
2473 
2474   switch (N->getOpcode()) {
2475   default: break;
2476 
2477   case ISD::Constant: {
2478     if (N->getValueType(0) == MVT::i64) {
2479       ReplaceNode(N, getInt64(CurDAG, N));
2480       return;
2481     }
2482     break;
2483   }
2484 
2485   case ISD::SETCC: {
2486     if (trySETCC(N))
2487       return;
2488     break;
2489   }
2490   case PPCISD::GlobalBaseReg:
2491     ReplaceNode(N, getGlobalBaseReg());
2492     return;
2493 
2494   case ISD::FrameIndex:
2495     selectFrameIndex(N, N);
2496     return;
2497 
2498   case PPCISD::MFOCRF: {
2499     SDValue InFlag = N->getOperand(1);
2500     ReplaceNode(N, CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
2501                                           N->getOperand(0), InFlag));
2502     return;
2503   }
2504 
2505   case PPCISD::READ_TIME_BASE: {
2506     ReplaceNode(N, CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
2507                                           MVT::Other, N->getOperand(0)));
2508     return;
2509   }
2510 
2511   case PPCISD::SRA_ADDZE: {
2512     SDValue N0 = N->getOperand(0);
2513     SDValue ShiftAmt =
2514       CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
2515                                   getConstantIntValue(), dl,
2516                                   N->getValueType(0));
2517     if (N->getValueType(0) == MVT::i64) {
2518       SDNode *Op =
2519         CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
2520                                N0, ShiftAmt);
2521       CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64, SDValue(Op, 0),
2522                            SDValue(Op, 1));
2523       return;
2524     } else {
2525       assert(N->getValueType(0) == MVT::i32 &&
2526              "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
2527       SDNode *Op =
2528         CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
2529                                N0, ShiftAmt);
2530       CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, SDValue(Op, 0),
2531                            SDValue(Op, 1));
2532       return;
2533     }
2534   }
2535 
2536   case ISD::LOAD: {
2537     // Handle preincrement loads.
2538     LoadSDNode *LD = cast<LoadSDNode>(N);
2539     EVT LoadedVT = LD->getMemoryVT();
2540 
2541     // Normal loads are handled by code generated from the .td file.
2542     if (LD->getAddressingMode() != ISD::PRE_INC)
2543       break;
2544 
2545     SDValue Offset = LD->getOffset();
2546     if (Offset.getOpcode() == ISD::TargetConstant ||
2547         Offset.getOpcode() == ISD::TargetGlobalAddress) {
2548 
2549       unsigned Opcode;
2550       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2551       if (LD->getValueType(0) != MVT::i64) {
2552         // Handle PPC32 integer and normal FP loads.
2553         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2554         switch (LoadedVT.getSimpleVT().SimpleTy) {
2555           default: llvm_unreachable("Invalid PPC load type!");
2556           case MVT::f64: Opcode = PPC::LFDU; break;
2557           case MVT::f32: Opcode = PPC::LFSU; break;
2558           case MVT::i32: Opcode = PPC::LWZU; break;
2559           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
2560           case MVT::i1:
2561           case MVT::i8:  Opcode = PPC::LBZU; break;
2562         }
2563       } else {
2564         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2565         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2566         switch (LoadedVT.getSimpleVT().SimpleTy) {
2567           default: llvm_unreachable("Invalid PPC load type!");
2568           case MVT::i64: Opcode = PPC::LDU; break;
2569           case MVT::i32: Opcode = PPC::LWZU8; break;
2570           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
2571           case MVT::i1:
2572           case MVT::i8:  Opcode = PPC::LBZU8; break;
2573         }
2574       }
2575 
2576       SDValue Chain = LD->getChain();
2577       SDValue Base = LD->getBasePtr();
2578       SDValue Ops[] = { Offset, Base, Chain };
2579       SDNode *MN = CurDAG->getMachineNode(
2580           Opcode, dl, LD->getValueType(0),
2581           PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
2582       transferMemOperands(N, MN);
2583       ReplaceNode(N, MN);
2584       return;
2585     } else {
2586       unsigned Opcode;
2587       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
2588       if (LD->getValueType(0) != MVT::i64) {
2589         // Handle PPC32 integer and normal FP loads.
2590         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
2591         switch (LoadedVT.getSimpleVT().SimpleTy) {
2592           default: llvm_unreachable("Invalid PPC load type!");
2593           case MVT::v4f64: Opcode = PPC::QVLFDUX; break; // QPX
2594           case MVT::v4f32: Opcode = PPC::QVLFSUX; break; // QPX
2595           case MVT::f64: Opcode = PPC::LFDUX; break;
2596           case MVT::f32: Opcode = PPC::LFSUX; break;
2597           case MVT::i32: Opcode = PPC::LWZUX; break;
2598           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
2599           case MVT::i1:
2600           case MVT::i8:  Opcode = PPC::LBZUX; break;
2601         }
2602       } else {
2603         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
2604         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
2605                "Invalid sext update load");
2606         switch (LoadedVT.getSimpleVT().SimpleTy) {
2607           default: llvm_unreachable("Invalid PPC load type!");
2608           case MVT::i64: Opcode = PPC::LDUX; break;
2609           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
2610           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
2611           case MVT::i1:
2612           case MVT::i8:  Opcode = PPC::LBZUX8; break;
2613         }
2614       }
2615 
2616       SDValue Chain = LD->getChain();
2617       SDValue Base = LD->getBasePtr();
2618       SDValue Ops[] = { Base, Offset, Chain };
2619       SDNode *MN = CurDAG->getMachineNode(
2620           Opcode, dl, LD->getValueType(0),
2621           PPCLowering->getPointerTy(CurDAG->getDataLayout()), MVT::Other, Ops);
2622       transferMemOperands(N, MN);
2623       ReplaceNode(N, MN);
2624       return;
2625     }
2626   }
2627 
2628   case ISD::AND: {
2629     unsigned Imm, Imm2, SH, MB, ME;
2630     uint64_t Imm64;
2631 
2632     // If this is an and of a value rotated between 0 and 31 bits and then and'd
2633     // with a mask, emit rlwinm
2634     if (isInt32Immediate(N->getOperand(1), Imm) &&
2635         isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
2636       SDValue Val = N->getOperand(0).getOperand(0);
2637       SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl),
2638                         getI32Imm(ME, dl) };
2639       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2640       return;
2641     }
2642     // If this is just a masked value where the input is not handled above, and
2643     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
2644     if (isInt32Immediate(N->getOperand(1), Imm) &&
2645         isRunOfOnes(Imm, MB, ME) &&
2646         N->getOperand(0).getOpcode() != ISD::ROTL) {
2647       SDValue Val = N->getOperand(0);
2648       SDValue Ops[] = { Val, getI32Imm(0, dl), getI32Imm(MB, dl),
2649                         getI32Imm(ME, dl) };
2650       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2651       return;
2652     }
2653     // If this is a 64-bit zero-extension mask, emit rldicl.
2654     if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
2655         isMask_64(Imm64)) {
2656       SDValue Val = N->getOperand(0);
2657       MB = 64 - countTrailingOnes(Imm64);
2658       SH = 0;
2659 
2660       // If the operand is a logical right shift, we can fold it into this
2661       // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
2662       // for n <= mb. The right shift is really a left rotate followed by a
2663       // mask, and this mask is a more-restrictive sub-mask of the mask implied
2664       // by the shift.
2665       if (Val.getOpcode() == ISD::SRL &&
2666           isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
2667         assert(Imm < 64 && "Illegal shift amount");
2668         Val = Val.getOperand(0);
2669         SH = 64 - Imm;
2670       }
2671 
2672       SDValue Ops[] = { Val, getI32Imm(SH, dl), getI32Imm(MB, dl) };
2673       CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
2674       return;
2675     }
2676     // AND X, 0 -> 0, not "rlwinm 32".
2677     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
2678       ReplaceUses(SDValue(N, 0), N->getOperand(1));
2679       return;
2680     }
2681     // ISD::OR doesn't get all the bitfield insertion fun.
2682     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) might be a
2683     // bitfield insert.
2684     if (isInt32Immediate(N->getOperand(1), Imm) &&
2685         N->getOperand(0).getOpcode() == ISD::OR &&
2686         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
2687       // The idea here is to check whether this is equivalent to:
2688       //   (c1 & m) | (x & ~m)
2689       // where m is a run-of-ones mask. The logic here is that, for each bit in
2690       // c1 and c2:
2691       //  - if both are 1, then the output will be 1.
2692       //  - if both are 0, then the output will be 0.
2693       //  - if the bit in c1 is 0, and the bit in c2 is 1, then the output will
2694       //    come from x.
2695       //  - if the bit in c1 is 1, and the bit in c2 is 0, then the output will
2696       //    be 0.
2697       //  If that last condition is never the case, then we can form m from the
2698       //  bits that are the same between c1 and c2.
2699       unsigned MB, ME;
2700       if (isRunOfOnes(~(Imm^Imm2), MB, ME) && !(~Imm & Imm2)) {
2701         SDValue Ops[] = { N->getOperand(0).getOperand(0),
2702                             N->getOperand(0).getOperand(1),
2703                             getI32Imm(0, dl), getI32Imm(MB, dl),
2704                             getI32Imm(ME, dl) };
2705         ReplaceNode(N, CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops));
2706         return;
2707       }
2708     }
2709 
2710     // Other cases are autogenerated.
2711     break;
2712   }
2713   case ISD::OR: {
2714     if (N->getValueType(0) == MVT::i32)
2715       if (tryBitfieldInsert(N))
2716         return;
2717 
2718     short Imm;
2719     if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2720         isIntS16Immediate(N->getOperand(1), Imm)) {
2721       APInt LHSKnownZero, LHSKnownOne;
2722       CurDAG->computeKnownBits(N->getOperand(0), LHSKnownZero, LHSKnownOne);
2723 
2724       // If this is equivalent to an add, then we can fold it with the
2725       // FrameIndex calculation.
2726       if ((LHSKnownZero.getZExtValue()|~(uint64_t)Imm) == ~0ULL) {
2727         selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2728         return;
2729       }
2730     }
2731 
2732     // Other cases are autogenerated.
2733     break;
2734   }
2735   case ISD::ADD: {
2736     short Imm;
2737     if (N->getOperand(0)->getOpcode() == ISD::FrameIndex &&
2738         isIntS16Immediate(N->getOperand(1), Imm)) {
2739       selectFrameIndex(N, N->getOperand(0).getNode(), (int)Imm);
2740       return;
2741     }
2742 
2743     break;
2744   }
2745   case ISD::SHL: {
2746     unsigned Imm, SH, MB, ME;
2747     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2748         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2749       SDValue Ops[] = { N->getOperand(0).getOperand(0),
2750                           getI32Imm(SH, dl), getI32Imm(MB, dl),
2751                           getI32Imm(ME, dl) };
2752       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2753       return;
2754     }
2755 
2756     // Other cases are autogenerated.
2757     break;
2758   }
2759   case ISD::SRL: {
2760     unsigned Imm, SH, MB, ME;
2761     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
2762         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
2763       SDValue Ops[] = { N->getOperand(0).getOperand(0),
2764                           getI32Imm(SH, dl), getI32Imm(MB, dl),
2765                           getI32Imm(ME, dl) };
2766       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
2767       return;
2768     }
2769 
2770     // Other cases are autogenerated.
2771     break;
2772   }
2773   // FIXME: Remove this once the ANDI glue bug is fixed:
2774   case PPCISD::ANDIo_1_EQ_BIT:
2775   case PPCISD::ANDIo_1_GT_BIT: {
2776     if (!ANDIGlueBug)
2777       break;
2778 
2779     EVT InVT = N->getOperand(0).getValueType();
2780     assert((InVT == MVT::i64 || InVT == MVT::i32) &&
2781            "Invalid input type for ANDIo_1_EQ_BIT");
2782 
2783     unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
2784     SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
2785                                         N->getOperand(0),
2786                                         CurDAG->getTargetConstant(1, dl, InVT)),
2787                  0);
2788     SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
2789     SDValue SRIdxVal =
2790       CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
2791                                 PPC::sub_eq : PPC::sub_gt, dl, MVT::i32);
2792 
2793     CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1, CR0Reg,
2794                          SRIdxVal, SDValue(AndI.getNode(), 1) /* glue */);
2795     return;
2796   }
2797   case ISD::SELECT_CC: {
2798     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
2799     EVT PtrVT =
2800         CurDAG->getTargetLoweringInfo().getPointerTy(CurDAG->getDataLayout());
2801     bool isPPC64 = (PtrVT == MVT::i64);
2802 
2803     // If this is a select of i1 operands, we'll pattern match it.
2804     if (PPCSubTarget->useCRBits() &&
2805         N->getOperand(0).getValueType() == MVT::i1)
2806       break;
2807 
2808     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
2809     if (!isPPC64)
2810       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
2811         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
2812           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
2813             if (N1C->isNullValue() && N3C->isNullValue() &&
2814                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
2815                 // FIXME: Implement this optzn for PPC64.
2816                 N->getValueType(0) == MVT::i32) {
2817               SDNode *Tmp =
2818                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
2819                                        N->getOperand(0), getI32Imm(~0U, dl));
2820               CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(Tmp, 0),
2821                                    N->getOperand(0), SDValue(Tmp, 1));
2822               return;
2823             }
2824 
2825     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
2826 
2827     if (N->getValueType(0) == MVT::i1) {
2828       // An i1 select is: (c & t) | (!c & f).
2829       bool Inv;
2830       unsigned Idx = getCRIdxForSetCC(CC, Inv);
2831 
2832       unsigned SRI;
2833       switch (Idx) {
2834       default: llvm_unreachable("Invalid CC index");
2835       case 0: SRI = PPC::sub_lt; break;
2836       case 1: SRI = PPC::sub_gt; break;
2837       case 2: SRI = PPC::sub_eq; break;
2838       case 3: SRI = PPC::sub_un; break;
2839       }
2840 
2841       SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
2842 
2843       SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
2844                                               CCBit, CCBit), 0);
2845       SDValue C =    Inv ? NotCCBit : CCBit,
2846               NotC = Inv ? CCBit    : NotCCBit;
2847 
2848       SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2849                                            C, N->getOperand(2)), 0);
2850       SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
2851                                               NotC, N->getOperand(3)), 0);
2852 
2853       CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
2854       return;
2855     }
2856 
2857     unsigned BROpc = getPredicateForSetCC(CC);
2858 
2859     unsigned SelectCCOp;
2860     if (N->getValueType(0) == MVT::i32)
2861       SelectCCOp = PPC::SELECT_CC_I4;
2862     else if (N->getValueType(0) == MVT::i64)
2863       SelectCCOp = PPC::SELECT_CC_I8;
2864     else if (N->getValueType(0) == MVT::f32)
2865       if (PPCSubTarget->hasP8Vector())
2866         SelectCCOp = PPC::SELECT_CC_VSSRC;
2867       else
2868         SelectCCOp = PPC::SELECT_CC_F4;
2869     else if (N->getValueType(0) == MVT::f64)
2870       if (PPCSubTarget->hasVSX())
2871         SelectCCOp = PPC::SELECT_CC_VSFRC;
2872       else
2873         SelectCCOp = PPC::SELECT_CC_F8;
2874     else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f64)
2875       SelectCCOp = PPC::SELECT_CC_QFRC;
2876     else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4f32)
2877       SelectCCOp = PPC::SELECT_CC_QSRC;
2878     else if (PPCSubTarget->hasQPX() && N->getValueType(0) == MVT::v4i1)
2879       SelectCCOp = PPC::SELECT_CC_QBRC;
2880     else if (N->getValueType(0) == MVT::v2f64 ||
2881              N->getValueType(0) == MVT::v2i64)
2882       SelectCCOp = PPC::SELECT_CC_VSRC;
2883     else
2884       SelectCCOp = PPC::SELECT_CC_VRRC;
2885 
2886     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
2887                         getI32Imm(BROpc, dl) };
2888     CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
2889     return;
2890   }
2891   case ISD::VSELECT:
2892     if (PPCSubTarget->hasVSX()) {
2893       SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
2894       CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
2895       return;
2896     }
2897 
2898     break;
2899   case ISD::VECTOR_SHUFFLE:
2900     if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
2901                                   N->getValueType(0) == MVT::v2i64)) {
2902       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
2903 
2904       SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
2905               Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
2906       unsigned DM[2];
2907 
2908       for (int i = 0; i < 2; ++i)
2909         if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
2910           DM[i] = 0;
2911         else
2912           DM[i] = 1;
2913 
2914       if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
2915           Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
2916           isa<LoadSDNode>(Op1.getOperand(0))) {
2917         LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
2918         SDValue Base, Offset;
2919 
2920         if (LD->isUnindexed() && LD->hasOneUse() && Op1.hasOneUse() &&
2921             (LD->getMemoryVT() == MVT::f64 ||
2922              LD->getMemoryVT() == MVT::i64) &&
2923             SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
2924           SDValue Chain = LD->getChain();
2925           SDValue Ops[] = { Base, Offset, Chain };
2926           CurDAG->SelectNodeTo(N, PPC::LXVDSX, N->getValueType(0), Ops);
2927           return;
2928         }
2929       }
2930 
2931       // For little endian, we must swap the input operands and adjust
2932       // the mask elements (reverse and invert them).
2933       if (PPCSubTarget->isLittleEndian()) {
2934         std::swap(Op1, Op2);
2935         unsigned tmp = DM[0];
2936         DM[0] = 1 - DM[1];
2937         DM[1] = 1 - tmp;
2938       }
2939 
2940       SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), dl,
2941                                               MVT::i32);
2942       SDValue Ops[] = { Op1, Op2, DMV };
2943       CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
2944       return;
2945     }
2946 
2947     break;
2948   case PPCISD::BDNZ:
2949   case PPCISD::BDZ: {
2950     bool IsPPC64 = PPCSubTarget->isPPC64();
2951     SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
2952     CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ
2953                                 ? (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ)
2954                                 : (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
2955                          MVT::Other, Ops);
2956     return;
2957   }
2958   case PPCISD::COND_BRANCH: {
2959     // Op #0 is the Chain.
2960     // Op #1 is the PPC::PRED_* number.
2961     // Op #2 is the CR#
2962     // Op #3 is the Dest MBB
2963     // Op #4 is the Flag.
2964     // Prevent PPC::PRED_* from being selected into LI.
2965     unsigned PCC = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
2966     if (EnableBranchHint)
2967       PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(3));
2968 
2969     SDValue Pred = getI32Imm(PCC, dl);
2970     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
2971       N->getOperand(0), N->getOperand(4) };
2972     CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
2973     return;
2974   }
2975   case ISD::BR_CC: {
2976     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
2977     unsigned PCC = getPredicateForSetCC(CC);
2978 
2979     if (N->getOperand(2).getValueType() == MVT::i1) {
2980       unsigned Opc;
2981       bool Swap;
2982       switch (PCC) {
2983       default: llvm_unreachable("Unexpected Boolean-operand predicate");
2984       case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true;  break;
2985       case PPC::PRED_LE: Opc = PPC::CRORC;  Swap = true;  break;
2986       case PPC::PRED_EQ: Opc = PPC::CREQV;  Swap = false; break;
2987       case PPC::PRED_GE: Opc = PPC::CRORC;  Swap = false; break;
2988       case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
2989       case PPC::PRED_NE: Opc = PPC::CRXOR;  Swap = false; break;
2990       }
2991 
2992       SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
2993                                              N->getOperand(Swap ? 3 : 2),
2994                                              N->getOperand(Swap ? 2 : 3)), 0);
2995       CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other, BitComp, N->getOperand(4),
2996                            N->getOperand(0));
2997       return;
2998     }
2999 
3000     if (EnableBranchHint)
3001       PCC |= getBranchHint(PCC, FuncInfo, N->getOperand(4));
3002 
3003     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
3004     SDValue Ops[] = { getI32Imm(PCC, dl), CondCode,
3005                         N->getOperand(4), N->getOperand(0) };
3006     CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
3007     return;
3008   }
3009   case ISD::BRIND: {
3010     // FIXME: Should custom lower this.
3011     SDValue Chain = N->getOperand(0);
3012     SDValue Target = N->getOperand(1);
3013     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
3014     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
3015     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
3016                                            Chain), 0);
3017     CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
3018     return;
3019   }
3020   case PPCISD::TOC_ENTRY: {
3021     assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
3022             "Only supported for 64-bit ABI and 32-bit SVR4");
3023     if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
3024       SDValue GA = N->getOperand(0);
3025       SDNode *MN = CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
3026                                           N->getOperand(1));
3027       transferMemOperands(N, MN);
3028       ReplaceNode(N, MN);
3029       return;
3030     }
3031 
3032     // For medium and large code model, we generate two instructions as
3033     // described below.  Otherwise we allow SelectCodeCommon to handle this,
3034     // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
3035     CodeModel::Model CModel = TM.getCodeModel();
3036     if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
3037       break;
3038 
3039     // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
3040     // If it must be toc-referenced according to PPCSubTarget, we generate:
3041     //   LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
3042     // Otherwise we generate:
3043     //   ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
3044     SDValue GA = N->getOperand(0);
3045     SDValue TOCbase = N->getOperand(1);
3046     SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
3047                                          TOCbase, GA);
3048 
3049     if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
3050         CModel == CodeModel::Large) {
3051       SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
3052                                           SDValue(Tmp, 0));
3053       transferMemOperands(N, MN);
3054       ReplaceNode(N, MN);
3055       return;
3056     }
3057 
3058     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
3059       const GlobalValue *GV = G->getGlobal();
3060       unsigned char GVFlags = PPCSubTarget->classifyGlobalReference(GV);
3061       if (GVFlags & PPCII::MO_NLP_FLAG) {
3062         SDNode *MN = CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
3063                                             SDValue(Tmp, 0));
3064         transferMemOperands(N, MN);
3065         ReplaceNode(N, MN);
3066         return;
3067       }
3068     }
3069 
3070     ReplaceNode(N, CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
3071                                           SDValue(Tmp, 0), GA));
3072     return;
3073   }
3074   case PPCISD::PPC32_PICGOT: {
3075     // Generate a PIC-safe GOT reference.
3076     assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
3077       "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
3078     CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT,
3079                          PPCLowering->getPointerTy(CurDAG->getDataLayout()),
3080                          MVT::i32);
3081     return;
3082   }
3083   case PPCISD::VADD_SPLAT: {
3084     // This expands into one of three sequences, depending on whether
3085     // the first operand is odd or even, positive or negative.
3086     assert(isa<ConstantSDNode>(N->getOperand(0)) &&
3087            isa<ConstantSDNode>(N->getOperand(1)) &&
3088            "Invalid operand on VADD_SPLAT!");
3089 
3090     int Elt     = N->getConstantOperandVal(0);
3091     int EltSize = N->getConstantOperandVal(1);
3092     unsigned Opc1, Opc2, Opc3;
3093     EVT VT;
3094 
3095     if (EltSize == 1) {
3096       Opc1 = PPC::VSPLTISB;
3097       Opc2 = PPC::VADDUBM;
3098       Opc3 = PPC::VSUBUBM;
3099       VT = MVT::v16i8;
3100     } else if (EltSize == 2) {
3101       Opc1 = PPC::VSPLTISH;
3102       Opc2 = PPC::VADDUHM;
3103       Opc3 = PPC::VSUBUHM;
3104       VT = MVT::v8i16;
3105     } else {
3106       assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
3107       Opc1 = PPC::VSPLTISW;
3108       Opc2 = PPC::VADDUWM;
3109       Opc3 = PPC::VSUBUWM;
3110       VT = MVT::v4i32;
3111     }
3112 
3113     if ((Elt & 1) == 0) {
3114       // Elt is even, in the range [-32,-18] + [16,30].
3115       //
3116       // Convert: VADD_SPLAT elt, size
3117       // Into:    tmp = VSPLTIS[BHW] elt
3118       //          VADDU[BHW]M tmp, tmp
3119       // Where:   [BHW] = B for size = 1, H for size = 2, W for size = 4
3120       SDValue EltVal = getI32Imm(Elt >> 1, dl);
3121       SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3122       SDValue TmpVal = SDValue(Tmp, 0);
3123       ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal));
3124       return;
3125 
3126     } else if (Elt > 0) {
3127       // Elt is odd and positive, in the range [17,31].
3128       //
3129       // Convert: VADD_SPLAT elt, size
3130       // Into:    tmp1 = VSPLTIS[BHW] elt-16
3131       //          tmp2 = VSPLTIS[BHW] -16
3132       //          VSUBU[BHW]M tmp1, tmp2
3133       SDValue EltVal = getI32Imm(Elt - 16, dl);
3134       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3135       EltVal = getI32Imm(-16, dl);
3136       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3137       ReplaceNode(N, CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
3138                                             SDValue(Tmp2, 0)));
3139       return;
3140 
3141     } else {
3142       // Elt is odd and negative, in the range [-31,-17].
3143       //
3144       // Convert: VADD_SPLAT elt, size
3145       // Into:    tmp1 = VSPLTIS[BHW] elt+16
3146       //          tmp2 = VSPLTIS[BHW] -16
3147       //          VADDU[BHW]M tmp1, tmp2
3148       SDValue EltVal = getI32Imm(Elt + 16, dl);
3149       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3150       EltVal = getI32Imm(-16, dl);
3151       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
3152       ReplaceNode(N, CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
3153                                             SDValue(Tmp2, 0)));
3154       return;
3155     }
3156   }
3157   }
3158 
3159   SelectCode(N);
3160 }
3161 
3162 // If the target supports the cmpb instruction, do the idiom recognition here.
3163 // We don't do this as a DAG combine because we don't want to do it as nodes
3164 // are being combined (because we might miss part of the eventual idiom). We
3165 // don't want to do it during instruction selection because we want to reuse
3166 // the logic for lowering the masking operations already part of the
3167 // instruction selector.
3168 SDValue PPCDAGToDAGISel::combineToCMPB(SDNode *N) {
3169   SDLoc dl(N);
3170 
3171   assert(N->getOpcode() == ISD::OR &&
3172          "Only OR nodes are supported for CMPB");
3173 
3174   SDValue Res;
3175   if (!PPCSubTarget->hasCMPB())
3176     return Res;
3177 
3178   if (N->getValueType(0) != MVT::i32 &&
3179       N->getValueType(0) != MVT::i64)
3180     return Res;
3181 
3182   EVT VT = N->getValueType(0);
3183 
3184   SDValue RHS, LHS;
3185   bool BytesFound[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
3186   uint64_t Mask = 0, Alt = 0;
3187 
3188   auto IsByteSelectCC = [this](SDValue O, unsigned &b,
3189                                uint64_t &Mask, uint64_t &Alt,
3190                                SDValue &LHS, SDValue &RHS) {
3191     if (O.getOpcode() != ISD::SELECT_CC)
3192       return false;
3193     ISD::CondCode CC = cast<CondCodeSDNode>(O.getOperand(4))->get();
3194 
3195     if (!isa<ConstantSDNode>(O.getOperand(2)) ||
3196         !isa<ConstantSDNode>(O.getOperand(3)))
3197       return false;
3198 
3199     uint64_t PM = O.getConstantOperandVal(2);
3200     uint64_t PAlt = O.getConstantOperandVal(3);
3201     for (b = 0; b < 8; ++b) {
3202       uint64_t Mask = UINT64_C(0xFF) << (8*b);
3203       if (PM && (PM & Mask) == PM && (PAlt & Mask) == PAlt)
3204         break;
3205     }
3206 
3207     if (b == 8)
3208       return false;
3209     Mask |= PM;
3210     Alt  |= PAlt;
3211 
3212     if (!isa<ConstantSDNode>(O.getOperand(1)) ||
3213         O.getConstantOperandVal(1) != 0) {
3214       SDValue Op0 = O.getOperand(0), Op1 = O.getOperand(1);
3215       if (Op0.getOpcode() == ISD::TRUNCATE)
3216         Op0 = Op0.getOperand(0);
3217       if (Op1.getOpcode() == ISD::TRUNCATE)
3218         Op1 = Op1.getOperand(0);
3219 
3220       if (Op0.getOpcode() == ISD::SRL && Op1.getOpcode() == ISD::SRL &&
3221           Op0.getOperand(1) == Op1.getOperand(1) && CC == ISD::SETEQ &&
3222           isa<ConstantSDNode>(Op0.getOperand(1))) {
3223 
3224         unsigned Bits = Op0.getValueSizeInBits();
3225         if (b != Bits/8-1)
3226           return false;
3227         if (Op0.getConstantOperandVal(1) != Bits-8)
3228           return false;
3229 
3230         LHS = Op0.getOperand(0);
3231         RHS = Op1.getOperand(0);
3232         return true;
3233       }
3234 
3235       // When we have small integers (i16 to be specific), the form present
3236       // post-legalization uses SETULT in the SELECT_CC for the
3237       // higher-order byte, depending on the fact that the
3238       // even-higher-order bytes are known to all be zero, for example:
3239       //   select_cc (xor $lhs, $rhs), 256, 65280, 0, setult
3240       // (so when the second byte is the same, because all higher-order
3241       // bits from bytes 3 and 4 are known to be zero, the result of the
3242       // xor can be at most 255)
3243       if (Op0.getOpcode() == ISD::XOR && CC == ISD::SETULT &&
3244           isa<ConstantSDNode>(O.getOperand(1))) {
3245 
3246         uint64_t ULim = O.getConstantOperandVal(1);
3247         if (ULim != (UINT64_C(1) << b*8))
3248           return false;
3249 
3250         // Now we need to make sure that the upper bytes are known to be
3251         // zero.
3252         unsigned Bits = Op0.getValueSizeInBits();
3253         if (!CurDAG->MaskedValueIsZero(
3254                 Op0, APInt::getHighBitsSet(Bits, Bits - (b + 1) * 8)))
3255           return false;
3256 
3257         LHS = Op0.getOperand(0);
3258         RHS = Op0.getOperand(1);
3259         return true;
3260       }
3261 
3262       return false;
3263     }
3264 
3265     if (CC != ISD::SETEQ)
3266       return false;
3267 
3268     SDValue Op = O.getOperand(0);
3269     if (Op.getOpcode() == ISD::AND) {
3270       if (!isa<ConstantSDNode>(Op.getOperand(1)))
3271         return false;
3272       if (Op.getConstantOperandVal(1) != (UINT64_C(0xFF) << (8*b)))
3273         return false;
3274 
3275       SDValue XOR = Op.getOperand(0);
3276       if (XOR.getOpcode() == ISD::TRUNCATE)
3277         XOR = XOR.getOperand(0);
3278       if (XOR.getOpcode() != ISD::XOR)
3279         return false;
3280 
3281       LHS = XOR.getOperand(0);
3282       RHS = XOR.getOperand(1);
3283       return true;
3284     } else if (Op.getOpcode() == ISD::SRL) {
3285       if (!isa<ConstantSDNode>(Op.getOperand(1)))
3286         return false;
3287       unsigned Bits = Op.getValueSizeInBits();
3288       if (b != Bits/8-1)
3289         return false;
3290       if (Op.getConstantOperandVal(1) != Bits-8)
3291         return false;
3292 
3293       SDValue XOR = Op.getOperand(0);
3294       if (XOR.getOpcode() == ISD::TRUNCATE)
3295         XOR = XOR.getOperand(0);
3296       if (XOR.getOpcode() != ISD::XOR)
3297         return false;
3298 
3299       LHS = XOR.getOperand(0);
3300       RHS = XOR.getOperand(1);
3301       return true;
3302     }
3303 
3304     return false;
3305   };
3306 
3307   SmallVector<SDValue, 8> Queue(1, SDValue(N, 0));
3308   while (!Queue.empty()) {
3309     SDValue V = Queue.pop_back_val();
3310 
3311     for (const SDValue &O : V.getNode()->ops()) {
3312       unsigned b;
3313       uint64_t M = 0, A = 0;
3314       SDValue OLHS, ORHS;
3315       if (O.getOpcode() == ISD::OR) {
3316         Queue.push_back(O);
3317       } else if (IsByteSelectCC(O, b, M, A, OLHS, ORHS)) {
3318         if (!LHS) {
3319           LHS = OLHS;
3320           RHS = ORHS;
3321           BytesFound[b] = true;
3322           Mask |= M;
3323           Alt  |= A;
3324         } else if ((LHS == ORHS && RHS == OLHS) ||
3325                    (RHS == ORHS && LHS == OLHS)) {
3326           BytesFound[b] = true;
3327           Mask |= M;
3328           Alt  |= A;
3329         } else {
3330           return Res;
3331         }
3332       } else {
3333         return Res;
3334       }
3335     }
3336   }
3337 
3338   unsigned LastB = 0, BCnt = 0;
3339   for (unsigned i = 0; i < 8; ++i)
3340     if (BytesFound[LastB]) {
3341       ++BCnt;
3342       LastB = i;
3343     }
3344 
3345   if (!LastB || BCnt < 2)
3346     return Res;
3347 
3348   // Because we'll be zero-extending the output anyway if don't have a specific
3349   // value for each input byte (via the Mask), we can 'anyext' the inputs.
3350   if (LHS.getValueType() != VT) {
3351     LHS = CurDAG->getAnyExtOrTrunc(LHS, dl, VT);
3352     RHS = CurDAG->getAnyExtOrTrunc(RHS, dl, VT);
3353   }
3354 
3355   Res = CurDAG->getNode(PPCISD::CMPB, dl, VT, LHS, RHS);
3356 
3357   bool NonTrivialMask = ((int64_t) Mask) != INT64_C(-1);
3358   if (NonTrivialMask && !Alt) {
3359     // Res = Mask & CMPB
3360     Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3361                           CurDAG->getConstant(Mask, dl, VT));
3362   } else if (Alt) {
3363     // Res = (CMPB & Mask) | (~CMPB & Alt)
3364     // Which, as suggested here:
3365     //   https://graphics.stanford.edu/~seander/bithacks.html#MaskedMerge
3366     // can be written as:
3367     // Res = Alt ^ ((Alt ^ Mask) & CMPB)
3368     // useful because the (Alt ^ Mask) can be pre-computed.
3369     Res = CurDAG->getNode(ISD::AND, dl, VT, Res,
3370                           CurDAG->getConstant(Mask ^ Alt, dl, VT));
3371     Res = CurDAG->getNode(ISD::XOR, dl, VT, Res,
3372                           CurDAG->getConstant(Alt, dl, VT));
3373   }
3374 
3375   return Res;
3376 }
3377 
3378 // When CR bit registers are enabled, an extension of an i1 variable to a i32
3379 // or i64 value is lowered in terms of a SELECT_I[48] operation, and thus
3380 // involves constant materialization of a 0 or a 1 or both. If the result of
3381 // the extension is then operated upon by some operator that can be constant
3382 // folded with a constant 0 or 1, and that constant can be materialized using
3383 // only one instruction (like a zero or one), then we should fold in those
3384 // operations with the select.
3385 void PPCDAGToDAGISel::foldBoolExts(SDValue &Res, SDNode *&N) {
3386   if (!PPCSubTarget->useCRBits())
3387     return;
3388 
3389   if (N->getOpcode() != ISD::ZERO_EXTEND &&
3390       N->getOpcode() != ISD::SIGN_EXTEND &&
3391       N->getOpcode() != ISD::ANY_EXTEND)
3392     return;
3393 
3394   if (N->getOperand(0).getValueType() != MVT::i1)
3395     return;
3396 
3397   if (!N->hasOneUse())
3398     return;
3399 
3400   SDLoc dl(N);
3401   EVT VT = N->getValueType(0);
3402   SDValue Cond = N->getOperand(0);
3403   SDValue ConstTrue =
3404     CurDAG->getConstant(N->getOpcode() == ISD::SIGN_EXTEND ? -1 : 1, dl, VT);
3405   SDValue ConstFalse = CurDAG->getConstant(0, dl, VT);
3406 
3407   do {
3408     SDNode *User = *N->use_begin();
3409     if (User->getNumOperands() != 2)
3410       break;
3411 
3412     auto TryFold = [this, N, User, dl](SDValue Val) {
3413       SDValue UserO0 = User->getOperand(0), UserO1 = User->getOperand(1);
3414       SDValue O0 = UserO0.getNode() == N ? Val : UserO0;
3415       SDValue O1 = UserO1.getNode() == N ? Val : UserO1;
3416 
3417       return CurDAG->FoldConstantArithmetic(User->getOpcode(), dl,
3418                                             User->getValueType(0),
3419                                             O0.getNode(), O1.getNode());
3420     };
3421 
3422     SDValue TrueRes = TryFold(ConstTrue);
3423     if (!TrueRes)
3424       break;
3425     SDValue FalseRes = TryFold(ConstFalse);
3426     if (!FalseRes)
3427       break;
3428 
3429     // For us to materialize these using one instruction, we must be able to
3430     // represent them as signed 16-bit integers.
3431     uint64_t True  = cast<ConstantSDNode>(TrueRes)->getZExtValue(),
3432              False = cast<ConstantSDNode>(FalseRes)->getZExtValue();
3433     if (!isInt<16>(True) || !isInt<16>(False))
3434       break;
3435 
3436     // We can replace User with a new SELECT node, and try again to see if we
3437     // can fold the select with its user.
3438     Res = CurDAG->getSelect(dl, User->getValueType(0), Cond, TrueRes, FalseRes);
3439     N = User;
3440     ConstTrue = TrueRes;
3441     ConstFalse = FalseRes;
3442   } while (N->hasOneUse());
3443 }
3444 
3445 void PPCDAGToDAGISel::PreprocessISelDAG() {
3446   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
3447   ++Position;
3448 
3449   bool MadeChange = false;
3450   while (Position != CurDAG->allnodes_begin()) {
3451     SDNode *N = &*--Position;
3452     if (N->use_empty())
3453       continue;
3454 
3455     SDValue Res;
3456     switch (N->getOpcode()) {
3457     default: break;
3458     case ISD::OR:
3459       Res = combineToCMPB(N);
3460       break;
3461     }
3462 
3463     if (!Res)
3464       foldBoolExts(Res, N);
3465 
3466     if (Res) {
3467       DEBUG(dbgs() << "PPC DAG preprocessing replacing:\nOld:    ");
3468       DEBUG(N->dump(CurDAG));
3469       DEBUG(dbgs() << "\nNew: ");
3470       DEBUG(Res.getNode()->dump(CurDAG));
3471       DEBUG(dbgs() << "\n");
3472 
3473       CurDAG->ReplaceAllUsesOfValueWith(SDValue(N, 0), Res);
3474       MadeChange = true;
3475     }
3476   }
3477 
3478   if (MadeChange)
3479     CurDAG->RemoveDeadNodes();
3480 }
3481 
3482 /// PostprocessISelDAG - Perform some late peephole optimizations
3483 /// on the DAG representation.
3484 void PPCDAGToDAGISel::PostprocessISelDAG() {
3485 
3486   // Skip peepholes at -O0.
3487   if (TM.getOptLevel() == CodeGenOpt::None)
3488     return;
3489 
3490   PeepholePPC64();
3491   PeepholeCROps();
3492   PeepholePPC64ZExt();
3493 }
3494 
3495 // Check if all users of this node will become isel where the second operand
3496 // is the constant zero. If this is so, and if we can negate the condition,
3497 // then we can flip the true and false operands. This will allow the zero to
3498 // be folded with the isel so that we don't need to materialize a register
3499 // containing zero.
3500 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
3501   // If we're not using isel, then this does not matter.
3502   if (!PPCSubTarget->hasISEL())
3503     return false;
3504 
3505   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3506        UI != UE; ++UI) {
3507     SDNode *User = *UI;
3508     if (!User->isMachineOpcode())
3509       return false;
3510     if (User->getMachineOpcode() != PPC::SELECT_I4 &&
3511         User->getMachineOpcode() != PPC::SELECT_I8)
3512       return false;
3513 
3514     SDNode *Op2 = User->getOperand(2).getNode();
3515     if (!Op2->isMachineOpcode())
3516       return false;
3517 
3518     if (Op2->getMachineOpcode() != PPC::LI &&
3519         Op2->getMachineOpcode() != PPC::LI8)
3520       return false;
3521 
3522     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
3523     if (!C)
3524       return false;
3525 
3526     if (!C->isNullValue())
3527       return false;
3528   }
3529 
3530   return true;
3531 }
3532 
3533 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
3534   SmallVector<SDNode *, 4> ToReplace;
3535   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
3536        UI != UE; ++UI) {
3537     SDNode *User = *UI;
3538     assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
3539             User->getMachineOpcode() == PPC::SELECT_I8) &&
3540            "Must have all select users");
3541     ToReplace.push_back(User);
3542   }
3543 
3544   for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
3545        UE = ToReplace.end(); UI != UE; ++UI) {
3546     SDNode *User = *UI;
3547     SDNode *ResNode =
3548       CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
3549                              User->getValueType(0), User->getOperand(0),
3550                              User->getOperand(2),
3551                              User->getOperand(1));
3552 
3553       DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
3554       DEBUG(User->dump(CurDAG));
3555       DEBUG(dbgs() << "\nNew: ");
3556       DEBUG(ResNode->dump(CurDAG));
3557       DEBUG(dbgs() << "\n");
3558 
3559       ReplaceUses(User, ResNode);
3560   }
3561 }
3562 
3563 void PPCDAGToDAGISel::PeepholeCROps() {
3564   bool IsModified;
3565   do {
3566     IsModified = false;
3567     for (SDNode &Node : CurDAG->allnodes()) {
3568       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(&Node);
3569       if (!MachineNode || MachineNode->use_empty())
3570         continue;
3571       SDNode *ResNode = MachineNode;
3572 
3573       bool Op1Set   = false, Op1Unset = false,
3574            Op1Not   = false,
3575            Op2Set   = false, Op2Unset = false,
3576            Op2Not   = false;
3577 
3578       unsigned Opcode = MachineNode->getMachineOpcode();
3579       switch (Opcode) {
3580       default: break;
3581       case PPC::CRAND:
3582       case PPC::CRNAND:
3583       case PPC::CROR:
3584       case PPC::CRXOR:
3585       case PPC::CRNOR:
3586       case PPC::CREQV:
3587       case PPC::CRANDC:
3588       case PPC::CRORC: {
3589         SDValue Op = MachineNode->getOperand(1);
3590         if (Op.isMachineOpcode()) {
3591           if (Op.getMachineOpcode() == PPC::CRSET)
3592             Op2Set = true;
3593           else if (Op.getMachineOpcode() == PPC::CRUNSET)
3594             Op2Unset = true;
3595           else if (Op.getMachineOpcode() == PPC::CRNOR &&
3596                    Op.getOperand(0) == Op.getOperand(1))
3597             Op2Not = true;
3598         }
3599         LLVM_FALLTHROUGH;
3600       }
3601       case PPC::BC:
3602       case PPC::BCn:
3603       case PPC::SELECT_I4:
3604       case PPC::SELECT_I8:
3605       case PPC::SELECT_F4:
3606       case PPC::SELECT_F8:
3607       case PPC::SELECT_QFRC:
3608       case PPC::SELECT_QSRC:
3609       case PPC::SELECT_QBRC:
3610       case PPC::SELECT_VRRC:
3611       case PPC::SELECT_VSFRC:
3612       case PPC::SELECT_VSSRC:
3613       case PPC::SELECT_VSRC: {
3614         SDValue Op = MachineNode->getOperand(0);
3615         if (Op.isMachineOpcode()) {
3616           if (Op.getMachineOpcode() == PPC::CRSET)
3617             Op1Set = true;
3618           else if (Op.getMachineOpcode() == PPC::CRUNSET)
3619             Op1Unset = true;
3620           else if (Op.getMachineOpcode() == PPC::CRNOR &&
3621                    Op.getOperand(0) == Op.getOperand(1))
3622             Op1Not = true;
3623         }
3624         }
3625         break;
3626       }
3627 
3628       bool SelectSwap = false;
3629       switch (Opcode) {
3630       default: break;
3631       case PPC::CRAND:
3632         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3633           // x & x = x
3634           ResNode = MachineNode->getOperand(0).getNode();
3635         else if (Op1Set)
3636           // 1 & y = y
3637           ResNode = MachineNode->getOperand(1).getNode();
3638         else if (Op2Set)
3639           // x & 1 = x
3640           ResNode = MachineNode->getOperand(0).getNode();
3641         else if (Op1Unset || Op2Unset)
3642           // x & 0 = 0 & y = 0
3643           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3644                                            MVT::i1);
3645         else if (Op1Not)
3646           // ~x & y = andc(y, x)
3647           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3648                                            MVT::i1, MachineNode->getOperand(1),
3649                                            MachineNode->getOperand(0).
3650                                              getOperand(0));
3651         else if (Op2Not)
3652           // x & ~y = andc(x, y)
3653           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3654                                            MVT::i1, MachineNode->getOperand(0),
3655                                            MachineNode->getOperand(1).
3656                                              getOperand(0));
3657         else if (AllUsersSelectZero(MachineNode)) {
3658           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3659                                            MVT::i1, MachineNode->getOperand(0),
3660                                            MachineNode->getOperand(1));
3661           SelectSwap = true;
3662         }
3663         break;
3664       case PPC::CRNAND:
3665         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3666           // nand(x, x) -> nor(x, x)
3667           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3668                                            MVT::i1, MachineNode->getOperand(0),
3669                                            MachineNode->getOperand(0));
3670         else if (Op1Set)
3671           // nand(1, y) -> nor(y, y)
3672           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3673                                            MVT::i1, MachineNode->getOperand(1),
3674                                            MachineNode->getOperand(1));
3675         else if (Op2Set)
3676           // nand(x, 1) -> nor(x, x)
3677           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3678                                            MVT::i1, MachineNode->getOperand(0),
3679                                            MachineNode->getOperand(0));
3680         else if (Op1Unset || Op2Unset)
3681           // nand(x, 0) = nand(0, y) = 1
3682           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3683                                            MVT::i1);
3684         else if (Op1Not)
3685           // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
3686           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3687                                            MVT::i1, MachineNode->getOperand(0).
3688                                                       getOperand(0),
3689                                            MachineNode->getOperand(1));
3690         else if (Op2Not)
3691           // nand(x, ~y) = ~x | y = orc(y, x)
3692           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3693                                            MVT::i1, MachineNode->getOperand(1).
3694                                                       getOperand(0),
3695                                            MachineNode->getOperand(0));
3696         else if (AllUsersSelectZero(MachineNode)) {
3697           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3698                                            MVT::i1, MachineNode->getOperand(0),
3699                                            MachineNode->getOperand(1));
3700           SelectSwap = true;
3701         }
3702         break;
3703       case PPC::CROR:
3704         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3705           // x | x = x
3706           ResNode = MachineNode->getOperand(0).getNode();
3707         else if (Op1Set || Op2Set)
3708           // x | 1 = 1 | y = 1
3709           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3710                                            MVT::i1);
3711         else if (Op1Unset)
3712           // 0 | y = y
3713           ResNode = MachineNode->getOperand(1).getNode();
3714         else if (Op2Unset)
3715           // x | 0 = x
3716           ResNode = MachineNode->getOperand(0).getNode();
3717         else if (Op1Not)
3718           // ~x | y = orc(y, x)
3719           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3720                                            MVT::i1, MachineNode->getOperand(1),
3721                                            MachineNode->getOperand(0).
3722                                              getOperand(0));
3723         else if (Op2Not)
3724           // x | ~y = orc(x, y)
3725           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3726                                            MVT::i1, MachineNode->getOperand(0),
3727                                            MachineNode->getOperand(1).
3728                                              getOperand(0));
3729         else if (AllUsersSelectZero(MachineNode)) {
3730           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3731                                            MVT::i1, MachineNode->getOperand(0),
3732                                            MachineNode->getOperand(1));
3733           SelectSwap = true;
3734         }
3735         break;
3736       case PPC::CRXOR:
3737         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3738           // xor(x, x) = 0
3739           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3740                                            MVT::i1);
3741         else if (Op1Set)
3742           // xor(1, y) -> nor(y, y)
3743           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3744                                            MVT::i1, MachineNode->getOperand(1),
3745                                            MachineNode->getOperand(1));
3746         else if (Op2Set)
3747           // xor(x, 1) -> nor(x, x)
3748           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3749                                            MVT::i1, MachineNode->getOperand(0),
3750                                            MachineNode->getOperand(0));
3751         else if (Op1Unset)
3752           // xor(0, y) = y
3753           ResNode = MachineNode->getOperand(1).getNode();
3754         else if (Op2Unset)
3755           // xor(x, 0) = x
3756           ResNode = MachineNode->getOperand(0).getNode();
3757         else if (Op1Not)
3758           // xor(~x, y) = eqv(x, y)
3759           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3760                                            MVT::i1, MachineNode->getOperand(0).
3761                                                       getOperand(0),
3762                                            MachineNode->getOperand(1));
3763         else if (Op2Not)
3764           // xor(x, ~y) = eqv(x, y)
3765           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3766                                            MVT::i1, MachineNode->getOperand(0),
3767                                            MachineNode->getOperand(1).
3768                                              getOperand(0));
3769         else if (AllUsersSelectZero(MachineNode)) {
3770           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
3771                                            MVT::i1, MachineNode->getOperand(0),
3772                                            MachineNode->getOperand(1));
3773           SelectSwap = true;
3774         }
3775         break;
3776       case PPC::CRNOR:
3777         if (Op1Set || Op2Set)
3778           // nor(1, y) -> 0
3779           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3780                                            MVT::i1);
3781         else if (Op1Unset)
3782           // nor(0, y) = ~y -> nor(y, y)
3783           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3784                                            MVT::i1, MachineNode->getOperand(1),
3785                                            MachineNode->getOperand(1));
3786         else if (Op2Unset)
3787           // nor(x, 0) = ~x
3788           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3789                                            MVT::i1, MachineNode->getOperand(0),
3790                                            MachineNode->getOperand(0));
3791         else if (Op1Not)
3792           // nor(~x, y) = andc(x, y)
3793           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3794                                            MVT::i1, MachineNode->getOperand(0).
3795                                                       getOperand(0),
3796                                            MachineNode->getOperand(1));
3797         else if (Op2Not)
3798           // nor(x, ~y) = andc(y, x)
3799           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3800                                            MVT::i1, MachineNode->getOperand(1).
3801                                                       getOperand(0),
3802                                            MachineNode->getOperand(0));
3803         else if (AllUsersSelectZero(MachineNode)) {
3804           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3805                                            MVT::i1, MachineNode->getOperand(0),
3806                                            MachineNode->getOperand(1));
3807           SelectSwap = true;
3808         }
3809         break;
3810       case PPC::CREQV:
3811         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3812           // eqv(x, x) = 1
3813           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3814                                            MVT::i1);
3815         else if (Op1Set)
3816           // eqv(1, y) = y
3817           ResNode = MachineNode->getOperand(1).getNode();
3818         else if (Op2Set)
3819           // eqv(x, 1) = x
3820           ResNode = MachineNode->getOperand(0).getNode();
3821         else if (Op1Unset)
3822           // eqv(0, y) = ~y -> nor(y, y)
3823           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3824                                            MVT::i1, MachineNode->getOperand(1),
3825                                            MachineNode->getOperand(1));
3826         else if (Op2Unset)
3827           // eqv(x, 0) = ~x
3828           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3829                                            MVT::i1, MachineNode->getOperand(0),
3830                                            MachineNode->getOperand(0));
3831         else if (Op1Not)
3832           // eqv(~x, y) = xor(x, y)
3833           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3834                                            MVT::i1, MachineNode->getOperand(0).
3835                                                       getOperand(0),
3836                                            MachineNode->getOperand(1));
3837         else if (Op2Not)
3838           // eqv(x, ~y) = xor(x, y)
3839           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3840                                            MVT::i1, MachineNode->getOperand(0),
3841                                            MachineNode->getOperand(1).
3842                                              getOperand(0));
3843         else if (AllUsersSelectZero(MachineNode)) {
3844           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
3845                                            MVT::i1, MachineNode->getOperand(0),
3846                                            MachineNode->getOperand(1));
3847           SelectSwap = true;
3848         }
3849         break;
3850       case PPC::CRANDC:
3851         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3852           // andc(x, x) = 0
3853           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3854                                            MVT::i1);
3855         else if (Op1Set)
3856           // andc(1, y) = ~y
3857           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3858                                            MVT::i1, MachineNode->getOperand(1),
3859                                            MachineNode->getOperand(1));
3860         else if (Op1Unset || Op2Set)
3861           // andc(0, y) = andc(x, 1) = 0
3862           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
3863                                            MVT::i1);
3864         else if (Op2Unset)
3865           // andc(x, 0) = x
3866           ResNode = MachineNode->getOperand(0).getNode();
3867         else if (Op1Not)
3868           // andc(~x, y) = ~(x | y) = nor(x, y)
3869           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3870                                            MVT::i1, MachineNode->getOperand(0).
3871                                                       getOperand(0),
3872                                            MachineNode->getOperand(1));
3873         else if (Op2Not)
3874           // andc(x, ~y) = x & y
3875           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
3876                                            MVT::i1, MachineNode->getOperand(0),
3877                                            MachineNode->getOperand(1).
3878                                              getOperand(0));
3879         else if (AllUsersSelectZero(MachineNode)) {
3880           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
3881                                            MVT::i1, MachineNode->getOperand(1),
3882                                            MachineNode->getOperand(0));
3883           SelectSwap = true;
3884         }
3885         break;
3886       case PPC::CRORC:
3887         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
3888           // orc(x, x) = 1
3889           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3890                                            MVT::i1);
3891         else if (Op1Set || Op2Unset)
3892           // orc(1, y) = orc(x, 0) = 1
3893           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
3894                                            MVT::i1);
3895         else if (Op2Set)
3896           // orc(x, 1) = x
3897           ResNode = MachineNode->getOperand(0).getNode();
3898         else if (Op1Unset)
3899           // orc(0, y) = ~y
3900           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
3901                                            MVT::i1, MachineNode->getOperand(1),
3902                                            MachineNode->getOperand(1));
3903         else if (Op1Not)
3904           // orc(~x, y) = ~(x & y) = nand(x, y)
3905           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
3906                                            MVT::i1, MachineNode->getOperand(0).
3907                                                       getOperand(0),
3908                                            MachineNode->getOperand(1));
3909         else if (Op2Not)
3910           // orc(x, ~y) = x | y
3911           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
3912                                            MVT::i1, MachineNode->getOperand(0),
3913                                            MachineNode->getOperand(1).
3914                                              getOperand(0));
3915         else if (AllUsersSelectZero(MachineNode)) {
3916           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
3917                                            MVT::i1, MachineNode->getOperand(1),
3918                                            MachineNode->getOperand(0));
3919           SelectSwap = true;
3920         }
3921         break;
3922       case PPC::SELECT_I4:
3923       case PPC::SELECT_I8:
3924       case PPC::SELECT_F4:
3925       case PPC::SELECT_F8:
3926       case PPC::SELECT_QFRC:
3927       case PPC::SELECT_QSRC:
3928       case PPC::SELECT_QBRC:
3929       case PPC::SELECT_VRRC:
3930       case PPC::SELECT_VSFRC:
3931       case PPC::SELECT_VSSRC:
3932       case PPC::SELECT_VSRC:
3933         if (Op1Set)
3934           ResNode = MachineNode->getOperand(1).getNode();
3935         else if (Op1Unset)
3936           ResNode = MachineNode->getOperand(2).getNode();
3937         else if (Op1Not)
3938           ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
3939                                            SDLoc(MachineNode),
3940                                            MachineNode->getValueType(0),
3941                                            MachineNode->getOperand(0).
3942                                              getOperand(0),
3943                                            MachineNode->getOperand(2),
3944                                            MachineNode->getOperand(1));
3945         break;
3946       case PPC::BC:
3947       case PPC::BCn:
3948         if (Op1Not)
3949           ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
3950                                                                PPC::BC,
3951                                            SDLoc(MachineNode),
3952                                            MVT::Other,
3953                                            MachineNode->getOperand(0).
3954                                              getOperand(0),
3955                                            MachineNode->getOperand(1),
3956                                            MachineNode->getOperand(2));
3957         // FIXME: Handle Op1Set, Op1Unset here too.
3958         break;
3959       }
3960 
3961       // If we're inverting this node because it is used only by selects that
3962       // we'd like to swap, then swap the selects before the node replacement.
3963       if (SelectSwap)
3964         SwapAllSelectUsers(MachineNode);
3965 
3966       if (ResNode != MachineNode) {
3967         DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
3968         DEBUG(MachineNode->dump(CurDAG));
3969         DEBUG(dbgs() << "\nNew: ");
3970         DEBUG(ResNode->dump(CurDAG));
3971         DEBUG(dbgs() << "\n");
3972 
3973         ReplaceUses(MachineNode, ResNode);
3974         IsModified = true;
3975       }
3976     }
3977     if (IsModified)
3978       CurDAG->RemoveDeadNodes();
3979   } while (IsModified);
3980 }
3981 
3982 // Gather the set of 32-bit operations that are known to have their
3983 // higher-order 32 bits zero, where ToPromote contains all such operations.
3984 static bool PeepholePPC64ZExtGather(SDValue Op32,
3985                                     SmallPtrSetImpl<SDNode *> &ToPromote) {
3986   if (!Op32.isMachineOpcode())
3987     return false;
3988 
3989   // First, check for the "frontier" instructions (those that will clear the
3990   // higher-order 32 bits.
3991 
3992   // For RLWINM and RLWNM, we need to make sure that the mask does not wrap
3993   // around. If it does not, then these instructions will clear the
3994   // higher-order bits.
3995   if ((Op32.getMachineOpcode() == PPC::RLWINM ||
3996        Op32.getMachineOpcode() == PPC::RLWNM) &&
3997       Op32.getConstantOperandVal(2) <= Op32.getConstantOperandVal(3)) {
3998     ToPromote.insert(Op32.getNode());
3999     return true;
4000   }
4001 
4002   // SLW and SRW always clear the higher-order bits.
4003   if (Op32.getMachineOpcode() == PPC::SLW ||
4004       Op32.getMachineOpcode() == PPC::SRW) {
4005     ToPromote.insert(Op32.getNode());
4006     return true;
4007   }
4008 
4009   // For LI and LIS, we need the immediate to be positive (so that it is not
4010   // sign extended).
4011   if (Op32.getMachineOpcode() == PPC::LI ||
4012       Op32.getMachineOpcode() == PPC::LIS) {
4013     if (!isUInt<15>(Op32.getConstantOperandVal(0)))
4014       return false;
4015 
4016     ToPromote.insert(Op32.getNode());
4017     return true;
4018   }
4019 
4020   // LHBRX and LWBRX always clear the higher-order bits.
4021   if (Op32.getMachineOpcode() == PPC::LHBRX ||
4022       Op32.getMachineOpcode() == PPC::LWBRX) {
4023     ToPromote.insert(Op32.getNode());
4024     return true;
4025   }
4026 
4027   // CNTLZW always produces a 64-bit value in [0,32], and so is zero extended.
4028   if (Op32.getMachineOpcode() == PPC::CNTLZW) {
4029     ToPromote.insert(Op32.getNode());
4030     return true;
4031   }
4032 
4033   // Next, check for those instructions we can look through.
4034 
4035   // Assuming the mask does not wrap around, then the higher-order bits are
4036   // taken directly from the first operand.
4037   if (Op32.getMachineOpcode() == PPC::RLWIMI &&
4038       Op32.getConstantOperandVal(3) <= Op32.getConstantOperandVal(4)) {
4039     SmallPtrSet<SDNode *, 16> ToPromote1;
4040     if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
4041       return false;
4042 
4043     ToPromote.insert(Op32.getNode());
4044     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4045     return true;
4046   }
4047 
4048   // For OR, the higher-order bits are zero if that is true for both operands.
4049   // For SELECT_I4, the same is true (but the relevant operand numbers are
4050   // shifted by 1).
4051   if (Op32.getMachineOpcode() == PPC::OR ||
4052       Op32.getMachineOpcode() == PPC::SELECT_I4) {
4053     unsigned B = Op32.getMachineOpcode() == PPC::SELECT_I4 ? 1 : 0;
4054     SmallPtrSet<SDNode *, 16> ToPromote1;
4055     if (!PeepholePPC64ZExtGather(Op32.getOperand(B+0), ToPromote1))
4056       return false;
4057     if (!PeepholePPC64ZExtGather(Op32.getOperand(B+1), ToPromote1))
4058       return false;
4059 
4060     ToPromote.insert(Op32.getNode());
4061     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4062     return true;
4063   }
4064 
4065   // For ORI and ORIS, we need the higher-order bits of the first operand to be
4066   // zero, and also for the constant to be positive (so that it is not sign
4067   // extended).
4068   if (Op32.getMachineOpcode() == PPC::ORI ||
4069       Op32.getMachineOpcode() == PPC::ORIS) {
4070     SmallPtrSet<SDNode *, 16> ToPromote1;
4071     if (!PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1))
4072       return false;
4073     if (!isUInt<15>(Op32.getConstantOperandVal(1)))
4074       return false;
4075 
4076     ToPromote.insert(Op32.getNode());
4077     ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4078     return true;
4079   }
4080 
4081   // The higher-order bits of AND are zero if that is true for at least one of
4082   // the operands.
4083   if (Op32.getMachineOpcode() == PPC::AND) {
4084     SmallPtrSet<SDNode *, 16> ToPromote1, ToPromote2;
4085     bool Op0OK =
4086       PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4087     bool Op1OK =
4088       PeepholePPC64ZExtGather(Op32.getOperand(1), ToPromote2);
4089     if (!Op0OK && !Op1OK)
4090       return false;
4091 
4092     ToPromote.insert(Op32.getNode());
4093 
4094     if (Op0OK)
4095       ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4096 
4097     if (Op1OK)
4098       ToPromote.insert(ToPromote2.begin(), ToPromote2.end());
4099 
4100     return true;
4101   }
4102 
4103   // For ANDI and ANDIS, the higher-order bits are zero if either that is true
4104   // of the first operand, or if the second operand is positive (so that it is
4105   // not sign extended).
4106   if (Op32.getMachineOpcode() == PPC::ANDIo ||
4107       Op32.getMachineOpcode() == PPC::ANDISo) {
4108     SmallPtrSet<SDNode *, 16> ToPromote1;
4109     bool Op0OK =
4110       PeepholePPC64ZExtGather(Op32.getOperand(0), ToPromote1);
4111     bool Op1OK = isUInt<15>(Op32.getConstantOperandVal(1));
4112     if (!Op0OK && !Op1OK)
4113       return false;
4114 
4115     ToPromote.insert(Op32.getNode());
4116 
4117     if (Op0OK)
4118       ToPromote.insert(ToPromote1.begin(), ToPromote1.end());
4119 
4120     return true;
4121   }
4122 
4123   return false;
4124 }
4125 
4126 void PPCDAGToDAGISel::PeepholePPC64ZExt() {
4127   if (!PPCSubTarget->isPPC64())
4128     return;
4129 
4130   // When we zero-extend from i32 to i64, we use a pattern like this:
4131   // def : Pat<(i64 (zext i32:$in)),
4132   //           (RLDICL (INSERT_SUBREG (i64 (IMPLICIT_DEF)), $in, sub_32),
4133   //                   0, 32)>;
4134   // There are several 32-bit shift/rotate instructions, however, that will
4135   // clear the higher-order bits of their output, rendering the RLDICL
4136   // unnecessary. When that happens, we remove it here, and redefine the
4137   // relevant 32-bit operation to be a 64-bit operation.
4138 
4139   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4140   ++Position;
4141 
4142   bool MadeChange = false;
4143   while (Position != CurDAG->allnodes_begin()) {
4144     SDNode *N = &*--Position;
4145     // Skip dead nodes and any non-machine opcodes.
4146     if (N->use_empty() || !N->isMachineOpcode())
4147       continue;
4148 
4149     if (N->getMachineOpcode() != PPC::RLDICL)
4150       continue;
4151 
4152     if (N->getConstantOperandVal(1) != 0 ||
4153         N->getConstantOperandVal(2) != 32)
4154       continue;
4155 
4156     SDValue ISR = N->getOperand(0);
4157     if (!ISR.isMachineOpcode() ||
4158         ISR.getMachineOpcode() != TargetOpcode::INSERT_SUBREG)
4159       continue;
4160 
4161     if (!ISR.hasOneUse())
4162       continue;
4163 
4164     if (ISR.getConstantOperandVal(2) != PPC::sub_32)
4165       continue;
4166 
4167     SDValue IDef = ISR.getOperand(0);
4168     if (!IDef.isMachineOpcode() ||
4169         IDef.getMachineOpcode() != TargetOpcode::IMPLICIT_DEF)
4170       continue;
4171 
4172     // We now know that we're looking at a canonical i32 -> i64 zext. See if we
4173     // can get rid of it.
4174 
4175     SDValue Op32 = ISR->getOperand(1);
4176     if (!Op32.isMachineOpcode())
4177       continue;
4178 
4179     // There are some 32-bit instructions that always clear the high-order 32
4180     // bits, there are also some instructions (like AND) that we can look
4181     // through.
4182     SmallPtrSet<SDNode *, 16> ToPromote;
4183     if (!PeepholePPC64ZExtGather(Op32, ToPromote))
4184       continue;
4185 
4186     // If the ToPromote set contains nodes that have uses outside of the set
4187     // (except for the original INSERT_SUBREG), then abort the transformation.
4188     bool OutsideUse = false;
4189     for (SDNode *PN : ToPromote) {
4190       for (SDNode *UN : PN->uses()) {
4191         if (!ToPromote.count(UN) && UN != ISR.getNode()) {
4192           OutsideUse = true;
4193           break;
4194         }
4195       }
4196 
4197       if (OutsideUse)
4198         break;
4199     }
4200     if (OutsideUse)
4201       continue;
4202 
4203     MadeChange = true;
4204 
4205     // We now know that this zero extension can be removed by promoting to
4206     // nodes in ToPromote to 64-bit operations, where for operations in the
4207     // frontier of the set, we need to insert INSERT_SUBREGs for their
4208     // operands.
4209     for (SDNode *PN : ToPromote) {
4210       unsigned NewOpcode;
4211       switch (PN->getMachineOpcode()) {
4212       default:
4213         llvm_unreachable("Don't know the 64-bit variant of this instruction");
4214       case PPC::RLWINM:    NewOpcode = PPC::RLWINM8; break;
4215       case PPC::RLWNM:     NewOpcode = PPC::RLWNM8; break;
4216       case PPC::SLW:       NewOpcode = PPC::SLW8; break;
4217       case PPC::SRW:       NewOpcode = PPC::SRW8; break;
4218       case PPC::LI:        NewOpcode = PPC::LI8; break;
4219       case PPC::LIS:       NewOpcode = PPC::LIS8; break;
4220       case PPC::LHBRX:     NewOpcode = PPC::LHBRX8; break;
4221       case PPC::LWBRX:     NewOpcode = PPC::LWBRX8; break;
4222       case PPC::CNTLZW:    NewOpcode = PPC::CNTLZW8; break;
4223       case PPC::RLWIMI:    NewOpcode = PPC::RLWIMI8; break;
4224       case PPC::OR:        NewOpcode = PPC::OR8; break;
4225       case PPC::SELECT_I4: NewOpcode = PPC::SELECT_I8; break;
4226       case PPC::ORI:       NewOpcode = PPC::ORI8; break;
4227       case PPC::ORIS:      NewOpcode = PPC::ORIS8; break;
4228       case PPC::AND:       NewOpcode = PPC::AND8; break;
4229       case PPC::ANDIo:     NewOpcode = PPC::ANDIo8; break;
4230       case PPC::ANDISo:    NewOpcode = PPC::ANDISo8; break;
4231       }
4232 
4233       // Note: During the replacement process, the nodes will be in an
4234       // inconsistent state (some instructions will have operands with values
4235       // of the wrong type). Once done, however, everything should be right
4236       // again.
4237 
4238       SmallVector<SDValue, 4> Ops;
4239       for (const SDValue &V : PN->ops()) {
4240         if (!ToPromote.count(V.getNode()) && V.getValueType() == MVT::i32 &&
4241             !isa<ConstantSDNode>(V)) {
4242           SDValue ReplOpOps[] = { ISR.getOperand(0), V, ISR.getOperand(2) };
4243           SDNode *ReplOp =
4244             CurDAG->getMachineNode(TargetOpcode::INSERT_SUBREG, SDLoc(V),
4245                                    ISR.getNode()->getVTList(), ReplOpOps);
4246           Ops.push_back(SDValue(ReplOp, 0));
4247         } else {
4248           Ops.push_back(V);
4249         }
4250       }
4251 
4252       // Because all to-be-promoted nodes only have users that are other
4253       // promoted nodes (or the original INSERT_SUBREG), we can safely replace
4254       // the i32 result value type with i64.
4255 
4256       SmallVector<EVT, 2> NewVTs;
4257       SDVTList VTs = PN->getVTList();
4258       for (unsigned i = 0, ie = VTs.NumVTs; i != ie; ++i)
4259         if (VTs.VTs[i] == MVT::i32)
4260           NewVTs.push_back(MVT::i64);
4261         else
4262           NewVTs.push_back(VTs.VTs[i]);
4263 
4264       DEBUG(dbgs() << "PPC64 ZExt Peephole morphing:\nOld:    ");
4265       DEBUG(PN->dump(CurDAG));
4266 
4267       CurDAG->SelectNodeTo(PN, NewOpcode, CurDAG->getVTList(NewVTs), Ops);
4268 
4269       DEBUG(dbgs() << "\nNew: ");
4270       DEBUG(PN->dump(CurDAG));
4271       DEBUG(dbgs() << "\n");
4272     }
4273 
4274     // Now we replace the original zero extend and its associated INSERT_SUBREG
4275     // with the value feeding the INSERT_SUBREG (which has now been promoted to
4276     // return an i64).
4277 
4278     DEBUG(dbgs() << "PPC64 ZExt Peephole replacing:\nOld:    ");
4279     DEBUG(N->dump(CurDAG));
4280     DEBUG(dbgs() << "\nNew: ");
4281     DEBUG(Op32.getNode()->dump(CurDAG));
4282     DEBUG(dbgs() << "\n");
4283 
4284     ReplaceUses(N, Op32.getNode());
4285   }
4286 
4287   if (MadeChange)
4288     CurDAG->RemoveDeadNodes();
4289 }
4290 
4291 void PPCDAGToDAGISel::PeepholePPC64() {
4292   // These optimizations are currently supported only for 64-bit SVR4.
4293   if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
4294     return;
4295 
4296   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
4297   ++Position;
4298 
4299   while (Position != CurDAG->allnodes_begin()) {
4300     SDNode *N = &*--Position;
4301     // Skip dead nodes and any non-machine opcodes.
4302     if (N->use_empty() || !N->isMachineOpcode())
4303       continue;
4304 
4305     unsigned FirstOp;
4306     unsigned StorageOpcode = N->getMachineOpcode();
4307 
4308     switch (StorageOpcode) {
4309     default: continue;
4310 
4311     case PPC::LBZ:
4312     case PPC::LBZ8:
4313     case PPC::LD:
4314     case PPC::LFD:
4315     case PPC::LFS:
4316     case PPC::LHA:
4317     case PPC::LHA8:
4318     case PPC::LHZ:
4319     case PPC::LHZ8:
4320     case PPC::LWA:
4321     case PPC::LWZ:
4322     case PPC::LWZ8:
4323       FirstOp = 0;
4324       break;
4325 
4326     case PPC::STB:
4327     case PPC::STB8:
4328     case PPC::STD:
4329     case PPC::STFD:
4330     case PPC::STFS:
4331     case PPC::STH:
4332     case PPC::STH8:
4333     case PPC::STW:
4334     case PPC::STW8:
4335       FirstOp = 1;
4336       break;
4337     }
4338 
4339     // If this is a load or store with a zero offset, or within the alignment,
4340     // we may be able to fold an add-immediate into the memory operation.
4341     // The check against alignment is below, as it can't occur until we check
4342     // the arguments to N
4343     if (!isa<ConstantSDNode>(N->getOperand(FirstOp)))
4344       continue;
4345 
4346     SDValue Base = N->getOperand(FirstOp + 1);
4347     if (!Base.isMachineOpcode())
4348       continue;
4349 
4350     unsigned Flags = 0;
4351     bool ReplaceFlags = true;
4352 
4353     // When the feeding operation is an add-immediate of some sort,
4354     // determine whether we need to add relocation information to the
4355     // target flags on the immediate operand when we fold it into the
4356     // load instruction.
4357     //
4358     // For something like ADDItocL, the relocation information is
4359     // inferred from the opcode; when we process it in the AsmPrinter,
4360     // we add the necessary relocation there.  A load, though, can receive
4361     // relocation from various flavors of ADDIxxx, so we need to carry
4362     // the relocation information in the target flags.
4363     switch (Base.getMachineOpcode()) {
4364     default: continue;
4365 
4366     case PPC::ADDI8:
4367     case PPC::ADDI:
4368       // In some cases (such as TLS) the relocation information
4369       // is already in place on the operand, so copying the operand
4370       // is sufficient.
4371       ReplaceFlags = false;
4372       // For these cases, the immediate may not be divisible by 4, in
4373       // which case the fold is illegal for DS-form instructions.  (The
4374       // other cases provide aligned addresses and are always safe.)
4375       if ((StorageOpcode == PPC::LWA ||
4376            StorageOpcode == PPC::LD  ||
4377            StorageOpcode == PPC::STD) &&
4378           (!isa<ConstantSDNode>(Base.getOperand(1)) ||
4379            Base.getConstantOperandVal(1) % 4 != 0))
4380         continue;
4381       break;
4382     case PPC::ADDIdtprelL:
4383       Flags = PPCII::MO_DTPREL_LO;
4384       break;
4385     case PPC::ADDItlsldL:
4386       Flags = PPCII::MO_TLSLD_LO;
4387       break;
4388     case PPC::ADDItocL:
4389       Flags = PPCII::MO_TOC_LO;
4390       break;
4391     }
4392 
4393     SDValue ImmOpnd = Base.getOperand(1);
4394 
4395     // On PPC64, the TOC base pointer is guaranteed by the ABI only to have
4396     // 8-byte alignment, and so we can only use offsets less than 8 (otherwise,
4397     // we might have needed different @ha relocation values for the offset
4398     // pointers).
4399     int MaxDisplacement = 7;
4400     if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4401       const GlobalValue *GV = GA->getGlobal();
4402       MaxDisplacement = std::min((int) GV->getAlignment() - 1, MaxDisplacement);
4403     }
4404 
4405     bool UpdateHBase = false;
4406     SDValue HBase = Base.getOperand(0);
4407 
4408     int Offset = N->getConstantOperandVal(FirstOp);
4409     if (ReplaceFlags) {
4410       if (Offset < 0 || Offset > MaxDisplacement) {
4411         // If we have a addi(toc@l)/addis(toc@ha) pair, and the addis has only
4412         // one use, then we can do this for any offset, we just need to also
4413         // update the offset (i.e. the symbol addend) on the addis also.
4414         if (Base.getMachineOpcode() != PPC::ADDItocL)
4415           continue;
4416 
4417         if (!HBase.isMachineOpcode() ||
4418             HBase.getMachineOpcode() != PPC::ADDIStocHA)
4419           continue;
4420 
4421         if (!Base.hasOneUse() || !HBase.hasOneUse())
4422           continue;
4423 
4424         SDValue HImmOpnd = HBase.getOperand(1);
4425         if (HImmOpnd != ImmOpnd)
4426           continue;
4427 
4428         UpdateHBase = true;
4429       }
4430     } else {
4431       // If we're directly folding the addend from an addi instruction, then:
4432       //  1. In general, the offset on the memory access must be zero.
4433       //  2. If the addend is a constant, then it can be combined with a
4434       //     non-zero offset, but only if the result meets the encoding
4435       //     requirements.
4436       if (auto *C = dyn_cast<ConstantSDNode>(ImmOpnd)) {
4437         Offset += C->getSExtValue();
4438 
4439         if ((StorageOpcode == PPC::LWA || StorageOpcode == PPC::LD ||
4440              StorageOpcode == PPC::STD) && (Offset % 4) != 0)
4441           continue;
4442 
4443         if (!isInt<16>(Offset))
4444           continue;
4445 
4446         ImmOpnd = CurDAG->getTargetConstant(Offset, SDLoc(ImmOpnd),
4447                                             ImmOpnd.getValueType());
4448       } else if (Offset != 0) {
4449         continue;
4450       }
4451     }
4452 
4453     // We found an opportunity.  Reverse the operands from the add
4454     // immediate and substitute them into the load or store.  If
4455     // needed, update the target flags for the immediate operand to
4456     // reflect the necessary relocation information.
4457     DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
4458     DEBUG(Base->dump(CurDAG));
4459     DEBUG(dbgs() << "\nN: ");
4460     DEBUG(N->dump(CurDAG));
4461     DEBUG(dbgs() << "\n");
4462 
4463     // If the relocation information isn't already present on the
4464     // immediate operand, add it now.
4465     if (ReplaceFlags) {
4466       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
4467         SDLoc dl(GA);
4468         const GlobalValue *GV = GA->getGlobal();
4469         // We can't perform this optimization for data whose alignment
4470         // is insufficient for the instruction encoding.
4471         if (GV->getAlignment() < 4 &&
4472             (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
4473              StorageOpcode == PPC::LWA || (Offset % 4) != 0)) {
4474           DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
4475           continue;
4476         }
4477         ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, Offset, Flags);
4478       } else if (ConstantPoolSDNode *CP =
4479                  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
4480         const Constant *C = CP->getConstVal();
4481         ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
4482                                                 CP->getAlignment(),
4483                                                 Offset, Flags);
4484       }
4485     }
4486 
4487     if (FirstOp == 1) // Store
4488       (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
4489                                        Base.getOperand(0), N->getOperand(3));
4490     else // Load
4491       (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
4492                                        N->getOperand(2));
4493 
4494     if (UpdateHBase)
4495       (void)CurDAG->UpdateNodeOperands(HBase.getNode(), HBase.getOperand(0),
4496                                        ImmOpnd);
4497 
4498     // The add-immediate may now be dead, in which case remove it.
4499     if (Base.getNode()->use_empty())
4500       CurDAG->RemoveDeadNode(Base.getNode());
4501   }
4502 }
4503 
4504 
4505 /// createPPCISelDag - This pass converts a legalized DAG into a
4506 /// PowerPC-specific DAG, ready for instruction scheduling.
4507 ///
4508 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
4509   return new PPCDAGToDAGISel(TM);
4510 }
4511