Vector op lowering.
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPCISelLowering.cpp - PPC DAG Lowering Implementation -------------===//
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 implements the PPCISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPCISelLowering.h"
15 #include "PPCTargetMachine.h"
16 #include "llvm/ADT/VectorExtras.h"
17 #include "llvm/CodeGen/MachineFrameInfo.h"
18 #include "llvm/CodeGen/MachineFunction.h"
19 #include "llvm/CodeGen/MachineInstrBuilder.h"
20 #include "llvm/CodeGen/SelectionDAG.h"
21 #include "llvm/CodeGen/SSARegMap.h"
22 #include "llvm/Constants.h"
23 #include "llvm/Function.h"
24 #include "llvm/Support/MathExtras.h"
25 #include "llvm/Target/TargetOptions.h"
26 using namespace llvm;
27
28 PPCTargetLowering::PPCTargetLowering(TargetMachine &TM)
29   : TargetLowering(TM) {
30     
31   // Fold away setcc operations if possible.
32   setSetCCIsExpensive();
33   setPow2DivIsCheap();
34   
35   // Use _setjmp/_longjmp instead of setjmp/longjmp.
36   setUseUnderscoreSetJmpLongJmp(true);
37     
38   // Set up the register classes.
39   addRegisterClass(MVT::i32, PPC::GPRCRegisterClass);
40   addRegisterClass(MVT::f32, PPC::F4RCRegisterClass);
41   addRegisterClass(MVT::f64, PPC::F8RCRegisterClass);
42   
43   setOperationAction(ISD::ConstantFP, MVT::f64, Expand);
44   setOperationAction(ISD::ConstantFP, MVT::f32, Expand);
45
46   // PowerPC has no intrinsics for these particular operations
47   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
48   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
49   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
50   
51   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
52   setOperationAction(ISD::SEXTLOAD, MVT::i1, Expand);
53   setOperationAction(ISD::SEXTLOAD, MVT::i8, Expand);
54   
55   // PowerPC has no SREM/UREM instructions
56   setOperationAction(ISD::SREM, MVT::i32, Expand);
57   setOperationAction(ISD::UREM, MVT::i32, Expand);
58   
59   // We don't support sin/cos/sqrt/fmod
60   setOperationAction(ISD::FSIN , MVT::f64, Expand);
61   setOperationAction(ISD::FCOS , MVT::f64, Expand);
62   setOperationAction(ISD::FREM , MVT::f64, Expand);
63   setOperationAction(ISD::FSIN , MVT::f32, Expand);
64   setOperationAction(ISD::FCOS , MVT::f32, Expand);
65   setOperationAction(ISD::FREM , MVT::f32, Expand);
66   
67   // If we're enabling GP optimizations, use hardware square root
68   if (!TM.getSubtarget<PPCSubtarget>().hasFSQRT()) {
69     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
70     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
71   }
72   
73   // PowerPC does not have BSWAP, CTPOP or CTTZ
74   setOperationAction(ISD::BSWAP, MVT::i32  , Expand);
75   setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
76   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
77   
78   // PowerPC does not have ROTR
79   setOperationAction(ISD::ROTR, MVT::i32   , Expand);
80   
81   // PowerPC does not have Select
82   setOperationAction(ISD::SELECT, MVT::i32, Expand);
83   setOperationAction(ISD::SELECT, MVT::f32, Expand);
84   setOperationAction(ISD::SELECT, MVT::f64, Expand);
85   
86   // PowerPC wants to turn select_cc of FP into fsel when possible.
87   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
88   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
89
90   // PowerPC wants to optimize integer setcc a bit
91   setOperationAction(ISD::SETCC, MVT::i32, Custom);
92   
93   // PowerPC does not have BRCOND* which requires SetCC
94   setOperationAction(ISD::BRCOND,       MVT::Other, Expand);
95   setOperationAction(ISD::BRCONDTWOWAY, MVT::Other, Expand);
96   
97   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
98   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
99
100   // PowerPC does not have [U|S]INT_TO_FP
101   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
102   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
103
104   setOperationAction(ISD::BIT_CONVERT, MVT::f32, Expand);
105   setOperationAction(ISD::BIT_CONVERT, MVT::i32, Expand);
106
107   // PowerPC does not have truncstore for i1.
108   setOperationAction(ISD::TRUNCSTORE, MVT::i1, Promote);
109
110   // Support label based line numbers.
111   setOperationAction(ISD::LOCATION, MVT::Other, Expand);
112   setOperationAction(ISD::DEBUG_LOC, MVT::Other, Expand);
113   // FIXME - use subtarget debug flags
114   if (!TM.getSubtarget<PPCSubtarget>().isDarwin())
115     setOperationAction(ISD::DEBUG_LABEL, MVT::Other, Expand);
116   
117   // We want to legalize GlobalAddress and ConstantPool nodes into the 
118   // appropriate instructions to materialize the address.
119   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
120   setOperationAction(ISD::ConstantPool,  MVT::i32, Custom);
121
122   // RET must be custom lowered, to meet ABI requirements
123   setOperationAction(ISD::RET               , MVT::Other, Custom);
124   
125   // VASTART needs to be custom lowered to use the VarArgsFrameIndex
126   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
127   
128   // Use the default implementation.
129   setOperationAction(ISD::VAARG             , MVT::Other, Expand);
130   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
131   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
132   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand); 
133   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
134   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Expand);
135   
136   if (TM.getSubtarget<PPCSubtarget>().is64Bit()) {
137     // They also have instructions for converting between i64 and fp.
138     setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
139     setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
140     // To take advantage of the above i64 FP_TO_SINT, promote i32 FP_TO_UINT
141     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Promote);
142   } else {
143     // PowerPC does not have FP_TO_UINT on 32-bit implementations.
144     setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
145   }
146
147   if (TM.getSubtarget<PPCSubtarget>().has64BitRegs()) {
148     // 64 bit PowerPC implementations can support i64 types directly
149     addRegisterClass(MVT::i64, PPC::G8RCRegisterClass);
150     // BUILD_PAIR can't be handled natively, and should be expanded to shl/or
151     setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
152   } else {
153     // 32 bit PowerPC wants to expand i64 shifts itself.
154     setOperationAction(ISD::SHL, MVT::i64, Custom);
155     setOperationAction(ISD::SRL, MVT::i64, Custom);
156     setOperationAction(ISD::SRA, MVT::i64, Custom);
157   }
158   
159   // First set operation action for all vector types to expand. Then we
160   // will selectively turn on ones that can be effectively codegen'd.
161   for (unsigned VT = (unsigned)MVT::Vector + 1;
162        VT != (unsigned)MVT::LAST_VALUETYPE; VT++) {
163     setOperationAction(ISD::ADD , (MVT::ValueType)VT, Expand);
164     setOperationAction(ISD::SUB , (MVT::ValueType)VT, Expand);
165     setOperationAction(ISD::MUL , (MVT::ValueType)VT, Expand);
166     setOperationAction(ISD::LOAD, (MVT::ValueType)VT, Expand);
167   }
168
169   if (TM.getSubtarget<PPCSubtarget>().hasAltivec()) {
170     addRegisterClass(MVT::v4f32, PPC::VRRCRegisterClass);
171     addRegisterClass(MVT::v4i32, PPC::VRRCRegisterClass);
172     
173     setOperationAction(ISD::ADD        , MVT::v4f32, Legal);
174     setOperationAction(ISD::SUB        , MVT::v4f32, Legal);
175     setOperationAction(ISD::MUL        , MVT::v4f32, Legal);
176     setOperationAction(ISD::LOAD       , MVT::v4f32, Legal);
177     setOperationAction(ISD::ADD        , MVT::v4i32, Legal);
178     setOperationAction(ISD::LOAD       , MVT::v4i32, Legal);
179     // FIXME: We don't support any ConstantVec's yet.  We should custom expand
180     // the ones we do!
181     setOperationAction(ISD::ConstantVec, MVT::v4f32, Expand);
182     setOperationAction(ISD::ConstantVec, MVT::v4i32, Expand);
183   }
184   
185   setSetCCResultContents(ZeroOrOneSetCCResult);
186   setStackPointerRegisterToSaveRestore(PPC::R1);
187   
188   computeRegisterProperties();
189 }
190
191 const char *PPCTargetLowering::getTargetNodeName(unsigned Opcode) const {
192   switch (Opcode) {
193   default: return 0;
194   case PPCISD::FSEL:          return "PPCISD::FSEL";
195   case PPCISD::FCFID:         return "PPCISD::FCFID";
196   case PPCISD::FCTIDZ:        return "PPCISD::FCTIDZ";
197   case PPCISD::FCTIWZ:        return "PPCISD::FCTIWZ";
198   case PPCISD::VMADDFP:       return "PPCISD::VMADDFP";
199   case PPCISD::VNMSUBFP:      return "PPCISD::VNMSUBFP";
200   case PPCISD::Hi:            return "PPCISD::Hi";
201   case PPCISD::Lo:            return "PPCISD::Lo";
202   case PPCISD::GlobalBaseReg: return "PPCISD::GlobalBaseReg";
203   case PPCISD::SRL:           return "PPCISD::SRL";
204   case PPCISD::SRA:           return "PPCISD::SRA";
205   case PPCISD::SHL:           return "PPCISD::SHL";
206   case PPCISD::CALL:          return "PPCISD::CALL";
207   case PPCISD::RET_FLAG:      return "PPCISD::RET_FLAG";
208   }
209 }
210
211 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
212 static bool isFloatingPointZero(SDOperand Op) {
213   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
214     return CFP->isExactlyValue(-0.0) || CFP->isExactlyValue(0.0);
215   else if (Op.getOpcode() == ISD::EXTLOAD || Op.getOpcode() == ISD::LOAD) {
216     // Maybe this has already been legalized into the constant pool?
217     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
218       if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->get()))
219         return CFP->isExactlyValue(-0.0) || CFP->isExactlyValue(0.0);
220   }
221   return false;
222 }
223
224 /// LowerOperation - Provide custom lowering hooks for some operations.
225 ///
226 SDOperand PPCTargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
227   switch (Op.getOpcode()) {
228   default: assert(0 && "Wasn't expecting to be able to lower this!"); 
229   case ISD::FP_TO_SINT: {
230     assert(MVT::isFloatingPoint(Op.getOperand(0).getValueType()));
231     SDOperand Src = Op.getOperand(0);
232     if (Src.getValueType() == MVT::f32)
233       Src = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Src);
234     
235     SDOperand Tmp;
236     switch (Op.getValueType()) {
237     default: assert(0 && "Unhandled FP_TO_SINT type in custom expander!");
238     case MVT::i32:
239       Tmp = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Src);
240       break;
241     case MVT::i64:
242       Tmp = DAG.getNode(PPCISD::FCTIDZ, MVT::f64, Src);
243       break;
244     }
245    
246     // Convert the FP value to an int value through memory.
247     SDOperand Bits = DAG.getNode(ISD::BIT_CONVERT, MVT::i64, Tmp);
248     if (Op.getValueType() == MVT::i32)
249       Bits = DAG.getNode(ISD::TRUNCATE, MVT::i32, Bits);
250     return Bits;
251   }
252   case ISD::SINT_TO_FP: {
253     assert(MVT::i64 == Op.getOperand(0).getValueType() && 
254            "Unhandled SINT_TO_FP type in custom expander!");
255     SDOperand Bits = DAG.getNode(ISD::BIT_CONVERT, MVT::f64, Op.getOperand(0));
256     SDOperand FP = DAG.getNode(PPCISD::FCFID, MVT::f64, Bits);
257     if (MVT::f32 == Op.getValueType())
258       FP = DAG.getNode(ISD::FP_ROUND, MVT::f32, FP);
259     return FP;
260   }
261   case ISD::SELECT_CC: {
262     // Turn FP only select_cc's into fsel instructions.
263     if (!MVT::isFloatingPoint(Op.getOperand(0).getValueType()) ||
264         !MVT::isFloatingPoint(Op.getOperand(2).getValueType()))
265       break;
266     
267     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
268     
269     // Cannot handle SETEQ/SETNE.
270     if (CC == ISD::SETEQ || CC == ISD::SETNE) break;
271     
272     MVT::ValueType ResVT = Op.getValueType();
273     MVT::ValueType CmpVT = Op.getOperand(0).getValueType();
274     SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
275     SDOperand TV  = Op.getOperand(2), FV  = Op.getOperand(3);
276
277     // If the RHS of the comparison is a 0.0, we don't need to do the
278     // subtraction at all.
279     if (isFloatingPointZero(RHS))
280       switch (CC) {
281       default: break;       // SETUO etc aren't handled by fsel.
282       case ISD::SETULT:
283       case ISD::SETLT:
284         std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
285       case ISD::SETUGE:
286       case ISD::SETGE:
287         if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
288           LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
289         return DAG.getNode(PPCISD::FSEL, ResVT, LHS, TV, FV);
290       case ISD::SETUGT:
291       case ISD::SETGT:
292         std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
293       case ISD::SETULE:
294       case ISD::SETLE:
295         if (LHS.getValueType() == MVT::f32)   // Comparison is always 64-bits
296           LHS = DAG.getNode(ISD::FP_EXTEND, MVT::f64, LHS);
297         return DAG.getNode(PPCISD::FSEL, ResVT,
298                            DAG.getNode(ISD::FNEG, MVT::f64, LHS), TV, FV);
299       }
300     
301     SDOperand Cmp;
302     switch (CC) {
303     default: break;       // SETUO etc aren't handled by fsel.
304     case ISD::SETULT:
305     case ISD::SETLT:
306       Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
307       if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
308         Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
309       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
310     case ISD::SETUGE:
311     case ISD::SETGE:
312       Cmp = DAG.getNode(ISD::FSUB, CmpVT, LHS, RHS);
313       if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
314         Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
315       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
316     case ISD::SETUGT:
317     case ISD::SETGT:
318       Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
319       if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
320         Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
321       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, FV, TV);
322     case ISD::SETULE:
323     case ISD::SETLE:
324       Cmp = DAG.getNode(ISD::FSUB, CmpVT, RHS, LHS);
325       if (Cmp.getValueType() == MVT::f32)   // Comparison is always 64-bits
326         Cmp = DAG.getNode(ISD::FP_EXTEND, MVT::f64, Cmp);
327       return DAG.getNode(PPCISD::FSEL, ResVT, Cmp, TV, FV);
328     }
329     break;
330   }
331   case ISD::SHL: {
332     assert(Op.getValueType() == MVT::i64 &&
333            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SHL!");
334     // The generic code does a fine job expanding shift by a constant.
335     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
336     
337     // Otherwise, expand into a bunch of logical ops.  Note that these ops
338     // depend on the PPC behavior for oversized shift amounts.
339     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
340                                DAG.getConstant(0, MVT::i32));
341     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
342                                DAG.getConstant(1, MVT::i32));
343     SDOperand Amt = Op.getOperand(1);
344     
345     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
346                                  DAG.getConstant(32, MVT::i32), Amt);
347     SDOperand Tmp2 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Amt);
348     SDOperand Tmp3 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Tmp1);
349     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
350     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
351                                  DAG.getConstant(-32U, MVT::i32));
352     SDOperand Tmp6 = DAG.getNode(PPCISD::SHL, MVT::i32, Lo, Tmp5);
353     SDOperand OutHi = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
354     SDOperand OutLo = DAG.getNode(PPCISD::SHL, MVT::i32, Lo, Amt);
355     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
356   }
357   case ISD::SRL: {
358     assert(Op.getValueType() == MVT::i64 &&
359            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SHL!");
360     // The generic code does a fine job expanding shift by a constant.
361     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
362     
363     // Otherwise, expand into a bunch of logical ops.  Note that these ops
364     // depend on the PPC behavior for oversized shift amounts.
365     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
366                                DAG.getConstant(0, MVT::i32));
367     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
368                                DAG.getConstant(1, MVT::i32));
369     SDOperand Amt = Op.getOperand(1);
370     
371     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
372                                  DAG.getConstant(32, MVT::i32), Amt);
373     SDOperand Tmp2 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Amt);
374     SDOperand Tmp3 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Tmp1);
375     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
376     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
377                                  DAG.getConstant(-32U, MVT::i32));
378     SDOperand Tmp6 = DAG.getNode(PPCISD::SRL, MVT::i32, Hi, Tmp5);
379     SDOperand OutLo = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
380     SDOperand OutHi = DAG.getNode(PPCISD::SRL, MVT::i32, Hi, Amt);
381     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
382   }    
383   case ISD::SRA: {
384     assert(Op.getValueType() == MVT::i64 &&
385            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SRA!");
386     // The generic code does a fine job expanding shift by a constant.
387     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
388       
389     // Otherwise, expand into a bunch of logical ops, followed by a select_cc.
390     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
391                                DAG.getConstant(0, MVT::i32));
392     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
393                                DAG.getConstant(1, MVT::i32));
394     SDOperand Amt = Op.getOperand(1);
395     
396     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
397                                  DAG.getConstant(32, MVT::i32), Amt);
398     SDOperand Tmp2 = DAG.getNode(PPCISD::SRL, MVT::i32, Lo, Amt);
399     SDOperand Tmp3 = DAG.getNode(PPCISD::SHL, MVT::i32, Hi, Tmp1);
400     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
401     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
402                                  DAG.getConstant(-32U, MVT::i32));
403     SDOperand Tmp6 = DAG.getNode(PPCISD::SRA, MVT::i32, Hi, Tmp5);
404     SDOperand OutHi = DAG.getNode(PPCISD::SRA, MVT::i32, Hi, Amt);
405     SDOperand OutLo = DAG.getSelectCC(Tmp5, DAG.getConstant(0, MVT::i32),
406                                       Tmp4, Tmp6, ISD::SETLE);
407     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
408   }
409   case ISD::ConstantPool: {
410     ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
411     Constant *C = CP->get();
412     SDOperand CPI = DAG.getTargetConstantPool(C, MVT::i32, CP->getAlignment());
413     SDOperand Zero = DAG.getConstant(0, MVT::i32);
414     
415     if (getTargetMachine().getRelocationModel() == Reloc::Static) {
416       // Generate non-pic code that has direct accesses to the constant pool.
417       // The address of the global is just (hi(&g)+lo(&g)).
418       SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, CPI, Zero);
419       SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, CPI, Zero);
420       return DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
421     }
422     
423     // Only lower ConstantPool on Darwin.
424     if (!getTargetMachine().getSubtarget<PPCSubtarget>().isDarwin()) break;
425     SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, CPI, Zero);
426     if (getTargetMachine().getRelocationModel() == Reloc::PIC) {
427       // With PIC, the first instruction is actually "GR+hi(&G)".
428       Hi = DAG.getNode(ISD::ADD, MVT::i32,
429                        DAG.getNode(PPCISD::GlobalBaseReg, MVT::i32), Hi);
430     }
431
432     SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, CPI, Zero);
433     Lo = DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
434     return Lo;
435   }
436   case ISD::GlobalAddress: {
437     GlobalAddressSDNode *GSDN = cast<GlobalAddressSDNode>(Op);
438     GlobalValue *GV = GSDN->getGlobal();
439     SDOperand GA = DAG.getTargetGlobalAddress(GV, MVT::i32, GSDN->getOffset());
440     SDOperand Zero = DAG.getConstant(0, MVT::i32);
441
442     if (getTargetMachine().getRelocationModel() == Reloc::Static) {
443       // Generate non-pic code that has direct accesses to globals.
444       // The address of the global is just (hi(&g)+lo(&g)).
445       SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, GA, Zero);
446       SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, GA, Zero);
447       return DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
448     }
449     
450     // Only lower GlobalAddress on Darwin.
451     if (!getTargetMachine().getSubtarget<PPCSubtarget>().isDarwin()) break;
452     
453     SDOperand Hi = DAG.getNode(PPCISD::Hi, MVT::i32, GA, Zero);
454     if (getTargetMachine().getRelocationModel() == Reloc::PIC) {
455       // With PIC, the first instruction is actually "GR+hi(&G)".
456       Hi = DAG.getNode(ISD::ADD, MVT::i32,
457                        DAG.getNode(PPCISD::GlobalBaseReg, MVT::i32), Hi);
458     }
459     
460     SDOperand Lo = DAG.getNode(PPCISD::Lo, MVT::i32, GA, Zero);
461     Lo = DAG.getNode(ISD::ADD, MVT::i32, Hi, Lo);
462                                    
463     if (!GV->hasWeakLinkage() && !GV->hasLinkOnceLinkage() &&
464         (!GV->isExternal() || GV->hasNotBeenReadFromBytecode()))
465       return Lo;
466
467     // If the global is weak or external, we have to go through the lazy
468     // resolution stub.
469     return DAG.getLoad(MVT::i32, DAG.getEntryNode(), Lo, DAG.getSrcValue(0));
470   }
471   case ISD::SETCC: {
472     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
473     
474     // If we're comparing for equality to zero, expose the fact that this is
475     // implented as a ctlz/srl pair on ppc, so that the dag combiner can
476     // fold the new nodes.
477     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
478       if (C->isNullValue() && CC == ISD::SETEQ) {
479         MVT::ValueType VT = Op.getOperand(0).getValueType();
480         SDOperand Zext = Op.getOperand(0);
481         if (VT < MVT::i32) {
482           VT = MVT::i32;
483           Zext = DAG.getNode(ISD::ZERO_EXTEND, VT, Op.getOperand(0));
484         } 
485         unsigned Log2b = Log2_32(MVT::getSizeInBits(VT));
486         SDOperand Clz = DAG.getNode(ISD::CTLZ, VT, Zext);
487         SDOperand Scc = DAG.getNode(ISD::SRL, VT, Clz,
488                                     DAG.getConstant(Log2b, getShiftAmountTy()));
489         return DAG.getNode(ISD::TRUNCATE, getSetCCResultTy(), Scc);
490       }
491       // Leave comparisons against 0 and -1 alone for now, since they're usually 
492       // optimized.  FIXME: revisit this when we can custom lower all setcc
493       // optimizations.
494       if (C->isAllOnesValue() || C->isNullValue())
495         break;
496     }
497         
498     // If we have an integer seteq/setne, turn it into a compare against zero
499     // by subtracting the rhs from the lhs, which is faster than setting a
500     // condition register, reading it back out, and masking the correct bit.
501     MVT::ValueType LHSVT = Op.getOperand(0).getValueType();
502     if (MVT::isInteger(LHSVT) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
503       MVT::ValueType VT = Op.getValueType();
504       SDOperand Sub = DAG.getNode(ISD::SUB, LHSVT, Op.getOperand(0), 
505                                   Op.getOperand(1));
506       return DAG.getSetCC(VT, Sub, DAG.getConstant(0, LHSVT), CC);
507     }
508     break;
509   }
510   case ISD::VASTART: {
511     // vastart just stores the address of the VarArgsFrameIndex slot into the
512     // memory location argument.
513     // FIXME: Replace MVT::i32 with PointerTy
514     SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
515     return DAG.getNode(ISD::STORE, MVT::Other, Op.getOperand(0), FR, 
516                        Op.getOperand(1), Op.getOperand(2));
517   }
518   case ISD::RET: {
519     SDOperand Copy;
520     
521     switch(Op.getNumOperands()) {
522     default:
523       assert(0 && "Do not know how to return this many arguments!");
524       abort();
525     case 1: 
526       return SDOperand(); // ret void is legal
527     case 2: {
528       MVT::ValueType ArgVT = Op.getOperand(1).getValueType();
529       unsigned ArgReg = MVT::isInteger(ArgVT) ? PPC::R3 : PPC::F1;
530       Copy = DAG.getCopyToReg(Op.getOperand(0), ArgReg, Op.getOperand(1),
531                               SDOperand());
532       break;
533     }
534     case 3:
535       Copy = DAG.getCopyToReg(Op.getOperand(0), PPC::R3, Op.getOperand(2), 
536                               SDOperand());
537       Copy = DAG.getCopyToReg(Copy, PPC::R4, Op.getOperand(1),Copy.getValue(1));
538       break;
539     }
540     return DAG.getNode(PPCISD::RET_FLAG, MVT::Other, Copy, Copy.getValue(1));
541   }
542   }
543   return SDOperand();
544 }
545
546 std::vector<SDOperand>
547 PPCTargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
548   //
549   // add beautiful description of PPC stack frame format, or at least some docs
550   //
551   MachineFunction &MF = DAG.getMachineFunction();
552   MachineFrameInfo *MFI = MF.getFrameInfo();
553   MachineBasicBlock& BB = MF.front();
554   SSARegMap *RegMap = MF.getSSARegMap();
555   std::vector<SDOperand> ArgValues;
556   
557   unsigned ArgOffset = 24;
558   unsigned GPR_remaining = 8;
559   unsigned FPR_remaining = 13;
560   unsigned GPR_idx = 0, FPR_idx = 0;
561   static const unsigned GPR[] = {
562     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
563     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
564   };
565   static const unsigned FPR[] = {
566     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
567     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
568   };
569   
570   // Add DAG nodes to load the arguments...  On entry to a function on PPC,
571   // the arguments start at offset 24, although they are likely to be passed
572   // in registers.
573   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
574     SDOperand newroot, argt;
575     unsigned ObjSize;
576     bool needsLoad = false;
577     bool ArgLive = !I->use_empty();
578     MVT::ValueType ObjectVT = getValueType(I->getType());
579     
580     switch (ObjectVT) {
581     default: assert(0 && "Unhandled argument type!");
582     case MVT::i1:
583     case MVT::i8:
584     case MVT::i16:
585     case MVT::i32:
586       ObjSize = 4;
587       if (!ArgLive) break;
588       if (GPR_remaining > 0) {
589         unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
590         MF.addLiveIn(GPR[GPR_idx], VReg);
591         argt = newroot = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
592         if (ObjectVT != MVT::i32) {
593           unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext 
594                                                        : ISD::AssertZext;
595           argt = DAG.getNode(AssertOp, MVT::i32, argt, 
596                              DAG.getValueType(ObjectVT));
597           argt = DAG.getNode(ISD::TRUNCATE, ObjectVT, argt);
598         }
599       } else {
600         needsLoad = true;
601       }
602       break;
603     case MVT::i64:
604       ObjSize = 8;
605       if (!ArgLive) break;
606       if (GPR_remaining > 0) {
607         SDOperand argHi, argLo;
608         unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
609         MF.addLiveIn(GPR[GPR_idx], VReg);
610         argHi = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
611         // If we have two or more remaining argument registers, then both halves
612         // of the i64 can be sourced from there.  Otherwise, the lower half will
613         // have to come off the stack.  This can happen when an i64 is preceded
614         // by 28 bytes of arguments.
615         if (GPR_remaining > 1) {
616           unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
617           MF.addLiveIn(GPR[GPR_idx+1], VReg);
618           argLo = DAG.getCopyFromReg(argHi, VReg, MVT::i32);
619         } else {
620           int FI = MFI->CreateFixedObject(4, ArgOffset+4);
621           SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
622           argLo = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
623                               DAG.getSrcValue(NULL));
624         }
625         // Build the outgoing arg thingy
626         argt = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, argLo, argHi);
627         newroot = argLo;
628       } else {
629         needsLoad = true;
630       }
631       break;
632     case MVT::f32:
633     case MVT::f64:
634       ObjSize = (ObjectVT == MVT::f64) ? 8 : 4;
635       if (!ArgLive) {
636         if (FPR_remaining > 0) {
637           --FPR_remaining;
638           ++FPR_idx;
639         }        
640         break;
641       }
642       if (FPR_remaining > 0) {
643         unsigned VReg;
644         if (ObjectVT == MVT::f32)
645           VReg = RegMap->createVirtualRegister(&PPC::F4RCRegClass);
646         else
647           VReg = RegMap->createVirtualRegister(&PPC::F8RCRegClass);
648         MF.addLiveIn(FPR[FPR_idx], VReg);
649         argt = newroot = DAG.getCopyFromReg(DAG.getRoot(), VReg, ObjectVT);
650         --FPR_remaining;
651         ++FPR_idx;
652       } else {
653         needsLoad = true;
654       }
655       break;
656     }
657     
658     // We need to load the argument to a virtual register if we determined above
659     // that we ran out of physical registers of the appropriate type
660     if (needsLoad) {
661       unsigned SubregOffset = 0;
662       if (ObjectVT == MVT::i8 || ObjectVT == MVT::i1) SubregOffset = 3;
663       if (ObjectVT == MVT::i16) SubregOffset = 2;
664       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
665       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
666       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN,
667                         DAG.getConstant(SubregOffset, MVT::i32));
668       argt = newroot = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
669                                    DAG.getSrcValue(NULL));
670     }
671     
672     // Every 4 bytes of argument space consumes one of the GPRs available for
673     // argument passing.
674     if (GPR_remaining > 0) {
675       unsigned delta = (GPR_remaining > 1 && ObjSize == 8) ? 2 : 1;
676       GPR_remaining -= delta;
677       GPR_idx += delta;
678     }
679     ArgOffset += ObjSize;
680     if (newroot.Val)
681       DAG.setRoot(newroot.getValue(1));
682     
683     ArgValues.push_back(argt);
684   }
685   
686   // If the function takes variable number of arguments, make a frame index for
687   // the start of the first vararg value... for expansion of llvm.va_start.
688   if (F.isVarArg()) {
689     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
690     SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
691     // If this function is vararg, store any remaining integer argument regs
692     // to their spots on the stack so that they may be loaded by deferencing the
693     // result of va_next.
694     std::vector<SDOperand> MemOps;
695     for (; GPR_remaining > 0; --GPR_remaining, ++GPR_idx) {
696       unsigned VReg = RegMap->createVirtualRegister(&PPC::GPRCRegClass);
697       MF.addLiveIn(GPR[GPR_idx], VReg);
698       SDOperand Val = DAG.getCopyFromReg(DAG.getRoot(), VReg, MVT::i32);
699       SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
700                                     Val, FIN, DAG.getSrcValue(NULL));
701       MemOps.push_back(Store);
702       // Increment the address by four for the next argument to store
703       SDOperand PtrOff = DAG.getConstant(4, getPointerTy());
704       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN, PtrOff);
705     }
706     if (!MemOps.empty()) {
707       MemOps.push_back(DAG.getRoot());
708       DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps));
709     }
710   }
711   
712   // Finally, inform the code generator which regs we return values in.
713   switch (getValueType(F.getReturnType())) {
714     default: assert(0 && "Unknown type!");
715     case MVT::isVoid: break;
716     case MVT::i1:
717     case MVT::i8:
718     case MVT::i16:
719     case MVT::i32:
720       MF.addLiveOut(PPC::R3);
721       break;
722     case MVT::i64:
723       MF.addLiveOut(PPC::R3);
724       MF.addLiveOut(PPC::R4);
725       break;
726     case MVT::f32:
727     case MVT::f64:
728       MF.addLiveOut(PPC::F1);
729       break;
730   }
731   
732   return ArgValues;
733 }
734
735 std::pair<SDOperand, SDOperand>
736 PPCTargetLowering::LowerCallTo(SDOperand Chain,
737                                const Type *RetTy, bool isVarArg,
738                                unsigned CallingConv, bool isTailCall,
739                                SDOperand Callee, ArgListTy &Args,
740                                SelectionDAG &DAG) {
741   // args_to_use will accumulate outgoing args for the PPCISD::CALL case in
742   // SelectExpr to use to put the arguments in the appropriate registers.
743   std::vector<SDOperand> args_to_use;
744   
745   // Count how many bytes are to be pushed on the stack, including the linkage
746   // area, and parameter passing area.
747   unsigned NumBytes = 24;
748   
749   if (Args.empty()) {
750     Chain = DAG.getCALLSEQ_START(Chain,
751                                  DAG.getConstant(NumBytes, getPointerTy()));
752   } else {
753     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
754       switch (getValueType(Args[i].second)) {
755       default: assert(0 && "Unknown value type!");
756       case MVT::i1:
757       case MVT::i8:
758       case MVT::i16:
759       case MVT::i32:
760       case MVT::f32:
761         NumBytes += 4;
762         break;
763       case MVT::i64:
764       case MVT::f64:
765         NumBytes += 8;
766         break;
767       }
768     }
769         
770     // Just to be safe, we'll always reserve the full 24 bytes of linkage area
771     // plus 32 bytes of argument space in case any called code gets funky on us.
772     // (Required by ABI to support var arg)
773     if (NumBytes < 56) NumBytes = 56;
774     
775     // Adjust the stack pointer for the new arguments...
776     // These operations are automatically eliminated by the prolog/epilog pass
777     Chain = DAG.getCALLSEQ_START(Chain,
778                                  DAG.getConstant(NumBytes, getPointerTy()));
779     
780     // Set up a copy of the stack pointer for use loading and storing any
781     // arguments that may not fit in the registers available for argument
782     // passing.
783     SDOperand StackPtr = DAG.getRegister(PPC::R1, MVT::i32);
784     
785     // Figure out which arguments are going to go in registers, and which in
786     // memory.  Also, if this is a vararg function, floating point operations
787     // must be stored to our stack, and loaded into integer regs as well, if
788     // any integer regs are available for argument passing.
789     unsigned ArgOffset = 24;
790     unsigned GPR_remaining = 8;
791     unsigned FPR_remaining = 13;
792     
793     std::vector<SDOperand> MemOps;
794     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
795       // PtrOff will be used to store the current argument to the stack if a
796       // register cannot be found for it.
797       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
798       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
799       MVT::ValueType ArgVT = getValueType(Args[i].second);
800       
801       switch (ArgVT) {
802       default: assert(0 && "Unexpected ValueType for argument!");
803       case MVT::i1:
804       case MVT::i8:
805       case MVT::i16:
806         // Promote the integer to 32 bits.  If the input type is signed use a
807         // sign extend, otherwise use a zero extend.
808         if (Args[i].second->isSigned())
809           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
810         else
811           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
812         // FALL THROUGH
813       case MVT::i32:
814         if (GPR_remaining > 0) {
815           args_to_use.push_back(Args[i].first);
816           --GPR_remaining;
817         } else {
818           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
819                                        Args[i].first, PtrOff,
820                                        DAG.getSrcValue(NULL)));
821         }
822         ArgOffset += 4;
823         break;
824       case MVT::i64:
825         // If we have one free GPR left, we can place the upper half of the i64
826         // in it, and store the other half to the stack.  If we have two or more
827         // free GPRs, then we can pass both halves of the i64 in registers.
828         if (GPR_remaining > 0) {
829           SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
830                                      Args[i].first, DAG.getConstant(1, MVT::i32));
831           SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
832                                      Args[i].first, DAG.getConstant(0, MVT::i32));
833           args_to_use.push_back(Hi);
834           --GPR_remaining;
835           if (GPR_remaining > 0) {
836             args_to_use.push_back(Lo);
837             --GPR_remaining;
838           } else {
839             SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
840             PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
841             MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
842                                          Lo, PtrOff, DAG.getSrcValue(NULL)));
843           }
844         } else {
845           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
846                                        Args[i].first, PtrOff,
847                                        DAG.getSrcValue(NULL)));
848         }
849         ArgOffset += 8;
850         break;
851       case MVT::f32:
852       case MVT::f64:
853         if (FPR_remaining > 0) {
854           args_to_use.push_back(Args[i].first);
855           --FPR_remaining;
856           if (isVarArg) {
857             SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Chain,
858                                           Args[i].first, PtrOff,
859                                           DAG.getSrcValue(NULL));
860             MemOps.push_back(Store);
861             // Float varargs are always shadowed in available integer registers
862             if (GPR_remaining > 0) {
863               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
864                                            DAG.getSrcValue(NULL));
865               MemOps.push_back(Load.getValue(1));
866               args_to_use.push_back(Load);
867               --GPR_remaining;
868             }
869             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
870               SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
871               PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
872               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
873                                            DAG.getSrcValue(NULL));
874               MemOps.push_back(Load.getValue(1));
875               args_to_use.push_back(Load);
876               --GPR_remaining;
877             }
878           } else {
879             // If we have any FPRs remaining, we may also have GPRs remaining.
880             // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
881             // GPRs.
882             if (GPR_remaining > 0) {
883               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
884               --GPR_remaining;
885             }
886             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
887               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
888               --GPR_remaining;
889             }
890           }
891         } else {
892           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
893                                        Args[i].first, PtrOff,
894                                        DAG.getSrcValue(NULL)));
895         }
896         ArgOffset += (ArgVT == MVT::f32) ? 4 : 8;
897         break;
898       }
899     }
900     if (!MemOps.empty())
901       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps);
902   }
903   
904   std::vector<MVT::ValueType> RetVals;
905   MVT::ValueType RetTyVT = getValueType(RetTy);
906   MVT::ValueType ActualRetTyVT = RetTyVT;
907   if (RetTyVT >= MVT::i1 && RetTyVT <= MVT::i16)
908     ActualRetTyVT = MVT::i32;   // Promote result to i32.
909     
910   if (RetTyVT == MVT::i64) {
911     RetVals.push_back(MVT::i32);
912     RetVals.push_back(MVT::i32);
913   } else if (RetTyVT != MVT::isVoid) {
914     RetVals.push_back(ActualRetTyVT);
915   }
916   RetVals.push_back(MVT::Other);
917   
918   // If the callee is a GlobalAddress node (quite common, every direct call is)
919   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
920   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
921     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), MVT::i32);
922   
923   std::vector<SDOperand> Ops;
924   Ops.push_back(Chain);
925   Ops.push_back(Callee);
926   Ops.insert(Ops.end(), args_to_use.begin(), args_to_use.end());
927   SDOperand TheCall = DAG.getNode(PPCISD::CALL, RetVals, Ops);
928   Chain = TheCall.getValue(TheCall.Val->getNumValues()-1);
929   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
930                       DAG.getConstant(NumBytes, getPointerTy()));
931   SDOperand RetVal = TheCall;
932   
933   // If the result is a small value, add a note so that we keep track of the
934   // information about whether it is sign or zero extended.
935   if (RetTyVT != ActualRetTyVT) {
936     RetVal = DAG.getNode(RetTy->isSigned() ? ISD::AssertSext : ISD::AssertZext,
937                          MVT::i32, RetVal, DAG.getValueType(RetTyVT));
938     RetVal = DAG.getNode(ISD::TRUNCATE, RetTyVT, RetVal);
939   } else if (RetTyVT == MVT::i64) {
940     RetVal = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, RetVal, RetVal.getValue(1));
941   }
942   
943   return std::make_pair(RetVal, Chain);
944 }
945
946 MachineBasicBlock *
947 PPCTargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
948                                            MachineBasicBlock *BB) {
949   assert((MI->getOpcode() == PPC::SELECT_CC_Int ||
950           MI->getOpcode() == PPC::SELECT_CC_F4 ||
951           MI->getOpcode() == PPC::SELECT_CC_F8) &&
952          "Unexpected instr type to insert");
953   
954   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
955   // control-flow pattern.  The incoming instruction knows the destination vreg
956   // to set, the condition code register to branch on, the true/false values to
957   // select between, and a branch opcode to use.
958   const BasicBlock *LLVM_BB = BB->getBasicBlock();
959   ilist<MachineBasicBlock>::iterator It = BB;
960   ++It;
961   
962   //  thisMBB:
963   //  ...
964   //   TrueVal = ...
965   //   cmpTY ccX, r1, r2
966   //   bCC copy1MBB
967   //   fallthrough --> copy0MBB
968   MachineBasicBlock *thisMBB = BB;
969   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
970   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
971   BuildMI(BB, MI->getOperand(4).getImmedValue(), 2)
972     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
973   MachineFunction *F = BB->getParent();
974   F->getBasicBlockList().insert(It, copy0MBB);
975   F->getBasicBlockList().insert(It, sinkMBB);
976   // Update machine-CFG edges
977   BB->addSuccessor(copy0MBB);
978   BB->addSuccessor(sinkMBB);
979   
980   //  copy0MBB:
981   //   %FalseValue = ...
982   //   # fallthrough to sinkMBB
983   BB = copy0MBB;
984   
985   // Update machine-CFG edges
986   BB->addSuccessor(sinkMBB);
987   
988   //  sinkMBB:
989   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
990   //  ...
991   BB = sinkMBB;
992   BuildMI(BB, PPC::PHI, 4, MI->getOperand(0).getReg())
993     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
994     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
995
996   delete MI;   // The pseudo instruction is gone now.
997   return BB;
998 }
999
1000 /// getConstraintType - Given a constraint letter, return the type of
1001 /// constraint it is for this target.
1002 PPCTargetLowering::ConstraintType 
1003 PPCTargetLowering::getConstraintType(char ConstraintLetter) const {
1004   switch (ConstraintLetter) {
1005   default: break;
1006   case 'b':
1007   case 'r':
1008   case 'f':
1009   case 'v':
1010   case 'y':
1011     return C_RegisterClass;
1012   }  
1013   return TargetLowering::getConstraintType(ConstraintLetter);
1014 }
1015
1016
1017 std::vector<unsigned> PPCTargetLowering::
1018 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1019                                   MVT::ValueType VT) const {
1020   if (Constraint.size() == 1) {
1021     switch (Constraint[0]) {      // GCC RS6000 Constraint Letters
1022     default: break;  // Unknown constriant letter
1023     case 'b': 
1024       return make_vector<unsigned>(/*no R0*/ PPC::R1 , PPC::R2 , PPC::R3 ,
1025                                    PPC::R4 , PPC::R5 , PPC::R6 , PPC::R7 ,
1026                                    PPC::R8 , PPC::R9 , PPC::R10, PPC::R11, 
1027                                    PPC::R12, PPC::R13, PPC::R14, PPC::R15, 
1028                                    PPC::R16, PPC::R17, PPC::R18, PPC::R19, 
1029                                    PPC::R20, PPC::R21, PPC::R22, PPC::R23, 
1030                                    PPC::R24, PPC::R25, PPC::R26, PPC::R27, 
1031                                    PPC::R28, PPC::R29, PPC::R30, PPC::R31, 
1032                                    0);
1033     case 'r': 
1034       return make_vector<unsigned>(PPC::R0 , PPC::R1 , PPC::R2 , PPC::R3 ,
1035                                    PPC::R4 , PPC::R5 , PPC::R6 , PPC::R7 ,
1036                                    PPC::R8 , PPC::R9 , PPC::R10, PPC::R11, 
1037                                    PPC::R12, PPC::R13, PPC::R14, PPC::R15, 
1038                                    PPC::R16, PPC::R17, PPC::R18, PPC::R19, 
1039                                    PPC::R20, PPC::R21, PPC::R22, PPC::R23, 
1040                                    PPC::R24, PPC::R25, PPC::R26, PPC::R27, 
1041                                    PPC::R28, PPC::R29, PPC::R30, PPC::R31, 
1042                                    0);
1043     case 'f': 
1044       return make_vector<unsigned>(PPC::F0 , PPC::F1 , PPC::F2 , PPC::F3 ,
1045                                    PPC::F4 , PPC::F5 , PPC::F6 , PPC::F7 ,
1046                                    PPC::F8 , PPC::F9 , PPC::F10, PPC::F11, 
1047                                    PPC::F12, PPC::F13, PPC::F14, PPC::F15, 
1048                                    PPC::F16, PPC::F17, PPC::F18, PPC::F19, 
1049                                    PPC::F20, PPC::F21, PPC::F22, PPC::F23, 
1050                                    PPC::F24, PPC::F25, PPC::F26, PPC::F27, 
1051                                    PPC::F28, PPC::F29, PPC::F30, PPC::F31, 
1052                                    0);
1053     case 'v': 
1054       return make_vector<unsigned>(PPC::V0 , PPC::V1 , PPC::V2 , PPC::V3 ,
1055                                    PPC::V4 , PPC::V5 , PPC::V6 , PPC::V7 ,
1056                                    PPC::V8 , PPC::V9 , PPC::V10, PPC::V11, 
1057                                    PPC::V12, PPC::V13, PPC::V14, PPC::V15, 
1058                                    PPC::V16, PPC::V17, PPC::V18, PPC::V19, 
1059                                    PPC::V20, PPC::V21, PPC::V22, PPC::V23, 
1060                                    PPC::V24, PPC::V25, PPC::V26, PPC::V27, 
1061                                    PPC::V28, PPC::V29, PPC::V30, PPC::V31, 
1062                                    0);
1063     case 'y': 
1064       return make_vector<unsigned>(PPC::CR0, PPC::CR1, PPC::CR2, PPC::CR3,
1065                                    PPC::CR4, PPC::CR5, PPC::CR6, PPC::CR7,
1066                                    0);
1067     }
1068   }
1069   
1070   return std::vector<unsigned>();
1071 }
1072
1073 // isOperandValidForConstraint
1074 bool PPCTargetLowering::
1075 isOperandValidForConstraint(SDOperand Op, char Letter) {
1076   switch (Letter) {
1077   default: break;
1078   case 'I':
1079   case 'J':
1080   case 'K':
1081   case 'L':
1082   case 'M':
1083   case 'N':
1084   case 'O':
1085   case 'P': {
1086     if (!isa<ConstantSDNode>(Op)) return false;  // Must be an immediate.
1087     unsigned Value = cast<ConstantSDNode>(Op)->getValue();
1088     switch (Letter) {
1089     default: assert(0 && "Unknown constraint letter!");
1090     case 'I':  // "I" is a signed 16-bit constant.
1091       return (short)Value == (int)Value;
1092     case 'J':  // "J" is a constant with only the high-order 16 bits nonzero.
1093     case 'L':  // "L" is a signed 16-bit constant shifted left 16 bits.
1094       return (short)Value == 0;
1095     case 'K':  // "K" is a constant with only the low-order 16 bits nonzero.
1096       return (Value >> 16) == 0;
1097     case 'M':  // "M" is a constant that is greater than 31.
1098       return Value > 31;
1099     case 'N':  // "N" is a positive constant that is an exact power of two.
1100       return (int)Value > 0 && isPowerOf2_32(Value);
1101     case 'O':  // "O" is the constant zero. 
1102       return Value == 0;
1103     case 'P':  // "P" is a constant whose negation is a signed 16-bit constant.
1104       return (short)-Value == (int)-Value;
1105     }
1106     break;
1107   }
1108   }
1109   
1110   // Handle standard constraint letters.
1111   return TargetLowering::isOperandValidForConstraint(Op, Letter);
1112 }