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