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