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