The PowerPC VRSAVE register has been somewhat of an odd beast since
[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 #define DEBUG_TYPE "ppc-codegen"
16 #include "PPC.h"
17 #include "PPCTargetMachine.h"
18 #include "MCTargetDesc/PPCPredicates.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/MachineRegisterInfo.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Constants.h"
26 #include "llvm/Function.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/Intrinsics.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/raw_ostream.h"
33 using namespace llvm;
34
35 namespace {
36   //===--------------------------------------------------------------------===//
37   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
38   /// instructions for SelectionDAG operations.
39   ///
40   class PPCDAGToDAGISel : public SelectionDAGISel {
41     const PPCTargetMachine &TM;
42     const PPCTargetLowering &PPCLowering;
43     const PPCSubtarget &PPCSubTarget;
44     unsigned GlobalBaseReg;
45   public:
46     explicit PPCDAGToDAGISel(PPCTargetMachine &tm)
47       : SelectionDAGISel(tm), TM(tm),
48         PPCLowering(*TM.getTargetLowering()),
49         PPCSubTarget(*TM.getSubtargetImpl()) {}
50
51     virtual bool runOnMachineFunction(MachineFunction &MF) {
52       // Make sure we re-emit a set of the global base reg if necessary
53       GlobalBaseReg = 0;
54       SelectionDAGISel::runOnMachineFunction(MF);
55
56       if (!PPCSubTarget.isSVR4ABI())
57         InsertVRSaveCode(MF);
58
59       return true;
60     }
61
62     /// getI32Imm - Return a target constant with the specified value, of type
63     /// i32.
64     inline SDValue getI32Imm(unsigned Imm) {
65       return CurDAG->getTargetConstant(Imm, MVT::i32);
66     }
67
68     /// getI64Imm - Return a target constant with the specified value, of type
69     /// i64.
70     inline SDValue getI64Imm(uint64_t Imm) {
71       return CurDAG->getTargetConstant(Imm, MVT::i64);
72     }
73
74     /// getSmallIPtrImm - Return a target constant of pointer type.
75     inline SDValue getSmallIPtrImm(unsigned Imm) {
76       return CurDAG->getTargetConstant(Imm, PPCLowering.getPointerTy());
77     }
78
79     /// isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s
80     /// with any number of 0s on either side.  The 1s are allowed to wrap from
81     /// LSB to MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.
82     /// 0x0F0F0000 is not, since all 1s are not contiguous.
83     static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME);
84
85
86     /// isRotateAndMask - Returns true if Mask and Shift can be folded into a
87     /// rotate and mask opcode and mask operation.
88     static bool isRotateAndMask(SDNode *N, unsigned Mask, bool isShiftMask,
89                                 unsigned &SH, unsigned &MB, unsigned &ME);
90
91     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
92     /// base register.  Return the virtual register that holds this value.
93     SDNode *getGlobalBaseReg();
94
95     // Select - Convert the specified operand from a target-independent to a
96     // target-specific node if it hasn't already been changed.
97     SDNode *Select(SDNode *N);
98
99     SDNode *SelectBitfieldInsert(SDNode *N);
100
101     /// SelectCC - Select a comparison of the specified values with the
102     /// specified condition code, returning the CR# of the expression.
103     SDValue SelectCC(SDValue LHS, SDValue RHS, ISD::CondCode CC, DebugLoc dl);
104
105     /// SelectAddrImm - Returns true if the address N can be represented by
106     /// a base register plus a signed 16-bit displacement [r+imm].
107     bool SelectAddrImm(SDValue N, SDValue &Disp,
108                        SDValue &Base) {
109       return PPCLowering.SelectAddressRegImm(N, Disp, Base, *CurDAG);
110     }
111
112     /// SelectAddrImmOffs - Return true if the operand is valid for a preinc
113     /// immediate field.  Because preinc imms have already been validated, just
114     /// accept it.
115     bool SelectAddrImmOffs(SDValue N, SDValue &Out) const {
116       if (isa<ConstantSDNode>(N) || N.getOpcode() == PPCISD::Lo ||
117           N.getOpcode() == ISD::TargetGlobalAddress) {
118         Out = N;
119         return true;
120       }
121
122       return false;
123     }
124
125     /// SelectAddrIdxOffs - Return true if the operand is valid for a preinc
126     /// index field.  Because preinc imms have already been validated, just
127     /// accept it.
128     bool SelectAddrIdxOffs(SDValue N, SDValue &Out) const {
129       if (isa<ConstantSDNode>(N) || N.getOpcode() == PPCISD::Lo ||
130           N.getOpcode() == ISD::TargetGlobalAddress)
131         return false;
132
133       Out = N;
134       return true;
135     }
136
137     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
138     /// represented as an indexed [r+r] operation.  Returns false if it can
139     /// be represented by [r+imm], which are preferred.
140     bool SelectAddrIdx(SDValue N, SDValue &Base, SDValue &Index) {
141       return PPCLowering.SelectAddressRegReg(N, Base, Index, *CurDAG);
142     }
143
144     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
145     /// represented as an indexed [r+r] operation.
146     bool SelectAddrIdxOnly(SDValue N, SDValue &Base, SDValue &Index) {
147       return PPCLowering.SelectAddressRegRegOnly(N, Base, Index, *CurDAG);
148     }
149
150     /// SelectAddrImmShift - Returns true if the address N can be represented by
151     /// a base register plus a signed 14-bit displacement [r+imm*4].  Suitable
152     /// for use by STD and friends.
153     bool SelectAddrImmShift(SDValue N, SDValue &Disp, SDValue &Base) {
154       return PPCLowering.SelectAddressRegImmShift(N, Disp, Base, *CurDAG);
155     }
156
157     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
158     /// inline asm expressions.  It is always correct to compute the value into
159     /// a register.  The case of adding a (possibly relocatable) constant to a
160     /// register can be improved, but it is wrong to substitute Reg+Reg for
161     /// Reg in an asm, because the load or store opcode would have to change.
162    virtual bool SelectInlineAsmMemoryOperand(const SDValue &Op,
163                                               char ConstraintCode,
164                                               std::vector<SDValue> &OutOps) {
165       OutOps.push_back(Op);
166       return false;
167     }
168
169     void InsertVRSaveCode(MachineFunction &MF);
170
171     virtual const char *getPassName() const {
172       return "PowerPC DAG->DAG Pattern Instruction Selection";
173     }
174
175 // Include the pieces autogenerated from the target description.
176 #include "PPCGenDAGISel.inc"
177
178 private:
179     SDNode *SelectSETCC(SDNode *N);
180   };
181 }
182
183 /// InsertVRSaveCode - Once the entire function has been instruction selected,
184 /// all virtual registers are created and all machine instructions are built,
185 /// check to see if we need to save/restore VRSAVE.  If so, do it.
186 void PPCDAGToDAGISel::InsertVRSaveCode(MachineFunction &Fn) {
187   // Check to see if this function uses vector registers, which means we have to
188   // save and restore the VRSAVE register and update it with the regs we use.
189   //
190   // In this case, there will be virtual registers of vector type created
191   // by the scheduler.  Detect them now.
192   bool HasVectorVReg = false;
193   for (unsigned i = 0, e = RegInfo->getNumVirtRegs(); i != e; ++i) {
194     unsigned Reg = TargetRegisterInfo::index2VirtReg(i);
195     if (RegInfo->getRegClass(Reg) == &PPC::VRRCRegClass) {
196       HasVectorVReg = true;
197       break;
198     }
199   }
200   if (!HasVectorVReg) return;  // nothing to do.
201
202   // If we have a vector register, we want to emit code into the entry and exit
203   // blocks to save and restore the VRSAVE register.  We do this here (instead
204   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
205   //
206   // 1. This (trivially) reduces the load on the register allocator, by not
207   //    having to represent the live range of the VRSAVE register.
208   // 2. This (more significantly) allows us to create a temporary virtual
209   //    register to hold the saved VRSAVE value, allowing this temporary to be
210   //    register allocated, instead of forcing it to be spilled to the stack.
211
212   // Create two vregs - one to hold the VRSAVE register that is live-in to the
213   // function and one for the value after having bits or'd into it.
214   unsigned InVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
215   unsigned UpdatedVRSAVE = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
216
217   const TargetInstrInfo &TII = *TM.getInstrInfo();
218   MachineBasicBlock &EntryBB = *Fn.begin();
219   DebugLoc dl;
220   // Emit the following code into the entry block:
221   // InVRSAVE = MFVRSAVE
222   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
223   // MTVRSAVE UpdatedVRSAVE
224   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
225   BuildMI(EntryBB, IP, dl, TII.get(PPC::MFVRSAVE), InVRSAVE);
226   BuildMI(EntryBB, IP, dl, TII.get(PPC::UPDATE_VRSAVE),
227           UpdatedVRSAVE).addReg(InVRSAVE);
228   BuildMI(EntryBB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(UpdatedVRSAVE);
229
230   // Find all return blocks, outputting a restore in each epilog.
231   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
232     if (!BB->empty() && BB->back().isReturn()) {
233       IP = BB->end(); --IP;
234
235       // Skip over all terminator instructions, which are part of the return
236       // sequence.
237       MachineBasicBlock::iterator I2 = IP;
238       while (I2 != BB->begin() && (--I2)->isTerminator())
239         IP = I2;
240
241       // Emit: MTVRSAVE InVRSave
242       BuildMI(*BB, IP, dl, TII.get(PPC::MTVRSAVE)).addReg(InVRSAVE);
243     }
244   }
245 }
246
247
248 /// getGlobalBaseReg - Output the instructions required to put the
249 /// base address to use for accessing globals into a register.
250 ///
251 SDNode *PPCDAGToDAGISel::getGlobalBaseReg() {
252   if (!GlobalBaseReg) {
253     const TargetInstrInfo &TII = *TM.getInstrInfo();
254     // Insert the set of GlobalBaseReg into the first MBB of the function
255     MachineBasicBlock &FirstMBB = MF->front();
256     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
257     DebugLoc dl;
258
259     if (PPCLowering.getPointerTy() == MVT::i32) {
260       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::GPRCRegClass);
261       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR));
262       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR), GlobalBaseReg);
263     } else {
264       GlobalBaseReg = RegInfo->createVirtualRegister(&PPC::G8RCRegClass);
265       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MovePCtoLR8));
266       BuildMI(FirstMBB, MBBI, dl, TII.get(PPC::MFLR8), GlobalBaseReg);
267     }
268   }
269   return CurDAG->getRegister(GlobalBaseReg,
270                              PPCLowering.getPointerTy()).getNode();
271 }
272
273 /// isIntS16Immediate - This method tests to see if the node is either a 32-bit
274 /// or 64-bit immediate, and if the value can be accurately represented as a
275 /// sign extension from a 16-bit value.  If so, this returns true and the
276 /// immediate.
277 static bool isIntS16Immediate(SDNode *N, short &Imm) {
278   if (N->getOpcode() != ISD::Constant)
279     return false;
280
281   Imm = (short)cast<ConstantSDNode>(N)->getZExtValue();
282   if (N->getValueType(0) == MVT::i32)
283     return Imm == (int32_t)cast<ConstantSDNode>(N)->getZExtValue();
284   else
285     return Imm == (int64_t)cast<ConstantSDNode>(N)->getZExtValue();
286 }
287
288 static bool isIntS16Immediate(SDValue Op, short &Imm) {
289   return isIntS16Immediate(Op.getNode(), Imm);
290 }
291
292
293 /// isInt32Immediate - This method tests to see if the node is a 32-bit constant
294 /// operand. If so Imm will receive the 32-bit value.
295 static bool isInt32Immediate(SDNode *N, unsigned &Imm) {
296   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i32) {
297     Imm = cast<ConstantSDNode>(N)->getZExtValue();
298     return true;
299   }
300   return false;
301 }
302
303 /// isInt64Immediate - This method tests to see if the node is a 64-bit constant
304 /// operand.  If so Imm will receive the 64-bit value.
305 static bool isInt64Immediate(SDNode *N, uint64_t &Imm) {
306   if (N->getOpcode() == ISD::Constant && N->getValueType(0) == MVT::i64) {
307     Imm = cast<ConstantSDNode>(N)->getZExtValue();
308     return true;
309   }
310   return false;
311 }
312
313 // isInt32Immediate - This method tests to see if a constant operand.
314 // If so Imm will receive the 32 bit value.
315 static bool isInt32Immediate(SDValue N, unsigned &Imm) {
316   return isInt32Immediate(N.getNode(), Imm);
317 }
318
319
320 // isOpcWithIntImmediate - This method tests to see if the node is a specific
321 // opcode and that it has a immediate integer right operand.
322 // If so Imm will receive the 32 bit value.
323 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
324   return N->getOpcode() == Opc
325          && isInt32Immediate(N->getOperand(1).getNode(), Imm);
326 }
327
328 bool PPCDAGToDAGISel::isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
329   if (isShiftedMask_32(Val)) {
330     // look for the first non-zero bit
331     MB = CountLeadingZeros_32(Val);
332     // look for the first zero bit after the run of ones
333     ME = CountLeadingZeros_32((Val - 1) ^ Val);
334     return true;
335   } else {
336     Val = ~Val; // invert mask
337     if (isShiftedMask_32(Val)) {
338       // effectively look for the first zero bit
339       ME = CountLeadingZeros_32(Val) - 1;
340       // effectively look for the first one bit after the run of zeros
341       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
342       return true;
343     }
344   }
345   // no run present
346   return false;
347 }
348
349 bool PPCDAGToDAGISel::isRotateAndMask(SDNode *N, unsigned Mask,
350                                       bool isShiftMask, unsigned &SH,
351                                       unsigned &MB, unsigned &ME) {
352   // Don't even go down this path for i64, since different logic will be
353   // necessary for rldicl/rldicr/rldimi.
354   if (N->getValueType(0) != MVT::i32)
355     return false;
356
357   unsigned Shift  = 32;
358   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
359   unsigned Opcode = N->getOpcode();
360   if (N->getNumOperands() != 2 ||
361       !isInt32Immediate(N->getOperand(1).getNode(), Shift) || (Shift > 31))
362     return false;
363
364   if (Opcode == ISD::SHL) {
365     // apply shift left to mask if it comes first
366     if (isShiftMask) Mask = Mask << Shift;
367     // determine which bits are made indeterminant by shift
368     Indeterminant = ~(0xFFFFFFFFu << Shift);
369   } else if (Opcode == ISD::SRL) {
370     // apply shift right to mask if it comes first
371     if (isShiftMask) Mask = Mask >> Shift;
372     // determine which bits are made indeterminant by shift
373     Indeterminant = ~(0xFFFFFFFFu >> Shift);
374     // adjust for the left rotate
375     Shift = 32 - Shift;
376   } else if (Opcode == ISD::ROTL) {
377     Indeterminant = 0;
378   } else {
379     return false;
380   }
381
382   // if the mask doesn't intersect any Indeterminant bits
383   if (Mask && !(Mask & Indeterminant)) {
384     SH = Shift & 31;
385     // make sure the mask is still a mask (wrap arounds may not be)
386     return isRunOfOnes(Mask, MB, ME);
387   }
388   return false;
389 }
390
391 /// SelectBitfieldInsert - turn an or of two masked values into
392 /// the rotate left word immediate then mask insert (rlwimi) instruction.
393 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
394   SDValue Op0 = N->getOperand(0);
395   SDValue Op1 = N->getOperand(1);
396   DebugLoc dl = N->getDebugLoc();
397
398   APInt LKZ, LKO, RKZ, RKO;
399   CurDAG->ComputeMaskedBits(Op0, LKZ, LKO);
400   CurDAG->ComputeMaskedBits(Op1, RKZ, RKO);
401
402   unsigned TargetMask = LKZ.getZExtValue();
403   unsigned InsertMask = RKZ.getZExtValue();
404
405   if ((TargetMask | InsertMask) == 0xFFFFFFFF) {
406     unsigned Op0Opc = Op0.getOpcode();
407     unsigned Op1Opc = Op1.getOpcode();
408     unsigned Value, SH = 0;
409     TargetMask = ~TargetMask;
410     InsertMask = ~InsertMask;
411
412     // If the LHS has a foldable shift and the RHS does not, then swap it to the
413     // RHS so that we can fold the shift into the insert.
414     if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
415       if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
416           Op0.getOperand(0).getOpcode() == ISD::SRL) {
417         if (Op1.getOperand(0).getOpcode() != ISD::SHL &&
418             Op1.getOperand(0).getOpcode() != ISD::SRL) {
419           std::swap(Op0, Op1);
420           std::swap(Op0Opc, Op1Opc);
421           std::swap(TargetMask, InsertMask);
422         }
423       }
424     } else if (Op0Opc == ISD::SHL || Op0Opc == ISD::SRL) {
425       if (Op1Opc == ISD::AND && Op1.getOperand(0).getOpcode() != ISD::SHL &&
426           Op1.getOperand(0).getOpcode() != ISD::SRL) {
427         std::swap(Op0, Op1);
428         std::swap(Op0Opc, Op1Opc);
429         std::swap(TargetMask, InsertMask);
430       }
431     }
432
433     unsigned MB, ME;
434     if (InsertMask && isRunOfOnes(InsertMask, MB, ME)) {
435       SDValue Tmp1, Tmp2;
436
437       if ((Op1Opc == ISD::SHL || Op1Opc == ISD::SRL) &&
438           isInt32Immediate(Op1.getOperand(1), Value)) {
439         Op1 = Op1.getOperand(0);
440         SH  = (Op1Opc == ISD::SHL) ? Value : 32 - Value;
441       }
442       if (Op1Opc == ISD::AND) {
443         unsigned SHOpc = Op1.getOperand(0).getOpcode();
444         if ((SHOpc == ISD::SHL || SHOpc == ISD::SRL) &&
445             isInt32Immediate(Op1.getOperand(0).getOperand(1), Value)) {
446           Op1 = Op1.getOperand(0).getOperand(0);
447           SH  = (SHOpc == ISD::SHL) ? Value : 32 - Value;
448         } else {
449           Op1 = Op1.getOperand(0);
450         }
451       }
452
453       SH &= 31;
454       SDValue Ops[] = { Op0, Op1, getI32Imm(SH), getI32Imm(MB),
455                           getI32Imm(ME) };
456       return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops, 5);
457     }
458   }
459   return 0;
460 }
461
462 /// SelectCC - Select a comparison of the specified values with the specified
463 /// condition code, returning the CR# of the expression.
464 SDValue PPCDAGToDAGISel::SelectCC(SDValue LHS, SDValue RHS,
465                                     ISD::CondCode CC, DebugLoc dl) {
466   // Always select the LHS.
467   unsigned Opc;
468
469   if (LHS.getValueType() == MVT::i32) {
470     unsigned Imm;
471     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
472       if (isInt32Immediate(RHS, Imm)) {
473         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
474         if (isUInt<16>(Imm))
475           return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
476                                                 getI32Imm(Imm & 0xFFFF)), 0);
477         // If this is a 16-bit signed immediate, fold it.
478         if (isInt<16>((int)Imm))
479           return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
480                                                 getI32Imm(Imm & 0xFFFF)), 0);
481
482         // For non-equality comparisons, the default code would materialize the
483         // constant, then compare against it, like this:
484         //   lis r2, 4660
485         //   ori r2, r2, 22136
486         //   cmpw cr0, r3, r2
487         // Since we are just comparing for equality, we can emit this instead:
488         //   xoris r0,r3,0x1234
489         //   cmplwi cr0,r0,0x5678
490         //   beq cr0,L6
491         SDValue Xor(CurDAG->getMachineNode(PPC::XORIS, dl, MVT::i32, LHS,
492                                            getI32Imm(Imm >> 16)), 0);
493         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, Xor,
494                                               getI32Imm(Imm & 0xFFFF)), 0);
495       }
496       Opc = PPC::CMPLW;
497     } else if (ISD::isUnsignedIntSetCC(CC)) {
498       if (isInt32Immediate(RHS, Imm) && isUInt<16>(Imm))
499         return SDValue(CurDAG->getMachineNode(PPC::CMPLWI, dl, MVT::i32, LHS,
500                                               getI32Imm(Imm & 0xFFFF)), 0);
501       Opc = PPC::CMPLW;
502     } else {
503       short SImm;
504       if (isIntS16Immediate(RHS, SImm))
505         return SDValue(CurDAG->getMachineNode(PPC::CMPWI, dl, MVT::i32, LHS,
506                                               getI32Imm((int)SImm & 0xFFFF)),
507                          0);
508       Opc = PPC::CMPW;
509     }
510   } else if (LHS.getValueType() == MVT::i64) {
511     uint64_t Imm;
512     if (CC == ISD::SETEQ || CC == ISD::SETNE) {
513       if (isInt64Immediate(RHS.getNode(), Imm)) {
514         // SETEQ/SETNE comparison with 16-bit immediate, fold it.
515         if (isUInt<16>(Imm))
516           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
517                                                 getI32Imm(Imm & 0xFFFF)), 0);
518         // If this is a 16-bit signed immediate, fold it.
519         if (isInt<16>(Imm))
520           return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
521                                                 getI32Imm(Imm & 0xFFFF)), 0);
522
523         // For non-equality comparisons, the default code would materialize the
524         // constant, then compare against it, like this:
525         //   lis r2, 4660
526         //   ori r2, r2, 22136
527         //   cmpd cr0, r3, r2
528         // Since we are just comparing for equality, we can emit this instead:
529         //   xoris r0,r3,0x1234
530         //   cmpldi cr0,r0,0x5678
531         //   beq cr0,L6
532         if (isUInt<32>(Imm)) {
533           SDValue Xor(CurDAG->getMachineNode(PPC::XORIS8, dl, MVT::i64, LHS,
534                                              getI64Imm(Imm >> 16)), 0);
535           return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, Xor,
536                                                 getI64Imm(Imm & 0xFFFF)), 0);
537         }
538       }
539       Opc = PPC::CMPLD;
540     } else if (ISD::isUnsignedIntSetCC(CC)) {
541       if (isInt64Immediate(RHS.getNode(), Imm) && isUInt<16>(Imm))
542         return SDValue(CurDAG->getMachineNode(PPC::CMPLDI, dl, MVT::i64, LHS,
543                                               getI64Imm(Imm & 0xFFFF)), 0);
544       Opc = PPC::CMPLD;
545     } else {
546       short SImm;
547       if (isIntS16Immediate(RHS, SImm))
548         return SDValue(CurDAG->getMachineNode(PPC::CMPDI, dl, MVT::i64, LHS,
549                                               getI64Imm(SImm & 0xFFFF)),
550                          0);
551       Opc = PPC::CMPD;
552     }
553   } else if (LHS.getValueType() == MVT::f32) {
554     Opc = PPC::FCMPUS;
555   } else {
556     assert(LHS.getValueType() == MVT::f64 && "Unknown vt!");
557     Opc = PPC::FCMPUD;
558   }
559   return SDValue(CurDAG->getMachineNode(Opc, dl, MVT::i32, LHS, RHS), 0);
560 }
561
562 static PPC::Predicate getPredicateForSetCC(ISD::CondCode CC) {
563   switch (CC) {
564   case ISD::SETUEQ:
565   case ISD::SETONE:
566   case ISD::SETOLE:
567   case ISD::SETOGE:
568     llvm_unreachable("Should be lowered by legalize!");
569   default: llvm_unreachable("Unknown condition!");
570   case ISD::SETOEQ:
571   case ISD::SETEQ:  return PPC::PRED_EQ;
572   case ISD::SETUNE:
573   case ISD::SETNE:  return PPC::PRED_NE;
574   case ISD::SETOLT:
575   case ISD::SETLT:  return PPC::PRED_LT;
576   case ISD::SETULE:
577   case ISD::SETLE:  return PPC::PRED_LE;
578   case ISD::SETOGT:
579   case ISD::SETGT:  return PPC::PRED_GT;
580   case ISD::SETUGE:
581   case ISD::SETGE:  return PPC::PRED_GE;
582   case ISD::SETO:   return PPC::PRED_NU;
583   case ISD::SETUO:  return PPC::PRED_UN;
584     // These two are invalid for floating point.  Assume we have int.
585   case ISD::SETULT: return PPC::PRED_LT;
586   case ISD::SETUGT: return PPC::PRED_GT;
587   }
588 }
589
590 /// getCRIdxForSetCC - Return the index of the condition register field
591 /// associated with the SetCC condition, and whether or not the field is
592 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
593 ///
594 /// If this returns with Other != -1, then the returned comparison is an or of
595 /// two simpler comparisons.  In this case, Invert is guaranteed to be false.
596 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool &Invert, int &Other) {
597   Invert = false;
598   Other = -1;
599   switch (CC) {
600   default: llvm_unreachable("Unknown condition!");
601   case ISD::SETOLT:
602   case ISD::SETLT:  return 0;                  // Bit #0 = SETOLT
603   case ISD::SETOGT:
604   case ISD::SETGT:  return 1;                  // Bit #1 = SETOGT
605   case ISD::SETOEQ:
606   case ISD::SETEQ:  return 2;                  // Bit #2 = SETOEQ
607   case ISD::SETUO:  return 3;                  // Bit #3 = SETUO
608   case ISD::SETUGE:
609   case ISD::SETGE:  Invert = true; return 0;   // !Bit #0 = SETUGE
610   case ISD::SETULE:
611   case ISD::SETLE:  Invert = true; return 1;   // !Bit #1 = SETULE
612   case ISD::SETUNE:
613   case ISD::SETNE:  Invert = true; return 2;   // !Bit #2 = SETUNE
614   case ISD::SETO:   Invert = true; return 3;   // !Bit #3 = SETO
615   case ISD::SETUEQ:
616   case ISD::SETOGE:
617   case ISD::SETOLE:
618   case ISD::SETONE:
619     llvm_unreachable("Invalid branch code: should be expanded by legalize");
620   // These are invalid for floating point.  Assume integer.
621   case ISD::SETULT: return 0;
622   case ISD::SETUGT: return 1;
623   }
624 }
625
626 SDNode *PPCDAGToDAGISel::SelectSETCC(SDNode *N) {
627   DebugLoc dl = N->getDebugLoc();
628   unsigned Imm;
629   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
630   EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
631   bool isPPC64 = (PtrVT == MVT::i64);
632
633   if (isInt32Immediate(N->getOperand(1), Imm)) {
634     // We can codegen setcc op, imm very efficiently compared to a brcond.
635     // Check for those cases here.
636     // setcc op, 0
637     if (Imm == 0) {
638       SDValue Op = N->getOperand(0);
639       switch (CC) {
640       default: break;
641       case ISD::SETEQ: {
642         Op = SDValue(CurDAG->getMachineNode(PPC::CNTLZW, dl, MVT::i32, Op), 0);
643         SDValue Ops[] = { Op, getI32Imm(27), getI32Imm(5), getI32Imm(31) };
644         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
645       }
646       case ISD::SETNE: {
647         if (isPPC64) break;
648         SDValue AD =
649           SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
650                                          Op, getI32Imm(~0U)), 0);
651         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op,
652                                     AD.getValue(1));
653       }
654       case ISD::SETLT: {
655         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
656         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
657       }
658       case ISD::SETGT: {
659         SDValue T =
660           SDValue(CurDAG->getMachineNode(PPC::NEG, dl, MVT::i32, Op), 0);
661         T = SDValue(CurDAG->getMachineNode(PPC::ANDC, dl, MVT::i32, T, Op), 0);
662         SDValue Ops[] = { T, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
663         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
664       }
665       }
666     } else if (Imm == ~0U) {        // setcc op, -1
667       SDValue Op = N->getOperand(0);
668       switch (CC) {
669       default: break;
670       case ISD::SETEQ:
671         if (isPPC64) break;
672         Op = SDValue(CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
673                                             Op, getI32Imm(1)), 0);
674         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
675                               SDValue(CurDAG->getMachineNode(PPC::LI, dl,
676                                                              MVT::i32,
677                                                              getI32Imm(0)), 0),
678                                       Op.getValue(1));
679       case ISD::SETNE: {
680         if (isPPC64) break;
681         Op = SDValue(CurDAG->getMachineNode(PPC::NOR, dl, MVT::i32, Op, Op), 0);
682         SDNode *AD = CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
683                                             Op, getI32Imm(~0U));
684         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDValue(AD, 0),
685                                     Op, SDValue(AD, 1));
686       }
687       case ISD::SETLT: {
688         SDValue AD = SDValue(CurDAG->getMachineNode(PPC::ADDI, dl, MVT::i32, Op,
689                                                     getI32Imm(1)), 0);
690         SDValue AN = SDValue(CurDAG->getMachineNode(PPC::AND, dl, MVT::i32, AD,
691                                                     Op), 0);
692         SDValue Ops[] = { AN, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
693         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
694       }
695       case ISD::SETGT: {
696         SDValue Ops[] = { Op, getI32Imm(1), getI32Imm(31), getI32Imm(31) };
697         Op = SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops, 4),
698                      0);
699         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op,
700                                     getI32Imm(1));
701       }
702       }
703     }
704   }
705
706   SDValue LHS = N->getOperand(0);
707   SDValue RHS = N->getOperand(1);
708
709   // Altivec Vector compare instructions do not set any CR register by default
710   if (LHS.getValueType().isVector()) {
711     unsigned int Opc;
712     if (LHS.getValueType() == MVT::v16i8)
713       Opc = PPC::VCMPEQUB;
714     else if (LHS.getValueType() == MVT::v4i32)
715       Opc = PPC::VCMPEQUW;
716     else if (LHS.getValueType() == MVT::v8i16)
717       Opc = PPC::VCMPEQUH;
718     else if (LHS.getValueType() == MVT::v4f32)
719       Opc = PPC::VCMPEQFP;
720     else
721       llvm_unreachable("Invalid vector compare type: should be expanded by legalize");
722     return CurDAG->SelectNodeTo(N, Opc, LHS.getValueType(), LHS, RHS);
723   }
724
725   bool Inv;
726   int OtherCondIdx;
727   unsigned Idx = getCRIdxForSetCC(CC, Inv, OtherCondIdx);
728   SDValue CCReg = SelectCC(LHS, RHS, CC, dl);
729   SDValue IntCR;
730
731   // Force the ccreg into CR7.
732   SDValue CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
733
734   SDValue InFlag(0, 0);  // Null incoming flag value.
735   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), dl, CR7Reg, CCReg,
736                                InFlag).getValue(1);
737
738   if (PPCSubTarget.hasMFOCRF() && OtherCondIdx == -1)
739     IntCR = SDValue(CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32, CR7Reg,
740                                            CCReg), 0);
741   else
742     IntCR = SDValue(CurDAG->getMachineNode(PPC::MFCRpseud, dl, MVT::i32,
743                                            CR7Reg, CCReg), 0);
744
745   SDValue Ops[] = { IntCR, getI32Imm((32-(3-Idx)) & 31),
746                       getI32Imm(31), getI32Imm(31) };
747   if (OtherCondIdx == -1 && !Inv)
748     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
749
750   // Get the specified bit.
751   SDValue Tmp =
752     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops, 4), 0);
753   if (Inv) {
754     assert(OtherCondIdx == -1 && "Can't have split plus negation");
755     return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
756   }
757
758   // Otherwise, we have to turn an operation like SETONE -> SETOLT | SETOGT.
759   // We already got the bit for the first part of the comparison (e.g. SETULE).
760
761   // Get the other bit of the comparison.
762   Ops[1] = getI32Imm((32-(3-OtherCondIdx)) & 31);
763   SDValue OtherCond =
764     SDValue(CurDAG->getMachineNode(PPC::RLWINM, dl, MVT::i32, Ops, 4), 0);
765
766   return CurDAG->SelectNodeTo(N, PPC::OR, MVT::i32, Tmp, OtherCond);
767 }
768
769
770 // Select - Convert the specified operand from a target-independent to a
771 // target-specific node if it hasn't already been changed.
772 SDNode *PPCDAGToDAGISel::Select(SDNode *N) {
773   DebugLoc dl = N->getDebugLoc();
774   if (N->isMachineOpcode())
775     return NULL;   // Already selected.
776
777   switch (N->getOpcode()) {
778   default: break;
779
780   case ISD::Constant: {
781     if (N->getValueType(0) == MVT::i64) {
782       // Get 64 bit value.
783       int64_t Imm = cast<ConstantSDNode>(N)->getZExtValue();
784       // Assume no remaining bits.
785       unsigned Remainder = 0;
786       // Assume no shift required.
787       unsigned Shift = 0;
788
789       // If it can't be represented as a 32 bit value.
790       if (!isInt<32>(Imm)) {
791         Shift = CountTrailingZeros_64(Imm);
792         int64_t ImmSh = static_cast<uint64_t>(Imm) >> Shift;
793
794         // If the shifted value fits 32 bits.
795         if (isInt<32>(ImmSh)) {
796           // Go with the shifted value.
797           Imm = ImmSh;
798         } else {
799           // Still stuck with a 64 bit value.
800           Remainder = Imm;
801           Shift = 32;
802           Imm >>= 32;
803         }
804       }
805
806       // Intermediate operand.
807       SDNode *Result;
808
809       // Handle first 32 bits.
810       unsigned Lo = Imm & 0xFFFF;
811       unsigned Hi = (Imm >> 16) & 0xFFFF;
812
813       // Simple value.
814       if (isInt<16>(Imm)) {
815        // Just the Lo bits.
816         Result = CurDAG->getMachineNode(PPC::LI8, dl, MVT::i64, getI32Imm(Lo));
817       } else if (Lo) {
818         // Handle the Hi bits.
819         unsigned OpC = Hi ? PPC::LIS8 : PPC::LI8;
820         Result = CurDAG->getMachineNode(OpC, dl, MVT::i64, getI32Imm(Hi));
821         // And Lo bits.
822         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
823                                         SDValue(Result, 0), getI32Imm(Lo));
824       } else {
825        // Just the Hi bits.
826         Result = CurDAG->getMachineNode(PPC::LIS8, dl, MVT::i64, getI32Imm(Hi));
827       }
828
829       // If no shift, we're done.
830       if (!Shift) return Result;
831
832       // Shift for next step if the upper 32-bits were not zero.
833       if (Imm) {
834         Result = CurDAG->getMachineNode(PPC::RLDICR, dl, MVT::i64,
835                                         SDValue(Result, 0),
836                                         getI32Imm(Shift),
837                                         getI32Imm(63 - Shift));
838       }
839
840       // Add in the last bits as required.
841       if ((Hi = (Remainder >> 16) & 0xFFFF)) {
842         Result = CurDAG->getMachineNode(PPC::ORIS8, dl, MVT::i64,
843                                         SDValue(Result, 0), getI32Imm(Hi));
844       }
845       if ((Lo = Remainder & 0xFFFF)) {
846         Result = CurDAG->getMachineNode(PPC::ORI8, dl, MVT::i64,
847                                         SDValue(Result, 0), getI32Imm(Lo));
848       }
849
850       return Result;
851     }
852     break;
853   }
854
855   case ISD::SETCC:
856     return SelectSETCC(N);
857   case PPCISD::GlobalBaseReg:
858     return getGlobalBaseReg();
859
860   case ISD::FrameIndex: {
861     int FI = cast<FrameIndexSDNode>(N)->getIndex();
862     SDValue TFI = CurDAG->getTargetFrameIndex(FI, N->getValueType(0));
863     unsigned Opc = N->getValueType(0) == MVT::i32 ? PPC::ADDI : PPC::ADDI8;
864     if (N->hasOneUse())
865       return CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), TFI,
866                                   getSmallIPtrImm(0));
867     return CurDAG->getMachineNode(Opc, dl, N->getValueType(0), TFI,
868                                   getSmallIPtrImm(0));
869   }
870
871   case PPCISD::MFCR: {
872     SDValue InFlag = N->getOperand(1);
873     // Use MFOCRF if supported.
874     if (PPCSubTarget.hasMFOCRF())
875       return CurDAG->getMachineNode(PPC::MFOCRF, dl, MVT::i32,
876                                     N->getOperand(0), InFlag);
877     else
878       return CurDAG->getMachineNode(PPC::MFCRpseud, dl, MVT::i32,
879                                     N->getOperand(0), InFlag);
880   }
881
882   case ISD::SDIV: {
883     // FIXME: since this depends on the setting of the carry flag from the srawi
884     //        we should really be making notes about that for the scheduler.
885     // FIXME: It sure would be nice if we could cheaply recognize the
886     //        srl/add/sra pattern the dag combiner will generate for this as
887     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
888     unsigned Imm;
889     if (isInt32Immediate(N->getOperand(1), Imm)) {
890       SDValue N0 = N->getOperand(0);
891       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
892         SDNode *Op =
893           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
894                                  N0, getI32Imm(Log2_32(Imm)));
895         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32,
896                                     SDValue(Op, 0), SDValue(Op, 1));
897       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
898         SDNode *Op =
899           CurDAG->getMachineNode(PPC::SRAWI, dl, MVT::i32, MVT::Glue,
900                                  N0, getI32Imm(Log2_32(-Imm)));
901         SDValue PT =
902           SDValue(CurDAG->getMachineNode(PPC::ADDZE, dl, MVT::i32,
903                                          SDValue(Op, 0), SDValue(Op, 1)),
904                     0);
905         return CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
906       }
907     }
908
909     // Other cases are autogenerated.
910     break;
911   }
912
913   case ISD::LOAD: {
914     // Handle preincrement loads.
915     LoadSDNode *LD = cast<LoadSDNode>(N);
916     EVT LoadedVT = LD->getMemoryVT();
917
918     // Normal loads are handled by code generated from the .td file.
919     if (LD->getAddressingMode() != ISD::PRE_INC)
920       break;
921
922     SDValue Offset = LD->getOffset();
923     if (isa<ConstantSDNode>(Offset) ||
924         Offset.getOpcode() == ISD::TargetGlobalAddress) {
925
926       unsigned Opcode;
927       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
928       if (LD->getValueType(0) != MVT::i64) {
929         // Handle PPC32 integer and normal FP loads.
930         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
931         switch (LoadedVT.getSimpleVT().SimpleTy) {
932           default: llvm_unreachable("Invalid PPC load type!");
933           case MVT::f64: Opcode = PPC::LFDU; break;
934           case MVT::f32: Opcode = PPC::LFSU; break;
935           case MVT::i32: Opcode = PPC::LWZU; break;
936           case MVT::i16: Opcode = isSExt ? PPC::LHAU : PPC::LHZU; break;
937           case MVT::i1:
938           case MVT::i8:  Opcode = PPC::LBZU; break;
939         }
940       } else {
941         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
942         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
943         switch (LoadedVT.getSimpleVT().SimpleTy) {
944           default: llvm_unreachable("Invalid PPC load type!");
945           case MVT::i64: Opcode = PPC::LDU; break;
946           case MVT::i32: Opcode = PPC::LWZU8; break;
947           case MVT::i16: Opcode = isSExt ? PPC::LHAU8 : PPC::LHZU8; break;
948           case MVT::i1:
949           case MVT::i8:  Opcode = PPC::LBZU8; break;
950         }
951       }
952
953       SDValue Chain = LD->getChain();
954       SDValue Base = LD->getBasePtr();
955       SDValue Ops[] = { Offset, Base, Chain };
956       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
957                                     PPCLowering.getPointerTy(),
958                                     MVT::Other, Ops, 3);
959     } else {
960       unsigned Opcode;
961       bool isSExt = LD->getExtensionType() == ISD::SEXTLOAD;
962       if (LD->getValueType(0) != MVT::i64) {
963         // Handle PPC32 integer and normal FP loads.
964         assert((!isSExt || LoadedVT == MVT::i16) && "Invalid sext update load");
965         switch (LoadedVT.getSimpleVT().SimpleTy) {
966           default: llvm_unreachable("Invalid PPC load type!");
967           case MVT::f64: Opcode = PPC::LFDUX; break;
968           case MVT::f32: Opcode = PPC::LFSUX; break;
969           case MVT::i32: Opcode = PPC::LWZUX; break;
970           case MVT::i16: Opcode = isSExt ? PPC::LHAUX : PPC::LHZUX; break;
971           case MVT::i1:
972           case MVT::i8:  Opcode = PPC::LBZUX; break;
973         }
974       } else {
975         assert(LD->getValueType(0) == MVT::i64 && "Unknown load result type!");
976         assert((!isSExt || LoadedVT == MVT::i16 || LoadedVT == MVT::i32) &&
977                "Invalid sext update load");
978         switch (LoadedVT.getSimpleVT().SimpleTy) {
979           default: llvm_unreachable("Invalid PPC load type!");
980           case MVT::i64: Opcode = PPC::LDUX; break;
981           case MVT::i32: Opcode = isSExt ? PPC::LWAUX  : PPC::LWZUX8; break;
982           case MVT::i16: Opcode = isSExt ? PPC::LHAUX8 : PPC::LHZUX8; break;
983           case MVT::i1:
984           case MVT::i8:  Opcode = PPC::LBZUX8; break;
985         }
986       }
987
988       SDValue Chain = LD->getChain();
989       SDValue Base = LD->getBasePtr();
990       SDValue Ops[] = { Offset, Base, Chain };
991       return CurDAG->getMachineNode(Opcode, dl, LD->getValueType(0),
992                                     PPCLowering.getPointerTy(),
993                                     MVT::Other, Ops, 3);
994     }
995   }
996
997   case ISD::AND: {
998     unsigned Imm, Imm2, SH, MB, ME;
999     uint64_t Imm64;
1000
1001     // If this is an and of a value rotated between 0 and 31 bits and then and'd
1002     // with a mask, emit rlwinm
1003     if (isInt32Immediate(N->getOperand(1), Imm) &&
1004         isRotateAndMask(N->getOperand(0).getNode(), Imm, false, SH, MB, ME)) {
1005       SDValue Val = N->getOperand(0).getOperand(0);
1006       SDValue Ops[] = { Val, getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1007       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1008     }
1009     // If this is just a masked value where the input is not handled above, and
1010     // is not a rotate-left (handled by a pattern in the .td file), emit rlwinm
1011     if (isInt32Immediate(N->getOperand(1), Imm) &&
1012         isRunOfOnes(Imm, MB, ME) &&
1013         N->getOperand(0).getOpcode() != ISD::ROTL) {
1014       SDValue Val = N->getOperand(0);
1015       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB), getI32Imm(ME) };
1016       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1017     }
1018     // If this is a 64-bit zero-extension mask, emit rldicl.
1019     if (isInt64Immediate(N->getOperand(1).getNode(), Imm64) &&
1020         isMask_64(Imm64)) {
1021       SDValue Val = N->getOperand(0);
1022       MB = 64 - CountTrailingOnes_64(Imm64);
1023       SDValue Ops[] = { Val, getI32Imm(0), getI32Imm(MB) };
1024       return CurDAG->SelectNodeTo(N, PPC::RLDICL, MVT::i64, Ops, 3);
1025     }
1026     // AND X, 0 -> 0, not "rlwinm 32".
1027     if (isInt32Immediate(N->getOperand(1), Imm) && (Imm == 0)) {
1028       ReplaceUses(SDValue(N, 0), N->getOperand(1));
1029       return NULL;
1030     }
1031     // ISD::OR doesn't get all the bitfield insertion fun.
1032     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1033     if (isInt32Immediate(N->getOperand(1), Imm) &&
1034         N->getOperand(0).getOpcode() == ISD::OR &&
1035         isInt32Immediate(N->getOperand(0).getOperand(1), Imm2)) {
1036       unsigned MB, ME;
1037       Imm = ~(Imm^Imm2);
1038       if (isRunOfOnes(Imm, MB, ME)) {
1039         SDValue Ops[] = { N->getOperand(0).getOperand(0),
1040                             N->getOperand(0).getOperand(1),
1041                             getI32Imm(0), getI32Imm(MB),getI32Imm(ME) };
1042         return CurDAG->getMachineNode(PPC::RLWIMI, dl, MVT::i32, Ops, 5);
1043       }
1044     }
1045
1046     // Other cases are autogenerated.
1047     break;
1048   }
1049   case ISD::OR:
1050     if (N->getValueType(0) == MVT::i32)
1051       if (SDNode *I = SelectBitfieldInsert(N))
1052         return I;
1053
1054     // Other cases are autogenerated.
1055     break;
1056   case ISD::SHL: {
1057     unsigned Imm, SH, MB, ME;
1058     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1059         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1060       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1061                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1062       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1063     }
1064
1065     // Other cases are autogenerated.
1066     break;
1067   }
1068   case ISD::SRL: {
1069     unsigned Imm, SH, MB, ME;
1070     if (isOpcWithIntImmediate(N->getOperand(0).getNode(), ISD::AND, Imm) &&
1071         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1072       SDValue Ops[] = { N->getOperand(0).getOperand(0),
1073                           getI32Imm(SH), getI32Imm(MB), getI32Imm(ME) };
1074       return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Ops, 4);
1075     }
1076
1077     // Other cases are autogenerated.
1078     break;
1079   }
1080   case ISD::SELECT_CC: {
1081     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1082     EVT PtrVT = CurDAG->getTargetLoweringInfo().getPointerTy();
1083     bool isPPC64 = (PtrVT == MVT::i64);
1084
1085     // Handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1086     if (!isPPC64)
1087       if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1088         if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1089           if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1090             if (N1C->isNullValue() && N3C->isNullValue() &&
1091                 N2C->getZExtValue() == 1ULL && CC == ISD::SETNE &&
1092                 // FIXME: Implement this optzn for PPC64.
1093                 N->getValueType(0) == MVT::i32) {
1094               SDNode *Tmp =
1095                 CurDAG->getMachineNode(PPC::ADDIC, dl, MVT::i32, MVT::Glue,
1096                                        N->getOperand(0), getI32Imm(~0U));
1097               return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1098                                           SDValue(Tmp, 0), N->getOperand(0),
1099                                           SDValue(Tmp, 1));
1100             }
1101
1102     SDValue CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC, dl);
1103     unsigned BROpc = getPredicateForSetCC(CC);
1104
1105     unsigned SelectCCOp;
1106     if (N->getValueType(0) == MVT::i32)
1107       SelectCCOp = PPC::SELECT_CC_I4;
1108     else if (N->getValueType(0) == MVT::i64)
1109       SelectCCOp = PPC::SELECT_CC_I8;
1110     else if (N->getValueType(0) == MVT::f32)
1111       SelectCCOp = PPC::SELECT_CC_F4;
1112     else if (N->getValueType(0) == MVT::f64)
1113       SelectCCOp = PPC::SELECT_CC_F8;
1114     else
1115       SelectCCOp = PPC::SELECT_CC_VRRC;
1116
1117     SDValue Ops[] = { CCReg, N->getOperand(2), N->getOperand(3),
1118                         getI32Imm(BROpc) };
1119     return CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), Ops, 4);
1120   }
1121   case PPCISD::COND_BRANCH: {
1122     // Op #0 is the Chain.
1123     // Op #1 is the PPC::PRED_* number.
1124     // Op #2 is the CR#
1125     // Op #3 is the Dest MBB
1126     // Op #4 is the Flag.
1127     // Prevent PPC::PRED_* from being selected into LI.
1128     SDValue Pred =
1129       getI32Imm(cast<ConstantSDNode>(N->getOperand(1))->getZExtValue());
1130     SDValue Ops[] = { Pred, N->getOperand(2), N->getOperand(3),
1131       N->getOperand(0), N->getOperand(4) };
1132     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 5);
1133   }
1134   case ISD::BR_CC: {
1135     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1136     SDValue CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC, dl);
1137     SDValue Ops[] = { getI32Imm(getPredicateForSetCC(CC)), CondCode,
1138                         N->getOperand(4), N->getOperand(0) };
1139     return CurDAG->SelectNodeTo(N, PPC::BCC, MVT::Other, Ops, 4);
1140   }
1141   case ISD::BRIND: {
1142     // FIXME: Should custom lower this.
1143     SDValue Chain = N->getOperand(0);
1144     SDValue Target = N->getOperand(1);
1145     unsigned Opc = Target.getValueType() == MVT::i32 ? PPC::MTCTR : PPC::MTCTR8;
1146     unsigned Reg = Target.getValueType() == MVT::i32 ? PPC::BCTR : PPC::BCTR8;
1147     Chain = SDValue(CurDAG->getMachineNode(Opc, dl, MVT::Glue, Target,
1148                                            Chain), 0);
1149     return CurDAG->SelectNodeTo(N, Reg, MVT::Other, Chain);
1150   }
1151   }
1152
1153   return SelectCode(N);
1154 }
1155
1156
1157
1158 /// createPPCISelDag - This pass converts a legalized DAG into a
1159 /// PowerPC-specific DAG, ready for instruction scheduling.
1160 ///
1161 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1162   return new PPCDAGToDAGISel(TM);
1163 }
1164