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