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