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