Changes to adjust to new ReplaceAllUsesWith syntax. Change FP_EXTEND to
[oota-llvm.git] / lib / Target / PowerPC / PPCISelDAGToDAG.cpp
1 //===-- PPC32ISelDAGToDAG.cpp - PPC32 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 32 bit PowerPC,
11 // converting from a legalized dag to a PPC dag.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "PowerPC.h"
16 #include "PPC32TargetMachine.h"
17 #include "PPC32ISelLowering.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/MachineFunction.h"
20 #include "llvm/CodeGen/SSARegMap.h"
21 #include "llvm/CodeGen/SelectionDAG.h"
22 #include "llvm/CodeGen/SelectionDAGISel.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/ADT/Statistic.h"
25 #include "llvm/Constants.h"
26 #include "llvm/GlobalValue.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/MathExtras.h"
29 using namespace llvm;
30
31 namespace {
32   Statistic<> FusedFP ("ppc-codegen", "Number of fused fp operations");
33   Statistic<> FrameOff("ppc-codegen", "Number of frame idx offsets collapsed");
34     
35   //===--------------------------------------------------------------------===//
36   /// PPC32DAGToDAGISel - PPC32 specific code to select PPC32 machine
37   /// instructions for SelectionDAG operations.
38   ///
39   class PPC32DAGToDAGISel : public SelectionDAGISel {
40     PPC32TargetLowering PPC32Lowering;
41     unsigned GlobalBaseReg;
42   public:
43     PPC32DAGToDAGISel(TargetMachine &TM)
44       : SelectionDAGISel(PPC32Lowering), PPC32Lowering(TM) {}
45     
46     virtual bool runOnFunction(Function &Fn) {
47       // Make sure we re-emit a set of the global base reg if necessary
48       GlobalBaseReg = 0;
49       return SelectionDAGISel::runOnFunction(Fn);
50     }
51    
52     /// getI32Imm - Return a target constant with the specified value, of type
53     /// i32.
54     inline SDOperand getI32Imm(unsigned Imm) {
55       return CurDAG->getTargetConstant(Imm, MVT::i32);
56     }
57
58     /// getGlobalBaseReg - insert code into the entry mbb to materialize the PIC
59     /// base register.  Return the virtual register that holds this value.
60     SDOperand getGlobalBaseReg();
61     
62     // Select - Convert the specified operand from a target-independent to a
63     // target-specific node if it hasn't already been changed.
64     SDOperand Select(SDOperand Op);
65     
66     SDNode *SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
67                                    unsigned OCHi, unsigned OCLo,
68                                    bool IsArithmetic = false,
69                                    bool Negate = false);
70     SDNode *SelectBitfieldInsert(SDNode *N);
71
72     /// SelectCC - Select a comparison of the specified values with the
73     /// specified condition code, returning the CR# of the expression.
74     SDOperand SelectCC(SDOperand LHS, SDOperand RHS, ISD::CondCode CC);
75
76     /// SelectAddr - Given the specified address, return the two operands for a
77     /// load/store instruction, and return true if it should be an indexed [r+r]
78     /// operation.
79     bool SelectAddr(SDOperand Addr, SDOperand &Op1, SDOperand &Op2);
80
81     SDOperand BuildSDIVSequence(SDNode *N);
82     SDOperand BuildUDIVSequence(SDNode *N);
83     
84     /// InstructionSelectBasicBlock - This callback is invoked by
85     /// SelectionDAGISel when it has created a SelectionDAG for us to codegen.
86     virtual void InstructionSelectBasicBlock(SelectionDAG &DAG) {
87       DEBUG(BB->dump());
88       // Select target instructions for the DAG.
89       Select(DAG.getRoot());
90       DAG.RemoveDeadNodes();
91       
92       // Emit machine code to BB. 
93       ScheduleAndEmitDAG(DAG);
94     }
95  
96     virtual const char *getPassName() const {
97       return "PowerPC DAG->DAG Pattern Instruction Selection";
98     } 
99   };
100 }
101
102 /// getGlobalBaseReg - Output the instructions required to put the
103 /// base address to use for accessing globals into a register.
104 ///
105 SDOperand PPC32DAGToDAGISel::getGlobalBaseReg() {
106   if (!GlobalBaseReg) {
107     // Insert the set of GlobalBaseReg into the first MBB of the function
108     MachineBasicBlock &FirstMBB = BB->getParent()->front();
109     MachineBasicBlock::iterator MBBI = FirstMBB.begin();
110     SSARegMap *RegMap = BB->getParent()->getSSARegMap();
111     GlobalBaseReg = RegMap->createVirtualRegister(PPC32::GPRCRegisterClass);
112     BuildMI(FirstMBB, MBBI, PPC::MovePCtoLR, 0, PPC::LR);
113     BuildMI(FirstMBB, MBBI, PPC::MFLR, 1, GlobalBaseReg);
114   }
115   return CurDAG->getRegister(GlobalBaseReg, MVT::i32);
116 }
117
118
119 // isIntImmediate - This method tests to see if a constant operand.
120 // If so Imm will receive the 32 bit value.
121 static bool isIntImmediate(SDNode *N, unsigned& Imm) {
122   if (N->getOpcode() == ISD::Constant) {
123     Imm = cast<ConstantSDNode>(N)->getValue();
124     return true;
125   }
126   return false;
127 }
128
129 // isOprShiftImm - Returns true if the specified operand is a shift opcode with
130 // a immediate shift count less than 32.
131 static bool isOprShiftImm(SDNode *N, unsigned& Opc, unsigned& SH) {
132   Opc = N->getOpcode();
133   return (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA) &&
134     isIntImmediate(N->getOperand(1).Val, SH) && SH < 32;
135 }
136
137 // isRunOfOnes - Returns true iff Val consists of one contiguous run of 1s with
138 // any number of 0s on either side.  The 1s are allowed to wrap from LSB to
139 // MSB, so 0x000FFF0, 0x0000FFFF, and 0xFF0000FF are all runs.  0x0F0F0000 is
140 // not, since all 1s are not contiguous.
141 static bool isRunOfOnes(unsigned Val, unsigned &MB, unsigned &ME) {
142   if (isShiftedMask_32(Val)) {
143     // look for the first non-zero bit
144     MB = CountLeadingZeros_32(Val);
145     // look for the first zero bit after the run of ones
146     ME = CountLeadingZeros_32((Val - 1) ^ Val);
147     return true;
148   } else {
149     Val = ~Val; // invert mask
150     if (isShiftedMask_32(Val)) {
151       // effectively look for the first zero bit
152       ME = CountLeadingZeros_32(Val) - 1;
153       // effectively look for the first one bit after the run of zeros
154       MB = CountLeadingZeros_32((Val - 1) ^ Val) + 1;
155       return true;
156     }
157   }
158   // no run present
159   return false;
160 }
161
162 // isRotateAndMask - Returns true if Mask and Shift can be folded in to a rotate
163 // and mask opcode and mask operation.
164 static bool isRotateAndMask(SDNode *N, unsigned Mask, bool IsShiftMask,
165                             unsigned &SH, unsigned &MB, unsigned &ME) {
166   unsigned Shift  = 32;
167   unsigned Indeterminant = ~0;  // bit mask marking indeterminant results
168   unsigned Opcode = N->getOpcode();
169   if (!isIntImmediate(N->getOperand(1).Val, Shift) || (Shift > 31))
170     return false;
171   
172   if (Opcode == ISD::SHL) {
173     // apply shift left to mask if it comes first
174     if (IsShiftMask) Mask = Mask << Shift;
175     // determine which bits are made indeterminant by shift
176     Indeterminant = ~(0xFFFFFFFFu << Shift);
177   } else if (Opcode == ISD::SRA || Opcode == ISD::SRL) { 
178     // apply shift right to mask if it comes first
179     if (IsShiftMask) Mask = Mask >> Shift;
180     // determine which bits are made indeterminant by shift
181     Indeterminant = ~(0xFFFFFFFFu >> Shift);
182     // adjust for the left rotate
183     Shift = 32 - Shift;
184   } else {
185     return false;
186   }
187   
188   // if the mask doesn't intersect any Indeterminant bits
189   if (Mask && !(Mask & Indeterminant)) {
190     SH = Shift;
191     // make sure the mask is still a mask (wrap arounds may not be)
192     return isRunOfOnes(Mask, MB, ME);
193   }
194   return false;
195 }
196
197 // isOpcWithIntImmediate - This method tests to see if the node is a specific
198 // opcode and that it has a immediate integer right operand.
199 // If so Imm will receive the 32 bit value.
200 static bool isOpcWithIntImmediate(SDNode *N, unsigned Opc, unsigned& Imm) {
201   return N->getOpcode() == Opc && isIntImmediate(N->getOperand(1).Val, Imm);
202 }
203
204 // isOprNot - Returns true if the specified operand is an xor with immediate -1.
205 static bool isOprNot(SDNode *N) {
206   unsigned Imm;
207   return isOpcWithIntImmediate(N, ISD::XOR, Imm) && (signed)Imm == -1;
208 }
209
210 // Immediate constant composers.
211 // Lo16 - grabs the lo 16 bits from a 32 bit constant.
212 // Hi16 - grabs the hi 16 bits from a 32 bit constant.
213 // HA16 - computes the hi bits required if the lo bits are add/subtracted in
214 // arithmethically.
215 static unsigned Lo16(unsigned x)  { return x & 0x0000FFFF; }
216 static unsigned Hi16(unsigned x)  { return Lo16(x >> 16); }
217 static unsigned HA16(unsigned x)  { return Hi16((signed)x - (signed short)x); }
218
219 // isIntImmediate - This method tests to see if a constant operand.
220 // If so Imm will receive the 32 bit value.
221 static bool isIntImmediate(SDOperand N, unsigned& Imm) {
222   if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(N)) {
223     Imm = (unsigned)CN->getSignExtended();
224     return true;
225   }
226   return false;
227 }
228
229 /// SelectBitfieldInsert - turn an or of two masked values into
230 /// the rotate left word immediate then mask insert (rlwimi) instruction.
231 /// Returns true on success, false if the caller still needs to select OR.
232 ///
233 /// Patterns matched:
234 /// 1. or shl, and   5. or and, and
235 /// 2. or and, shl   6. or shl, shr
236 /// 3. or shr, and   7. or shr, shl
237 /// 4. or and, shr
238 SDNode *PPC32DAGToDAGISel::SelectBitfieldInsert(SDNode *N) {
239   bool IsRotate = false;
240   unsigned TgtMask = 0xFFFFFFFF, InsMask = 0xFFFFFFFF, SH = 0;
241   unsigned Value;
242   
243   SDOperand Op0 = N->getOperand(0);
244   SDOperand Op1 = N->getOperand(1);
245   
246   unsigned Op0Opc = Op0.getOpcode();
247   unsigned Op1Opc = Op1.getOpcode();
248   
249   // Verify that we have the correct opcodes
250   if (ISD::SHL != Op0Opc && ISD::SRL != Op0Opc && ISD::AND != Op0Opc)
251     return false;
252   if (ISD::SHL != Op1Opc && ISD::SRL != Op1Opc && ISD::AND != Op1Opc)
253     return false;
254   
255   // Generate Mask value for Target
256   if (isIntImmediate(Op0.getOperand(1), Value)) {
257     switch(Op0Opc) {
258       case ISD::SHL: TgtMask <<= Value; break;
259       case ISD::SRL: TgtMask >>= Value; break;
260       case ISD::AND: TgtMask &= Value; break;
261     }
262   } else {
263     return 0;
264   }
265   
266   // Generate Mask value for Insert
267   if (isIntImmediate(Op1.getOperand(1), Value)) {
268     switch(Op1Opc) {
269       case ISD::SHL:
270         SH = Value;
271         InsMask <<= SH;
272         if (Op0Opc == ISD::SRL) IsRotate = true;
273           break;
274       case ISD::SRL:
275         SH = Value;
276         InsMask >>= SH;
277         SH = 32-SH;
278         if (Op0Opc == ISD::SHL) IsRotate = true;
279           break;
280       case ISD::AND:
281         InsMask &= Value;
282         break;
283     }
284   } else {
285     return 0;
286   }
287   
288   // If both of the inputs are ANDs and one of them has a logical shift by
289   // constant as its input, make that AND the inserted value so that we can
290   // combine the shift into the rotate part of the rlwimi instruction
291   bool IsAndWithShiftOp = false;
292   if (Op0Opc == ISD::AND && Op1Opc == ISD::AND) {
293     if (Op1.getOperand(0).getOpcode() == ISD::SHL ||
294         Op1.getOperand(0).getOpcode() == ISD::SRL) {
295       if (isIntImmediate(Op1.getOperand(0).getOperand(1), Value)) {
296         SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
297         IsAndWithShiftOp = true;
298       }
299     } else if (Op0.getOperand(0).getOpcode() == ISD::SHL ||
300                Op0.getOperand(0).getOpcode() == ISD::SRL) {
301       if (isIntImmediate(Op0.getOperand(0).getOperand(1), Value)) {
302         std::swap(Op0, Op1);
303         std::swap(TgtMask, InsMask);
304         SH = Op1.getOperand(0).getOpcode() == ISD::SHL ? Value : 32 - Value;
305         IsAndWithShiftOp = true;
306       }
307     }
308   }
309   
310   // Verify that the Target mask and Insert mask together form a full word mask
311   // and that the Insert mask is a run of set bits (which implies both are runs
312   // of set bits).  Given that, Select the arguments and generate the rlwimi
313   // instruction.
314   unsigned MB, ME;
315   if (((TgtMask & InsMask) == 0) && isRunOfOnes(InsMask, MB, ME)) {
316     bool fullMask = (TgtMask ^ InsMask) == 0xFFFFFFFF;
317     bool Op0IsAND = Op0Opc == ISD::AND;
318     // Check for rotlwi / rotrwi here, a special case of bitfield insert
319     // where both bitfield halves are sourced from the same value.
320     if (IsRotate && fullMask &&
321         N->getOperand(0).getOperand(0) == N->getOperand(1).getOperand(0)) {
322       Op0 = CurDAG->getTargetNode(PPC::RLWINM, MVT::i32,
323                                   Select(N->getOperand(0).getOperand(0)),
324                                   getI32Imm(SH), getI32Imm(0), getI32Imm(31));
325       return Op0.Val;
326     }
327     SDOperand Tmp1 = (Op0IsAND && fullMask) ? Select(Op0.getOperand(0))
328                                             : Select(Op0);
329     SDOperand Tmp2 = IsAndWithShiftOp ? Select(Op1.getOperand(0).getOperand(0)) 
330                                       : Select(Op1.getOperand(0));
331     Op0 = CurDAG->getTargetNode(PPC::RLWIMI, MVT::i32, Tmp1, Tmp2,
332                                 getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
333     return Op0.Val;
334   }
335   return 0;
336 }
337
338 // SelectIntImmediateExpr - Choose code for integer operations with an immediate
339 // operand.
340 SDNode *PPC32DAGToDAGISel::SelectIntImmediateExpr(SDOperand LHS, SDOperand RHS,
341                                                   unsigned OCHi, unsigned OCLo,
342                                                   bool IsArithmetic,
343                                                   bool Negate) {
344   // Check to make sure this is a constant.
345   ConstantSDNode *CN = dyn_cast<ConstantSDNode>(RHS);
346   // Exit if not a constant.
347   if (!CN) return 0;
348   // Extract immediate.
349   unsigned C = (unsigned)CN->getValue();
350   // Negate if required (ISD::SUB).
351   if (Negate) C = -C;
352   // Get the hi and lo portions of constant.
353   unsigned Hi = IsArithmetic ? HA16(C) : Hi16(C);
354   unsigned Lo = Lo16(C);
355
356   // If two instructions are needed and usage indicates it would be better to
357   // load immediate into a register, bail out.
358   if (Hi && Lo && CN->use_size() > 2) return false;
359
360   // Select the first operand.
361   SDOperand Opr0 = Select(LHS);
362
363   if (Lo)  // Add in the lo-part.
364     Opr0 = CurDAG->getTargetNode(OCLo, MVT::i32, Opr0, getI32Imm(Lo));
365   if (Hi)  // Add in the hi-part.
366     Opr0 = CurDAG->getTargetNode(OCHi, MVT::i32, Opr0, getI32Imm(Hi));
367   return Opr0.Val;
368 }
369
370 /// SelectAddr - Given the specified address, return the two operands for a
371 /// load/store instruction, and return true if it should be an indexed [r+r]
372 /// operation.
373 bool PPC32DAGToDAGISel::SelectAddr(SDOperand Addr, SDOperand &Op1,
374                                    SDOperand &Op2) {
375   unsigned imm = 0;
376   if (Addr.getOpcode() == ISD::ADD) {
377     if (isIntImmediate(Addr.getOperand(1), imm) && isInt16(imm)) {
378       Op1 = getI32Imm(Lo16(imm));
379       if (FrameIndexSDNode *FI =
380             dyn_cast<FrameIndexSDNode>(Addr.getOperand(0))) {
381         ++FrameOff;
382         Op2 = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
383       } else {
384         Op2 = Select(Addr.getOperand(0));
385       }
386       return false;
387     } else {
388       Op1 = Select(Addr.getOperand(0));
389       Op2 = Select(Addr.getOperand(1));
390       return true;   // [r+r]
391     }
392   }
393
394   // Now check if we're dealing with a global, and whether or not we should emit
395   // an optimized load or store for statics.
396   if (GlobalAddressSDNode *GN = dyn_cast<GlobalAddressSDNode>(Addr)) {
397     GlobalValue *GV = GN->getGlobal();
398     if (!GV->hasWeakLinkage() && !GV->isExternal()) {
399       Op1 = CurDAG->getTargetGlobalAddress(GV, MVT::i32);
400       if (PICEnabled)
401         Op2 = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),
402                                     Op1);
403       else
404         Op2 = CurDAG->getTargetNode(PPC::LIS, MVT::i32, Op1);
405       return false;
406     }
407   } else if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(Addr)) {
408     Op1 = getI32Imm(0);
409     Op2 = CurDAG->getTargetFrameIndex(FI->getIndex(), MVT::i32);
410     return false;
411   } else if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Addr)) {
412     Op1 = Addr;
413     if (PICEnabled)
414       Op2 = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),Op1);
415     else
416       Op2 = CurDAG->getTargetNode(PPC::LIS, MVT::i32, Op1);
417     return false;
418   }
419   Op1 = getI32Imm(0);
420   Op2 = Select(Addr);
421   return false;
422 }
423
424 /// SelectCC - Select a comparison of the specified values with the specified
425 /// condition code, returning the CR# of the expression.
426 SDOperand PPC32DAGToDAGISel::SelectCC(SDOperand LHS, SDOperand RHS,
427                                       ISD::CondCode CC) {
428   // Always select the LHS.
429   LHS = Select(LHS);
430
431   // Use U to determine whether the SETCC immediate range is signed or not.
432   if (MVT::isInteger(LHS.getValueType())) {
433     bool U = ISD::isUnsignedIntSetCC(CC);
434     unsigned Imm;
435     if (isIntImmediate(RHS, Imm) && 
436         ((U && isUInt16(Imm)) || (!U && isInt16(Imm))))
437       return CurDAG->getTargetNode(U ? PPC::CMPLWI : PPC::CMPWI, MVT::i32,
438                                    LHS, getI32Imm(Lo16(Imm)));
439     return CurDAG->getTargetNode(U ? PPC::CMPLW : PPC::CMPW, MVT::i32,
440                                  LHS, Select(RHS));
441   } else {
442     return CurDAG->getTargetNode(PPC::FCMPU, MVT::i32, LHS, Select(RHS));
443   }
444 }
445
446 /// getBCCForSetCC - Returns the PowerPC condition branch mnemonic corresponding
447 /// to Condition.
448 static unsigned getBCCForSetCC(ISD::CondCode CC) {
449   switch (CC) {
450   default: assert(0 && "Unknown condition!"); abort();
451   case ISD::SETEQ:  return PPC::BEQ;
452   case ISD::SETNE:  return PPC::BNE;
453   case ISD::SETULT:
454   case ISD::SETLT:  return PPC::BLT;
455   case ISD::SETULE:
456   case ISD::SETLE:  return PPC::BLE;
457   case ISD::SETUGT:
458   case ISD::SETGT:  return PPC::BGT;
459   case ISD::SETUGE:
460   case ISD::SETGE:  return PPC::BGE;
461   }
462   return 0;
463 }
464
465 /// getCRIdxForSetCC - Return the index of the condition register field
466 /// associated with the SetCC condition, and whether or not the field is
467 /// treated as inverted.  That is, lt = 0; ge = 0 inverted.
468 static unsigned getCRIdxForSetCC(ISD::CondCode CC, bool& Inv) {
469   switch (CC) {
470   default: assert(0 && "Unknown condition!"); abort();
471   case ISD::SETULT:
472   case ISD::SETLT:  Inv = false;  return 0;
473   case ISD::SETUGE:
474   case ISD::SETGE:  Inv = true;   return 0;
475   case ISD::SETUGT:
476   case ISD::SETGT:  Inv = false;  return 1;
477   case ISD::SETULE:
478   case ISD::SETLE:  Inv = true;   return 1;
479   case ISD::SETEQ:  Inv = false;  return 2;
480   case ISD::SETNE:  Inv = true;   return 2;
481   }
482   return 0;
483 }
484
485 // Structure used to return the necessary information to codegen an SDIV as
486 // a multiply.
487 struct ms {
488   int m; // magic number
489   int s; // shift amount
490 };
491
492 struct mu {
493   unsigned int m; // magic number
494   int a;          // add indicator
495   int s;          // shift amount
496 };
497
498 /// magic - calculate the magic numbers required to codegen an integer sdiv as
499 /// a sequence of multiply and shifts.  Requires that the divisor not be 0, 1,
500 /// or -1.
501 static struct ms magic(int d) {
502   int p;
503   unsigned int ad, anc, delta, q1, r1, q2, r2, t;
504   const unsigned int two31 = 0x80000000U;
505   struct ms mag;
506   
507   ad = abs(d);
508   t = two31 + ((unsigned int)d >> 31);
509   anc = t - 1 - t%ad;   // absolute value of nc
510   p = 31;               // initialize p
511   q1 = two31/anc;       // initialize q1 = 2p/abs(nc)
512   r1 = two31 - q1*anc;  // initialize r1 = rem(2p,abs(nc))
513   q2 = two31/ad;        // initialize q2 = 2p/abs(d)
514   r2 = two31 - q2*ad;   // initialize r2 = rem(2p,abs(d))
515   do {
516     p = p + 1;
517     q1 = 2*q1;        // update q1 = 2p/abs(nc)
518     r1 = 2*r1;        // update r1 = rem(2p/abs(nc))
519     if (r1 >= anc) {  // must be unsigned comparison
520       q1 = q1 + 1;
521       r1 = r1 - anc;
522     }
523     q2 = 2*q2;        // update q2 = 2p/abs(d)
524     r2 = 2*r2;        // update r2 = rem(2p/abs(d))
525     if (r2 >= ad) {   // must be unsigned comparison
526       q2 = q2 + 1;
527       r2 = r2 - ad;
528     }
529     delta = ad - r2;
530   } while (q1 < delta || (q1 == delta && r1 == 0));
531   
532   mag.m = q2 + 1;
533   if (d < 0) mag.m = -mag.m; // resulting magic number
534   mag.s = p - 32;            // resulting shift
535   return mag;
536 }
537
538 /// magicu - calculate the magic numbers required to codegen an integer udiv as
539 /// a sequence of multiply, add and shifts.  Requires that the divisor not be 0.
540 static struct mu magicu(unsigned d)
541 {
542   int p;
543   unsigned int nc, delta, q1, r1, q2, r2;
544   struct mu magu;
545   magu.a = 0;               // initialize "add" indicator
546   nc = - 1 - (-d)%d;
547   p = 31;                   // initialize p
548   q1 = 0x80000000/nc;       // initialize q1 = 2p/nc
549   r1 = 0x80000000 - q1*nc;  // initialize r1 = rem(2p,nc)
550   q2 = 0x7FFFFFFF/d;        // initialize q2 = (2p-1)/d
551   r2 = 0x7FFFFFFF - q2*d;   // initialize r2 = rem((2p-1),d)
552   do {
553     p = p + 1;
554     if (r1 >= nc - r1 ) {
555       q1 = 2*q1 + 1;  // update q1
556       r1 = 2*r1 - nc; // update r1
557     }
558     else {
559       q1 = 2*q1; // update q1
560       r1 = 2*r1; // update r1
561     }
562     if (r2 + 1 >= d - r2) {
563       if (q2 >= 0x7FFFFFFF) magu.a = 1;
564       q2 = 2*q2 + 1;     // update q2
565       r2 = 2*r2 + 1 - d; // update r2
566     }
567     else {
568       if (q2 >= 0x80000000) magu.a = 1;
569       q2 = 2*q2;     // update q2
570       r2 = 2*r2 + 1; // update r2
571     }
572     delta = d - 1 - r2;
573   } while (p < 64 && (q1 < delta || (q1 == delta && r1 == 0)));
574   magu.m = q2 + 1; // resulting magic number
575   magu.s = p - 32;  // resulting shift
576   return magu;
577 }
578
579 /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
580 /// return a DAG expression to select that will generate the same value by
581 /// multiplying by a magic number.  See:
582 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
583 SDOperand PPC32DAGToDAGISel::BuildSDIVSequence(SDNode *N) {
584   int d = (int)cast<ConstantSDNode>(N->getOperand(1))->getValue();
585   ms magics = magic(d);
586   // Multiply the numerator (operand 0) by the magic value
587   SDOperand Q = CurDAG->getNode(ISD::MULHS, MVT::i32, N->getOperand(0),
588                                 CurDAG->getConstant(magics.m, MVT::i32));
589   // If d > 0 and m < 0, add the numerator
590   if (d > 0 && magics.m < 0)
591     Q = CurDAG->getNode(ISD::ADD, MVT::i32, Q, N->getOperand(0));
592   // If d < 0 and m > 0, subtract the numerator.
593   if (d < 0 && magics.m > 0)
594     Q = CurDAG->getNode(ISD::SUB, MVT::i32, Q, N->getOperand(0));
595   // Shift right algebraic if shift value is nonzero
596   if (magics.s > 0)
597     Q = CurDAG->getNode(ISD::SRA, MVT::i32, Q,
598                         CurDAG->getConstant(magics.s, MVT::i32));
599   // Extract the sign bit and add it to the quotient
600   SDOperand T =
601     CurDAG->getNode(ISD::SRL, MVT::i32, Q, CurDAG->getConstant(31, MVT::i32));
602   return CurDAG->getNode(ISD::ADD, MVT::i32, Q, T);
603 }
604
605 /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
606 /// return a DAG expression to select that will generate the same value by
607 /// multiplying by a magic number.  See:
608 /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
609 SDOperand PPC32DAGToDAGISel::BuildUDIVSequence(SDNode *N) {
610   unsigned d = (unsigned)cast<ConstantSDNode>(N->getOperand(1))->getValue();
611   mu magics = magicu(d);
612   // Multiply the numerator (operand 0) by the magic value
613   SDOperand Q = CurDAG->getNode(ISD::MULHU, MVT::i32, N->getOperand(0),
614                                 CurDAG->getConstant(magics.m, MVT::i32));
615   if (magics.a == 0) {
616     return CurDAG->getNode(ISD::SRL, MVT::i32, Q,
617                            CurDAG->getConstant(magics.s, MVT::i32));
618   } else {
619     SDOperand NPQ = CurDAG->getNode(ISD::SUB, MVT::i32, N->getOperand(0), Q);
620     NPQ = CurDAG->getNode(ISD::SRL, MVT::i32, NPQ,
621                            CurDAG->getConstant(1, MVT::i32));
622     NPQ = CurDAG->getNode(ISD::ADD, MVT::i32, NPQ, Q);
623     return CurDAG->getNode(ISD::SRL, MVT::i32, NPQ,
624                            CurDAG->getConstant(magics.s-1, MVT::i32));
625   }
626 }
627
628 // Select - Convert the specified operand from a target-independent to a
629 // target-specific node if it hasn't already been changed.
630 SDOperand PPC32DAGToDAGISel::Select(SDOperand Op) {
631   SDNode *N = Op.Val;
632   if (N->getOpcode() >= ISD::BUILTIN_OP_END)
633     return Op;   // Already selected.
634   
635   switch (N->getOpcode()) {
636   default:
637     std::cerr << "Cannot yet select: ";
638     N->dump();
639     std::cerr << "\n";
640     abort();
641   case ISD::EntryToken:       // These leaves remain the same.
642     return Op;
643   case ISD::TokenFactor: {
644     SDOperand New;
645     if (N->getNumOperands() == 2) {
646       SDOperand Op0 = Select(N->getOperand(0));
647       SDOperand Op1 = Select(N->getOperand(1));
648       New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Op0, Op1);
649     } else {
650       std::vector<SDOperand> Ops;
651       for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
652         Ops.push_back(Select(N->getOperand(i)));
653       New = CurDAG->getNode(ISD::TokenFactor, MVT::Other, Ops);
654     }
655     
656     if (New.Val != N) {
657       CurDAG->ReplaceAllUsesWith(Op, New);
658       N = New.Val;
659     }
660     break;
661   }
662   case ISD::CopyFromReg: {
663     SDOperand Chain = Select(N->getOperand(0));
664     if (Chain == N->getOperand(0)) return Op; // No change
665     SDOperand New = CurDAG->getCopyFromReg(Chain,
666          cast<RegisterSDNode>(N->getOperand(1))->getReg(), N->getValueType(0));
667     return New.getValue(Op.ResNo);
668   }
669   case ISD::CopyToReg: {
670     SDOperand Chain = Select(N->getOperand(0));
671     SDOperand Reg = N->getOperand(1);
672     SDOperand Val = Select(N->getOperand(2));
673     if (Chain != N->getOperand(0) || Val != N->getOperand(2)) {
674       SDOperand New = CurDAG->getNode(ISD::CopyToReg, MVT::Other,
675                                       Chain, Reg, Val);
676       CurDAG->ReplaceAllUsesWith(Op, New);
677       N = New.Val;
678     }
679     break;    
680   }
681   case ISD::Constant: {
682     assert(N->getValueType(0) == MVT::i32);
683     unsigned v = (unsigned)cast<ConstantSDNode>(N)->getValue();
684     unsigned Hi = HA16(v);
685     unsigned Lo = Lo16(v);
686     if (Hi && Lo) {
687       SDOperand Top = CurDAG->getTargetNode(PPC::LIS, MVT::i32, 
688                                             getI32Imm(v >> 16));
689       CurDAG->SelectNodeTo(N, PPC::ORI, MVT::i32, Top, getI32Imm(v & 0xFFFF));
690     } else if (Lo) {
691       CurDAG->SelectNodeTo(N, PPC::LI, MVT::i32, getI32Imm(v));
692     } else {
693       CurDAG->SelectNodeTo(N, PPC::LIS, MVT::i32, getI32Imm(v >> 16));
694     }
695     break;
696   }
697   case ISD::UNDEF:
698     if (N->getValueType(0) == MVT::i32)
699       CurDAG->SelectNodeTo(N, PPC::IMPLICIT_DEF_GPR, MVT::i32);
700     else
701       CurDAG->SelectNodeTo(N, PPC::IMPLICIT_DEF_FP, N->getValueType(0));
702     break;
703   case ISD::FrameIndex: {
704     int FI = cast<FrameIndexSDNode>(N)->getIndex();
705     CurDAG->SelectNodeTo(N, PPC::ADDI, MVT::i32,
706                          CurDAG->getTargetFrameIndex(FI, MVT::i32),
707                          getI32Imm(0));
708     break;
709   }
710   case ISD::ConstantPool: {
711     Constant *C = cast<ConstantPoolSDNode>(N)->get();
712     SDOperand Tmp, CPI = CurDAG->getTargetConstantPool(C, MVT::i32);
713     if (PICEnabled)
714       Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(),CPI);
715     else
716       Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, CPI);
717     CurDAG->SelectNodeTo(N, PPC::LA, MVT::i32, Tmp, CPI);
718     break;
719   }
720   case ISD::GlobalAddress: {
721     GlobalValue *GV = cast<GlobalAddressSDNode>(N)->getGlobal();
722     SDOperand Tmp;
723     SDOperand GA = CurDAG->getTargetGlobalAddress(GV, MVT::i32);
724     if (PICEnabled)
725       Tmp = CurDAG->getTargetNode(PPC::ADDIS, MVT::i32, getGlobalBaseReg(), GA);
726     else
727       Tmp = CurDAG->getTargetNode(PPC::LIS, MVT::i32, GA);
728
729     if (GV->hasWeakLinkage() || GV->isExternal())
730       CurDAG->SelectNodeTo(N, PPC::LWZ, MVT::i32, GA, Tmp);
731     else
732       CurDAG->SelectNodeTo(N, PPC::LA, MVT::i32, Tmp, GA);
733     break;
734   }
735   case ISD::SIGN_EXTEND_INREG:
736     switch(cast<VTSDNode>(N->getOperand(1))->getVT()) {
737     default: assert(0 && "Illegal type in SIGN_EXTEND_INREG"); break;
738     case MVT::i16:
739       CurDAG->SelectNodeTo(N, PPC::EXTSH, MVT::i32, Select(N->getOperand(0)));
740       break;
741     case MVT::i8:
742       CurDAG->SelectNodeTo(N, PPC::EXTSB, MVT::i32, Select(N->getOperand(0)));
743       break;
744     }
745     break;
746   case ISD::CTLZ:
747     assert(N->getValueType(0) == MVT::i32);
748     CurDAG->SelectNodeTo(N, PPC::CNTLZW, MVT::i32, Select(N->getOperand(0)));
749     break;
750   case ISD::ADD: {
751     MVT::ValueType Ty = N->getValueType(0);
752     if (Ty == MVT::i32) {
753       if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), N->getOperand(1),
754                                              PPC::ADDIS, PPC::ADDI, true)) {
755         CurDAG->ReplaceAllUsesWith(Op, SDOperand(I, 0));
756         N = I;
757       } else {
758         CurDAG->SelectNodeTo(N, PPC::ADD, MVT::i32, Select(N->getOperand(0)),
759                              Select(N->getOperand(1)));
760       }
761       break;
762     }
763     
764     if (!NoExcessFPPrecision) {  // Match FMA ops
765       if (N->getOperand(0).getOpcode() == ISD::MUL &&
766           N->getOperand(0).Val->hasOneUse()) {
767         ++FusedFP; // Statistic
768         CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FMADD : PPC::FMADDS, Ty,
769                              Select(N->getOperand(0).getOperand(0)),
770                              Select(N->getOperand(0).getOperand(1)),
771                              Select(N->getOperand(1)));
772         break;
773       } else if (N->getOperand(1).getOpcode() == ISD::MUL &&
774                  N->getOperand(1).hasOneUse()) {
775         ++FusedFP; // Statistic
776         CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FMADD : PPC::FMADDS, Ty,
777                              Select(N->getOperand(1).getOperand(0)),
778                              Select(N->getOperand(1).getOperand(1)),
779                              Select(N->getOperand(0)));
780         break;
781       }
782     }
783     
784     CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FADD : PPC::FADDS, Ty,
785                          Select(N->getOperand(0)), Select(N->getOperand(1)));
786     break;
787   }
788   case ISD::SUB: {
789     MVT::ValueType Ty = N->getValueType(0);
790     if (Ty == MVT::i32) {
791       unsigned Imm;
792       if (isIntImmediate(N->getOperand(0), Imm) && isInt16(Imm)) {
793         if (0 == Imm)
794           CurDAG->SelectNodeTo(N, PPC::NEG, Ty, Select(N->getOperand(1)));
795         else
796           CurDAG->SelectNodeTo(N, PPC::SUBFIC, Ty, Select(N->getOperand(1)),
797                                getI32Imm(Lo16(Imm)));
798         break;
799       }
800       if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), N->getOperand(1),
801                                           PPC::ADDIS, PPC::ADDI, true, true)) {
802         CurDAG->ReplaceAllUsesWith(Op, SDOperand(I, 0));
803         N = I;
804       } else {
805         CurDAG->SelectNodeTo(N, PPC::SUBF, Ty, Select(N->getOperand(1)),
806                              Select(N->getOperand(0)));
807       }
808       break;
809     }
810     
811     if (!NoExcessFPPrecision) {  // Match FMA ops
812       if (N->getOperand(0).getOpcode() == ISD::MUL &&
813           N->getOperand(0).Val->hasOneUse()) {
814         ++FusedFP; // Statistic
815         CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FMSUB : PPC::FMSUBS, Ty,
816                              Select(N->getOperand(0).getOperand(0)),
817                              Select(N->getOperand(0).getOperand(1)),
818                              Select(N->getOperand(1)));
819         break;
820       } else if (N->getOperand(1).getOpcode() == ISD::MUL &&
821                  N->getOperand(1).Val->hasOneUse()) {
822         ++FusedFP; // Statistic
823         CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FNMSUB : PPC::FNMSUBS, Ty,
824                              Select(N->getOperand(1).getOperand(0)),
825                              Select(N->getOperand(1).getOperand(1)),
826                              Select(N->getOperand(0)));
827         break;
828       }
829     }
830     CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FSUB : PPC::FSUBS, Ty,
831                          Select(N->getOperand(0)),
832                          Select(N->getOperand(1)));
833     break;
834   }
835   case ISD::MUL: {
836     unsigned Imm, Opc;
837     if (isIntImmediate(N->getOperand(1), Imm) && isInt16(Imm)) {
838       CurDAG->SelectNodeTo(N, PPC::MULLI, MVT::i32,
839                            Select(N->getOperand(0)), getI32Imm(Lo16(Imm)));
840       break;
841     } 
842     switch (N->getValueType(0)) {
843       default: assert(0 && "Unhandled multiply type!");
844       case MVT::i32: Opc = PPC::MULLW; break;
845       case MVT::f32: Opc = PPC::FMULS; break;
846       case MVT::f64: Opc = PPC::FMUL;  break;
847     }
848     CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), Select(N->getOperand(0)), 
849                          Select(N->getOperand(1)));
850     break;
851   }
852   case ISD::SDIV: {
853     unsigned Imm;
854     if (isIntImmediate(N->getOperand(1), Imm)) {
855       if ((signed)Imm > 0 && isPowerOf2_32(Imm)) {
856         SDOperand Op =
857           CurDAG->getTargetNode(PPC::SRAWI, MVT::i32, MVT::Flag,
858                                 Select(N->getOperand(0)),
859                                 getI32Imm(Log2_32(Imm)));
860         CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
861                              Op.getValue(0), Op.getValue(1));
862         break;
863       } else if ((signed)Imm < 0 && isPowerOf2_32(-Imm)) {
864         SDOperand Op =
865           CurDAG->getTargetNode(PPC::SRAWI, MVT::Flag, MVT::i32,
866                                 Select(N->getOperand(0)),
867                                 getI32Imm(Log2_32(-Imm)));
868         SDOperand PT =
869           CurDAG->getTargetNode(PPC::ADDZE, MVT::i32, Op.getValue(1),
870                                 Op.getValue(0));
871         CurDAG->SelectNodeTo(N, PPC::NEG, MVT::i32, PT);
872         break;
873       } else if (Imm) {
874         SDOperand Result = Select(BuildSDIVSequence(N));
875         assert(Result.ResNo == 0);
876         CurDAG->ReplaceAllUsesWith(Op, Result);
877         N = Result.Val;
878         break;
879       }
880     }
881     
882     unsigned Opc;
883     switch (N->getValueType(0)) {
884     default: assert(0 && "Unknown type to ISD::SDIV");
885     case MVT::i32: Opc = PPC::DIVW; break;
886     case MVT::f32: Opc = PPC::FDIVS; break;
887     case MVT::f64: Opc = PPC::FDIV; break;
888     }
889     CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), Select(N->getOperand(0)),
890                          Select(N->getOperand(1)));
891     break;
892   }
893   case ISD::UDIV: {
894     // If this is a divide by constant, we can emit code using some magic
895     // constants to implement it as a multiply instead.
896     unsigned Imm;
897     if (isIntImmediate(N->getOperand(1), Imm) && Imm) {
898       SDOperand Result = Select(BuildUDIVSequence(N));
899       assert(Result.ResNo == 0);
900       CurDAG->ReplaceAllUsesWith(Op, Result);
901       N = Result.Val;
902       break;
903     }
904     
905     CurDAG->SelectNodeTo(N, PPC::DIVWU, MVT::i32, Select(N->getOperand(0)),
906                          Select(N->getOperand(1)));
907     break;
908   }
909   case ISD::MULHS:
910     assert(N->getValueType(0) == MVT::i32);
911     CurDAG->SelectNodeTo(N, PPC::MULHW, MVT::i32, Select(N->getOperand(0)), 
912                          Select(N->getOperand(1)));
913     break;
914   case ISD::MULHU:
915     assert(N->getValueType(0) == MVT::i32);
916     CurDAG->SelectNodeTo(N, PPC::MULHWU, MVT::i32, Select(N->getOperand(0)),
917                          Select(N->getOperand(1)));
918     break;
919   case ISD::AND: {
920     unsigned Imm;
921     // If this is an and of a value rotated between 0 and 31 bits and then and'd
922     // with a mask, emit rlwinm
923     if (isIntImmediate(N->getOperand(1), Imm) && (isShiftedMask_32(Imm) ||
924                                                   isShiftedMask_32(~Imm))) {
925       SDOperand Val;
926       unsigned SH, MB, ME;
927       if (isRotateAndMask(N->getOperand(0).Val, Imm, false, SH, MB, ME)) {
928         Val = Select(N->getOperand(0).getOperand(0));
929       } else {
930         Val = Select(N->getOperand(0));
931         isRunOfOnes(Imm, MB, ME);
932         SH = 0;
933       }
934       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Val, getI32Imm(SH),
935                            getI32Imm(MB), getI32Imm(ME));
936       break;
937     }
938     // If this is an and with an immediate that isn't a mask, then codegen it as
939     // high and low 16 bit immediate ands.
940     if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), 
941                                            N->getOperand(1),
942                                            PPC::ANDISo, PPC::ANDIo)) {
943       CurDAG->ReplaceAllUsesWith(Op, SDOperand(I, 0));
944       N = I;
945       break;
946     }
947     // Finally, check for the case where we are being asked to select
948     // and (not(a), b) or and (a, not(b)) which can be selected as andc.
949     if (isOprNot(N->getOperand(0).Val))
950       CurDAG->SelectNodeTo(N, PPC::ANDC, MVT::i32, Select(N->getOperand(1)),
951                            Select(N->getOperand(0).getOperand(0)));
952     else if (isOprNot(N->getOperand(1).Val))
953       CurDAG->SelectNodeTo(N, PPC::ANDC, MVT::i32, Select(N->getOperand(0)),
954                            Select(N->getOperand(1).getOperand(0)));
955     else
956       CurDAG->SelectNodeTo(N, PPC::AND, MVT::i32, Select(N->getOperand(0)),
957                            Select(N->getOperand(1)));
958     break;
959   }
960   case ISD::OR:
961     if (SDNode *I = SelectBitfieldInsert(N)) {
962       CurDAG->ReplaceAllUsesWith(Op, SDOperand(I, 0));
963       N = I;
964       break;
965     }
966     if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), 
967                                            N->getOperand(1),
968                                            PPC::ORIS, PPC::ORI)) {
969       CurDAG->ReplaceAllUsesWith(Op, SDOperand(I, 0));
970       N = I;
971       break;
972     }
973     // Finally, check for the case where we are being asked to select
974     // 'or (not(a), b)' or 'or (a, not(b))' which can be selected as orc.
975     if (isOprNot(N->getOperand(0).Val))
976       CurDAG->SelectNodeTo(N, PPC::ORC, MVT::i32, Select(N->getOperand(1)),
977                            Select(N->getOperand(0).getOperand(0)));
978     else if (isOprNot(N->getOperand(1).Val))
979       CurDAG->SelectNodeTo(N, PPC::ORC, MVT::i32, Select(N->getOperand(0)),
980                            Select(N->getOperand(1).getOperand(0)));
981     else
982       CurDAG->SelectNodeTo(N, PPC::OR, MVT::i32, Select(N->getOperand(0)),
983                            Select(N->getOperand(1)));
984     break;
985   case ISD::XOR:
986     // Check whether or not this node is a logical 'not'.  This is represented
987     // by llvm as a xor with the constant value -1 (all bits set).  If this is a
988     // 'not', then fold 'or' into 'nor', and so forth for the supported ops.
989     if (isOprNot(N)) {
990       unsigned Opc;
991       SDOperand Val = Select(N->getOperand(0));
992       switch (Val.getTargetOpcode()) {
993       default:        Opc = 0;          break;
994       case PPC::OR:   Opc = PPC::NOR;   break;
995       case PPC::AND:  Opc = PPC::NAND;  break;
996       case PPC::XOR:  Opc = PPC::EQV;   break;
997       }
998       if (Opc)
999         CurDAG->SelectNodeTo(N, Opc, MVT::i32, Val.getOperand(0),
1000                              Val.getOperand(1));
1001       else
1002         CurDAG->SelectNodeTo(N, PPC::NOR, MVT::i32, Val, Val);
1003       break;
1004     }
1005     // If this is a xor with an immediate other than -1, then codegen it as high
1006     // and low 16 bit immediate xors.
1007     if (SDNode *I = SelectIntImmediateExpr(N->getOperand(0), 
1008                                            N->getOperand(1),
1009                                            PPC::XORIS, PPC::XORI)) {
1010       CurDAG->ReplaceAllUsesWith(Op, SDOperand(I, 0));
1011       N = I;
1012       break;
1013     }
1014     // Finally, check for the case where we are being asked to select
1015     // xor (not(a), b) which is equivalent to not(xor a, b), which is eqv
1016     if (isOprNot(N->getOperand(0).Val))
1017       CurDAG->SelectNodeTo(N, PPC::EQV, MVT::i32, 
1018                            Select(N->getOperand(0).getOperand(0)),
1019                            Select(N->getOperand(1)));
1020     else
1021       CurDAG->SelectNodeTo(N, PPC::XOR, MVT::i32, Select(N->getOperand(0)),
1022                            Select(N->getOperand(1)));
1023     break;
1024   case ISD::SHL: {
1025     unsigned Imm, SH, MB, ME;
1026     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1027         isRotateAndMask(N, Imm, true, SH, MB, ME))
1028       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1029                            Select(N->getOperand(0).getOperand(0)),
1030                            getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
1031     else if (isIntImmediate(N->getOperand(1), Imm))
1032       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Select(N->getOperand(0)),
1033                            getI32Imm(Imm), getI32Imm(0), getI32Imm(31-Imm));
1034     else
1035       CurDAG->SelectNodeTo(N, PPC::SLW, MVT::i32, Select(N->getOperand(0)),
1036                            Select(N->getOperand(1)));
1037     break;
1038   }
1039   case ISD::SRL: {
1040     unsigned Imm, SH, MB, ME;
1041     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1042         isRotateAndMask(N, Imm, true, SH, MB, ME))
1043       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1044                            Select(N->getOperand(0).getOperand(0)),
1045                            getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
1046     else if (isIntImmediate(N->getOperand(1), Imm))
1047       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Select(N->getOperand(0)),
1048                            getI32Imm(32-Imm), getI32Imm(Imm), getI32Imm(31));
1049     else
1050       CurDAG->SelectNodeTo(N, PPC::SRW, MVT::i32, Select(N->getOperand(0)),
1051                            Select(N->getOperand(1)));
1052     break;
1053   }
1054   case ISD::SRA: {
1055     unsigned Imm, SH, MB, ME;
1056     if (isOpcWithIntImmediate(N->getOperand(0).Val, ISD::AND, Imm) &&
1057         isRotateAndMask(N, Imm, true, SH, MB, ME))
1058       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, 
1059                            Select(N->getOperand(0).getOperand(0)),
1060                            getI32Imm(SH), getI32Imm(MB), getI32Imm(ME));
1061     else if (isIntImmediate(N->getOperand(1), Imm))
1062       CurDAG->SelectNodeTo(N, PPC::SRAWI, MVT::i32, Select(N->getOperand(0)), 
1063                            getI32Imm(Imm));
1064     else
1065       CurDAG->SelectNodeTo(N, PPC::SRAW, MVT::i32, Select(N->getOperand(0)),
1066                            Select(N->getOperand(1)));
1067     break;
1068   }
1069   case ISD::FABS:
1070     CurDAG->SelectNodeTo(N, PPC::FABS, N->getValueType(0), 
1071                          Select(N->getOperand(0)));
1072     break;
1073   case ISD::FP_EXTEND: {
1074     assert(MVT::f64 == N->getValueType(0) && 
1075            MVT::f32 == N->getOperand(0).getValueType() && "Illegal FP_EXTEND");
1076     SDOperand Tmp = Select(N->getOperand(0));
1077     CurDAG->ReplaceAllUsesWith(Op, Tmp);  // Just use the operand as the result.
1078     return Tmp;
1079   }
1080   case ISD::FP_ROUND:
1081     assert(MVT::f32 == N->getValueType(0) && 
1082            MVT::f64 == N->getOperand(0).getValueType() && "Illegal FP_ROUND");
1083     CurDAG->SelectNodeTo(N, PPC::FRSP, MVT::f32, Select(N->getOperand(0)));
1084     break;
1085   case ISD::FNEG: {
1086     SDOperand Val = Select(N->getOperand(0));
1087     MVT::ValueType Ty = N->getValueType(0);
1088     if (Val.Val->hasOneUse()) {
1089       unsigned Opc;
1090       switch (Val.getTargetOpcode()) {
1091       default:          Opc = 0;            break;
1092       case PPC::FABS:   Opc = PPC::FNABS;   break;
1093       case PPC::FMADD:  Opc = PPC::FNMADD;  break;
1094       case PPC::FMADDS: Opc = PPC::FNMADDS; break;
1095       case PPC::FMSUB:  Opc = PPC::FNMSUB;  break;
1096       case PPC::FMSUBS: Opc = PPC::FNMSUBS; break;
1097       }
1098       // If we inverted the opcode, then emit the new instruction with the
1099       // inverted opcode and the original instruction's operands.  Otherwise, 
1100       // fall through and generate a fneg instruction.
1101       if (Opc) {
1102         if (PPC::FNABS == Opc)
1103           CurDAG->SelectNodeTo(N, Opc, Ty, Val.getOperand(0));
1104         else
1105           CurDAG->SelectNodeTo(N, Opc, Ty, Val.getOperand(0),
1106                                Val.getOperand(1), Val.getOperand(2));
1107         break;
1108       }
1109     }
1110     CurDAG->SelectNodeTo(N, PPC::FNEG, Ty, Val);
1111     break;
1112   }
1113   case ISD::FSQRT: {
1114     MVT::ValueType Ty = N->getValueType(0);
1115     CurDAG->SelectNodeTo(N, Ty == MVT::f64 ? PPC::FSQRT : PPC::FSQRTS, Ty,
1116                          Select(N->getOperand(0)));
1117     break;
1118   }
1119     
1120   case ISD::ADD_PARTS: {
1121     SDOperand LHSL = Select(N->getOperand(0));
1122     SDOperand LHSH = Select(N->getOperand(1));
1123    
1124     unsigned Imm;
1125     bool ME = false, ZE = false;
1126     if (isIntImmediate(N->getOperand(3), Imm)) {
1127       ME = (signed)Imm == -1;
1128       ZE = Imm == 0;
1129     }
1130
1131     std::vector<SDOperand> Result;
1132     SDOperand CarryFromLo;
1133     if (isIntImmediate(N->getOperand(2), Imm) &&
1134         ((signed)Imm >= -32768 || (signed)Imm < 32768)) {
1135       // Codegen the low 32 bits of the add.  Interestingly, there is no
1136       // shifted form of add immediate carrying.
1137       CarryFromLo = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1138                                           LHSL, getI32Imm(Imm));
1139     } else {
1140       CarryFromLo = CurDAG->getTargetNode(PPC::ADDC, MVT::i32, MVT::Flag,
1141                                           LHSL, Select(N->getOperand(2)));
1142     }
1143     CarryFromLo = CarryFromLo.getValue(1);
1144     
1145     // Codegen the high 32 bits, adding zero, minus one, or the full value
1146     // along with the carry flag produced by addc/addic.
1147     SDOperand ResultHi;
1148     if (ZE)
1149       ResultHi = CurDAG->getTargetNode(PPC::ADDZE, MVT::i32, LHSH, CarryFromLo);
1150     else if (ME)
1151       ResultHi = CurDAG->getTargetNode(PPC::ADDME, MVT::i32, LHSH, CarryFromLo);
1152     else
1153       ResultHi = CurDAG->getTargetNode(PPC::ADDE, MVT::i32, LHSH,
1154                                        Select(N->getOperand(3)), CarryFromLo);
1155     Result.push_back(ResultHi);
1156     Result.push_back(CarryFromLo.getValue(0));
1157     CurDAG->ReplaceAllUsesWith(N, Result);
1158     return Result[Op.ResNo];
1159   }
1160   case ISD::SUB_PARTS: {
1161     SDOperand LHSL = Select(N->getOperand(0));
1162     SDOperand LHSH = Select(N->getOperand(1));
1163     SDOperand RHSL = Select(N->getOperand(2));
1164     SDOperand RHSH = Select(N->getOperand(3));
1165
1166     std::vector<SDOperand> Result;
1167     Result.push_back(CurDAG->getTargetNode(PPC::SUBFC, MVT::i32, MVT::Flag,
1168                                            RHSL, LHSL));
1169     Result.push_back(CurDAG->getTargetNode(PPC::SUBFE, MVT::i32, RHSH, LHSH,
1170                                            Result[0].getValue(1)));
1171     CurDAG->ReplaceAllUsesWith(N, Result);
1172     return Result[Op.ResNo];
1173   }
1174   case ISD::SHL_PARTS: {
1175     SDOperand HI = Select(N->getOperand(0));
1176     SDOperand LO = Select(N->getOperand(1));
1177     SDOperand SH = Select(N->getOperand(2));
1178     SDOperand SH_LO_R = CurDAG->getTargetNode(PPC::SUBFIC, MVT::i32, MVT::Flag,
1179                                               SH, getI32Imm(32));
1180     SDOperand SH_LO_L = CurDAG->getTargetNode(PPC::ADDI, MVT::i32, SH, 
1181                                           getI32Imm((unsigned)-32));
1182     SDOperand HI_SHL = CurDAG->getTargetNode(PPC::SLW, MVT::i32, HI, SH);
1183     SDOperand HI_LOR = CurDAG->getTargetNode(PPC::SRW, MVT::i32, LO, SH_LO_R);
1184     SDOperand HI_LOL = CurDAG->getTargetNode(PPC::SLW, MVT::i32, LO, SH_LO_L);
1185     SDOperand HI_OR =  CurDAG->getTargetNode(PPC::OR, MVT::i32, HI_SHL, HI_LOR);
1186
1187     std::vector<SDOperand> Result;
1188     Result.push_back(CurDAG->getTargetNode(PPC::SLW, MVT::i32, LO, SH));
1189     Result.push_back(CurDAG->getTargetNode(PPC::OR, MVT::i32, HI_OR, HI_LOL));
1190     CurDAG->ReplaceAllUsesWith(N, Result);
1191     return Result[Op.ResNo];
1192   }
1193   case ISD::SRL_PARTS: {
1194     SDOperand HI = Select(N->getOperand(0));
1195     SDOperand LO = Select(N->getOperand(1));
1196     SDOperand SH = Select(N->getOperand(2));
1197     SDOperand SH_HI_L = CurDAG->getTargetNode(PPC::SUBFIC, MVT::i32, MVT::Flag,
1198                                               SH, getI32Imm(32));
1199     SDOperand SH_HI_R = CurDAG->getTargetNode(PPC::ADDI, MVT::i32, SH, 
1200                                               getI32Imm((unsigned)-32));
1201     SDOperand LO_SHR = CurDAG->getTargetNode(PPC::SRW, MVT::i32, LO, SH);
1202     SDOperand LO_HIL = CurDAG->getTargetNode(PPC::SLW, MVT::i32, HI, SH_HI_L);
1203     SDOperand LO_HIR = CurDAG->getTargetNode(PPC::SRW, MVT::i32, HI, SH_HI_R);
1204     SDOperand LO_OR =  CurDAG->getTargetNode(PPC::OR, MVT::i32, LO_SHR, LO_HIL);
1205
1206     std::vector<SDOperand> Result;
1207     Result.push_back(CurDAG->getTargetNode(PPC::OR, MVT::i32, LO_OR, LO_HIR));
1208     Result.push_back(CurDAG->getTargetNode(PPC::SRW, MVT::i32, HI, SH));
1209     CurDAG->ReplaceAllUsesWith(N, Result);
1210     return Result[Op.ResNo];
1211   }
1212     
1213   case ISD::LOAD:
1214   case ISD::EXTLOAD:
1215   case ISD::ZEXTLOAD:
1216   case ISD::SEXTLOAD: {
1217     SDOperand Op1, Op2;
1218     bool isIdx = SelectAddr(N->getOperand(1), Op1, Op2);
1219
1220     MVT::ValueType TypeBeingLoaded = (N->getOpcode() == ISD::LOAD) ?
1221       N->getValueType(0) : cast<VTSDNode>(N->getOperand(3))->getVT();
1222     unsigned Opc;
1223     switch (TypeBeingLoaded) {
1224     default: N->dump(); assert(0 && "Cannot load this type!");
1225     case MVT::i1:
1226     case MVT::i8:  Opc = isIdx ? PPC::LBZX : PPC::LBZ; break;
1227     case MVT::i16:
1228       if (N->getOpcode() == ISD::SEXTLOAD) { // SEXT load?
1229         Opc = isIdx ? PPC::LHAX : PPC::LHA;
1230       } else {
1231         Opc = isIdx ? PPC::LHZX : PPC::LHZ;
1232       }
1233       break;
1234     case MVT::i32: Opc = isIdx ? PPC::LWZX : PPC::LWZ; break;
1235     case MVT::f32: Opc = isIdx ? PPC::LFSX : PPC::LFS; break;
1236     case MVT::f64: Opc = isIdx ? PPC::LFDX : PPC::LFD; break;
1237     }
1238
1239     CurDAG->SelectNodeTo(N, Opc, N->getValueType(0), MVT::Other,
1240                          Op1, Op2, Select(N->getOperand(0)));
1241     break;
1242   }
1243
1244   case ISD::TRUNCSTORE:
1245   case ISD::STORE: {
1246     SDOperand AddrOp1, AddrOp2;
1247     bool isIdx = SelectAddr(N->getOperand(2), AddrOp1, AddrOp2);
1248
1249     unsigned Opc;
1250     if (N->getOpcode() == ISD::STORE) {
1251       switch (N->getOperand(1).getValueType()) {
1252       default: assert(0 && "unknown Type in store");
1253       case MVT::i32: Opc = isIdx ? PPC::STWX  : PPC::STW; break;
1254       case MVT::f64: Opc = isIdx ? PPC::STFDX : PPC::STFD; break;
1255       case MVT::f32: Opc = isIdx ? PPC::STFSX : PPC::STFS; break;
1256       }
1257     } else { //ISD::TRUNCSTORE
1258       switch(cast<VTSDNode>(N->getOperand(4))->getVT()) {
1259       default: assert(0 && "unknown Type in store");
1260       case MVT::i1:
1261       case MVT::i8:  Opc = isIdx ? PPC::STBX : PPC::STB; break;
1262       case MVT::i16: Opc = isIdx ? PPC::STHX : PPC::STH; break;
1263       }
1264     }
1265     
1266     CurDAG->SelectNodeTo(N, Opc, MVT::Other, Select(N->getOperand(1)),
1267                          AddrOp1, AddrOp2, Select(N->getOperand(0)));
1268     break;
1269   }
1270     
1271   case ISD::SETCC: {
1272     unsigned Imm;
1273     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(2))->get();
1274     if (isIntImmediate(N->getOperand(1), Imm)) {
1275       // We can codegen setcc op, imm very efficiently compared to a brcond.
1276       // Check for those cases here.
1277       // setcc op, 0
1278       if (Imm == 0) {
1279         SDOperand Op = Select(N->getOperand(0));
1280         switch (CC) {
1281         default: assert(0 && "Unhandled SetCC condition"); abort();
1282         case ISD::SETEQ:
1283           Op = CurDAG->getTargetNode(PPC::CNTLZW, MVT::i32, Op);
1284           CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(27),
1285                                getI32Imm(5), getI32Imm(31));
1286           break;
1287         case ISD::SETNE: {
1288           SDOperand AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1289                                                Op, getI32Imm(~0U));
1290           CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
1291           break;
1292         }
1293         case ISD::SETLT:
1294           CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
1295                                getI32Imm(31), getI32Imm(31));
1296           break;
1297         case ISD::SETGT: {
1298           SDOperand T = CurDAG->getTargetNode(PPC::NEG, MVT::i32, Op);
1299           T = CurDAG->getTargetNode(PPC::ANDC, MVT::i32, T, Op);;
1300           CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, T, getI32Imm(1),
1301                                getI32Imm(31), getI32Imm(31));
1302           break;
1303         }
1304         }
1305         break;
1306       } else if (Imm == ~0U) {        // setcc op, -1
1307         SDOperand Op = Select(N->getOperand(0));
1308         switch (CC) {
1309         default: assert(0 && "Unhandled SetCC condition"); abort();
1310         case ISD::SETEQ:
1311           Op = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, MVT::Flag,
1312                                      Op, getI32Imm(1));
1313           CurDAG->SelectNodeTo(N, PPC::ADDZE, MVT::i32, 
1314                                CurDAG->getTargetNode(PPC::LI, MVT::i32,
1315                                                      getI32Imm(0)),
1316                                Op.getValue(1));
1317           break;
1318         case ISD::SETNE: {
1319           Op = CurDAG->getTargetNode(PPC::NOR, MVT::i32, Op, Op);
1320           SDOperand AD = CurDAG->getTargetNode(PPC::ADDIC, MVT::i32, Op,
1321                                                getI32Imm(~0U));
1322           CurDAG->SelectNodeTo(N, PPC::SUBFE, MVT::i32, AD, Op, AD.getValue(1));
1323           break;
1324         }
1325         case ISD::SETLT: {
1326           SDOperand AD = CurDAG->getTargetNode(PPC::ADDI, MVT::i32, Op,
1327                                                getI32Imm(1));
1328           SDOperand AN = CurDAG->getTargetNode(PPC::AND, MVT::i32, AD, Op);
1329           CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, AN, getI32Imm(1),
1330                                getI32Imm(31), getI32Imm(31));
1331           break;
1332         }
1333         case ISD::SETGT:
1334           Op = CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, Op, getI32Imm(1),
1335                                      getI32Imm(31), getI32Imm(31));
1336           CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Op, getI32Imm(1));
1337           break;
1338         }
1339         break;
1340       }
1341     }
1342     
1343     bool Inv;
1344     unsigned Idx = getCRIdxForSetCC(CC, Inv);
1345     SDOperand CCReg =
1346       SelectCC(Select(N->getOperand(0)), Select(N->getOperand(1)), CC);
1347     SDOperand IntCR;
1348
1349     // Force the ccreg into CR7.
1350     SDOperand CR7Reg = CurDAG->getRegister(PPC::CR7, MVT::i32);
1351     
1352     std::vector<MVT::ValueType> VTs;
1353     VTs.push_back(MVT::Other);
1354     VTs.push_back(MVT::Flag);    // NONSTANDARD CopyToReg node: defines a flag
1355     std::vector<SDOperand> Ops;
1356     Ops.push_back(CurDAG->getEntryNode());
1357     Ops.push_back(CR7Reg);
1358     Ops.push_back(CCReg);
1359     CCReg = CurDAG->getNode(ISD::CopyToReg, VTs, Ops).getValue(1);
1360     
1361     if (TLI.getTargetMachine().getSubtarget<PPCSubtarget>().isGigaProcessor())
1362       IntCR = CurDAG->getTargetNode(PPC::MFOCRF, MVT::i32, CR7Reg, CCReg);
1363     else
1364       IntCR = CurDAG->getTargetNode(PPC::MFCR, MVT::i32, CCReg);
1365     
1366     if (!Inv) {
1367       CurDAG->SelectNodeTo(N, PPC::RLWINM, MVT::i32, IntCR,
1368                            getI32Imm(32-(3-Idx)), getI32Imm(31), getI32Imm(31));
1369     } else {
1370       SDOperand Tmp =
1371       CurDAG->getTargetNode(PPC::RLWINM, MVT::i32, IntCR,
1372                             getI32Imm(32-(3-Idx)), getI32Imm(31),getI32Imm(31));
1373       CurDAG->SelectNodeTo(N, PPC::XORI, MVT::i32, Tmp, getI32Imm(1));
1374     }
1375       
1376     break;
1377   }
1378
1379   case ISD::CALLSEQ_START:
1380   case ISD::CALLSEQ_END: {
1381     unsigned Amt = cast<ConstantSDNode>(N->getOperand(1))->getValue();
1382     unsigned Opc = N->getOpcode() == ISD::CALLSEQ_START ?
1383                        PPC::ADJCALLSTACKDOWN : PPC::ADJCALLSTACKUP;
1384     CurDAG->SelectNodeTo(N, Opc, MVT::Other,
1385                          getI32Imm(Amt), Select(N->getOperand(0)));
1386     break;
1387   }
1388   case ISD::CALL:
1389   case ISD::TAILCALL: {
1390     SDOperand Chain = Select(N->getOperand(0));
1391
1392     unsigned CallOpcode;
1393     std::vector<SDOperand> CallOperands;
1394     
1395     if (GlobalAddressSDNode *GASD =
1396         dyn_cast<GlobalAddressSDNode>(N->getOperand(1))) {
1397       CallOpcode = PPC::CALLpcrel;
1398       CallOperands.push_back(CurDAG->getTargetGlobalAddress(GASD->getGlobal(),
1399                                                             MVT::i32));
1400     } else if (ExternalSymbolSDNode *ESSDN =
1401                dyn_cast<ExternalSymbolSDNode>(N->getOperand(1))) {
1402       CallOpcode = PPC::CALLpcrel;
1403       CallOperands.push_back(N->getOperand(1));
1404     } else {
1405       // Copy the callee address into the CTR register.
1406       SDOperand Callee = Select(N->getOperand(1));
1407       Chain = CurDAG->getTargetNode(PPC::MTCTR, MVT::Other, Callee, Chain);
1408
1409       // Copy the callee address into R12 on darwin.
1410       SDOperand R12 = CurDAG->getRegister(PPC::R12, MVT::i32);
1411       Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, R12, Callee, Chain);
1412       
1413       CallOperands.push_back(getI32Imm(20));  // Information to encode indcall
1414       CallOperands.push_back(getI32Imm(0));   // Information to encode indcall
1415       CallOperands.push_back(R12);
1416       CallOpcode = PPC::CALLindirect;
1417     }
1418     
1419     unsigned GPR_idx = 0, FPR_idx = 0;
1420     static const unsigned GPR[] = {
1421       PPC::R3, PPC::R4, PPC::R5, PPC::R6,
1422       PPC::R7, PPC::R8, PPC::R9, PPC::R10,
1423     };
1424     static const unsigned FPR[] = {
1425       PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
1426       PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
1427     };
1428     
1429     for (unsigned i = 2, e = N->getNumOperands(); i != e; ++i)
1430       if (N->getOperand(i).getOpcode() != ISD::UNDEF) {
1431         unsigned DestReg = 0;
1432         MVT::ValueType RegTy;
1433         if (N->getOperand(i).getValueType() == MVT::i32) {
1434           assert(GPR_idx < 8 && "Too many int args");
1435           DestReg = GPR[GPR_idx++];
1436           RegTy = MVT::i32;
1437         } else {
1438           assert(MVT::isFloatingPoint(N->getOperand(i).getValueType()) &&
1439                  "Unpromoted integer arg?");
1440           assert(FPR_idx < 13 && "Too many fp args");
1441           DestReg = FPR[FPR_idx++];
1442           RegTy = MVT::f64;   // Even if this is really f32!
1443         }
1444         
1445         SDOperand Reg = CurDAG->getRegister(DestReg, RegTy);
1446         Chain = CurDAG->getNode(ISD::CopyToReg, MVT::Other, Chain, Reg,
1447                                 Select(N->getOperand(i)));
1448         CallOperands.push_back(Reg);
1449       }
1450
1451     // Finally, once everything is in registers to pass to the call, emit the
1452     // call itself.
1453     CallOperands.push_back(Chain);
1454     Chain = CurDAG->getTargetNode(CallOpcode, MVT::Other, CallOperands);
1455     
1456     std::vector<SDOperand> CallResults;
1457     
1458     // If the call has results, copy the values out of the ret val registers.
1459     switch (N->getValueType(0)) {
1460     default: assert(0 && "Unexpected ret value!");
1461     case MVT::Other: break;
1462     case MVT::i32:
1463       if (N->getValueType(1) == MVT::i32) {
1464         Chain = CurDAG->getCopyFromReg(Chain, PPC::R4, MVT::i32).getValue(1);
1465         CallResults.push_back(Chain.getValue(0));
1466         Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32).getValue(1);
1467         CallResults.push_back(Chain.getValue(0));
1468       } else {
1469         Chain = CurDAG->getCopyFromReg(Chain, PPC::R3, MVT::i32).getValue(1);
1470         CallResults.push_back(Chain.getValue(0));
1471       }
1472       break;
1473     case MVT::f32:
1474     case MVT::f64:
1475       Chain = CurDAG->getCopyFromReg(Chain, PPC::F1, MVT::f64).getValue(1);
1476       CallResults.push_back(Chain.getValue(0));
1477       break;
1478     }
1479     
1480     CallResults.push_back(Chain);
1481     CurDAG->ReplaceAllUsesWith(N, CallResults);
1482     return CallResults[Op.ResNo];
1483   }
1484   case ISD::RET: {
1485     SDOperand Chain = Select(N->getOperand(0));     // Token chain.
1486
1487     if (N->getNumOperands() > 1) {
1488       SDOperand Val = Select(N->getOperand(1));
1489       switch (N->getOperand(1).getValueType()) {
1490       default: assert(0 && "Unknown return type!");
1491       case MVT::f64:
1492       case MVT::f32:
1493         Chain = CurDAG->getCopyToReg(Chain, PPC::F1, Val);
1494         break;
1495       case MVT::i32:
1496         Chain = CurDAG->getCopyToReg(Chain, PPC::R3, Val);
1497         break;
1498       }
1499
1500       if (N->getNumOperands() > 2) {
1501         assert(N->getOperand(1).getValueType() == MVT::i32 &&
1502                N->getOperand(2).getValueType() == MVT::i32 &&
1503                N->getNumOperands() == 3 && "Unknown two-register ret value!");
1504         Val = Select(N->getOperand(2));
1505         Chain = CurDAG->getCopyToReg(Chain, PPC::R4, Val);
1506       }
1507     }
1508
1509     // Finally, select this to a blr (return) instruction.
1510     CurDAG->SelectNodeTo(N, PPC::BLR, MVT::Other, Chain);
1511     break;
1512   }
1513   case ISD::BR:
1514     CurDAG->SelectNodeTo(N, PPC::B, MVT::Other, N->getOperand(1),
1515                          Select(N->getOperand(0)));
1516     break;
1517   case ISD::BR_CC:
1518   case ISD::BRTWOWAY_CC: {
1519     SDOperand Chain = Select(N->getOperand(0));
1520     MachineBasicBlock *Dest =
1521       cast<BasicBlockSDNode>(N->getOperand(4))->getBasicBlock();
1522     ISD::CondCode CC = cast<CondCodeSDNode>(N->getOperand(1))->get();
1523     SDOperand CondCode = SelectCC(N->getOperand(2), N->getOperand(3), CC);
1524     unsigned Opc = getBCCForSetCC(CC);
1525
1526     // If this is a two way branch, then grab the fallthrough basic block
1527     // argument and build a PowerPC branch pseudo-op, suitable for long branch
1528     // conversion if necessary by the branch selection pass.  Otherwise, emit a
1529     // standard conditional branch.
1530     if (N->getOpcode() == ISD::BRTWOWAY_CC) {
1531       MachineBasicBlock *Fallthrough =
1532         cast<BasicBlockSDNode>(N->getOperand(5))->getBasicBlock();
1533       SDOperand CB = CurDAG->getTargetNode(PPC::COND_BRANCH, MVT::Other,
1534                                            CondCode, getI32Imm(Opc),
1535                                            N->getOperand(4), N->getOperand(5),
1536                                            Chain);
1537       CurDAG->SelectNodeTo(N, PPC::B, MVT::Other, N->getOperand(5), CB);
1538     } else {
1539       // Iterate to the next basic block
1540       ilist<MachineBasicBlock>::iterator It = BB;
1541       ++It;
1542
1543       // If the fallthrough path is off the end of the function, which would be
1544       // undefined behavior, set it to be the same as the current block because
1545       // we have nothing better to set it to, and leaving it alone will cause
1546       // the PowerPC Branch Selection pass to crash.
1547       if (It == BB->getParent()->end()) It = Dest;
1548       CurDAG->SelectNodeTo(N, PPC::COND_BRANCH, MVT::Other, CondCode,
1549                            getI32Imm(Opc), N->getOperand(4),
1550                            CurDAG->getBasicBlock(It), Chain);
1551     }
1552     break;
1553   }
1554   }
1555   return SDOperand(N, Op.ResNo);
1556 }
1557
1558
1559 /// createPPC32ISelDag - This pass converts a legalized DAG into a 
1560 /// PowerPC-specific DAG, ready for instruction scheduling.
1561 ///
1562 FunctionPass *llvm::createPPC32ISelDag(TargetMachine &TM) {
1563   return new PPC32DAGToDAGISel(TM);
1564 }
1565