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