[PowerPC] Implement BuildSDIVPow2, lower i64 pow2 sdiv using sradi
[oota-llvm.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPCISelDAGToDAG.cpp - PPC --pattern matching inst selector --------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC.h"
16 #include "MCTargetDesc/PPCPredicates.h"
17 #include "PPCMachineFunctionInfo.h"
18 #include "PPCTargetMachine.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/MachineInstrBuilder.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/IR/Constants.h"
25 #include "llvm/IR/Function.h"
26 #include "llvm/IR/GlobalAlias.h"
27 #include "llvm/IR/GlobalValue.h"
28 #include "llvm/IR/GlobalVariable.h"
29 #include "llvm/IR/Intrinsics.h"
30 #include "llvm/IR/Module.h"
31 #include "llvm/Support/CommandLine.h"
32 #include "llvm/Support/Debug.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/MathExtras.h"
35 #include "llvm/Support/raw_ostream.h"
36 #include "llvm/Target/TargetOptions.h"
37 using namespace llvm;
38
39 #define DEBUG_TYPE "ppc-codegen"
40
41 // FIXME: Remove this once the bug has been fixed!
42 cl::opt<bool> ANDIGlueBug("expose-ppc-andi-glue-bug",
43 cl::desc("expose the ANDI glue bug on PPC"), cl::Hidden);
44
45 namespace llvm {
46   void initializePPCDAGToDAGISelPass(PassRegistry&);
47 }
48
49 namespace {
50   //===--------------------------------------------------------------------===//
51   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
52   /// instructions for SelectionDAG operations.
53   ///
54   class PPCDAGToDAGISel : public SelectionDAGISel {
55     const PPCTargetMachine &TM;
56     const PPCTargetLowering *PPCLowering;
57     const PPCSubtarget *PPCSubTarget;
58     unsigned GlobalBaseReg;
59   public:
60     explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
61         : SelectionDAGISel(tm), TM(tm),
62           PPCLowering(TM.getSubtargetImpl()->getTargetLowering()),
63           PPCSubTarget(TM.getSubtargetImpl()) {
64       initializePPCDAGToDAGISelPass(*PassRegistry::getPassRegistry());
65     }
66
67     bool runOnMachineFunction(MachineFunction &MF) override {
68       // Make sure we re-emit a set of the global base reg if necessary
69       GlobalBaseReg = 0;
70       PPCLowering = TM.getSubtargetImpl()->getTargetLowering();
71       PPCSubTarget = TM.getSubtargetImpl();
72       SelectionDAGISel::runOnMachineFunction(MF);
73
74       if (!PPCSubTarget->isSVR4ABI())
75         InsertVRSaveCode(MF);
76
77       return true;
78     }
79
80     void PostprocessISelDAG() override;
81
82     /// getI32Imm - Return a target constant with the specified value, of type
83     /// i32.
84     inline SDValue getI32Imm(unsigned Imm) {
85       return CurDAG->getTargetConstant(Imm, MVT::i32);
86     }
87
88     /// getI64Imm - Return a target constant with the specified value, of type
89     /// i64.
90     inline SDValue getI64Imm(uint64_t Imm) {
91       return CurDAG->getTargetConstant(Imm, MVT::i64);
92     }
93
94     /// getSmallIPtrImm - Return a target constant of pointer type.
95     inline SDValue getSmallIPtrImm(unsigned Imm) {
96       return CurDAG->getTargetConstant(Imm, PPCLowering->getPointerTy());
97     }
98
99     /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s
100     /// with any number of 0s on either side.  The 1s are allowed to wrap from
101     /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
102     /// 0x0F0F0000 is not, since all 1s are not contiguous.
103     static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
104
105
106     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
107     /// rotate and mask opcode and mask operation.
108     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
109                                 unsigned &SH, unsigned &MB, unsigned &ME);
110
111     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
112     /// base register.  Return the virtual register that holds this value.
113     SDNode *getGlobalBaseReg();
114
115     // Select - Convert the specified operand from a target-independent to a
116     // target-specific node if it hasn't already been changed.
117     SDNode *Select(SDNode *N) override;
118
119     SDNode *SelectBitfieldInsert(SDNode *N);
120
121     /// SelectCC - Select a comparison of the specified values with the
122     /// specified condition code, returning the CR# of the expression.
123     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, SDLoc dl);
124
125     /// SelectAddrImm - Returns true if the address N can be represented by
126     /// a base register plus a signed 16-bit displacement [r+imm].
127     bool SelectAddrImm(SDValue N, SDValue &Disp,
128                        SDValue &Base) {
129       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, false);
130     }
131
132     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
133     /// immediate field.  Note that the operand at this point is already the
134     /// result of a prior SelectAddressRegImm call.
135     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
136       if (N.getOpcode() == ISD::TargetConstant ||
137           N.getOpcode() == ISD::TargetGlobalAddress) {
138         Out = N;
139         return true;
140       }
141
142       return false;
143     }
144
145     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
146     /// represented as an indexed [r+r] operation.  Returns false if it can
147     /// be represented by [r+imm], which are preferred.
148     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
149       return PPCLowering->SelectAddressRegReg(N, Base, Index, *CurDAG);
150     }
151
152     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
153     /// represented as an indexed [r+r] operation.
154     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
155       return PPCLowering->SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
156     }
157
158     /// SelectAddrImmX4 - Returns true if the address N can be represented by
159     /// a base register plus a signed 16-bit displacement that is a multiple of 4.
160     /// Suitable for use by STD and friends.
161     bool SelectAddrImmX4(SDValue N, SDValue &Disp, SDValue &Base) {
162       return PPCLowering->SelectAddressRegImm(N, Disp, Base, *CurDAG, true);
163     }
164
165     // Select an address into a single register.
166     bool SelectAddr(SDValue N, SDValue &Base) {
167       Base = N;
168       return true;
169     }
170
171     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
172     /// inline asm expressions.  It is always correct to compute the value into
173     /// a register.  The case of adding a (possibly relocatable) constant to a
174     /// register can be improved, but it is wrong to substitute Reg+Reg for
175     /// Reg in an asm, because the load or store opcode would have to change.
176     bool SelectInlineAsmMemoryOperand(const SDValue &Op,
177                                       char ConstraintCode,
178                                       std::vector<SDValue> &OutOps) override {
179       // We need to make sure that this one operand does not end up in r0
180       // (because we might end up lowering this as 0(%op)).
181       const TargetRegisterInfo *TRI = TM.getSubtargetImpl()->getRegisterInfo();
182       const TargetRegisterClass *TRC = TRI->getPointerRegClass(*MF, /*Kind=*/1);
183       SDValue RC = CurDAG->getTargetConstant(TRC->getID(), MVT::i32);
184       SDValue NewOp =
185         SDValue(CurDAG->getMachineNode(TargetOpcode::COPY_TO_REGCLASS,
186                                        SDLoc(Op), Op.getValueType(),
187                                        Op, RC), 0);
188
189       OutOps.push_back(NewOp);
190       return false;
191     }
192
193     void InsertVRSaveCode(MachineFunction &MF);
194
195     const char *getPassName() const override {
196       return "PowerPC DAG->DAG Pattern Instruction Selection";
197     }
198
199 // Include the pieces autogenerated from the target description.
200 #include "PPCGenDAGISel.inc"
201
202 private:
203     SDNode *SelectSETCC(SDNode *N);
204
205     void PeepholePPC64();
206     void PeepholeCROps();
207
208     bool AllUsersSelectZero(SDNode *N);
209     void SwapAllSelectUsers(SDNode *N);
210   };
211 }
212
213 /// InsertVRSaveCode - Once the entire function has been instruction selected,
214 /// all virtual registers are created and all machine instructions are built,
215 /// check to see if we need to save/restore VRSAVE.  If so, do it.
216 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
217   // Check to see if this function uses vector registers, which means we have to
218   // save and restore the VRSAVE register and update it with the regs we use.
219   //
220   // In this case, there will be virtual registers of vector type created
221   // by the scheduler.  Detect them now.
222   bool HasVectorVReg = false;
223   for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
224     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
225     if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
226       HasVectorVReg = true;
227       break;
228     }
229   }
230   if (!HasVectorVReg) return;  // nothing to do.
231
232   // If we have a vector register, we want to emit code into the entry and exit
233   // blocks to save and restore the VRSAVE register.  We do this here (instead
234   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
235   //
236   // 1. This (trivially) reduces the load on the register allocator, by not
237   //    having to represent the live range of the VRSAVE register.
238   // 2. This (more significantly) allows us to create a temporary virtual
239   //    register to hold the saved VRSAVE value, allowing this temporary to be
240   //    register allocated, instead of forcing it to be spilled to the stack.
241
242   // Create two vregs - one to hold the VRSAVE register that is live-in to the
243   // function and one for the value after having bits or'd into it.
244   unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
245   unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
246
247   const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
248   MachineBasicBlock &EntryBB = *Fn.begin();
249   DebugLoc dl;
250   // Emit the following code into the entry block:
251   // InVRSAVE = MFVRSAVE
252   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
253   // MTVRSAVE UpdatedVRSAVE
254   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
255   BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
256   BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
257           UpdatedVRSAVE).addReg(InVRSAVE);
258   BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
259
260   // Find all return blocks, outputting a restore in each epilog.
261   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
262     if (!BB->empty() && BB->back().isReturn()) {
263       IP = BB->end(); --IP;
264
265       // Skip over all terminator instructions, which are part of the return
266       // sequence.
267       MachineBasicBlock::iterator I2 = IP;
268       while (I2 != BB->begin() && (--I2)->isTerminator())
269         IP = I2;
270
271       // Emit: MTVRSAVE InVRSave
272       BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
273     }
274   }
275 }
276
277
278 /// getGlobalBaseReg - Output the instructions required to put the
279 /// base address to use for accessing globals into a register.
280 ///
281 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
282   if (!GlobalBaseReg) {
283     const TargetInstrInfo &TII = *TM.getSubtargetImpl()->getInstrInfo();
284     // Insert the set of GlobalBaseReg into the first MBB of the function
285     MachineBasicBlock &FirstMBB = MF->front();
286     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
287     const Module *M = MF->getFunction()->getParent();
288     DebugLoc dl;
289
290     if (PPCLowering->getPointerTy() == MVT::i32) {
291       if (PPCSubTarget->isTargetELF()) {
292         GlobalBaseReg = PPC::R30;
293         if (M->getPICLevel() == PICLevel::Small) {
294           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MoveGOTtoLR));
295           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
296         } else {
297           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
298           BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
299           unsigned TempReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
300           BuildMI(FirstMBB, MBBI, dl,
301                   TII.get(PPC::UpdateGBR)).addReg(GlobalBaseReg)
302                   .addReg(TempReg, RegState::Define).addReg(GlobalBaseReg);
303           MF->getInfo<PPCFunctionInfo>()->setUsesPICBase(true);
304         }
305       } else {
306         GlobalBaseReg =
307           RegInfo->createVirtualRegister(&PPC::GPRC_NOR0RegClass);
308         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
309         BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
310       }
311     } else {
312       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RC_NOX0RegClass);
313       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
314       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
315     }
316   }
317   return CurDAG->getRegister(GlobalBaseReg,
318                              PPCLowering->getPointerTy()).getNode();
319 }
320
321 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
322 /// or 64-bit immediate, and if the value can be accurately represented as a
323 /// sign extension from a 16-bit value.  If so, this returns true and the
324 /// immediate.
325 static bool isIntS16Immediate(SDNode *N, short &Imm) {
326   if (N->getOpcode() != ISD::Constant)
327     return false;
328
329   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
330   if (N->getValueType(0) == MVT::i32)
331     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
332   else
333     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
334 }
335
336 static bool isIntS16Immediate(SDValue Op, short &Imm) {
337   return isIntS16Immediate(Op.getNode(), Imm);
338 }
339
340
341 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
342 /// operand. If so Imm will receive the 32-bit value.
343 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
344   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
345     Imm = cast<ConstantSDNode>(N)->getZExtValue();
346     return true;
347   }
348   return false;
349 }
350
351 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
352 /// operand.  If so Imm will receive the 64-bit value.
353 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
354   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
355     Imm = cast<ConstantSDNode>(N)->getZExtValue();
356     return true;
357   }
358   return false;
359 }
360
361 // isInt32Immediate - This method tests to see if a constant operand.
362 // If so Imm will receive the 32 bit value.
363 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
364   return isInt32Immediate(N.getNode(), Imm);
365 }
366
367
368 // isOpcWithIntImmediate - This method tests to see if the node is a specific
369 // opcode and that it has a immediate integer right operand.
370 // If so Imm will receive the 32 bit value.
371 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
372   return N->getOpcode() == Opc
373          && isInt32Immediate(N->getOperand(1).getNode(), Imm);
374 }
375
376 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
377   if (!Val)
378     return false;
379
380   if (isShiftedMask_32(Val)) {
381     // look for the first non-zero bit
382     MB = countLeadingZeros(Val);
383     // look for the first zero bit after the run of ones
384     ME = countLeadingZeros((Val - 1) ^ Val);
385     return true;
386   } else {
387     Val = ~Val; // invert mask
388     if (isShiftedMask_32(Val)) {
389       // effectively look for the first zero bit
390       ME = countLeadingZeros(Val) - 1;
391       // effectively look for the first one bit after the run of zeros
392       MB = countLeadingZeros((Val - 1) ^ Val) + 1;
393       return true;
394     }
395   }
396   // no run present
397   return false;
398 }
399
400 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
401                                       bool isShiftMask, unsigned &SH,
402                                       unsigned &MB, unsigned &ME) {
403   // Don't even go down this path for i64, since different logic will be
404   // necessary for rldicl/rldicr/rldimi.
405   if (N->getValueType(0) != MVT::i32)
406     return false;
407
408   unsigned Shift  = 32;
409   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
410   unsigned Opcode = N->getOpcode();
411   if (N->getNumOperands() != 2 ||
412       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
413     return false;
414
415   if (Opcode == ISD::SHL) {
416     // apply shift left to mask if it comes first
417     if (isShiftMask) Mask = Mask << Shift;
418     // determine which bits are made indeterminant by shift
419     Indeterminant = ~(0xFFFFFFFFu << Shift);
420   } else if (Opcode == ISD::SRL) {
421     // apply shift right to mask if it comes first
422     if (isShiftMask) Mask = Mask >> Shift;
423     // determine which bits are made indeterminant by shift
424     Indeterminant = ~(0xFFFFFFFFu >> Shift);
425     // adjust for the left rotate
426     Shift = 32 - Shift;
427   } else if (Opcode == ISD::ROTL) {
428     Indeterminant = 0;
429   } else {
430     return false;
431   }
432
433   // if the mask doesn't intersect any Indeterminant bits
434   if (Mask && !(Mask & Indeterminant)) {
435     SH = Shift & 31;
436     // make sure the mask is still a mask (wrap arounds may not be)
437     return isRunOfOnes(Mask, MB, ME);
438   }
439   return false;
440 }
441
442 /// SelectBitfieldInsert - turn an or of two masked values into
443 /// the rotate left word immediate then mask insert (rlwimi) instruction.
444 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
445   SDValue Op0 = N->getOperand(0);
446   SDValue Op1 = N->getOperand(1);
447   SDLoc dl(N);
448
449   APInt LKZ, LKO, RKZ, RKO;
450   CurDAG->computeKnownBits(Op0, LKZ, LKO);
451   CurDAG->computeKnownBits(Op1, RKZ, RKO);
452
453   unsigned TargetMask = LKZ.getZExtValue();
454   unsigned InsertMask = RKZ.getZExtValue();
455
456   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
457     unsigned Op0Opc = Op0.getOpcode();
458     unsigned Op1Opc = Op1.getOpcode();
459     unsigned Value, SH = 0;
460     TargetMask = ~TargetMask;
461     InsertMask = ~InsertMask;
462
463     // If the LHS has a foldable shift and the RHS does not, then swap it to the
464     // RHS so that we can fold the shift into the insert.
465     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
466       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
467           Op0.getOperand(0).getOpcode() == ISD::SRL) {
468         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
469             Op1.getOperand(0).getOpcode() != ISD::SRL) {
470           std::swap(Op0, Op1);
471           std::swap(Op0Opc, Op1Opc);
472           std::swap(TargetMask, InsertMask);
473         }
474       }
475     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
476       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
477           Op1.getOperand(0).getOpcode() != ISD::SRL) {
478         std::swap(Op0, Op1);
479         std::swap(Op0Opc, Op1Opc);
480         std::swap(TargetMask, InsertMask);
481       }
482     }
483
484     unsigned MB, ME;
485     if (isRunOfOnes(InsertMask, MB, ME)) {
486       SDValue Tmp1, Tmp2;
487
488       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
489           isInt32Immediate(Op1.getOperand(1), Value)) {
490         Op1 = Op1.getOperand(0);
491         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
492       }
493       if (Op1Opc == ISD::AND) {
494        // The AND mask might not be a constant, and we need to make sure that
495        // if we're going to fold the masking with the insert, all bits not
496        // know to be zero in the mask are known to be one.
497         APInt MKZ, MKO;
498         CurDAG->computeKnownBits(Op1.getOperand(1), MKZ, MKO);
499         bool CanFoldMask = InsertMask == MKO.getZExtValue();
500
501         unsigned SHOpc = Op1.getOperand(0).getOpcode();
502         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) && CanFoldMask &&
503             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
504           // Note that Value must be in range here (less than 32) because
505           // otherwise there would not be any bits set in InsertMask.
506           Op1 = Op1.getOperand(0).getOperand(0);
507           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
508         }
509       }
510
511       SH &= 31;
512       SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
513                           getI32Imm(ME) };
514       return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
515     }
516   }
517   return nullptr;
518 }
519
520 /// SelectCC - Select a comparison of the specified values with the specified
521 /// condition code, returning the CR# of the expression.
522 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
523                                     ISD::CondCode CC, SDLoc dl) {
524   // Always select the LHS.
525   unsigned Opc;
526
527   if (LHS.getValueType() == MVT::i32) {
528     unsigned Imm;
529     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
530       if (isInt32Immediate(RHS, Imm)) {
531         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
532         if (isUInt<16>(Imm))
533           return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
534                                                 getI32Imm(Imm & 0xFFFF)), 0);
535         // If this is a 16-bit signed immediate, fold it.
536         if (isInt<16>((int)Imm))
537           return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
538                                                 getI32Imm(Imm & 0xFFFF)), 0);
539
540         // For non-equality comparisons, the default code would materialize the
541         // constant, then compare against it, like this:
542         //   lis r2, 4660
543         //   ori r2, r2, 22136
544         //   cmpw cr0, r3, r2
545         // Since we are just comparing for equality, we can emit this instead:
546         //   xoris r0,r3,0x1234
547         //   cmplwi cr0,r0,0x5678
548         //   beq cr0,L6
549         SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
550                                            getI32Imm(Imm >> 16)), 0);
551         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
552                                               getI32Imm(Imm & 0xFFFF)), 0);
553       }
554       Opc = PPC::CMPLW;
555     } else if (ISD::isUnsignedIntSetCC(CC)) {
556       if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
557         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
558                                               getI32Imm(Imm & 0xFFFF)), 0);
559       Opc = PPC::CMPLW;
560     } else {
561       short SImm;
562       if (isIntS16Immediate(RHS, SImm))
563         return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
564                                               getI32Imm((int)SImm & 0xFFFF)),
565                          0);
566       Opc = PPC::CMPW;
567     }
568   } else if (LHS.getValueType() == MVT::i64) {
569     uint64_t Imm;
570     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
571       if (isInt64Immediate(RHS.getNode(), Imm)) {
572         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
573         if (isUInt<16>(Imm))
574           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
575                                                 getI32Imm(Imm & 0xFFFF)), 0);
576         // If this is a 16-bit signed immediate, fold it.
577         if (isInt<16>(Imm))
578           return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
579                                                 getI32Imm(Imm & 0xFFFF)), 0);
580
581         // For non-equality comparisons, the default code would materialize the
582         // constant, then compare against it, like this:
583         //   lis r2, 4660
584         //   ori r2, r2, 22136
585         //   cmpd cr0, r3, r2
586         // Since we are just comparing for equality, we can emit this instead:
587         //   xoris r0,r3,0x1234
588         //   cmpldi cr0,r0,0x5678
589         //   beq cr0,L6
590         if (isUInt<32>(Imm)) {
591           SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
592                                              getI64Imm(Imm >> 16)), 0);
593           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
594                                                 getI64Imm(Imm & 0xFFFF)), 0);
595         }
596       }
597       Opc = PPC::CMPLD;
598     } else if (ISD::isUnsignedIntSetCC(CC)) {
599       if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
600         return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
601                                               getI64Imm(Imm & 0xFFFF)), 0);
602       Opc = PPC::CMPLD;
603     } else {
604       short SImm;
605       if (isIntS16Immediate(RHS, SImm))
606         return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
607                                               getI64Imm(SImm & 0xFFFF)),
608                          0);
609       Opc = PPC::CMPD;
610     }
611   } else if (LHS.getValueType() == MVT::f32) {
612     Opc = PPC::FCMPUS;
613   } else {
614     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
615     Opc = PPCSubTarget->hasVSX() ? PPC::XSCMPUDP : PPC::FCMPUD;
616   }
617   return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
618 }
619
620 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
621   switch (CC) {
622   case ISD::SETUEQ:
623   case ISD::SETONE:
624   case ISD::SETOLE:
625   case ISD::SETOGE:
626     llvm_unreachable("Should be lowered by legalize!");
627   default: llvm_unreachable("Unknown condition!");
628   case ISD::SETOEQ:
629   case ISD::SETEQ:  return PPC::PRED_EQ;
630   case ISD::SETUNE:
631   case ISD::SETNE:  return PPC::PRED_NE;
632   case ISD::SETOLT:
633   case ISD::SETLT:  return PPC::PRED_LT;
634   case ISD::SETULE:
635   case ISD::SETLE:  return PPC::PRED_LE;
636   case ISD::SETOGT:
637   case ISD::SETGT:  return PPC::PRED_GT;
638   case ISD::SETUGE:
639   case ISD::SETGE:  return PPC::PRED_GE;
640   case ISD::SETO:   return PPC::PRED_NU;
641   case ISD::SETUO:  return PPC::PRED_UN;
642     // These two are invalid for floating point.  Assume we have int.
643   case ISD::SETULT: return PPC::PRED_LT;
644   case ISD::SETUGT: return PPC::PRED_GT;
645   }
646 }
647
648 /// getCRIdxForSetCC - Return the index of the condition register field
649 /// associated with the SetCC condition, and whether or not the field is
650 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
651 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert) {
652   Invert = false;
653   switch (CC) {
654   default: llvm_unreachable("Unknown condition!");
655   case ISD::SETOLT:
656   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
657   case ISD::SETOGT:
658   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
659   case ISD::SETOEQ:
660   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
661   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
662   case ISD::SETUGE:
663   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
664   case ISD::SETULE:
665   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
666   case ISD::SETUNE:
667   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
668   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
669   case ISD::SETUEQ:
670   case ISD::SETOGE:
671   case ISD::SETOLE:
672   case ISD::SETONE:
673     llvm_unreachable("Invalid branch code: should be expanded by legalize");
674   // These are invalid for floating point.  Assume integer.
675   case ISD::SETULT: return 0;
676   case ISD::SETUGT: return 1;
677   }
678 }
679
680 // getVCmpInst: return the vector compare instruction for the specified
681 // vector type and condition code. Since this is for altivec specific code,
682 // only support the altivec types (v16i8, v8i16, v4i32, and v4f32).
683 static unsigned int getVCmpInst(MVT VecVT, ISD::CondCode CC,
684                                 bool HasVSX, bool &Swap, bool &Negate) {
685   Swap = false;
686   Negate = false;
687
688   if (VecVT.isFloatingPoint()) {
689     /* Handle some cases by swapping input operands.  */
690     switch (CC) {
691       case ISD::SETLE: CC = ISD::SETGE; Swap = true; break;
692       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
693       case ISD::SETOLE: CC = ISD::SETOGE; Swap = true; break;
694       case ISD::SETOLT: CC = ISD::SETOGT; Swap = true; break;
695       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
696       case ISD::SETUGT: CC = ISD::SETULT; Swap = true; break;
697       default: break;
698     }
699     /* Handle some cases by negating the result.  */
700     switch (CC) {
701       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
702       case ISD::SETUNE: CC = ISD::SETOEQ; Negate = true; break;
703       case ISD::SETULE: CC = ISD::SETOGT; Negate = true; break;
704       case ISD::SETULT: CC = ISD::SETOGE; Negate = true; break;
705       default: break;
706     }
707     /* We have instructions implementing the remaining cases.  */
708     switch (CC) {
709       case ISD::SETEQ:
710       case ISD::SETOEQ:
711         if (VecVT == MVT::v4f32)
712           return HasVSX ? PPC::XVCMPEQSP : PPC::VCMPEQFP;
713         else if (VecVT == MVT::v2f64)
714           return PPC::XVCMPEQDP;
715         break;
716       case ISD::SETGT:
717       case ISD::SETOGT:
718         if (VecVT == MVT::v4f32)
719           return HasVSX ? PPC::XVCMPGTSP : PPC::VCMPGTFP;
720         else if (VecVT == MVT::v2f64)
721           return PPC::XVCMPGTDP;
722         break;
723       case ISD::SETGE:
724       case ISD::SETOGE:
725         if (VecVT == MVT::v4f32)
726           return HasVSX ? PPC::XVCMPGESP : PPC::VCMPGEFP;
727         else if (VecVT == MVT::v2f64)
728           return PPC::XVCMPGEDP;
729         break;
730       default:
731         break;
732     }
733     llvm_unreachable("Invalid floating-point vector compare condition");
734   } else {
735     /* Handle some cases by swapping input operands.  */
736     switch (CC) {
737       case ISD::SETGE: CC = ISD::SETLE; Swap = true; break;
738       case ISD::SETLT: CC = ISD::SETGT; Swap = true; break;
739       case ISD::SETUGE: CC = ISD::SETULE; Swap = true; break;
740       case ISD::SETULT: CC = ISD::SETUGT; Swap = true; break;
741       default: break;
742     }
743     /* Handle some cases by negating the result.  */
744     switch (CC) {
745       case ISD::SETNE: CC = ISD::SETEQ; Negate = true; break;
746       case ISD::SETUNE: CC = ISD::SETUEQ; Negate = true; break;
747       case ISD::SETLE: CC = ISD::SETGT; Negate = true; break;
748       case ISD::SETULE: CC = ISD::SETUGT; Negate = true; break;
749       default: break;
750     }
751     /* We have instructions implementing the remaining cases.  */
752     switch (CC) {
753       case ISD::SETEQ:
754       case ISD::SETUEQ:
755         if (VecVT == MVT::v16i8)
756           return PPC::VCMPEQUB;
757         else if (VecVT == MVT::v8i16)
758           return PPC::VCMPEQUH;
759         else if (VecVT == MVT::v4i32)
760           return PPC::VCMPEQUW;
761         break;
762       case ISD::SETGT:
763         if (VecVT == MVT::v16i8)
764           return PPC::VCMPGTSB;
765         else if (VecVT == MVT::v8i16)
766           return PPC::VCMPGTSH;
767         else if (VecVT == MVT::v4i32)
768           return PPC::VCMPGTSW;
769         break;
770       case ISD::SETUGT:
771         if (VecVT == MVT::v16i8)
772           return PPC::VCMPGTUB;
773         else if (VecVT == MVT::v8i16)
774           return PPC::VCMPGTUH;
775         else if (VecVT == MVT::v4i32)
776           return PPC::VCMPGTUW;
777         break;
778       default:
779         break;
780     }
781     llvm_unreachable("Invalid integer vector compare condition");
782   }
783 }
784
785 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
786   SDLoc dl(N);
787   unsigned Imm;
788   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
789   EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
790   bool isPPC64 = (PtrVT == MVT::i64);
791
792   if (!PPCSubTarget->useCRBits() &&
793       isInt32Immediate(N->getOperand(1), Imm)) {
794     // We can codegen setcc op, imm very efficiently compared to a brcond.
795     // Check for those cases here.
796     // setcc op, 0
797     if (Imm == 0) {
798       SDValue Op = N->getOperand(0);
799       switch (CC) {
800       default: break;
801       case ISD::SETEQ: {
802         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
803         SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
804         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
805       }
806       case ISD::SETNE: {
807         if (isPPC64) break;
808         SDValue AD =
809           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
810                                          Op, getI32Imm(~0U)), 0);
811         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
812                                     AD.getValue(1));
813       }
814       case ISD::SETLT: {
815         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
816         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
817       }
818       case ISD::SETGT: {
819         SDValue T =
820           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
821         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
822         SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
823         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
824       }
825       }
826     } else if (Imm == ~0U) {        // setcc op, -1
827       SDValue Op = N->getOperand(0);
828       switch (CC) {
829       default: break;
830       case ISD::SETEQ:
831         if (isPPC64) break;
832         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
833                                             Op, getI32Imm(1)), 0);
834         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
835                               SDValue(CurDAG->getMachineNode(PPC::LI, dl,
836                                                              MVT::i32,
837                                                              getI32Imm(0)), 0),
838                                       Op.getValue(1));
839       case ISD::SETNE: {
840         if (isPPC64) break;
841         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
842         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
843                                             Op, getI32Imm(~0U));
844         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
845                                     Op, SDValue(AD, 1));
846       }
847       case ISD::SETLT: {
848         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
849                                                     getI32Imm(1)), 0);
850         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
851                                                     Op), 0);
852         SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
853         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
854       }
855       case ISD::SETGT: {
856         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
857         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops),
858                      0);
859         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
860                                     getI32Imm(1));
861       }
862       }
863     }
864   }
865
866   SDValue LHS = N->getOperand(0);
867   SDValue RHS = N->getOperand(1);
868
869   // Altivec Vector compare instructions do not set any CR register by default and
870   // vector compare operations return the same type as the operands.
871   if (LHS.getValueType().isVector()) {
872     EVT VecVT = LHS.getValueType();
873     bool Swap, Negate;
874     unsigned int VCmpInst = getVCmpInst(VecVT.getSimpleVT(), CC,
875                                         PPCSubTarget->hasVSX(), Swap, Negate);
876     if (Swap)
877       std::swap(LHS, RHS);
878
879     if (Negate) {
880       SDValue VCmp(CurDAG->getMachineNode(VCmpInst, dl, VecVT, LHS, RHS), 0);
881       return CurDAG->SelectNodeTo(N, PPCSubTarget->hasVSX() ? PPC::XXLNOR :
882                                                               PPC::VNOR,
883                                   VecVT, VCmp, VCmp);
884     }
885
886     return CurDAG->SelectNodeTo(N, VCmpInst, VecVT, LHS, RHS);
887   }
888
889   if (PPCSubTarget->useCRBits())
890     return nullptr;
891
892   bool Inv;
893   unsigned Idx = getCRIdxForSetCC(CC, Inv);
894   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
895   SDValue IntCR;
896
897   // Force the ccreg into CR7.
898   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
899
900   SDValue InFlag(nullptr, 0);  // Null incoming flag value.
901   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
902                                InFlag).getValue(1);
903
904   IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
905                                          CCReg), 0);
906
907   SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
908                       getI32Imm(31), getI32Imm(31) };
909   if (!Inv)
910     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
911
912   // Get the specified bit.
913   SDValue Tmp =
914     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops), 0);
915   return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
916 }
917
918
919 // Select - Convert the specified operand from a target-independent to a
920 // target-specific node if it hasn't already been changed.
921 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
922   SDLoc dl(N);
923   if (N->isMachineOpcode()) {
924     N->setNodeId(-1);
925     return nullptr;   // Already selected.
926   }
927
928   // In case any misguided DAG-level optimizations form an ADD with a
929   // TargetConstant operand, crash here instead of miscompiling (by selecting
930   // an r+r add instead of some kind of r+i add).
931   if (N->getOpcode() == ISD::ADD &&
932       N->getOperand(1).getOpcode() == ISD::TargetConstant)
933     llvm_unreachable("Invalid ADD with TargetConstant operand");
934
935   switch (N->getOpcode()) {
936   default: break;
937
938   case ISD::Constant: {
939     if (N->getValueType(0) == MVT::i64) {
940       // Get 64 bit value.
941       int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
942       // Assume no remaining bits.
943       unsigned Remainder = 0;
944       // Assume no shift required.
945       unsigned Shift = 0;
946
947       // If it can't be represented as a 32 bit value.
948       if (!isInt<32>(Imm)) {
949         Shift = countTrailingZeros<uint64_t>(Imm);
950         int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
951
952         // If the shifted value fits 32 bits.
953         if (isInt<32>(ImmSh)) {
954           // Go with the shifted value.
955           Imm = ImmSh;
956         } else {
957           // Still stuck with a 64 bit value.
958           Remainder = Imm;
959           Shift = 32;
960           Imm >>= 32;
961         }
962       }
963
964       // Intermediate operand.
965       SDNode *Result;
966
967       // Handle first 32 bits.
968       unsigned Lo = Imm & 0xFFFF;
969       unsigned Hi = (Imm >> 16) & 0xFFFF;
970
971       // Simple value.
972       if (isInt<16>(Imm)) {
973        // Just the Lo bits.
974         Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
975       } else if (Lo) {
976         // Handle the Hi bits.
977         unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
978         Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
979         // And Lo bits.
980         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
981                                         SDValue(Result, 0), getI32Imm(Lo));
982       } else {
983        // Just the Hi bits.
984         Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
985       }
986
987       // If no shift, we're done.
988       if (!Shift) return Result;
989
990       // Shift for next step if the upper 32-bits were not zero.
991       if (Imm) {
992         Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
993                                         SDValue(Result, 0),
994                                         getI32Imm(Shift),
995                                         getI32Imm(63 - Shift));
996       }
997
998       // Add in the last bits as required.
999       if ((Hi = (Remainder >> 16) & 0xFFFF)) {
1000         Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
1001                                         SDValue(Result, 0), getI32Imm(Hi));
1002       }
1003       if ((Lo = Remainder & 0xFFFF)) {
1004         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
1005                                         SDValue(Result, 0), getI32Imm(Lo));
1006       }
1007
1008       return Result;
1009     }
1010     break;
1011   }
1012
1013   case ISD::SETCC: {
1014     SDNode *SN = SelectSETCC(N);
1015     if (SN)
1016       return SN;
1017     break;
1018   }
1019   case PPCISD::GlobalBaseReg:
1020     return getGlobalBaseReg();
1021
1022   case ISD::FrameIndex: {
1023     int FI = cast<FrameIndexSDNode>(N)->getIndex();
1024     SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
1025     unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
1026     if (N->hasOneUse())
1027       return CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), TFI,
1028                                   getSmallIPtrImm(0));
1029     return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
1030                                   getSmallIPtrImm(0));
1031   }
1032
1033   case PPCISD::MFOCRF: {
1034     SDValue InFlag = N->getOperand(1);
1035     return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
1036                                   N->getOperand(0), InFlag);
1037   }
1038
1039   case PPCISD::READ_TIME_BASE: {
1040     return CurDAG->getMachineNode(PPC::ReadTB, dl, MVT::i32, MVT::i32,
1041                                   MVT::Other, N->getOperand(0));
1042   }
1043
1044   case PPCISD::SRA_ADDZE: {
1045     SDValue N0 = N->getOperand(0);
1046     SDValue ShiftAmt =
1047       CurDAG->getTargetConstant(*cast<ConstantSDNode>(N->getOperand(1))->
1048                                   getConstantIntValue(), N->getValueType(0));
1049     if (N->getValueType(0) == MVT::i64) {
1050       SDNode *Op =
1051         CurDAG->getMachineNode(PPC::SRADI, dl, MVT::i64, MVT::Glue,
1052                                N0, ShiftAmt);
1053       return CurDAG->SelectNodeTo(N, PPC::ADDZE8, MVT::i64,
1054                                   SDValue(Op, 0), SDValue(Op, 1));
1055     } else {
1056       assert(N->getValueType(0) == MVT::i32 &&
1057              "Expecting i64 or i32 in PPCISD::SRA_ADDZE");
1058       SDNode *Op =
1059         CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
1060                                N0, ShiftAmt);
1061       return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
1062                                   SDValue(Op, 0), SDValue(Op, 1));
1063     }
1064   }
1065
1066   case ISD::LOAD: {
1067     // Handle preincrement loads.
1068     LoadSDNode *LD = cast<LoadSDNode>(N);
1069     EVT LoadedVT = LD->getMemoryVT();
1070
1071     // Normal loads are handled by code generated from the .td file.
1072     if (LD->getAddressingMode() != ISD::PRE_INC)
1073       break;
1074
1075     SDValue Offset = LD->getOffset();
1076     if (Offset.getOpcode() == ISD::TargetConstant ||
1077         Offset.getOpcode() == ISD::TargetGlobalAddress) {
1078
1079       unsigned Opcode;
1080       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1081       if (LD->getValueType(0) != MVT::i64) {
1082         // Handle PPC32 integer and normal FP loads.
1083         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1084         switch (LoadedVT.getSimpleVT().SimpleTy) {
1085           default: llvm_unreachable("Invalid PPC load type!");
1086           case MVT::f64: Opcode = PPC::LFDU; break;
1087           case MVT::f32: Opcode = PPC::LFSU; break;
1088           case MVT::i32: Opcode = PPC::LWZU; break;
1089           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
1090           case MVT::i1:
1091           case MVT::i8:  Opcode = PPC::LBZU; break;
1092         }
1093       } else {
1094         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1095         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1096         switch (LoadedVT.getSimpleVT().SimpleTy) {
1097           default: llvm_unreachable("Invalid PPC load type!");
1098           case MVT::i64: Opcode = PPC::LDU; break;
1099           case MVT::i32: Opcode = PPC::LWZU8; break;
1100           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
1101           case MVT::i1:
1102           case MVT::i8:  Opcode = PPC::LBZU8; break;
1103         }
1104       }
1105
1106       SDValue Chain = LD->getChain();
1107       SDValue Base = LD->getBasePtr();
1108       SDValue Ops[] = { Offset, Base, Chain };
1109       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1110                                     PPCLowering->getPointerTy(),
1111                                     MVT::Other, Ops);
1112     } else {
1113       unsigned Opcode;
1114       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
1115       if (LD->getValueType(0) != MVT::i64) {
1116         // Handle PPC32 integer and normal FP loads.
1117         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
1118         switch (LoadedVT.getSimpleVT().SimpleTy) {
1119           default: llvm_unreachable("Invalid PPC load type!");
1120           case MVT::f64: Opcode = PPC::LFDUX; break;
1121           case MVT::f32: Opcode = PPC::LFSUX; break;
1122           case MVT::i32: Opcode = PPC::LWZUX; break;
1123           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
1124           case MVT::i1:
1125           case MVT::i8:  Opcode = PPC::LBZUX; break;
1126         }
1127       } else {
1128         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
1129         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
1130                "Invalid sext update load");
1131         switch (LoadedVT.getSimpleVT().SimpleTy) {
1132           default: llvm_unreachable("Invalid PPC load type!");
1133           case MVT::i64: Opcode = PPC::LDUX; break;
1134           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
1135           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
1136           case MVT::i1:
1137           case MVT::i8:  Opcode = PPC::LBZUX8; break;
1138         }
1139       }
1140
1141       SDValue Chain = LD->getChain();
1142       SDValue Base = LD->getBasePtr();
1143       SDValue Ops[] = { Base, Offset, Chain };
1144       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
1145                                     PPCLowering->getPointerTy(),
1146                                     MVT::Other, Ops);
1147     }
1148   }
1149
1150   case ISD::AND: {
1151     unsigned Imm, Imm2, SH, MB, ME;
1152     uint64_t Imm64;
1153
1154     // If this is an and of a value rotated between 0 and 31 bits and then and'd
1155     // with a mask, emit rlwinm
1156     if (isInt32Immediate(N->getOperand(1), Imm) &&
1157         isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
1158       SDValue Val = N->getOperand(0).getOperand(0);
1159       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1160       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
1161     }
1162     // If this is just a masked value where the input is not handled above, and
1163     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
1164     if (isInt32Immediate(N->getOperand(1), Imm) &&
1165         isRunOfOnes(Imm, MB, ME) &&
1166         N->getOperand(0).getOpcode() != ISD::ROTL) {
1167       SDValue Val = N->getOperand(0);
1168       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
1169       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
1170     }
1171     // If this is a 64-bit zero-extension mask, emit rldicl.
1172     if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
1173         isMask_64(Imm64)) {
1174       SDValue Val = N->getOperand(0);
1175       MB = 64 - CountTrailingOnes_64(Imm64);
1176       SH = 0;
1177
1178       // If the operand is a logical right shift, we can fold it into this
1179       // instruction: rldicl(rldicl(x, 64-n, n), 0, mb) -> rldicl(x, 64-n, mb)
1180       // for n <= mb. The right shift is really a left rotate followed by a
1181       // mask, and this mask is a more-restrictive sub-mask of the mask implied
1182       // by the shift.
1183       if (Val.getOpcode() == ISD::SRL &&
1184           isInt32Immediate(Val.getOperand(1).getNode(), Imm) && Imm <= MB) {
1185         assert(Imm < 64 && "Illegal shift amount");
1186         Val = Val.getOperand(0);
1187         SH = 64 - Imm;
1188       }
1189
1190       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB) };
1191       return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops);
1192     }
1193     // AND X, 0 -> 0, not "rlwinm 32".
1194     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
1195       ReplaceUses(SDValue(N, 0), N->getOperand(1));
1196       return nullptr;
1197     }
1198     // ISD::OR doesn't get all the bitfield insertion fun.
1199     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1200     if (isInt32Immediate(N->getOperand(1), Imm) &&
1201         N->getOperand(0).getOpcode() == ISD::OR &&
1202         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
1203       unsigned MB, ME;
1204       Imm = ~(Imm^Imm2);
1205       if (isRunOfOnes(Imm, MB, ME)) {
1206         SDValue Ops[] = { N->getOperand(0).getOperand(0),
1207                             N->getOperand(0).getOperand(1),
1208                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
1209         return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops);
1210       }
1211     }
1212
1213     // Other cases are autogenerated.
1214     break;
1215   }
1216   case ISD::OR:
1217     if (N->getValueType(0) == MVT::i32)
1218       if (SDNode *I = SelectBitfieldInsert(N))
1219         return I;
1220
1221     // Other cases are autogenerated.
1222     break;
1223   case ISD::SHL: {
1224     unsigned Imm, SH, MB, ME;
1225     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1226         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1227       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1228                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1229       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
1230     }
1231
1232     // Other cases are autogenerated.
1233     break;
1234   }
1235   case ISD::SRL: {
1236     unsigned Imm, SH, MB, ME;
1237     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1238         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1239       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1240                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1241       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops);
1242     }
1243
1244     // Other cases are autogenerated.
1245     break;
1246   }
1247   // FIXME: Remove this once the ANDI glue bug is fixed:
1248   case PPCISD::ANDIo_1_EQ_BIT:
1249   case PPCISD::ANDIo_1_GT_BIT: {
1250     if (!ANDIGlueBug)
1251       break;
1252
1253     EVT InVT = N->getOperand(0).getValueType();
1254     assert((InVT == MVT::i64 || InVT == MVT::i32) &&
1255            "Invalid input type for ANDIo_1_EQ_BIT");
1256
1257     unsigned Opcode = (InVT == MVT::i64) ? PPC::ANDIo8 : PPC::ANDIo;
1258     SDValue AndI(CurDAG->getMachineNode(Opcode, dl, InVT, MVT::Glue,
1259                                         N->getOperand(0),
1260                                         CurDAG->getTargetConstant(1, InVT)), 0);
1261     SDValue CR0Reg = CurDAG->getRegister(PPC::CR0, MVT::i32);
1262     SDValue SRIdxVal =
1263       CurDAG->getTargetConstant(N->getOpcode() == PPCISD::ANDIo_1_EQ_BIT ?
1264                                 PPC::sub_eq : PPC::sub_gt, MVT::i32);
1265
1266     return CurDAG->SelectNodeTo(N, TargetOpcode::EXTRACT_SUBREG, MVT::i1,
1267                                 CR0Reg, SRIdxVal,
1268                                 SDValue(AndI.getNode(), 1) /* glue */);
1269   }
1270   case ISD::SELECT_CC: {
1271     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1272     EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
1273     bool isPPC64 = (PtrVT == MVT::i64);
1274
1275     // If this is a select of i1 operands, we'll pattern match it.
1276     if (PPCSubTarget->useCRBits() &&
1277         N->getOperand(0).getValueType() == MVT::i1)
1278       break;
1279
1280     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1281     if (!isPPC64)
1282       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1283         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1284           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1285             if (N1C->isNullValue() && N3C->isNullValue() &&
1286                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
1287                 // FIXME: Implement this optzn for PPC64.
1288                 N->getValueType(0) == MVT::i32) {
1289               SDNode *Tmp =
1290                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
1291                                        N->getOperand(0), getI32Imm(~0U));
1292               return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1293                                           SDValue(Tmp, 0), N->getOperand(0),
1294                                           SDValue(Tmp, 1));
1295             }
1296
1297     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
1298
1299     if (N->getValueType(0) == MVT::i1) {
1300       // An i1 select is: (c & t) | (!c & f).
1301       bool Inv;
1302       unsigned Idx = getCRIdxForSetCC(CC, Inv);
1303
1304       unsigned SRI;
1305       switch (Idx) {
1306       default: llvm_unreachable("Invalid CC index");
1307       case 0: SRI = PPC::sub_lt; break;
1308       case 1: SRI = PPC::sub_gt; break;
1309       case 2: SRI = PPC::sub_eq; break;
1310       case 3: SRI = PPC::sub_un; break;
1311       }
1312
1313       SDValue CCBit = CurDAG->getTargetExtractSubreg(SRI, dl, MVT::i1, CCReg);
1314
1315       SDValue NotCCBit(CurDAG->getMachineNode(PPC::CRNOR, dl, MVT::i1,
1316                                               CCBit, CCBit), 0);
1317       SDValue C =    Inv ? NotCCBit : CCBit,
1318               NotC = Inv ? CCBit    : NotCCBit;
1319
1320       SDValue CAndT(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
1321                                            C, N->getOperand(2)), 0);
1322       SDValue NotCAndF(CurDAG->getMachineNode(PPC::CRAND, dl, MVT::i1,
1323                                               NotC, N->getOperand(3)), 0);
1324
1325       return CurDAG->SelectNodeTo(N, PPC::CROR, MVT::i1, CAndT, NotCAndF);
1326     }
1327
1328     unsigned BROpc = getPredicateForSetCC(CC);
1329
1330     unsigned SelectCCOp;
1331     if (N->getValueType(0) == MVT::i32)
1332       SelectCCOp = PPC::SELECT_CC_I4;
1333     else if (N->getValueType(0) == MVT::i64)
1334       SelectCCOp = PPC::SELECT_CC_I8;
1335     else if (N->getValueType(0) == MVT::f32)
1336       SelectCCOp = PPC::SELECT_CC_F4;
1337     else if (N->getValueType(0) == MVT::f64)
1338       if (PPCSubTarget->hasVSX())
1339         SelectCCOp = PPC::SELECT_CC_VSFRC;
1340       else
1341         SelectCCOp = PPC::SELECT_CC_F8;
1342     else if (N->getValueType(0) == MVT::v2f64 ||
1343              N->getValueType(0) == MVT::v2i64)
1344       SelectCCOp = PPC::SELECT_CC_VSRC;
1345     else
1346       SelectCCOp = PPC::SELECT_CC_VRRC;
1347
1348     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
1349                         getI32Imm(BROpc) };
1350     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops);
1351   }
1352   case ISD::VSELECT:
1353     if (PPCSubTarget->hasVSX()) {
1354       SDValue Ops[] = { N->getOperand(2), N->getOperand(1), N->getOperand(0) };
1355       return CurDAG->SelectNodeTo(N, PPC::XXSEL, N->getValueType(0), Ops);
1356     }
1357
1358     break;
1359   case ISD::VECTOR_SHUFFLE:
1360     if (PPCSubTarget->hasVSX() && (N->getValueType(0) == MVT::v2f64 ||
1361                                   N->getValueType(0) == MVT::v2i64)) {
1362       ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
1363       
1364       SDValue Op1 = N->getOperand(SVN->getMaskElt(0) < 2 ? 0 : 1),
1365               Op2 = N->getOperand(SVN->getMaskElt(1) < 2 ? 0 : 1);
1366       unsigned DM[2];
1367
1368       for (int i = 0; i < 2; ++i)
1369         if (SVN->getMaskElt(i) <= 0 || SVN->getMaskElt(i) == 2)
1370           DM[i] = 0;
1371         else
1372           DM[i] = 1;
1373
1374       // For little endian, we must swap the input operands and adjust
1375       // the mask elements (reverse and invert them).
1376       if (PPCSubTarget->isLittleEndian()) {
1377         std::swap(Op1, Op2);
1378         unsigned tmp = DM[0];
1379         DM[0] = 1 - DM[1];
1380         DM[1] = 1 - tmp;
1381       }
1382
1383       SDValue DMV = CurDAG->getTargetConstant(DM[1] | (DM[0] << 1), MVT::i32);
1384
1385       if (Op1 == Op2 && DM[0] == 0 && DM[1] == 0 &&
1386           Op1.getOpcode() == ISD::SCALAR_TO_VECTOR &&
1387           isa<LoadSDNode>(Op1.getOperand(0))) {
1388         LoadSDNode *LD = cast<LoadSDNode>(Op1.getOperand(0));
1389         SDValue Base, Offset;
1390
1391         if (LD->isUnindexed() &&
1392             SelectAddrIdxOnly(LD->getBasePtr(), Base, Offset)) {
1393           SDValue Chain = LD->getChain();
1394           SDValue Ops[] = { Base, Offset, Chain };
1395           return CurDAG->SelectNodeTo(N, PPC::LXVDSX,
1396                                       N->getValueType(0), Ops);
1397         }
1398       }
1399
1400       SDValue Ops[] = { Op1, Op2, DMV };
1401       return CurDAG->SelectNodeTo(N, PPC::XXPERMDI, N->getValueType(0), Ops);
1402     }
1403
1404     break;
1405   case PPCISD::BDNZ:
1406   case PPCISD::BDZ: {
1407     bool IsPPC64 = PPCSubTarget->isPPC64();
1408     SDValue Ops[] = { N->getOperand(1), N->getOperand(0) };
1409     return CurDAG->SelectNodeTo(N, N->getOpcode() == PPCISD::BDNZ ?
1410                                    (IsPPC64 ? PPC::BDNZ8 : PPC::BDNZ) :
1411                                    (IsPPC64 ? PPC::BDZ8 : PPC::BDZ),
1412                                 MVT::Other, Ops);
1413   }
1414   case PPCISD::COND_BRANCH: {
1415     // Op #0 is the Chain.
1416     // Op #1 is the PPC::PRED_* number.
1417     // Op #2 is the CR#
1418     // Op #3 is the Dest MBB
1419     // Op #4 is the Flag.
1420     // Prevent PPC::PRED_* from being selected into LI.
1421     SDValue Pred =
1422       getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
1423     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
1424       N->getOperand(0), N->getOperand(4) };
1425     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
1426   }
1427   case ISD::BR_CC: {
1428     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1429     unsigned PCC = getPredicateForSetCC(CC);
1430
1431     if (N->getOperand(2).getValueType() == MVT::i1) {
1432       unsigned Opc;
1433       bool Swap;
1434       switch (PCC) {
1435       default: llvm_unreachable("Unexpected Boolean-operand predicate");
1436       case PPC::PRED_LT: Opc = PPC::CRANDC; Swap = true;  break;
1437       case PPC::PRED_LE: Opc = PPC::CRORC;  Swap = true;  break;
1438       case PPC::PRED_EQ: Opc = PPC::CREQV;  Swap = false; break;
1439       case PPC::PRED_GE: Opc = PPC::CRORC;  Swap = false; break;
1440       case PPC::PRED_GT: Opc = PPC::CRANDC; Swap = false; break;
1441       case PPC::PRED_NE: Opc = PPC::CRXOR;  Swap = false; break;
1442       }
1443
1444       SDValue BitComp(CurDAG->getMachineNode(Opc, dl, MVT::i1,
1445                                              N->getOperand(Swap ? 3 : 2),
1446                                              N->getOperand(Swap ? 2 : 3)), 0);
1447       return CurDAG->SelectNodeTo(N, PPC::BC, MVT::Other,
1448                                   BitComp, N->getOperand(4), N->getOperand(0));
1449     }
1450
1451     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
1452     SDValue Ops[] = { getI32Imm(PCC), CondCode,
1453                         N->getOperand(4), N->getOperand(0) };
1454     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops);
1455   }
1456   case ISD::BRIND: {
1457     // FIXME: Should custom lower this.
1458     SDValue Chain = N->getOperand(0);
1459     SDValue Target = N->getOperand(1);
1460     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1461     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
1462     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
1463                                            Chain), 0);
1464     return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
1465   }
1466   case PPCISD::TOC_ENTRY: {
1467     assert ((PPCSubTarget->isPPC64() || PPCSubTarget->isSVR4ABI()) &&
1468             "Only supported for 64-bit ABI and 32-bit SVR4");
1469     if (PPCSubTarget->isSVR4ABI() && !PPCSubTarget->isPPC64()) {
1470       SDValue GA = N->getOperand(0);
1471       return CurDAG->getMachineNode(PPC::LWZtoc, dl, MVT::i32, GA,
1472                                     N->getOperand(1));
1473     }
1474
1475     // For medium and large code model, we generate two instructions as
1476     // described below.  Otherwise we allow SelectCodeCommon to handle this,
1477     // selecting one of LDtoc, LDtocJTI, LDtocCPT, and LDtocBA.
1478     CodeModel::Model CModel = TM.getCodeModel();
1479     if (CModel != CodeModel::Medium && CModel != CodeModel::Large)
1480       break;
1481
1482     // The first source operand is a TargetGlobalAddress or a TargetJumpTable.
1483     // If it is an externally defined symbol, a symbol with common linkage,
1484     // a non-local function address, or a jump table address, or if we are
1485     // generating code for large code model, we generate:
1486     //   LDtocL(<ga:@sym>, ADDIStocHA(%X2, <ga:@sym>))
1487     // Otherwise we generate:
1488     //   ADDItocL(ADDIStocHA(%X2, <ga:@sym>), <ga:@sym>)
1489     SDValue GA = N->getOperand(0);
1490     SDValue TOCbase = N->getOperand(1);
1491     SDNode *Tmp = CurDAG->getMachineNode(PPC::ADDIStocHA, dl, MVT::i64,
1492                                         TOCbase, GA);
1493
1494     if (isa<JumpTableSDNode>(GA) || isa<BlockAddressSDNode>(GA) ||
1495         CModel == CodeModel::Large)
1496       return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1497                                     SDValue(Tmp, 0));
1498
1499     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(GA)) {
1500       const GlobalValue *GValue = G->getGlobal();
1501       if ((GValue->getType()->getElementType()->isFunctionTy() &&
1502            (GValue->isDeclaration() || GValue->isWeakForLinker())) ||
1503           GValue->isDeclaration() || GValue->hasCommonLinkage() ||
1504           GValue->hasAvailableExternallyLinkage())
1505         return CurDAG->getMachineNode(PPC::LDtocL, dl, MVT::i64, GA,
1506                                       SDValue(Tmp, 0));
1507     }
1508
1509     return CurDAG->getMachineNode(PPC::ADDItocL, dl, MVT::i64,
1510                                   SDValue(Tmp, 0), GA);
1511   }
1512   case PPCISD::PPC32_PICGOT: {
1513     // Generate a PIC-safe GOT reference.
1514     assert(!PPCSubTarget->isPPC64() && PPCSubTarget->isSVR4ABI() &&
1515       "PPCISD::PPC32_PICGOT is only supported for 32-bit SVR4");
1516     return CurDAG->SelectNodeTo(N, PPC::PPC32PICGOT, PPCLowering->getPointerTy(),  MVT::i32);
1517   }
1518   case PPCISD::VADD_SPLAT: {
1519     // This expands into one of three sequences, depending on whether
1520     // the first operand is odd or even, positive or negative.
1521     assert(isa<ConstantSDNode>(N->getOperand(0)) &&
1522            isa<ConstantSDNode>(N->getOperand(1)) &&
1523            "Invalid operand on VADD_SPLAT!");
1524
1525     int Elt     = N->getConstantOperandVal(0);
1526     int EltSize = N->getConstantOperandVal(1);
1527     unsigned Opc1, Opc2, Opc3;
1528     EVT VT;
1529
1530     if (EltSize == 1) {
1531       Opc1 = PPC::VSPLTISB;
1532       Opc2 = PPC::VADDUBM;
1533       Opc3 = PPC::VSUBUBM;
1534       VT = MVT::v16i8;
1535     } else if (EltSize == 2) {
1536       Opc1 = PPC::VSPLTISH;
1537       Opc2 = PPC::VADDUHM;
1538       Opc3 = PPC::VSUBUHM;
1539       VT = MVT::v8i16;
1540     } else {
1541       assert(EltSize == 4 && "Invalid element size on VADD_SPLAT!");
1542       Opc1 = PPC::VSPLTISW;
1543       Opc2 = PPC::VADDUWM;
1544       Opc3 = PPC::VSUBUWM;
1545       VT = MVT::v4i32;
1546     }
1547
1548     if ((Elt & 1) == 0) {
1549       // Elt is even, in the range [-32,-18] + [16,30].
1550       //
1551       // Convert: VADD_SPLAT elt, size
1552       // Into:    tmp = VSPLTIS[BHW] elt
1553       //          VADDU[BHW]M tmp, tmp
1554       // Where:   [BHW] = B for size = 1, H for size = 2, W for size = 4
1555       SDValue EltVal = getI32Imm(Elt >> 1);
1556       SDNode *Tmp = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1557       SDValue TmpVal = SDValue(Tmp, 0);
1558       return CurDAG->getMachineNode(Opc2, dl, VT, TmpVal, TmpVal);
1559
1560     } else if (Elt > 0) {
1561       // Elt is odd and positive, in the range [17,31].
1562       //
1563       // Convert: VADD_SPLAT elt, size
1564       // Into:    tmp1 = VSPLTIS[BHW] elt-16
1565       //          tmp2 = VSPLTIS[BHW] -16
1566       //          VSUBU[BHW]M tmp1, tmp2
1567       SDValue EltVal = getI32Imm(Elt - 16);
1568       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1569       EltVal = getI32Imm(-16);
1570       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1571       return CurDAG->getMachineNode(Opc3, dl, VT, SDValue(Tmp1, 0),
1572                                     SDValue(Tmp2, 0));
1573
1574     } else {
1575       // Elt is odd and negative, in the range [-31,-17].
1576       //
1577       // Convert: VADD_SPLAT elt, size
1578       // Into:    tmp1 = VSPLTIS[BHW] elt+16
1579       //          tmp2 = VSPLTIS[BHW] -16
1580       //          VADDU[BHW]M tmp1, tmp2
1581       SDValue EltVal = getI32Imm(Elt + 16);
1582       SDNode *Tmp1 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1583       EltVal = getI32Imm(-16);
1584       SDNode *Tmp2 = CurDAG->getMachineNode(Opc1, dl, VT, EltVal);
1585       return CurDAG->getMachineNode(Opc2, dl, VT, SDValue(Tmp1, 0),
1586                                     SDValue(Tmp2, 0));
1587     }
1588   }
1589   }
1590
1591   return SelectCode(N);
1592 }
1593
1594 /// PostprocessISelDAG - Perform some late peephole optimizations
1595 /// on the DAG representation.
1596 void PPCDAGToDAGISel::PostprocessISelDAG() {
1597
1598   // Skip peepholes at -O0.
1599   if (TM.getOptLevel() == CodeGenOpt::None)
1600     return;
1601
1602   PeepholePPC64();
1603   PeepholeCROps();
1604 }
1605
1606 // Check if all users of this node will become isel where the second operand
1607 // is the constant zero. If this is so, and if we can negate the condition,
1608 // then we can flip the true and false operands. This will allow the zero to
1609 // be folded with the isel so that we don't need to materialize a register
1610 // containing zero.
1611 bool PPCDAGToDAGISel::AllUsersSelectZero(SDNode *N) {
1612   // If we're not using isel, then this does not matter.
1613   if (!PPCSubTarget->hasISEL())
1614     return false;
1615
1616   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
1617        UI != UE; ++UI) {
1618     SDNode *User = *UI;
1619     if (!User->isMachineOpcode())
1620       return false;
1621     if (User->getMachineOpcode() != PPC::SELECT_I4 &&
1622         User->getMachineOpcode() != PPC::SELECT_I8)
1623       return false;
1624
1625     SDNode *Op2 = User->getOperand(2).getNode();
1626     if (!Op2->isMachineOpcode())
1627       return false;
1628
1629     if (Op2->getMachineOpcode() != PPC::LI &&
1630         Op2->getMachineOpcode() != PPC::LI8)
1631       return false;
1632
1633     ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op2->getOperand(0));
1634     if (!C)
1635       return false;
1636
1637     if (!C->isNullValue())
1638       return false;
1639   }
1640
1641   return true;
1642 }
1643
1644 void PPCDAGToDAGISel::SwapAllSelectUsers(SDNode *N) {
1645   SmallVector<SDNode *, 4> ToReplace;
1646   for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
1647        UI != UE; ++UI) {
1648     SDNode *User = *UI;
1649     assert((User->getMachineOpcode() == PPC::SELECT_I4 ||
1650             User->getMachineOpcode() == PPC::SELECT_I8) &&
1651            "Must have all select users");
1652     ToReplace.push_back(User);
1653   }
1654
1655   for (SmallVector<SDNode *, 4>::iterator UI = ToReplace.begin(),
1656        UE = ToReplace.end(); UI != UE; ++UI) {
1657     SDNode *User = *UI;
1658     SDNode *ResNode =
1659       CurDAG->getMachineNode(User->getMachineOpcode(), SDLoc(User),
1660                              User->getValueType(0), User->getOperand(0),
1661                              User->getOperand(2),
1662                              User->getOperand(1));
1663
1664       DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
1665       DEBUG(User->dump(CurDAG));
1666       DEBUG(dbgs() << "\nNew: ");
1667       DEBUG(ResNode->dump(CurDAG));
1668       DEBUG(dbgs() << "\n");
1669
1670       ReplaceUses(User, ResNode);
1671   }
1672 }
1673
1674 void PPCDAGToDAGISel::PeepholeCROps() {
1675   bool IsModified;
1676   do {
1677     IsModified = false;
1678     for (SelectionDAG::allnodes_iterator I = CurDAG->allnodes_begin(),
1679          E = CurDAG->allnodes_end(); I != E; ++I) {
1680       MachineSDNode *MachineNode = dyn_cast<MachineSDNode>(I);
1681       if (!MachineNode || MachineNode->use_empty())
1682         continue;
1683       SDNode *ResNode = MachineNode;
1684
1685       bool Op1Set   = false, Op1Unset = false,
1686            Op1Not   = false,
1687            Op2Set   = false, Op2Unset = false,
1688            Op2Not   = false;
1689
1690       unsigned Opcode = MachineNode->getMachineOpcode();
1691       switch (Opcode) {
1692       default: break;
1693       case PPC::CRAND:
1694       case PPC::CRNAND:
1695       case PPC::CROR:
1696       case PPC::CRXOR:
1697       case PPC::CRNOR:
1698       case PPC::CREQV:
1699       case PPC::CRANDC:
1700       case PPC::CRORC: {
1701         SDValue Op = MachineNode->getOperand(1);
1702         if (Op.isMachineOpcode()) {
1703           if (Op.getMachineOpcode() == PPC::CRSET)
1704             Op2Set = true;
1705           else if (Op.getMachineOpcode() == PPC::CRUNSET)
1706             Op2Unset = true;
1707           else if (Op.getMachineOpcode() == PPC::CRNOR &&
1708                    Op.getOperand(0) == Op.getOperand(1))
1709             Op2Not = true;
1710         }
1711         }  // fallthrough
1712       case PPC::BC:
1713       case PPC::BCn:
1714       case PPC::SELECT_I4:
1715       case PPC::SELECT_I8:
1716       case PPC::SELECT_F4:
1717       case PPC::SELECT_F8:
1718       case PPC::SELECT_VRRC:
1719       case PPC::SELECT_VSFRC:
1720       case PPC::SELECT_VSRC: {
1721         SDValue Op = MachineNode->getOperand(0);
1722         if (Op.isMachineOpcode()) {
1723           if (Op.getMachineOpcode() == PPC::CRSET)
1724             Op1Set = true;
1725           else if (Op.getMachineOpcode() == PPC::CRUNSET)
1726             Op1Unset = true;
1727           else if (Op.getMachineOpcode() == PPC::CRNOR &&
1728                    Op.getOperand(0) == Op.getOperand(1))
1729             Op1Not = true;
1730         }
1731         }
1732         break;
1733       }
1734
1735       bool SelectSwap = false;
1736       switch (Opcode) {
1737       default: break;
1738       case PPC::CRAND:
1739         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1740           // x & x = x
1741           ResNode = MachineNode->getOperand(0).getNode();
1742         else if (Op1Set)
1743           // 1 & y = y
1744           ResNode = MachineNode->getOperand(1).getNode();
1745         else if (Op2Set)
1746           // x & 1 = x
1747           ResNode = MachineNode->getOperand(0).getNode();
1748         else if (Op1Unset || Op2Unset)
1749           // x & 0 = 0 & y = 0
1750           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1751                                            MVT::i1);
1752         else if (Op1Not)
1753           // ~x & y = andc(y, x)
1754           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1755                                            MVT::i1, MachineNode->getOperand(1),
1756                                            MachineNode->getOperand(0).
1757                                              getOperand(0));
1758         else if (Op2Not)
1759           // x & ~y = andc(x, y)
1760           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1761                                            MVT::i1, MachineNode->getOperand(0),
1762                                            MachineNode->getOperand(1).
1763                                              getOperand(0));
1764         else if (AllUsersSelectZero(MachineNode))
1765           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
1766                                            MVT::i1, MachineNode->getOperand(0),
1767                                            MachineNode->getOperand(1)),
1768           SelectSwap = true;
1769         break;
1770       case PPC::CRNAND:
1771         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1772           // nand(x, x) -> nor(x, x)
1773           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1774                                            MVT::i1, MachineNode->getOperand(0),
1775                                            MachineNode->getOperand(0));
1776         else if (Op1Set)
1777           // nand(1, y) -> nor(y, y)
1778           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1779                                            MVT::i1, MachineNode->getOperand(1),
1780                                            MachineNode->getOperand(1));
1781         else if (Op2Set)
1782           // nand(x, 1) -> nor(x, x)
1783           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1784                                            MVT::i1, MachineNode->getOperand(0),
1785                                            MachineNode->getOperand(0));
1786         else if (Op1Unset || Op2Unset)
1787           // nand(x, 0) = nand(0, y) = 1
1788           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1789                                            MVT::i1);
1790         else if (Op1Not)
1791           // nand(~x, y) = ~(~x & y) = x | ~y = orc(x, y)
1792           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1793                                            MVT::i1, MachineNode->getOperand(0).
1794                                                       getOperand(0),
1795                                            MachineNode->getOperand(1));
1796         else if (Op2Not)
1797           // nand(x, ~y) = ~x | y = orc(y, x)
1798           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1799                                            MVT::i1, MachineNode->getOperand(1).
1800                                                       getOperand(0),
1801                                            MachineNode->getOperand(0));
1802         else if (AllUsersSelectZero(MachineNode))
1803           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
1804                                            MVT::i1, MachineNode->getOperand(0),
1805                                            MachineNode->getOperand(1)),
1806           SelectSwap = true;
1807         break;
1808       case PPC::CROR:
1809         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1810           // x | x = x
1811           ResNode = MachineNode->getOperand(0).getNode();
1812         else if (Op1Set || Op2Set)
1813           // x | 1 = 1 | y = 1
1814           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1815                                            MVT::i1);
1816         else if (Op1Unset)
1817           // 0 | y = y
1818           ResNode = MachineNode->getOperand(1).getNode();
1819         else if (Op2Unset)
1820           // x | 0 = x
1821           ResNode = MachineNode->getOperand(0).getNode();
1822         else if (Op1Not)
1823           // ~x | y = orc(y, x)
1824           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1825                                            MVT::i1, MachineNode->getOperand(1),
1826                                            MachineNode->getOperand(0).
1827                                              getOperand(0));
1828         else if (Op2Not)
1829           // x | ~y = orc(x, y)
1830           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1831                                            MVT::i1, MachineNode->getOperand(0),
1832                                            MachineNode->getOperand(1).
1833                                              getOperand(0));
1834         else if (AllUsersSelectZero(MachineNode))
1835           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1836                                            MVT::i1, MachineNode->getOperand(0),
1837                                            MachineNode->getOperand(1)),
1838           SelectSwap = true;
1839         break;
1840       case PPC::CRXOR:
1841         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1842           // xor(x, x) = 0
1843           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1844                                            MVT::i1);
1845         else if (Op1Set)
1846           // xor(1, y) -> nor(y, y)
1847           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1848                                            MVT::i1, MachineNode->getOperand(1),
1849                                            MachineNode->getOperand(1));
1850         else if (Op2Set)
1851           // xor(x, 1) -> nor(x, x)
1852           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1853                                            MVT::i1, MachineNode->getOperand(0),
1854                                            MachineNode->getOperand(0));
1855         else if (Op1Unset)
1856           // xor(0, y) = y
1857           ResNode = MachineNode->getOperand(1).getNode();
1858         else if (Op2Unset)
1859           // xor(x, 0) = x
1860           ResNode = MachineNode->getOperand(0).getNode();
1861         else if (Op1Not)
1862           // xor(~x, y) = eqv(x, y)
1863           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1864                                            MVT::i1, MachineNode->getOperand(0).
1865                                                       getOperand(0),
1866                                            MachineNode->getOperand(1));
1867         else if (Op2Not)
1868           // xor(x, ~y) = eqv(x, y)
1869           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1870                                            MVT::i1, MachineNode->getOperand(0),
1871                                            MachineNode->getOperand(1).
1872                                              getOperand(0));
1873         else if (AllUsersSelectZero(MachineNode))
1874           ResNode = CurDAG->getMachineNode(PPC::CREQV, SDLoc(MachineNode),
1875                                            MVT::i1, MachineNode->getOperand(0),
1876                                            MachineNode->getOperand(1)),
1877           SelectSwap = true;
1878         break;
1879       case PPC::CRNOR:
1880         if (Op1Set || Op2Set)
1881           // nor(1, y) -> 0
1882           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1883                                            MVT::i1);
1884         else if (Op1Unset)
1885           // nor(0, y) = ~y -> nor(y, y)
1886           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1887                                            MVT::i1, MachineNode->getOperand(1),
1888                                            MachineNode->getOperand(1));
1889         else if (Op2Unset)
1890           // nor(x, 0) = ~x
1891           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1892                                            MVT::i1, MachineNode->getOperand(0),
1893                                            MachineNode->getOperand(0));
1894         else if (Op1Not)
1895           // nor(~x, y) = andc(x, y)
1896           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1897                                            MVT::i1, MachineNode->getOperand(0).
1898                                                       getOperand(0),
1899                                            MachineNode->getOperand(1));
1900         else if (Op2Not)
1901           // nor(x, ~y) = andc(y, x)
1902           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
1903                                            MVT::i1, MachineNode->getOperand(1).
1904                                                       getOperand(0),
1905                                            MachineNode->getOperand(0));
1906         else if (AllUsersSelectZero(MachineNode))
1907           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
1908                                            MVT::i1, MachineNode->getOperand(0),
1909                                            MachineNode->getOperand(1)),
1910           SelectSwap = true;
1911         break;
1912       case PPC::CREQV:
1913         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1914           // eqv(x, x) = 1
1915           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1916                                            MVT::i1);
1917         else if (Op1Set)
1918           // eqv(1, y) = y
1919           ResNode = MachineNode->getOperand(1).getNode();
1920         else if (Op2Set)
1921           // eqv(x, 1) = x
1922           ResNode = MachineNode->getOperand(0).getNode();
1923         else if (Op1Unset)
1924           // eqv(0, y) = ~y -> nor(y, y)
1925           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1926                                            MVT::i1, MachineNode->getOperand(1),
1927                                            MachineNode->getOperand(1));
1928         else if (Op2Unset)
1929           // eqv(x, 0) = ~x
1930           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1931                                            MVT::i1, MachineNode->getOperand(0),
1932                                            MachineNode->getOperand(0));
1933         else if (Op1Not)
1934           // eqv(~x, y) = xor(x, y)
1935           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1936                                            MVT::i1, MachineNode->getOperand(0).
1937                                                       getOperand(0),
1938                                            MachineNode->getOperand(1));
1939         else if (Op2Not)
1940           // eqv(x, ~y) = xor(x, y)
1941           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1942                                            MVT::i1, MachineNode->getOperand(0),
1943                                            MachineNode->getOperand(1).
1944                                              getOperand(0));
1945         else if (AllUsersSelectZero(MachineNode))
1946           ResNode = CurDAG->getMachineNode(PPC::CRXOR, SDLoc(MachineNode),
1947                                            MVT::i1, MachineNode->getOperand(0),
1948                                            MachineNode->getOperand(1)),
1949           SelectSwap = true;
1950         break;
1951       case PPC::CRANDC:
1952         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1953           // andc(x, x) = 0
1954           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1955                                            MVT::i1);
1956         else if (Op1Set)
1957           // andc(1, y) = ~y
1958           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1959                                            MVT::i1, MachineNode->getOperand(1),
1960                                            MachineNode->getOperand(1));
1961         else if (Op1Unset || Op2Set)
1962           // andc(0, y) = andc(x, 1) = 0
1963           ResNode = CurDAG->getMachineNode(PPC::CRUNSET, SDLoc(MachineNode),
1964                                            MVT::i1);
1965         else if (Op2Unset)
1966           // andc(x, 0) = x
1967           ResNode = MachineNode->getOperand(0).getNode();
1968         else if (Op1Not)
1969           // andc(~x, y) = ~(x | y) = nor(x, y)
1970           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
1971                                            MVT::i1, MachineNode->getOperand(0).
1972                                                       getOperand(0),
1973                                            MachineNode->getOperand(1));
1974         else if (Op2Not)
1975           // andc(x, ~y) = x & y
1976           ResNode = CurDAG->getMachineNode(PPC::CRAND, SDLoc(MachineNode),
1977                                            MVT::i1, MachineNode->getOperand(0),
1978                                            MachineNode->getOperand(1).
1979                                              getOperand(0));
1980         else if (AllUsersSelectZero(MachineNode))
1981           ResNode = CurDAG->getMachineNode(PPC::CRORC, SDLoc(MachineNode),
1982                                            MVT::i1, MachineNode->getOperand(1),
1983                                            MachineNode->getOperand(0)),
1984           SelectSwap = true;
1985         break;
1986       case PPC::CRORC:
1987         if (MachineNode->getOperand(0) == MachineNode->getOperand(1))
1988           // orc(x, x) = 1
1989           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1990                                            MVT::i1);
1991         else if (Op1Set || Op2Unset)
1992           // orc(1, y) = orc(x, 0) = 1
1993           ResNode = CurDAG->getMachineNode(PPC::CRSET, SDLoc(MachineNode),
1994                                            MVT::i1);
1995         else if (Op2Set)
1996           // orc(x, 1) = x
1997           ResNode = MachineNode->getOperand(0).getNode();
1998         else if (Op1Unset)
1999           // orc(0, y) = ~y
2000           ResNode = CurDAG->getMachineNode(PPC::CRNOR, SDLoc(MachineNode),
2001                                            MVT::i1, MachineNode->getOperand(1),
2002                                            MachineNode->getOperand(1));
2003         else if (Op1Not)
2004           // orc(~x, y) = ~(x & y) = nand(x, y)
2005           ResNode = CurDAG->getMachineNode(PPC::CRNAND, SDLoc(MachineNode),
2006                                            MVT::i1, MachineNode->getOperand(0).
2007                                                       getOperand(0),
2008                                            MachineNode->getOperand(1));
2009         else if (Op2Not)
2010           // orc(x, ~y) = x | y
2011           ResNode = CurDAG->getMachineNode(PPC::CROR, SDLoc(MachineNode),
2012                                            MVT::i1, MachineNode->getOperand(0),
2013                                            MachineNode->getOperand(1).
2014                                              getOperand(0));
2015         else if (AllUsersSelectZero(MachineNode))
2016           ResNode = CurDAG->getMachineNode(PPC::CRANDC, SDLoc(MachineNode),
2017                                            MVT::i1, MachineNode->getOperand(1),
2018                                            MachineNode->getOperand(0)),
2019           SelectSwap = true;
2020         break;
2021       case PPC::SELECT_I4:
2022       case PPC::SELECT_I8:
2023       case PPC::SELECT_F4:
2024       case PPC::SELECT_F8:
2025       case PPC::SELECT_VRRC:
2026       case PPC::SELECT_VSFRC:
2027       case PPC::SELECT_VSRC:
2028         if (Op1Set)
2029           ResNode = MachineNode->getOperand(1).getNode();
2030         else if (Op1Unset)
2031           ResNode = MachineNode->getOperand(2).getNode();
2032         else if (Op1Not)
2033           ResNode = CurDAG->getMachineNode(MachineNode->getMachineOpcode(),
2034                                            SDLoc(MachineNode),
2035                                            MachineNode->getValueType(0),
2036                                            MachineNode->getOperand(0).
2037                                              getOperand(0),
2038                                            MachineNode->getOperand(2),
2039                                            MachineNode->getOperand(1));
2040         break;
2041       case PPC::BC:
2042       case PPC::BCn:
2043         if (Op1Not)
2044           ResNode = CurDAG->getMachineNode(Opcode == PPC::BC ? PPC::BCn :
2045                                                                PPC::BC,
2046                                            SDLoc(MachineNode),
2047                                            MVT::Other,
2048                                            MachineNode->getOperand(0).
2049                                              getOperand(0),
2050                                            MachineNode->getOperand(1),
2051                                            MachineNode->getOperand(2));
2052         // FIXME: Handle Op1Set, Op1Unset here too.
2053         break;
2054       }
2055
2056       // If we're inverting this node because it is used only by selects that
2057       // we'd like to swap, then swap the selects before the node replacement.
2058       if (SelectSwap)
2059         SwapAllSelectUsers(MachineNode);
2060
2061       if (ResNode != MachineNode) {
2062         DEBUG(dbgs() << "CR Peephole replacing:\nOld:    ");
2063         DEBUG(MachineNode->dump(CurDAG));
2064         DEBUG(dbgs() << "\nNew: ");
2065         DEBUG(ResNode->dump(CurDAG));
2066         DEBUG(dbgs() << "\n");
2067
2068         ReplaceUses(MachineNode, ResNode);
2069         IsModified = true;
2070       }
2071     }
2072     if (IsModified)
2073       CurDAG->RemoveDeadNodes();
2074   } while (IsModified);
2075 }
2076
2077 void PPCDAGToDAGISel::PeepholePPC64() {
2078   // These optimizations are currently supported only for 64-bit SVR4.
2079   if (PPCSubTarget->isDarwin() || !PPCSubTarget->isPPC64())
2080     return;
2081
2082   SelectionDAG::allnodes_iterator Position(CurDAG->getRoot().getNode());
2083   ++Position;
2084
2085   while (Position != CurDAG->allnodes_begin()) {
2086     SDNode *N = --Position;
2087     // Skip dead nodes and any non-machine opcodes.
2088     if (N->use_empty() || !N->isMachineOpcode())
2089       continue;
2090
2091     unsigned FirstOp;
2092     unsigned StorageOpcode = N->getMachineOpcode();
2093
2094     switch (StorageOpcode) {
2095     default: continue;
2096
2097     case PPC::LBZ:
2098     case PPC::LBZ8:
2099     case PPC::LD:
2100     case PPC::LFD:
2101     case PPC::LFS:
2102     case PPC::LHA:
2103     case PPC::LHA8:
2104     case PPC::LHZ:
2105     case PPC::LHZ8:
2106     case PPC::LWA:
2107     case PPC::LWZ:
2108     case PPC::LWZ8:
2109       FirstOp = 0;
2110       break;
2111
2112     case PPC::STB:
2113     case PPC::STB8:
2114     case PPC::STD:
2115     case PPC::STFD:
2116     case PPC::STFS:
2117     case PPC::STH:
2118     case PPC::STH8:
2119     case PPC::STW:
2120     case PPC::STW8:
2121       FirstOp = 1;
2122       break;
2123     }
2124
2125     // If this is a load or store with a zero offset, we may be able to
2126     // fold an add-immediate into the memory operation.
2127     if (!isa<ConstantSDNode>(N->getOperand(FirstOp)) ||
2128         N->getConstantOperandVal(FirstOp) != 0)
2129       continue;
2130
2131     SDValue Base = N->getOperand(FirstOp + 1);
2132     if (!Base.isMachineOpcode())
2133       continue;
2134
2135     unsigned Flags = 0;
2136     bool ReplaceFlags = true;
2137
2138     // When the feeding operation is an add-immediate of some sort,
2139     // determine whether we need to add relocation information to the
2140     // target flags on the immediate operand when we fold it into the
2141     // load instruction.
2142     //
2143     // For something like ADDItocL, the relocation information is
2144     // inferred from the opcode; when we process it in the AsmPrinter,
2145     // we add the necessary relocation there.  A load, though, can receive
2146     // relocation from various flavors of ADDIxxx, so we need to carry
2147     // the relocation information in the target flags.
2148     switch (Base.getMachineOpcode()) {
2149     default: continue;
2150
2151     case PPC::ADDI8:
2152     case PPC::ADDI:
2153       // In some cases (such as TLS) the relocation information
2154       // is already in place on the operand, so copying the operand
2155       // is sufficient.
2156       ReplaceFlags = false;
2157       // For these cases, the immediate may not be divisible by 4, in
2158       // which case the fold is illegal for DS-form instructions.  (The
2159       // other cases provide aligned addresses and are always safe.)
2160       if ((StorageOpcode == PPC::LWA ||
2161            StorageOpcode == PPC::LD  ||
2162            StorageOpcode == PPC::STD) &&
2163           (!isa<ConstantSDNode>(Base.getOperand(1)) ||
2164            Base.getConstantOperandVal(1) % 4 != 0))
2165         continue;
2166       break;
2167     case PPC::ADDIdtprelL:
2168       Flags = PPCII::MO_DTPREL_LO;
2169       break;
2170     case PPC::ADDItlsldL:
2171       Flags = PPCII::MO_TLSLD_LO;
2172       break;
2173     case PPC::ADDItocL:
2174       Flags = PPCII::MO_TOC_LO;
2175       break;
2176     }
2177
2178     // We found an opportunity.  Reverse the operands from the add
2179     // immediate and substitute them into the load or store.  If
2180     // needed, update the target flags for the immediate operand to
2181     // reflect the necessary relocation information.
2182     DEBUG(dbgs() << "Folding add-immediate into mem-op:\nBase:    ");
2183     DEBUG(Base->dump(CurDAG));
2184     DEBUG(dbgs() << "\nN: ");
2185     DEBUG(N->dump(CurDAG));
2186     DEBUG(dbgs() << "\n");
2187
2188     SDValue ImmOpnd = Base.getOperand(1);
2189
2190     // If the relocation information isn't already present on the
2191     // immediate operand, add it now.
2192     if (ReplaceFlags) {
2193       if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(ImmOpnd)) {
2194         SDLoc dl(GA);
2195         const GlobalValue *GV = GA->getGlobal();
2196         // We can't perform this optimization for data whose alignment
2197         // is insufficient for the instruction encoding.
2198         if (GV->getAlignment() < 4 &&
2199             (StorageOpcode == PPC::LD || StorageOpcode == PPC::STD ||
2200              StorageOpcode == PPC::LWA)) {
2201           DEBUG(dbgs() << "Rejected this candidate for alignment.\n\n");
2202           continue;
2203         }
2204         ImmOpnd = CurDAG->getTargetGlobalAddress(GV, dl, MVT::i64, 0, Flags);
2205       } else if (ConstantPoolSDNode *CP =
2206                  dyn_cast<ConstantPoolSDNode>(ImmOpnd)) {
2207         const Constant *C = CP->getConstVal();
2208         ImmOpnd = CurDAG->getTargetConstantPool(C, MVT::i64,
2209                                                 CP->getAlignment(),
2210                                                 0, Flags);
2211       }
2212     }
2213
2214     if (FirstOp == 1) // Store
2215       (void)CurDAG->UpdateNodeOperands(N, N->getOperand(0), ImmOpnd,
2216                                        Base.getOperand(0), N->getOperand(3));
2217     else // Load
2218       (void)CurDAG->UpdateNodeOperands(N, ImmOpnd, Base.getOperand(0),
2219                                        N->getOperand(2));
2220
2221     // The add-immediate may now be dead, in which case remove it.
2222     if (Base.getNode()->use_empty())
2223       CurDAG->RemoveDeadNode(Base.getNode());
2224   }
2225 }
2226
2227
2228 /// createPPCISelDag - This pass converts a legalized DAG into a
2229 /// PowerPC-specific DAG, ready for instruction scheduling.
2230 ///
2231 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
2232   return new PPCDAGToDAGISel(TM);
2233 }
2234
2235 static void initializePassOnce(PassRegistry &Registry) {
2236   const char *Name = "PowerPC DAG->DAG Pattern Instruction Selection";
2237   PassInfo *PI = new PassInfo(Name, "ppc-codegen", &SelectionDAGISel::ID,
2238                               nullptr, false, false);
2239   Registry.registerPass(*PI, true);
2240 }
2241
2242 void llvm::initializePPCDAGToDAGISelPass(PassRegistry &Registry) {
2243   CALL_ONCE_INITIALIZATION(initializePassOnce);
2244 }
2245