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