reenable this hack, the tblgen version isn't quite ready
[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 was developed by Chris Lattner and is distributed under
6 // the University of Illinois Open Source License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines a pattern matching instruction selector for PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PPC.h"
16 #include "PPCTargetMachine.h"
17 #include "PPCISelLowering.h"
18 #include "PPCHazardRecognizers.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/MachineFunction.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/CodeGen/SelectionDAG.h"
23 #include "llvm/CodeGen/SelectionDAGISel.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/ADT/Statistic.h"
26 #include "llvm/Constants.h"
27 #include "llvm/GlobalValue.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/MathExtras.h"
30 #include <iostream>
31 #include <set>
32 using namespace llvm;
33
34 namespace {
35   Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
36     
37   //===--------------------------------------------------------------------===//
38   /// PPCDAGToDAGISel - PPC specific code to select PPC machine
39   /// instructions for SelectionDAG operations.
40   ///
41   class PPCDAGToDAGISel : public SelectionDAGISel {
42     PPCTargetMachine &TM;
43     PPCTargetLowering PPCLowering;
44     unsigned GlobalBaseReg;
45   public:
46     PPCDAGToDAGISel(PPCTargetMachine &tm)
47       : SelectionDAGISel(PPCLowering), TM(tm),
48         PPCLowering(*TM.getTargetLowering()) {}
49     
50     virtual bool runOnFunction(Function &Fn) {
51       // Make sure we re-emit a set of the global base reg if necessary
52       GlobalBaseReg = 0;
53       SelectionDAGISel::runOnFunction(Fn);
54       
55       InsertVRSaveCode(Fn);
56       return true;
57     }
58    
59     /// getI32Imm - Return a target constant with the specified value, of type
60     /// i32.
61     inline SDOperand getI32Imm(unsigned Imm) {
62       return CurDAG->getTargetConstant(Imm, MVT::i32);
63     }
64
65     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
66     /// base register.  Return the virtual register that holds this value.
67     SDOperand getGlobalBaseReg();
68     
69     // Select - Convert the specified operand from a target-independent to a
70     // target-specific node if it hasn't already been changed.
71     void Select(SDOperand &Result, SDOperand Op);
72     
73     SDNode *SelectBitfieldInsert(SDNode *N);
74
75     /// SelectCC - Select a comparison of the specified values with the
76     /// specified condition code, returning the CR# of the expression.
77     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
78
79     /// SelectAddrImm - Returns true if the address N can be represented by
80     /// a base register plus a signed 16-bit displacement [r+imm].
81     bool SelectAddrImm(SDOperand N, SDOperand &Disp, SDOperand &Base);
82       
83     /// SelectAddrIdx - Given the specified addressed, check to see if it can be
84     /// represented as an indexed [r+r] operation.  Returns false if it can
85     /// be represented by [r+imm], which are preferred.
86     bool SelectAddrIdx(SDOperand N, SDOperand &Base, SDOperand &Index);
87     
88     /// SelectAddrIdxOnly - Given the specified addressed, force it to be
89     /// represented as an indexed [r+r] operation.
90     bool SelectAddrIdxOnly(SDOperand N, SDOperand &Base, SDOperand &Index);
91
92     /// SelectInlineAsmMemoryOperand - Implement addressing mode selection for
93     /// inline asm expressions.
94     virtual bool SelectInlineAsmMemoryOperand(const SDOperand &Op,
95                                               char ConstraintCode,
96                                               std::vector<SDOperand> &OutOps,
97                                               SelectionDAG &DAG) {
98       SDOperand Op0, Op1;
99       switch (ConstraintCode) {
100       default: return true;
101       case 'm':   // memory
102         if (!SelectAddrIdx(Op, Op0, Op1))
103           SelectAddrImm(Op, Op0, Op1);
104         break;
105       case 'o':   // offsetable
106         if (!SelectAddrImm(Op, Op0, Op1)) {
107           Select(Op0, Op);     // r+0.
108           Op1 = getI32Imm(0);
109         }
110         break;
111       case 'v':   // not offsetable
112         SelectAddrIdxOnly(Op, Op0, Op1);
113         break;
114       }
115       
116       OutOps.push_back(Op0);
117       OutOps.push_back(Op1);
118       return false;
119     }
120     
121     SDOperand BuildSDIVSequence(SDNode *N);
122     SDOperand BuildUDIVSequence(SDNode *N);
123     
124     /// InstructionSelectBasicBlock - This callback is invoked by
125     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
126     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG);
127     
128     void InsertVRSaveCode(Function &Fn);
129
130     virtual const char *getPassName() const {
131       return "PowerPC DAG->DAG Pattern Instruction Selection";
132     } 
133     
134     /// CreateTargetHazardRecognizer - Return the hazard recognizer to use for this
135     /// target when scheduling the DAG.
136     virtual HazardRecognizer *CreateTargetHazardRecognizer() {
137       // Should use subtarget info to pick the right hazard recognizer.  For
138       // now, always return a PPC970 recognizer.
139       const TargetInstrInfo *II = PPCLowering.getTargetMachine().getInstrInfo();
140       assert(II && "No InstrInfo?");
141       return new PPCHazardRecognizer970(*II); 
142     }
143
144 // Include the pieces autogenerated from the target description.
145 #include "PPCGenDAGISel.inc"
146     
147 private:
148     SDOperand SelectSETCC(SDOperand Op);
149     SDOperand SelectCALL(SDOperand Op);
150   };
151 }
152
153 /// InstructionSelectBasicBlock - This callback is invoked by
154 /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
155 void PPCDAGToDAGISel::InstructionSelectBasicBlock(SelectionDAG &DAG) {
156   DEBUG(BB->dump());
157   
158   // The selection process is inherently a bottom-up recursive process (users
159   // select their uses before themselves).  Given infinite stack space, we
160   // could just start selecting on the root and traverse the whole graph.  In
161   // practice however, this causes us to run out of stack space on large basic
162   // blocks.  To avoid this problem, select the entry node, then all its uses,
163   // iteratively instead of recursively.
164   std::vector<SDOperand> Worklist;
165   Worklist.push_back(DAG.getEntryNode());
166   
167   // Note that we can do this in the PPC target (scanning forward across token
168   // chain edges) because no nodes ever get folded across these edges.  On a
169   // target like X86 which supports load/modify/store operations, this would
170   // have to be more careful.
171   while (!Worklist.empty()) {
172     SDOperand Node = Worklist.back();
173     Worklist.pop_back();
174     
175     // Chose from the least deep of the top two nodes.
176     if (!Worklist.empty() &&
177         Worklist.back().Val->getNodeDepth() < Node.Val->getNodeDepth())
178       std::swap(Worklist.back(), Node);
179     
180     if ((Node.Val->getOpcode() >= ISD::BUILTIN_OP_END &&
181          Node.Val->getOpcode() < PPCISD::FIRST_NUMBER) ||
182         CodeGenMap.count(Node)) continue;
183     
184     for (SDNode::use_iterator UI = Node.Val->use_begin(),
185          E = Node.Val->use_end(); UI != E; ++UI) {
186       // Scan the values.  If this use has a value that is a token chain, add it
187       // to the worklist.
188       SDNode *User = *UI;
189       for (unsigned i = 0, e = User->getNumValues(); i != e; ++i)
190         if (User->getValueType(i) == MVT::Other) {
191           Worklist.push_back(SDOperand(User, i));
192           break; 
193         }
194     }
195
196     // Finally, legalize this node.
197     SDOperand Dummy;
198     Select(Dummy, Node);
199   }
200     
201   // Select target instructions for the DAG.
202   DAG.setRoot(SelectRoot(DAG.getRoot()));
203   CodeGenMap.clear();
204   DAG.RemoveDeadNodes();
205   
206   // Emit machine code to BB.
207   ScheduleAndEmitDAG(DAG);
208 }
209
210 /// InsertVRSaveCode - Once the entire function has been instruction selected,
211 /// all virtual registers are created and all machine instructions are built,
212 /// check to see if we need to save/restore VRSAVE.  If so, do it.
213 void PPCDAGToDAGISel::InsertVRSaveCode(Function &F) {
214   // Check to see if this function uses vector registers, which means we have to
215   // save and restore the VRSAVE register and update it with the regs we use.  
216   //
217   // In this case, there will be virtual registers of vector type type created
218   // by the scheduler.  Detect them now.
219   MachineFunction &Fn = MachineFunction::get(&F);
220   SSARegMap *RegMap = Fn.getSSARegMap();
221   bool HasVectorVReg = false;
222   for (unsigned i = MRegisterInfo::FirstVirtualRegister, 
223        e = RegMap->getLastVirtReg()+1; i != e; ++i)
224     if (RegMap->getRegClass(i) == &PPC::VRRCRegClass) {
225       HasVectorVReg = true;
226       break;
227     }
228   if (!HasVectorVReg) return;  // nothing to do.
229       
230   // If we have a vector register, we want to emit code into the entry and exit
231   // blocks to save and restore the VRSAVE register.  We do this here (instead
232   // of marking all vector instructions as clobbering VRSAVE) for two reasons:
233   //
234   // 1. This (trivially) reduces the load on the register allocator, by not
235   //    having to represent the live range of the VRSAVE register.
236   // 2. This (more significantly) allows us to create a temporary virtual
237   //    register to hold the saved VRSAVE value, allowing this temporary to be
238   //    register allocated, instead of forcing it to be spilled to the stack.
239
240   // Create two vregs - one to hold the VRSAVE register that is live-in to the
241   // function and one for the value after having bits or'd into it.
242   unsigned InVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
243   unsigned UpdatedVRSAVE = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
244   
245   MachineBasicBlock &EntryBB = *Fn.begin();
246   // Emit the following code into the entry block:
247   // InVRSAVE = MFVRSAVE
248   // UpdatedVRSAVE = UPDATE_VRSAVE InVRSAVE
249   // MTVRSAVE UpdatedVRSAVE
250   MachineBasicBlock::iterator IP = EntryBB.begin();  // Insert Point
251   BuildMI(EntryBB, IP, PPC::MFVRSAVE, 0, InVRSAVE);
252   BuildMI(EntryBB, IP, PPC::UPDATE_VRSAVE, 1, UpdatedVRSAVE).addReg(InVRSAVE);
253   BuildMI(EntryBB, IP, PPC::MTVRSAVE, 1).addReg(UpdatedVRSAVE);
254   
255   // Find all return blocks, outputting a restore in each epilog.
256   const TargetInstrInfo &TII = *TM.getInstrInfo();
257   for (MachineFunction::iterator BB = Fn.begin(), E = Fn.end(); BB != E; ++BB) {
258     if (!BB->empty() && TII.isReturn(BB->back().getOpcode())) {
259       IP = BB->end(); --IP;
260       
261       // Skip over all terminator instructions, which are part of the return
262       // sequence.
263       MachineBasicBlock::iterator I2 = IP;
264       while (I2 != BB->begin() && TII.isTerminatorInstr((--I2)->getOpcode()))
265         IP = I2;
266       
267       // Emit: MTVRSAVE InVRSave
268       BuildMI(*BB, IP, PPC::MTVRSAVE, 1).addReg(InVRSAVE);
269     }        
270   }
271 }
272
273
274 /// getGlobalBaseReg - Output the instructions required to put the
275 /// base address to use for accessing globals into a register.
276 ///
277 SDOperand PPCDAGToDAGISel::getGlobalBaseReg() {
278   if (!GlobalBaseReg) {
279     // Insert the set of GlobalBaseReg into the first MBB of the function
280     MachineBasicBlock &FirstMBB = BB->getParent()->front();
281     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
282     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
283     // FIXME: when we get to LP64, we will need to create the appropriate
284     // type of register here.
285     GlobalBaseReg = RegMap->createVirtualRegister(PPC::GPRCRegisterClass);
286     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
287     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
288   }
289   return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
290 }
291
292
293 // isIntImmediate - This method tests to see if a constant operand.
294 // If so Imm will receive the 32 bit value.
295 static bool isIntImmediate(SDNode *N, unsigned& Imm) {
296   if (N->getOpcode() == ISD::Constant) {
297     Imm = cast<ConstantSDNode>(N)->getValue();
298     return true;
299   }
300   return false;
301 }
302
303 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
304 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
305 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
306 // not, since all 1s are not contiguous.
307 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
308   if (isShiftedMask_32(Val)) {
309     // look for the first non-zero bit
310     MB = CountLeadingZeros_32(Val);
311     // look for the first zero bit after the run of ones
312     ME = CountLeadingZeros_32((Val - 1) ^ Val);
313     return true;
314   } else {
315     Val = ~Val; // invert mask
316     if (isShiftedMask_32(Val)) {
317       // effectively look for the first zero bit
318       ME = CountLeadingZeros_32(Val) - 1;
319       // effectively look for the first one bit after the run of zeros
320       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
321       return true;
322     }
323   }
324   // no run present
325   return false;
326 }
327
328 // isRotateAndMask - Returns true if Mask and Shift can be folded into a rotate
329 // and mask opcode and mask operation.
330 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
331                             unsigned &SH, unsigned &MB, unsigned &ME) {
332   // Don't even go down this path for i64, since different logic will be
333   // necessary for rldicl/rldicr/rldimi.
334   if (N->getValueType(0) != MVT::i32)
335     return false;
336
337   unsigned Shift  = 32;
338   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
339   unsigned Opcode = N->getOpcode();
340   if (N->getNumOperands() != 2 ||
341       !isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
342     return false;
343   
344   if (Opcode == ISD::SHL) {
345     // apply shift left to mask if it comes first
346     if (IsShiftMask) Mask = Mask << Shift;
347     // determine which bits are made indeterminant by shift
348     Indeterminant = ~(0xFFFFFFFFu << Shift);
349   } else if (Opcode == ISD::SRL) { 
350     // apply shift right to mask if it comes first
351     if (IsShiftMask) Mask = Mask >> Shift;
352     // determine which bits are made indeterminant by shift
353     Indeterminant = ~(0xFFFFFFFFu >> Shift);
354     // adjust for the left rotate
355     Shift = 32 - Shift;
356   } else {
357     return false;
358   }
359   
360   // if the mask doesn't intersect any Indeterminant bits
361   if (Mask && !(Mask & Indeterminant)) {
362     SH = Shift;
363     // make sure the mask is still a mask (wrap arounds may not be)
364     return isRunOfOnes(Mask, MB, ME);
365   }
366   return false;
367 }
368
369 // isOpcWithIntImmediate - This method tests to see if the node is a specific
370 // opcode and that it has a immediate integer right operand.
371 // If so Imm will receive the 32 bit value.
372 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
373   return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
374 }
375
376 // isIntImmediate - This method tests to see if a constant operand.
377 // If so Imm will receive the 32 bit value.
378 static bool isIntImmediate(SDOperand N, unsigned& Imm) {
379   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
380     Imm = (unsigned)CN->getSignExtended();
381     return true;
382   }
383   return false;
384 }
385
386 /// SelectBitfieldInsert - turn an or of two masked values into
387 /// the rotate left word immediate then mask insert (rlwimi) instruction.
388 /// Returns true on success, false if the caller still needs to select OR.
389 ///
390 /// Patterns matched:
391 /// 1. or shl, and   5. or and, and
392 /// 2. or and, shl   6. or shl, shr
393 /// 3. or shr, and   7. or shr, shl
394 /// 4. or and, shr
395 SDNode *PPCDAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
396   bool IsRotate = false;
397   unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, SH = 0;
398   unsigned Value;
399   
400   SDOperand Op0 = N->getOperand(0);
401   SDOperand Op1 = N->getOperand(1);
402   
403   unsigned Op0Opc = Op0.getOpcode();
404   unsigned Op1Opc = Op1.getOpcode();
405   
406   // Verify that we have the correct opcodes
407   if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
408     return false;
409   if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
410     return false;
411   
412   // Generate Mask value for Target
413   if (isIntImmediate(Op0.getOperand(1), Value)) {
414     switch(Op0Opc) {
415     case ISD::SHL: TgtMask <<= Value; break;
416     case ISD::SRL: TgtMask >>= Value; break;
417     case ISD::AND: TgtMask &= Value; break;
418     }
419   } else {
420     return 0;
421   }
422   
423   // Generate Mask value for Insert
424   if (!isIntImmediate(Op1.getOperand(1), Value))
425     return 0;
426   
427   switch(Op1Opc) {
428   case ISD::SHL:
429     SH = Value;
430     InsMask <<= SH;
431     if (Op0Opc == ISD::SRL) IsRotate = true;
432     break;
433   case ISD::SRL:
434     SH = Value;
435     InsMask >>= SH;
436     SH = 32-SH;
437     if (Op0Opc == ISD::SHL) IsRotate = true;
438     break;
439   case ISD::AND:
440     InsMask &= Value;
441     break;
442   }
443   
444   // If both of the inputs are ANDs and one of them has a logical shift by
445   // constant as its input, make that AND the inserted value so that we can
446   // combine the shift into the rotate part of the rlwimi instruction
447   bool IsAndWithShiftOp = false;
448   if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
449     if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
450         Op1.getOperand(0).getOpcode() == ISD::SRL) {
451       if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
452         SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
453         IsAndWithShiftOp = true;
454       }
455     } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
456                Op0.getOperand(0).getOpcode() == ISD::SRL) {
457       if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
458         std::swap(Op0, Op1);
459         std::swap(TgtMask, InsMask);
460         SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
461         IsAndWithShiftOp = true;
462       }
463     }
464   }
465   
466   // Verify that the Target mask and Insert mask together form a full word mask
467   // and that the Insert mask is a run of set bits (which implies both are runs
468   // of set bits).  Given that, Select the arguments and generate the rlwimi
469   // instruction.
470   unsigned MB, ME;
471   if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
472     bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
473     bool Op0IsAND = Op0Opc == ISD::AND;
474     // Check for rotlwi / rotrwi here, a special case of bitfield insert
475     // where both bitfield halves are sourced from the same value.
476     if (IsRotate && fullMask &&
477         N->getOperand(0).getOperand(0) == N->getOperand(1).getOperand(0)) {
478       SDOperand Tmp;
479       Select(Tmp, N->getOperand(0).getOperand(0));
480       return CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Tmp,
481                                    getI32Imm(SH), getI32Imm(0), getI32Imm(31));
482     }
483     SDOperand Tmp1, Tmp2;
484     Select(Tmp1, ((Op0IsAND && fullMask) ? Op0.getOperand(0) : Op0));
485     Select(Tmp2, (IsAndWithShiftOp ? Op1.getOperand(0).getOperand(0)
486                                    : Op1.getOperand(0)));
487     return CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
488                                  getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
489   }
490   return 0;
491 }
492
493 /// SelectAddrImm - Returns true if the address N can be represented by
494 /// a base register plus a signed 16-bit displacement [r+imm].
495 bool PPCDAGToDAGISel::SelectAddrImm(SDOperand N, SDOperand &Disp, 
496                                     SDOperand &Base) {
497   // If this can be more profitably realized as r+r, fail.
498   if (SelectAddrIdx(N, Disp, Base))
499     return false;
500
501   if (N.getOpcode() == ISD::ADD) {
502     unsigned imm = 0;
503     if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
504       Disp = getI32Imm(imm & 0xFFFF);
505       if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N.getOperand(0))) {
506         Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
507       } else {
508         Base = N.getOperand(0);
509       }
510       return true; // [r+i]
511     } else if (N.getOperand(1).getOpcode() == PPCISD::Lo) {
512       // Match LOAD (ADD (X, Lo(G))).
513       assert(!cast<ConstantSDNode>(N.getOperand(1).getOperand(1))->getValue()
514              && "Cannot handle constant offsets yet!");
515       Disp = N.getOperand(1).getOperand(0);  // The global address.
516       assert(Disp.getOpcode() == ISD::TargetGlobalAddress ||
517              Disp.getOpcode() == ISD::TargetConstantPool);
518       Base = N.getOperand(0);
519       return true;  // [&g+r]
520     }
521   } else if (N.getOpcode() == ISD::OR) {
522     unsigned imm = 0;
523     if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm)) {
524       // If this is an or of disjoint bitfields, we can codegen this as an add
525       // (for better address arithmetic) if the LHS and RHS of the OR are
526       // provably disjoint.
527       uint64_t LHSKnownZero, LHSKnownOne;
528       PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
529                                     LHSKnownZero, LHSKnownOne);
530       if ((LHSKnownZero|~imm) == ~0U) {
531         // If all of the bits are known zero on the LHS or RHS, the add won't
532         // carry.
533         Base = N.getOperand(0);
534         Disp = getI32Imm(imm & 0xFFFF);
535         return true;
536       }
537     }
538   }
539   Disp = getI32Imm(0);
540   if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(N))
541     Base = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
542   else
543     Base = N;
544   return true;      // [r+0]
545 }
546
547 /// SelectAddrIdx - Given the specified addressed, check to see if it can be
548 /// represented as an indexed [r+r] operation.  Returns false if it can
549 /// be represented by [r+imm], which are preferred.
550 bool PPCDAGToDAGISel::SelectAddrIdx(SDOperand N, SDOperand &Base, 
551                                     SDOperand &Index) {
552   unsigned imm = 0;
553   if (N.getOpcode() == ISD::ADD) {
554     if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
555       return false;    // r+i
556     if (N.getOperand(1).getOpcode() == PPCISD::Lo)
557       return false;    // r+i
558     
559     Base = N.getOperand(0);
560     Index = N.getOperand(1);
561     return true;
562   } else if (N.getOpcode() == ISD::OR) {
563     if (isIntImmediate(N.getOperand(1), imm) && isInt16(imm))
564       return false;    // r+i can fold it if we can.
565     
566     // If this is an or of disjoint bitfields, we can codegen this as an add
567     // (for better address arithmetic) if the LHS and RHS of the OR are provably
568     // disjoint.
569     uint64_t LHSKnownZero, LHSKnownOne;
570     uint64_t RHSKnownZero, RHSKnownOne;
571     PPCLowering.ComputeMaskedBits(N.getOperand(0), ~0U,
572                                   LHSKnownZero, LHSKnownOne);
573     
574     if (LHSKnownZero) {
575       PPCLowering.ComputeMaskedBits(N.getOperand(1), ~0U,
576                                     RHSKnownZero, RHSKnownOne);
577       // If all of the bits are known zero on the LHS or RHS, the add won't
578       // carry.
579       if ((LHSKnownZero | RHSKnownZero) == ~0U) {
580         Base = N.getOperand(0);
581         Index = N.getOperand(1);
582         return true;
583       }
584     }
585   }
586   
587   return false;
588 }
589
590 /// SelectAddrIdxOnly - Given the specified addressed, force it to be
591 /// represented as an indexed [r+r] operation.
592 bool PPCDAGToDAGISel::SelectAddrIdxOnly(SDOperand N, SDOperand &Base, 
593                                         SDOperand &Index) {
594   // Check to see if we can easily represent this as an [r+r] address.  This
595   // will fail if it thinks that the address is more profitably represented as
596   // reg+imm, e.g. where imm = 0.
597   if (!SelectAddrIdx(N, Base, Index)) {
598     // Nope, do it the hard way.
599     Base = CurDAG->getRegister(PPC::R0, MVT::i32);
600     Index = N;
601   }
602   return true;
603 }
604
605 /// SelectCC - Select a comparison of the specified values with the specified
606 /// condition code, returning the CR# of the expression.
607 SDOperand PPCDAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
608                                     ISD::CondCode CC) {
609   // Always select the LHS.
610   Select(LHS, LHS);
611
612   // Use U to determine whether the SETCC immediate range is signed or not.
613   if (MVT::isInteger(LHS.getValueType())) {
614     bool U = ISD::isUnsignedIntSetCC(CC);
615     unsigned Imm;
616     if (isIntImmediate(RHS, Imm) && 
617         ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
618       return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI,
619                                     MVT::i32, LHS, getI32Imm(Imm & 0xFFFF)), 0);
620     Select(RHS, RHS);
621     return SDOperand(CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
622                                            LHS, RHS), 0);
623   } else if (LHS.getValueType() == MVT::f32) {
624     Select(RHS, RHS);
625     return SDOperand(CurDAG->getTargetNode(PPC::FCMPUS, MVT::i32, LHS, RHS), 0);
626   } else {
627     Select(RHS, RHS);
628     return SDOperand(CurDAG->getTargetNode(PPC::FCMPUD, MVT::i32, LHS, RHS), 0);
629   }
630 }
631
632 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
633 /// to Condition.
634 static unsigned getBCCForSetCC(ISD::CondCode CC) {
635   switch (CC) {
636   default: assert(0 && "Unknown condition!"); abort();
637   case ISD::SETOEQ:    // FIXME: This is incorrect see PR642.
638   case ISD::SETEQ:  return PPC::BEQ;
639   case ISD::SETONE:    // FIXME: This is incorrect see PR642.
640   case ISD::SETNE:  return PPC::BNE;
641   case ISD::SETOLT:    // FIXME: This is incorrect see PR642.
642   case ISD::SETULT:
643   case ISD::SETLT:  return PPC::BLT;
644   case ISD::SETOLE:    // FIXME: This is incorrect see PR642.
645   case ISD::SETULE:
646   case ISD::SETLE:  return PPC::BLE;
647   case ISD::SETOGT:    // FIXME: This is incorrect see PR642.
648   case ISD::SETUGT:
649   case ISD::SETGT:  return PPC::BGT;
650   case ISD::SETOGE:    // FIXME: This is incorrect see PR642.
651   case ISD::SETUGE:
652   case ISD::SETGE:  return PPC::BGE;
653     
654   case ISD::SETO:   return PPC::BUN;
655   case ISD::SETUO:  return PPC::BNU;
656   }
657   return 0;
658 }
659
660 /// getCRIdxForSetCC - Return the index of the condition register field
661 /// associated with the SetCC condition, and whether or not the field is
662 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
663 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
664   switch (CC) {
665   default: assert(0 && "Unknown condition!"); abort();
666   case ISD::SETOLT:  // FIXME: This is incorrect see PR642.
667   case ISD::SETULT:
668   case ISD::SETLT:  Inv = false;  return 0;
669   case ISD::SETOGE:  // FIXME: This is incorrect see PR642.
670   case ISD::SETUGE:
671   case ISD::SETGE:  Inv = true;   return 0;
672   case ISD::SETOGT:  // FIXME: This is incorrect see PR642.
673   case ISD::SETUGT:
674   case ISD::SETGT:  Inv = false;  return 1;
675   case ISD::SETOLE:  // FIXME: This is incorrect see PR642.
676   case ISD::SETULE:
677   case ISD::SETLE:  Inv = true;   return 1;
678   case ISD::SETOEQ:  // FIXME: This is incorrect see PR642.
679   case ISD::SETEQ:  Inv = false;  return 2;
680   case ISD::SETONE:  // FIXME: This is incorrect see PR642.
681   case ISD::SETNE:  Inv = true;   return 2;
682   case ISD::SETO:   Inv = true;   return 3;
683   case ISD::SETUO:  Inv = false;  return 3;
684   }
685   return 0;
686 }
687
688 SDOperand PPCDAGToDAGISel::SelectSETCC(SDOperand Op) {
689   SDNode *N = Op.Val;
690   unsigned Imm;
691   ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
692   if (isIntImmediate(N->getOperand(1), Imm)) {
693     // We can codegen setcc op, imm very efficiently compared to a brcond.
694     // Check for those cases here.
695     // setcc op, 0
696     if (Imm == 0) {
697       SDOperand Op;
698       Select(Op, N->getOperand(0));
699       switch (CC) {
700       default: break;
701       case ISD::SETEQ:
702         Op = SDOperand(CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op), 0);
703         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
704                                     getI32Imm(5), getI32Imm(31));
705       case ISD::SETNE: {
706         SDOperand AD =
707           SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
708                                           Op, getI32Imm(~0U)), 0);
709         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, 
710                                     AD.getValue(1));
711       }
712       case ISD::SETLT:
713         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
714                                     getI32Imm(31), getI32Imm(31));
715       case ISD::SETGT: {
716         SDOperand T =
717           SDOperand(CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op), 0);
718         T = SDOperand(CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op), 0);
719         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
720                                     getI32Imm(31), getI32Imm(31));
721       }
722       }
723     } else if (Imm == ~0U) {        // setcc op, -1
724       SDOperand Op;
725       Select(Op, N->getOperand(0));
726       switch (CC) {
727       default: break;
728       case ISD::SETEQ:
729         Op = SDOperand(CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
730                                              Op, getI32Imm(1)), 0);
731         return CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
732                               SDOperand(CurDAG->getTargetNode(PPC::LI, MVT::i32,
733                                                               getI32Imm(0)), 0),
734                                     Op.getValue(1));
735       case ISD::SETNE: {
736         Op = SDOperand(CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op), 0);
737         SDNode *AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
738                                            Op, getI32Imm(~0U));
739         return CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, SDOperand(AD, 0), Op, 
740                                     SDOperand(AD, 1));
741       }
742       case ISD::SETLT: {
743         SDOperand AD = SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
744                                                        getI32Imm(1)), 0);
745         SDOperand AN = SDOperand(CurDAG->getTargetNode(PPC::AND, MVT::i32, AD,
746                                                        Op), 0);
747         return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
748                                     getI32Imm(31), getI32Imm(31));
749       }
750       case ISD::SETGT:
751         Op = SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op,
752                                              getI32Imm(1), getI32Imm(31),
753                                              getI32Imm(31)), 0);
754         return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
755       }
756     }
757   }
758   
759   bool Inv;
760   unsigned Idx = getCRIdxForSetCC(CC, Inv);
761   SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
762   SDOperand IntCR;
763   
764   // Force the ccreg into CR7.
765   SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
766   
767   SDOperand InFlag(0, 0);  // Null incoming flag value.
768   CCReg = CurDAG->getCopyToReg(CurDAG->getEntryNode(), CR7Reg, CCReg, 
769                                InFlag).getValue(1);
770   
771   if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
772     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg,
773                                             CCReg), 0);
774   else
775     IntCR = SDOperand(CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg), 0);
776   
777   if (!Inv) {
778     return CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
779                                 getI32Imm((32-(3-Idx)) & 31),
780                                 getI32Imm(31), getI32Imm(31));
781   } else {
782     SDOperand Tmp =
783       SDOperand(CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
784                                       getI32Imm((32-(3-Idx)) & 31),
785                                       getI32Imm(31),getI32Imm(31)), 0);
786     return CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
787   }
788 }
789
790 /// isCallCompatibleAddress - Return true if the specified 32-bit value is
791 /// representable in the immediate field of a Bx instruction.
792 static bool isCallCompatibleAddress(ConstantSDNode *C) {
793   int Addr = C->getValue();
794   if (Addr & 3) return false;  // Low 2 bits are implicitly zero.
795   return (Addr << 6 >> 6) == Addr;  // Top 6 bits have to be sext of immediate.
796 }
797
798 SDOperand PPCDAGToDAGISel::SelectCALL(SDOperand Op) {
799   SDNode *N = Op.Val;
800   SDOperand Chain;
801   Select(Chain, N->getOperand(0));
802   
803   unsigned CallOpcode;
804   std::vector<SDOperand> CallOperands;
805   
806   if (GlobalAddressSDNode *GASD =
807       dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
808     CallOpcode = PPC::BL;
809     CallOperands.push_back(N->getOperand(1));
810   } else if (ExternalSymbolSDNode *ESSDN =
811              dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
812     CallOpcode = PPC::BL;
813     CallOperands.push_back(N->getOperand(1));
814   } else if (isa<ConstantSDNode>(N->getOperand(1)) &&
815              isCallCompatibleAddress(cast<ConstantSDNode>(N->getOperand(1)))) {
816     ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
817     CallOpcode = PPC::BLA;
818     CallOperands.push_back(getI32Imm((int)C->getValue() >> 2));
819   } else {
820     // Copy the callee address into the CTR register.
821     SDOperand Callee;
822     Select(Callee, N->getOperand(1));
823     Chain = SDOperand(CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Callee,
824                                             Chain), 0);
825     
826     // Copy the callee address into R12 on darwin.
827     SDOperand R12 = CurDAG->getRegister(PPC::R12, MVT::i32);
828     Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, R12, Callee);
829
830     CallOperands.push_back(R12);
831     CallOpcode = PPC::BCTRL;
832   }
833   
834   unsigned GPR_idx = 0, FPR_idx = 0;
835   static const unsigned GPR[] = {
836     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
837     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
838   };
839   static const unsigned FPR[] = {
840     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
841     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
842   };
843   
844   SDOperand InFlag;  // Null incoming flag value.
845   
846   for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i) {
847     unsigned DestReg = 0;
848     MVT::ValueType RegTy = N->getOperand(i).getValueType();
849     if (RegTy == MVT::i32) {
850       assert(GPR_idx < 8 && "Too many int args");
851       DestReg = GPR[GPR_idx++];
852     } else {
853       assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
854              "Unpromoted integer arg?");
855       assert(FPR_idx < 13 && "Too many fp args");
856       DestReg = FPR[FPR_idx++];
857     }
858     
859     if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
860       SDOperand Val;
861       Select(Val, N->getOperand(i));
862       Chain = CurDAG->getCopyToReg(Chain, DestReg, Val, InFlag);
863       InFlag = Chain.getValue(1);
864       CallOperands.push_back(CurDAG->getRegister(DestReg, RegTy));
865     }
866   }
867   
868   // Finally, once everything is in registers to pass to the call, emit the
869   // call itself.
870   if (InFlag.Val)
871     CallOperands.push_back(InFlag);   // Strong dep on register copies.
872   else
873     CallOperands.push_back(Chain);    // Weak dep on whatever occurs before
874   Chain = SDOperand(CurDAG->getTargetNode(CallOpcode, MVT::Other, MVT::Flag,
875                                           CallOperands), 0);
876   
877   std::vector<SDOperand> CallResults;
878   
879   // If the call has results, copy the values out of the ret val registers.
880   switch (N->getValueType(0)) {
881     default: assert(0 && "Unexpected ret value!");
882     case MVT::Other: break;
883     case MVT::i32:
884       if (N->getValueType(1) == MVT::i32) {
885         Chain = CurDAG->getCopyFromReg(Chain, PPC::R4, MVT::i32, 
886                                        Chain.getValue(1)).getValue(1);
887         CallResults.push_back(Chain.getValue(0));
888         Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
889                                        Chain.getValue(2)).getValue(1);
890         CallResults.push_back(Chain.getValue(0));
891       } else {
892         Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32,
893                                        Chain.getValue(1)).getValue(1);
894         CallResults.push_back(Chain.getValue(0));
895       }
896       break;
897     case MVT::f32:
898     case MVT::f64:
899       Chain = CurDAG->getCopyFromReg(Chain, PPC::F1, N->getValueType(0),
900                                      Chain.getValue(1)).getValue(1);
901       CallResults.push_back(Chain.getValue(0));
902       break;
903   }
904   
905   CallResults.push_back(Chain);
906   for (unsigned i = 0, e = CallResults.size(); i != e; ++i)
907     CodeGenMap[Op.getValue(i)] = CallResults[i];
908   return CallResults[Op.ResNo];
909 }
910
911 // Select - Convert the specified operand from a target-independent to a
912 // target-specific node if it hasn't already been changed.
913 void PPCDAGToDAGISel::Select(SDOperand &Result, SDOperand Op) {
914   SDNode *N = Op.Val;
915   if (N->getOpcode() >= ISD::BUILTIN_OP_END &&
916       N->getOpcode() < PPCISD::FIRST_NUMBER) {
917     Result = Op;
918     return;   // Already selected.
919   }
920
921   // If this has already been converted, use it.
922   std::map<SDOperand, SDOperand>::iterator CGMI = CodeGenMap.find(Op);
923   if (CGMI != CodeGenMap.end()) {
924     Result = CGMI->second;
925     return;
926   }
927   
928   switch (N->getOpcode()) {
929   default: break;
930   case ISD::VECTOR_SHUFFLE:
931     // FIXME: This should be autogenerated from the .td file, it is here for now
932     // due to bugs in tblgen.
933     if (Op.getOperand(1).getOpcode() == ISD::UNDEF &&
934         (Op.getValueType() == MVT::v4f32 || Op.getValueType() == MVT::v4i32) &&
935         PPC::isSplatShuffleMask(Op.getOperand(2).Val)) {
936       SDOperand N0;
937       Select(N0, N->getOperand(0));
938       Result = CodeGenMap[Op] = 
939         SDOperand(CurDAG->getTargetNode(PPC::VSPLTW, MVT::v4f32,
940                                         getI32Imm(PPC::getVSPLTImmediate(Op.getOperand(2).Val)),
941                                         N0), 0);
942       return;
943     }
944     assert(0 && "ILLEGAL VECTOR_SHUFFLE!");
945       
946   case ISD::SETCC:
947     Result = SelectSETCC(Op);
948     return;
949   case PPCISD::CALL:
950     Result = SelectCALL(Op);
951     return;
952   case PPCISD::GlobalBaseReg:
953     Result = getGlobalBaseReg();
954     return;
955     
956   case ISD::FrameIndex: {
957     int FI = cast<FrameIndexSDNode>(N)->getIndex();
958     if (N->hasOneUse()) {
959       Result = CurDAG->SelectNodeTo(N, PPC::ADDI, MVT::i32,
960                                     CurDAG->getTargetFrameIndex(FI, MVT::i32),
961                                     getI32Imm(0));
962       return;
963     }
964     Result = CodeGenMap[Op] = 
965       SDOperand(CurDAG->getTargetNode(PPC::ADDI, MVT::i32,
966                                       CurDAG->getTargetFrameIndex(FI, MVT::i32),
967                                       getI32Imm(0)), 0);
968     return;
969   }
970   case ISD::SDIV: {
971     // FIXME: since this depends on the setting of the carry flag from the srawi
972     //        we should really be making notes about that for the scheduler.
973     // FIXME: It sure would be nice if we could cheaply recognize the 
974     //        srl/add/sra pattern the dag combiner will generate for this as
975     //        sra/addze rather than having to handle sdiv ourselves.  oh well.
976     unsigned Imm;
977     if (isIntImmediate(N->getOperand(1), Imm)) {
978       SDOperand N0;
979       Select(N0, N->getOperand(0));
980       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
981         SDNode *Op =
982           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
983                                 N0, getI32Imm(Log2_32(Imm)));
984         Result = CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
985                                       SDOperand(Op, 0), SDOperand(Op, 1));
986       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
987         SDNode *Op =
988           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
989                                 N0, getI32Imm(Log2_32(-Imm)));
990         SDOperand PT =
991           SDOperand(CurDAG->getTargetNode(PPC::ADDZE, MVT::i32,
992                                           SDOperand(Op, 0), SDOperand(Op, 1)),
993                     0);
994         Result = CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
995       }
996       return;
997     }
998     
999     // Other cases are autogenerated.
1000     break;
1001   }
1002   case ISD::AND: {
1003     unsigned Imm, Imm2;
1004     // If this is an and of a value rotated between 0 and 31 bits and then and'd
1005     // with a mask, emit rlwinm
1006     if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
1007                                                   isShiftedMask_32(~Imm))) {
1008       SDOperand Val;
1009       unsigned SH, MB, ME;
1010       if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
1011         Select(Val, N->getOperand(0).getOperand(0));
1012       } else if (Imm == 0) {
1013         // AND X, 0 -> 0, not "rlwinm 32".
1014         Select(Result, N->getOperand(1));
1015         return ;
1016       } else {        
1017         Select(Val, N->getOperand(0));
1018         isRunOfOnes(Imm, MB, ME);
1019         SH = 0;
1020       }
1021       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val,
1022                                     getI32Imm(SH), getI32Imm(MB),
1023                                     getI32Imm(ME));
1024       return;
1025     }
1026     // ISD::OR doesn't get all the bitfield insertion fun.
1027     // (and (or x, c1), c2) where isRunOfOnes(~(c1^c2)) is a bitfield insert
1028     if (isIntImmediate(N->getOperand(1), Imm) && 
1029         N->getOperand(0).getOpcode() == ISD::OR &&
1030         isIntImmediate(N->getOperand(0).getOperand(1), Imm2)) {
1031       unsigned MB, ME;
1032       Imm = ~(Imm^Imm2);
1033       if (isRunOfOnes(Imm, MB, ME)) {
1034         SDOperand Tmp1, Tmp2;
1035         Select(Tmp1, N->getOperand(0).getOperand(0));
1036         Select(Tmp2, N->getOperand(0).getOperand(1));
1037         Result = SDOperand(CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32,
1038                                                  Tmp1, Tmp2,
1039                                                  getI32Imm(0), getI32Imm(MB),
1040                                                  getI32Imm(ME)), 0);
1041         return;
1042       }
1043     }
1044     
1045     // Other cases are autogenerated.
1046     break;
1047   }
1048   case ISD::OR:
1049     if (SDNode *I = SelectBitfieldInsert(N)) {
1050       Result = CodeGenMap[Op] = SDOperand(I, 0);
1051       return;
1052     }
1053       
1054     // Other cases are autogenerated.
1055     break;
1056   case ISD::SHL: {
1057     unsigned Imm, SH, MB, ME;
1058     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1059         isRotateAndMask(N, Imm, true, SH, MB, ME)) {
1060       SDOperand Val;
1061       Select(Val, N->getOperand(0).getOperand(0));
1062       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1063                                     Val, getI32Imm(SH), getI32Imm(MB),
1064                                     getI32Imm(ME));
1065       return;
1066     }
1067     
1068     // Other cases are autogenerated.
1069     break;
1070   }
1071   case ISD::SRL: {
1072     unsigned Imm, SH, MB, ME;
1073     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1074         isRotateAndMask(N, Imm, true, SH, MB, ME)) { 
1075       SDOperand Val;
1076       Select(Val, N->getOperand(0).getOperand(0));
1077       Result = CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1078                                     Val, getI32Imm(SH & 0x1F), getI32Imm(MB),
1079                                     getI32Imm(ME));
1080       return;
1081     }
1082     
1083     // Other cases are autogenerated.
1084     break;
1085   }
1086   case ISD::SELECT_CC: {
1087     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(4))->get();
1088     
1089     // handle the setcc cases here.  select_cc lhs, 0, 1, 0, cc
1090     if (ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1)))
1091       if (ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N->getOperand(2)))
1092         if (ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N->getOperand(3)))
1093           if (N1C->isNullValue() && N3C->isNullValue() &&
1094               N2C->getValue() == 1ULL && CC == ISD::SETNE) {
1095             SDOperand LHS;
1096             Select(LHS, N->getOperand(0));
1097             SDNode *Tmp =
1098               CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1099                                     LHS, getI32Imm(~0U));
1100             Result = CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32,
1101                                           SDOperand(Tmp, 0), LHS,
1102                                           SDOperand(Tmp, 1));
1103             return;
1104           }
1105
1106     SDOperand CCReg = SelectCC(N->getOperand(0), N->getOperand(1), CC);
1107     unsigned BROpc = getBCCForSetCC(CC);
1108
1109     bool isFP = MVT::isFloatingPoint(N->getValueType(0));
1110     unsigned SelectCCOp;
1111     if (MVT::isInteger(N->getValueType(0)))
1112       SelectCCOp = PPC::SELECT_CC_Int;
1113     else if (N->getValueType(0) == MVT::f32)
1114       SelectCCOp = PPC::SELECT_CC_F4;
1115     else
1116       SelectCCOp = PPC::SELECT_CC_F8;
1117     SDOperand N2, N3;
1118     Select(N2, N->getOperand(2));
1119     Select(N3, N->getOperand(3));
1120     Result = CurDAG->SelectNodeTo(N, SelectCCOp, N->getValueType(0), CCReg,
1121                                   N2, N3, getI32Imm(BROpc));
1122     return;
1123   }
1124   case ISD::BR_CC: {
1125     SDOperand Chain;
1126     Select(Chain, N->getOperand(0));
1127     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1128     SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1129     Result = CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, 
1130                                   CondCode, getI32Imm(getBCCForSetCC(CC)), 
1131                                   N->getOperand(4), Chain);
1132     return;
1133   }
1134   }
1135   
1136   SelectCode(Result, Op);
1137 }
1138
1139
1140 /// createPPCISelDag - This pass converts a legalized DAG into a 
1141 /// PowerPC-specific DAG, ready for instruction scheduling.
1142 ///
1143 FunctionPass *llvm::createPPCISelDag(PPCTargetMachine &TM) {
1144   return new PPCDAGToDAGISel(TM);
1145 }
1146