Move FCTIWZ handling out of the instruction selectors and into legalization,
[oota-llvm.git] / lib / Target / PowerPC / PPCISelLowering.cpp
1 //===-- PPC32ISelLowering.cpp - PPC32 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 PPC32ISelLowering class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "PPC32ISelLowering.h"
15 #include "PPC32TargetMachine.h"
16 #include "llvm/CodeGen/MachineFrameInfo.h"
17 #include "llvm/CodeGen/MachineFunction.h"
18 #include "llvm/CodeGen/MachineInstrBuilder.h"
19 #include "llvm/CodeGen/SelectionDAG.h"
20 #include "llvm/Constants.h"
21 #include "llvm/Function.h"
22 using namespace llvm;
23
24 PPC32TargetLowering::PPC32TargetLowering(TargetMachine &TM)
25   : TargetLowering(TM) {
26     
27   // Fold away setcc operations if possible.
28   setSetCCIsExpensive();
29   
30   // Set up the register classes.
31   addRegisterClass(MVT::i32, PPC32::GPRCRegisterClass);
32   addRegisterClass(MVT::f32, PPC32::FPRCRegisterClass);
33   addRegisterClass(MVT::f64, PPC32::FPRCRegisterClass);
34   
35   // PowerPC has no intrinsics for these particular operations
36   setOperationAction(ISD::MEMMOVE, MVT::Other, Expand);
37   setOperationAction(ISD::MEMSET, MVT::Other, Expand);
38   setOperationAction(ISD::MEMCPY, MVT::Other, Expand);
39   
40   // PowerPC has an i16 but no i8 (or i1) SEXTLOAD
41   setOperationAction(ISD::SEXTLOAD, MVT::i1, Expand);
42   setOperationAction(ISD::SEXTLOAD, MVT::i8, Expand);
43   
44   // PowerPC has no SREM/UREM instructions
45   setOperationAction(ISD::SREM, MVT::i32, Expand);
46   setOperationAction(ISD::UREM, MVT::i32, Expand);
47   
48   // We don't support sin/cos/sqrt/fmod
49   setOperationAction(ISD::FSIN , MVT::f64, Expand);
50   setOperationAction(ISD::FCOS , MVT::f64, Expand);
51   setOperationAction(ISD::SREM , MVT::f64, Expand);
52   setOperationAction(ISD::FSIN , MVT::f32, Expand);
53   setOperationAction(ISD::FCOS , MVT::f32, Expand);
54   setOperationAction(ISD::SREM , MVT::f32, Expand);
55   
56   // If we're enabling GP optimizations, use hardware square root
57   if (!TM.getSubtarget<PPCSubtarget>().isGigaProcessor()) {
58     setOperationAction(ISD::FSQRT, MVT::f64, Expand);
59     setOperationAction(ISD::FSQRT, MVT::f32, Expand);
60   }
61   
62   // PowerPC does not have CTPOP or CTTZ
63   setOperationAction(ISD::CTPOP, MVT::i32  , Expand);
64   setOperationAction(ISD::CTTZ , MVT::i32  , Expand);
65   
66   // PowerPC does not have Select
67   setOperationAction(ISD::SELECT, MVT::i32, Expand);
68   setOperationAction(ISD::SELECT, MVT::f32, Expand);
69   setOperationAction(ISD::SELECT, MVT::f64, Expand);
70   
71   // PowerPC wants to turn select_cc of FP into fsel when possible.
72   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
73   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
74   
75   // PowerPC wants to expand i64 shifts itself.
76   setOperationAction(ISD::SHL, MVT::i64, Custom);
77   setOperationAction(ISD::SRL, MVT::i64, Custom);
78   setOperationAction(ISD::SRA, MVT::i64, Custom);
79
80   // PowerPC does not have BRCOND* which requires SetCC
81   setOperationAction(ISD::BRCOND,       MVT::Other, Expand);
82   setOperationAction(ISD::BRCONDTWOWAY, MVT::Other, Expand);
83   
84   // PowerPC does not have FP_TO_UINT
85   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
86   
87   // PowerPC turns FP_TO_SINT into FCTIWZ and some load/stores.
88   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
89   
90   // PowerPC does not have [U|S]INT_TO_FP
91   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Expand);
92   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
93
94   setSetCCResultContents(ZeroOrOneSetCCResult);
95   
96   computeRegisterProperties();
97 }
98
99 /// isFloatingPointZero - Return true if this is 0.0 or -0.0.
100 static bool isFloatingPointZero(SDOperand Op) {
101   if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Op))
102     return CFP->isExactlyValue(-0.0) || CFP->isExactlyValue(0.0);
103   else if (Op.getOpcode() == ISD::EXTLOAD || Op.getOpcode() == ISD::LOAD) {
104     // Maybe this has already been legalized into the constant pool?
105     if (ConstantPoolSDNode *CP = dyn_cast<ConstantPoolSDNode>(Op.getOperand(1)))
106       if (ConstantFP *CFP = dyn_cast<ConstantFP>(CP->get()))
107         return CFP->isExactlyValue(-0.0) || CFP->isExactlyValue(0.0);
108   }
109   return false;
110 }
111
112 /// LowerOperation - Provide custom lowering hooks for some operations.
113 ///
114 SDOperand PPC32TargetLowering::LowerOperation(SDOperand Op, SelectionDAG &DAG) {
115   switch (Op.getOpcode()) {
116   default: assert(0 && "Wasn't expecting to be able to lower this!"); 
117   case ISD::FP_TO_SINT: {
118     assert(Op.getValueType() == MVT::i32 &&
119            MVT::isFloatingPoint(Op.getOperand(0).getValueType()));
120     Op = DAG.getNode(PPCISD::FCTIWZ, MVT::f64, Op.getOperand(0));
121    
122     int FrameIdx =
123       DAG.getMachineFunction().getFrameInfo()->CreateStackObject(8, 8);
124     SDOperand FI = DAG.getFrameIndex(FrameIdx, MVT::i32);
125     SDOperand ST = DAG.getNode(ISD::STORE, MVT::Other, DAG.getEntryNode(),
126                                Op, FI, DAG.getSrcValue(0));
127     FI = DAG.getNode(ISD::ADD, MVT::i32, FI, DAG.getConstant(4, MVT::i32));
128     return DAG.getLoad(MVT::i32, ST, FI, DAG.getSrcValue(0));
129   }
130   case ISD::SELECT_CC: {
131     // Turn FP only select_cc's into fsel instructions.
132     if (!MVT::isFloatingPoint(Op.getOperand(0).getValueType()) ||
133         !MVT::isFloatingPoint(Op.getOperand(2).getValueType()))
134       break;
135     
136     ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
137     
138     // Cannot handle SETEQ/SETNE.
139     if (CC == ISD::SETEQ || CC == ISD::SETNE) break;
140     
141     MVT::ValueType ResVT = Op.getValueType();
142     MVT::ValueType CmpVT = Op.getOperand(0).getValueType();
143     SDOperand LHS = Op.getOperand(0), RHS = Op.getOperand(1);
144     SDOperand TV  = Op.getOperand(2), FV  = Op.getOperand(3);
145
146     // If the RHS of the comparison is a 0.0, we don't need to do the
147     // subtraction at all.
148     if (isFloatingPointZero(RHS))
149       switch (CC) {
150       default: assert(0 && "Invalid FSEL condition"); abort();
151       case ISD::SETULT:
152       case ISD::SETLT:
153         std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
154       case ISD::SETUGE:
155       case ISD::SETGE:
156         return DAG.getNode(PPCISD::FSEL, ResVT, LHS, TV, FV);
157       case ISD::SETUGT:
158       case ISD::SETGT:
159         std::swap(TV, FV);  // fsel is natively setge, swap operands for setlt
160       case ISD::SETULE:
161       case ISD::SETLE:
162         return DAG.getNode(PPCISD::FSEL, ResVT,
163                            DAG.getNode(ISD::FNEG, ResVT, LHS), TV, FV);
164       }
165     
166     switch (CC) {
167     default: assert(0 && "Invalid FSEL condition"); abort();
168     case ISD::SETULT:
169     case ISD::SETLT:
170       return DAG.getNode(PPCISD::FSEL, ResVT,
171                          DAG.getNode(ISD::SUB, CmpVT, LHS, RHS), FV, TV);
172     case ISD::SETUGE:
173     case ISD::SETGE:
174       return DAG.getNode(PPCISD::FSEL, ResVT,
175                          DAG.getNode(ISD::SUB, CmpVT, LHS, RHS), TV, FV);
176     case ISD::SETUGT:
177     case ISD::SETGT:
178       return DAG.getNode(PPCISD::FSEL, ResVT,
179                          DAG.getNode(ISD::SUB, CmpVT, RHS, LHS), FV, TV);
180     case ISD::SETULE:
181     case ISD::SETLE:
182       return DAG.getNode(PPCISD::FSEL, ResVT,
183                          DAG.getNode(ISD::SUB, CmpVT, RHS, LHS), TV, FV);
184     }
185     break;
186   }
187   case ISD::SHL: {
188     assert(Op.getValueType() == MVT::i64 &&
189            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SHL!");
190     // The generic code does a fine job expanding shift by a constant.
191     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
192     
193     // Otherwise, expand into a bunch of logical ops.  Note that these ops
194     // depend on the PPC behavior for oversized shift amounts.
195     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
196                                DAG.getConstant(0, MVT::i32));
197     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
198                                DAG.getConstant(1, MVT::i32));
199     SDOperand Amt = Op.getOperand(1);
200     
201     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
202                                  DAG.getConstant(32, MVT::i32), Amt);
203     SDOperand Tmp2 = DAG.getNode(ISD::SHL, MVT::i32, Hi, Amt);
204     SDOperand Tmp3 = DAG.getNode(ISD::SRL, MVT::i32, Lo, Tmp1);
205     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
206     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
207                                  DAG.getConstant(-32U, MVT::i32));
208     SDOperand Tmp6 = DAG.getNode(ISD::SHL, MVT::i32, Lo, Tmp5);
209     SDOperand OutHi = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
210     SDOperand OutLo = DAG.getNode(ISD::SHL, MVT::i32, Lo, Amt);
211     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
212   }
213   case ISD::SRL: {
214     assert(Op.getValueType() == MVT::i64 &&
215            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SHL!");
216     // The generic code does a fine job expanding shift by a constant.
217     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
218     
219     // Otherwise, expand into a bunch of logical ops.  Note that these ops
220     // depend on the PPC behavior for oversized shift amounts.
221     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
222                                DAG.getConstant(0, MVT::i32));
223     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
224                                DAG.getConstant(1, MVT::i32));
225     SDOperand Amt = Op.getOperand(1);
226     
227     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
228                                  DAG.getConstant(32, MVT::i32), Amt);
229     SDOperand Tmp2 = DAG.getNode(ISD::SRL, MVT::i32, Lo, Amt);
230     SDOperand Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, Hi, Tmp1);
231     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
232     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
233                                  DAG.getConstant(-32U, MVT::i32));
234     SDOperand Tmp6 = DAG.getNode(ISD::SRL, MVT::i32, Hi, Tmp5);
235     SDOperand OutLo = DAG.getNode(ISD::OR, MVT::i32, Tmp4, Tmp6);
236     SDOperand OutHi = DAG.getNode(ISD::SRL, MVT::i32, Hi, Amt);
237     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
238   }    
239   case ISD::SRA: {
240     assert(Op.getValueType() == MVT::i64 &&
241            Op.getOperand(1).getValueType() == MVT::i32 && "Unexpected SRA!");
242     // The generic code does a fine job expanding shift by a constant.
243     if (isa<ConstantSDNode>(Op.getOperand(1))) break;
244       
245     // Otherwise, expand into a bunch of logical ops, followed by a select_cc.
246     SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
247                                DAG.getConstant(0, MVT::i32));
248     SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32, Op.getOperand(0),
249                                DAG.getConstant(1, MVT::i32));
250     SDOperand Amt = Op.getOperand(1);
251     
252     SDOperand Tmp1 = DAG.getNode(ISD::SUB, MVT::i32,
253                                  DAG.getConstant(32, MVT::i32), Amt);
254     SDOperand Tmp2 = DAG.getNode(ISD::SRL, MVT::i32, Lo, Amt);
255     SDOperand Tmp3 = DAG.getNode(ISD::SHL, MVT::i32, Hi, Tmp1);
256     SDOperand Tmp4 = DAG.getNode(ISD::OR , MVT::i32, Tmp2, Tmp3);
257     SDOperand Tmp5 = DAG.getNode(ISD::ADD, MVT::i32, Amt,
258                                  DAG.getConstant(-32U, MVT::i32));
259     SDOperand Tmp6 = DAG.getNode(ISD::SRA, MVT::i32, Hi, Tmp5);
260     SDOperand OutHi = DAG.getNode(ISD::SRA, MVT::i32, Hi, Amt);
261     SDOperand OutLo = DAG.getSelectCC(Tmp5, DAG.getConstant(0, MVT::i32),
262                                       Tmp4, Tmp6, ISD::SETLE);
263     return DAG.getNode(ISD::BUILD_PAIR, MVT::i64, OutLo, OutHi);
264   }
265   }
266   return SDOperand();
267 }
268
269 std::vector<SDOperand>
270 PPC32TargetLowering::LowerArguments(Function &F, SelectionDAG &DAG) {
271   //
272   // add beautiful description of PPC stack frame format, or at least some docs
273   //
274   MachineFunction &MF = DAG.getMachineFunction();
275   MachineFrameInfo *MFI = MF.getFrameInfo();
276   MachineBasicBlock& BB = MF.front();
277   std::vector<SDOperand> ArgValues;
278   
279   // Due to the rather complicated nature of the PowerPC ABI, rather than a
280   // fixed size array of physical args, for the sake of simplicity let the STL
281   // handle tracking them for us.
282   std::vector<unsigned> argVR, argPR, argOp;
283   unsigned ArgOffset = 24;
284   unsigned GPR_remaining = 8;
285   unsigned FPR_remaining = 13;
286   unsigned GPR_idx = 0, FPR_idx = 0;
287   static const unsigned GPR[] = {
288     PPC::R3, PPC::R4, PPC::R5, PPC::R6,
289     PPC::R7, PPC::R8, PPC::R9, PPC::R10,
290   };
291   static const unsigned FPR[] = {
292     PPC::F1, PPC::F2, PPC::F3, PPC::F4, PPC::F5, PPC::F6, PPC::F7,
293     PPC::F8, PPC::F9, PPC::F10, PPC::F11, PPC::F12, PPC::F13
294   };
295   
296   // Add DAG nodes to load the arguments...  On entry to a function on PPC,
297   // the arguments start at offset 24, although they are likely to be passed
298   // in registers.
299   for (Function::arg_iterator I = F.arg_begin(), E = F.arg_end(); I != E; ++I) {
300     SDOperand newroot, argt;
301     unsigned ObjSize;
302     bool needsLoad = false;
303     bool ArgLive = !I->use_empty();
304     MVT::ValueType ObjectVT = getValueType(I->getType());
305     
306     switch (ObjectVT) {
307     default: assert(0 && "Unhandled argument type!");
308     case MVT::i1:
309     case MVT::i8:
310     case MVT::i16:
311     case MVT::i32:
312       ObjSize = 4;
313       if (!ArgLive) break;
314       if (GPR_remaining > 0) {
315         MF.addLiveIn(GPR[GPR_idx]);
316         argt = newroot = DAG.getCopyFromReg(DAG.getRoot(),
317                                             GPR[GPR_idx], MVT::i32);
318         if (ObjectVT != MVT::i32) {
319           unsigned AssertOp = I->getType()->isSigned() ? ISD::AssertSext 
320                                                        : ISD::AssertZext;
321           argt = DAG.getNode(AssertOp, MVT::i32, argt, 
322                              DAG.getValueType(ObjectVT));
323           argt = DAG.getNode(ISD::TRUNCATE, ObjectVT, argt);
324         }
325       } else {
326         needsLoad = true;
327       }
328       break;
329     case MVT::i64: ObjSize = 8;
330       if (!ArgLive) break;
331       if (GPR_remaining > 0) {
332         SDOperand argHi, argLo;
333         MF.addLiveIn(GPR[GPR_idx]);
334         argHi = DAG.getCopyFromReg(DAG.getRoot(), GPR[GPR_idx], MVT::i32);
335         // If we have two or more remaining argument registers, then both halves
336         // of the i64 can be sourced from there.  Otherwise, the lower half will
337         // have to come off the stack.  This can happen when an i64 is preceded
338         // by 28 bytes of arguments.
339         if (GPR_remaining > 1) {
340           MF.addLiveIn(GPR[GPR_idx+1]);
341           argLo = DAG.getCopyFromReg(argHi, GPR[GPR_idx+1], MVT::i32);
342         } else {
343           int FI = MFI->CreateFixedObject(4, ArgOffset+4);
344           SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
345           argLo = DAG.getLoad(MVT::i32, DAG.getEntryNode(), FIN,
346                               DAG.getSrcValue(NULL));
347         }
348         // Build the outgoing arg thingy
349         argt = DAG.getNode(ISD::BUILD_PAIR, MVT::i64, argLo, argHi);
350         newroot = argLo;
351       } else {
352         needsLoad = true;
353       }
354       break;
355     case MVT::f32:
356     case MVT::f64:
357       ObjSize = (ObjectVT == MVT::f64) ? 8 : 4;
358       if (!ArgLive) break;
359       if (FPR_remaining > 0) {
360         MF.addLiveIn(FPR[FPR_idx]);
361         argt = newroot = DAG.getCopyFromReg(DAG.getRoot(), 
362                                             FPR[FPR_idx], ObjectVT);
363         --FPR_remaining;
364         ++FPR_idx;
365       } else {
366         needsLoad = true;
367       }
368       break;
369     }
370     
371     // We need to load the argument to a virtual register if we determined above
372     // that we ran out of physical registers of the appropriate type
373     if (needsLoad) {
374       unsigned SubregOffset = 0;
375       if (ObjectVT == MVT::i8 || ObjectVT == MVT::i1) SubregOffset = 3;
376       if (ObjectVT == MVT::i16) SubregOffset = 2;
377       int FI = MFI->CreateFixedObject(ObjSize, ArgOffset);
378       SDOperand FIN = DAG.getFrameIndex(FI, MVT::i32);
379       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN,
380                         DAG.getConstant(SubregOffset, MVT::i32));
381       argt = newroot = DAG.getLoad(ObjectVT, DAG.getEntryNode(), FIN,
382                                    DAG.getSrcValue(NULL));
383     }
384     
385     // Every 4 bytes of argument space consumes one of the GPRs available for
386     // argument passing.
387     if (GPR_remaining > 0) {
388       unsigned delta = (GPR_remaining > 1 && ObjSize == 8) ? 2 : 1;
389       GPR_remaining -= delta;
390       GPR_idx += delta;
391     }
392     ArgOffset += ObjSize;
393     if (newroot.Val)
394       DAG.setRoot(newroot.getValue(1));
395     
396     ArgValues.push_back(argt);
397   }
398   
399   // If the function takes variable number of arguments, make a frame index for
400   // the start of the first vararg value... for expansion of llvm.va_start.
401   if (F.isVarArg()) {
402     VarArgsFrameIndex = MFI->CreateFixedObject(4, ArgOffset);
403     SDOperand FIN = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
404     // If this function is vararg, store any remaining integer argument regs
405     // to their spots on the stack so that they may be loaded by deferencing the
406     // result of va_next.
407     std::vector<SDOperand> MemOps;
408     for (; GPR_remaining > 0; --GPR_remaining, ++GPR_idx) {
409       MF.addLiveIn(GPR[GPR_idx]);
410       SDOperand Val = DAG.getCopyFromReg(DAG.getRoot(), GPR[GPR_idx], MVT::i32);
411       SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Val.getValue(1),
412                                     Val, FIN, DAG.getSrcValue(NULL));
413       MemOps.push_back(Store);
414       // Increment the address by four for the next argument to store
415       SDOperand PtrOff = DAG.getConstant(4, getPointerTy());
416       FIN = DAG.getNode(ISD::ADD, MVT::i32, FIN, PtrOff);
417     }
418     DAG.setRoot(DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps));
419   }
420   
421   // Finally, inform the code generator which regs we return values in.
422   switch (getValueType(F.getReturnType())) {
423     default: assert(0 && "Unknown type!");
424     case MVT::isVoid: break;
425     case MVT::i1:
426     case MVT::i8:
427     case MVT::i16:
428     case MVT::i32:
429       MF.addLiveOut(PPC::R3);
430       break;
431     case MVT::i64:
432       MF.addLiveOut(PPC::R3);
433       MF.addLiveOut(PPC::R4);
434       break;
435     case MVT::f32:
436     case MVT::f64:
437       MF.addLiveOut(PPC::F1);
438       break;
439   }
440   
441   return ArgValues;
442 }
443
444 std::pair<SDOperand, SDOperand>
445 PPC32TargetLowering::LowerCallTo(SDOperand Chain,
446                                  const Type *RetTy, bool isVarArg,
447                                  unsigned CallingConv, bool isTailCall,
448                                  SDOperand Callee, ArgListTy &Args,
449                                  SelectionDAG &DAG) {
450   // args_to_use will accumulate outgoing args for the ISD::CALL case in
451   // SelectExpr to use to put the arguments in the appropriate registers.
452   std::vector<SDOperand> args_to_use;
453   
454   // Count how many bytes are to be pushed on the stack, including the linkage
455   // area, and parameter passing area.
456   unsigned NumBytes = 24;
457   
458   if (Args.empty()) {
459     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
460                         DAG.getConstant(NumBytes, getPointerTy()));
461   } else {
462     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
463       switch (getValueType(Args[i].second)) {
464       default: assert(0 && "Unknown value type!");
465       case MVT::i1:
466       case MVT::i8:
467       case MVT::i16:
468       case MVT::i32:
469       case MVT::f32:
470         NumBytes += 4;
471         break;
472       case MVT::i64:
473       case MVT::f64:
474         NumBytes += 8;
475         break;
476       }
477     }
478         
479     // Just to be safe, we'll always reserve the full 24 bytes of linkage area
480     // plus 32 bytes of argument space in case any called code gets funky on us.
481     // (Required by ABI to support var arg)
482     if (NumBytes < 56) NumBytes = 56;
483     
484     // Adjust the stack pointer for the new arguments...
485     // These operations are automatically eliminated by the prolog/epilog pass
486     Chain = DAG.getNode(ISD::CALLSEQ_START, MVT::Other, Chain,
487                         DAG.getConstant(NumBytes, getPointerTy()));
488     
489     // Set up a copy of the stack pointer for use loading and storing any
490     // arguments that may not fit in the registers available for argument
491     // passing.
492     SDOperand StackPtr = DAG.getCopyFromReg(DAG.getEntryNode(),
493                                             PPC::R1, MVT::i32);
494     
495     // Figure out which arguments are going to go in registers, and which in
496     // memory.  Also, if this is a vararg function, floating point operations
497     // must be stored to our stack, and loaded into integer regs as well, if
498     // any integer regs are available for argument passing.
499     unsigned ArgOffset = 24;
500     unsigned GPR_remaining = 8;
501     unsigned FPR_remaining = 13;
502     
503     std::vector<SDOperand> MemOps;
504     for (unsigned i = 0, e = Args.size(); i != e; ++i) {
505       // PtrOff will be used to store the current argument to the stack if a
506       // register cannot be found for it.
507       SDOperand PtrOff = DAG.getConstant(ArgOffset, getPointerTy());
508       PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
509       MVT::ValueType ArgVT = getValueType(Args[i].second);
510       
511       switch (ArgVT) {
512       default: assert(0 && "Unexpected ValueType for argument!");
513       case MVT::i1:
514       case MVT::i8:
515       case MVT::i16:
516         // Promote the integer to 32 bits.  If the input type is signed use a
517         // sign extend, otherwise use a zero extend.
518         if (Args[i].second->isSigned())
519           Args[i].first =DAG.getNode(ISD::SIGN_EXTEND, MVT::i32, Args[i].first);
520         else
521           Args[i].first =DAG.getNode(ISD::ZERO_EXTEND, MVT::i32, Args[i].first);
522         // FALL THROUGH
523       case MVT::i32:
524         if (GPR_remaining > 0) {
525           args_to_use.push_back(Args[i].first);
526           --GPR_remaining;
527         } else {
528           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
529                                        Args[i].first, PtrOff,
530                                        DAG.getSrcValue(NULL)));
531         }
532         ArgOffset += 4;
533         break;
534       case MVT::i64:
535         // If we have one free GPR left, we can place the upper half of the i64
536         // in it, and store the other half to the stack.  If we have two or more
537         // free GPRs, then we can pass both halves of the i64 in registers.
538         if (GPR_remaining > 0) {
539           SDOperand Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
540                                      Args[i].first, DAG.getConstant(1, MVT::i32));
541           SDOperand Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, MVT::i32,
542                                      Args[i].first, DAG.getConstant(0, MVT::i32));
543           args_to_use.push_back(Hi);
544           --GPR_remaining;
545           if (GPR_remaining > 0) {
546             args_to_use.push_back(Lo);
547             --GPR_remaining;
548           } else {
549             SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
550             PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
551             MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
552                                          Lo, PtrOff, DAG.getSrcValue(NULL)));
553           }
554         } else {
555           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
556                                        Args[i].first, PtrOff,
557                                        DAG.getSrcValue(NULL)));
558         }
559         ArgOffset += 8;
560         break;
561       case MVT::f32:
562       case MVT::f64:
563         if (FPR_remaining > 0) {
564           args_to_use.push_back(Args[i].first);
565           --FPR_remaining;
566           if (isVarArg) {
567             SDOperand Store = DAG.getNode(ISD::STORE, MVT::Other, Chain,
568                                           Args[i].first, PtrOff,
569                                           DAG.getSrcValue(NULL));
570             MemOps.push_back(Store);
571             // Float varargs are always shadowed in available integer registers
572             if (GPR_remaining > 0) {
573               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
574                                            DAG.getSrcValue(NULL));
575               MemOps.push_back(Load);
576               args_to_use.push_back(Load);
577               --GPR_remaining;
578             }
579             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
580               SDOperand ConstFour = DAG.getConstant(4, getPointerTy());
581               PtrOff = DAG.getNode(ISD::ADD, MVT::i32, PtrOff, ConstFour);
582               SDOperand Load = DAG.getLoad(MVT::i32, Store, PtrOff,
583                                            DAG.getSrcValue(NULL));
584               MemOps.push_back(Load);
585               args_to_use.push_back(Load);
586               --GPR_remaining;
587             }
588           } else {
589             // If we have any FPRs remaining, we may also have GPRs remaining.
590             // Args passed in FPRs consume either 1 (f32) or 2 (f64) available
591             // GPRs.
592             if (GPR_remaining > 0) {
593               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
594               --GPR_remaining;
595             }
596             if (GPR_remaining > 0 && MVT::f64 == ArgVT) {
597               args_to_use.push_back(DAG.getNode(ISD::UNDEF, MVT::i32));
598               --GPR_remaining;
599             }
600           }
601         } else {
602           MemOps.push_back(DAG.getNode(ISD::STORE, MVT::Other, Chain,
603                                        Args[i].first, PtrOff,
604                                        DAG.getSrcValue(NULL)));
605         }
606         ArgOffset += (ArgVT == MVT::f32) ? 4 : 8;
607         break;
608       }
609     }
610     if (!MemOps.empty())
611       Chain = DAG.getNode(ISD::TokenFactor, MVT::Other, MemOps);
612   }
613   
614   std::vector<MVT::ValueType> RetVals;
615   MVT::ValueType RetTyVT = getValueType(RetTy);
616   if (RetTyVT != MVT::isVoid)
617     RetVals.push_back(RetTyVT);
618   RetVals.push_back(MVT::Other);
619   
620   SDOperand TheCall = SDOperand(DAG.getCall(RetVals,
621                                             Chain, Callee, args_to_use), 0);
622   Chain = TheCall.getValue(RetTyVT != MVT::isVoid);
623   Chain = DAG.getNode(ISD::CALLSEQ_END, MVT::Other, Chain,
624                       DAG.getConstant(NumBytes, getPointerTy()));
625   return std::make_pair(TheCall, Chain);
626 }
627
628 SDOperand PPC32TargetLowering::LowerVAStart(SDOperand Chain, SDOperand VAListP,
629                                             Value *VAListV, SelectionDAG &DAG) {
630   // vastart just stores the address of the VarArgsFrameIndex slot into the
631   // memory location argument.
632   SDOperand FR = DAG.getFrameIndex(VarArgsFrameIndex, MVT::i32);
633   return DAG.getNode(ISD::STORE, MVT::Other, Chain, FR, VAListP,
634                      DAG.getSrcValue(VAListV));
635 }
636
637 std::pair<SDOperand,SDOperand>
638 PPC32TargetLowering::LowerVAArg(SDOperand Chain,
639                                 SDOperand VAListP, Value *VAListV,
640                                 const Type *ArgTy, SelectionDAG &DAG) {
641   MVT::ValueType ArgVT = getValueType(ArgTy);
642   
643   SDOperand VAList =
644     DAG.getLoad(MVT::i32, Chain, VAListP, DAG.getSrcValue(VAListV));
645   SDOperand Result = DAG.getLoad(ArgVT, Chain, VAList, DAG.getSrcValue(NULL));
646   unsigned Amt;
647   if (ArgVT == MVT::i32 || ArgVT == MVT::f32)
648     Amt = 4;
649   else {
650     assert((ArgVT == MVT::i64 || ArgVT == MVT::f64) &&
651            "Other types should have been promoted for varargs!");
652     Amt = 8;
653   }
654   VAList = DAG.getNode(ISD::ADD, VAList.getValueType(), VAList,
655                        DAG.getConstant(Amt, VAList.getValueType()));
656   Chain = DAG.getNode(ISD::STORE, MVT::Other, Chain,
657                       VAList, VAListP, DAG.getSrcValue(VAListV));
658   return std::make_pair(Result, Chain);
659 }
660
661
662 std::pair<SDOperand, SDOperand> PPC32TargetLowering::
663 LowerFrameReturnAddress(bool isFrameAddress, SDOperand Chain, unsigned Depth,
664                         SelectionDAG &DAG) {
665   assert(0 && "LowerFrameReturnAddress unimplemented");
666   abort();
667 }
668
669 MachineBasicBlock *
670 PPC32TargetLowering::InsertAtEndOfBasicBlock(MachineInstr *MI,
671                                              MachineBasicBlock *BB) {
672   assert((MI->getOpcode() == PPC::SELECT_CC_Int ||
673           MI->getOpcode() == PPC::SELECT_CC_FP) &&
674          "Unexpected instr type to insert");
675   
676   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
677   // control-flow pattern.  The incoming instruction knows the destination vreg
678   // to set, the condition code register to branch on, the true/false values to
679   // select between, and a branch opcode to use.
680   const BasicBlock *LLVM_BB = BB->getBasicBlock();
681   ilist<MachineBasicBlock>::iterator It = BB;
682   ++It;
683   
684   //  thisMBB:
685   //  ...
686   //   TrueVal = ...
687   //   cmpTY ccX, r1, r2
688   //   bCC copy1MBB
689   //   fallthrough --> copy0MBB
690   MachineBasicBlock *thisMBB = BB;
691   MachineBasicBlock *copy0MBB = new MachineBasicBlock(LLVM_BB);
692   MachineBasicBlock *sinkMBB = new MachineBasicBlock(LLVM_BB);
693   BuildMI(BB, MI->getOperand(4).getImmedValue(), 2)
694     .addReg(MI->getOperand(1).getReg()).addMBB(sinkMBB);
695   MachineFunction *F = BB->getParent();
696   F->getBasicBlockList().insert(It, copy0MBB);
697   F->getBasicBlockList().insert(It, sinkMBB);
698   // Update machine-CFG edges
699   BB->addSuccessor(copy0MBB);
700   BB->addSuccessor(sinkMBB);
701   
702   //  copy0MBB:
703   //   %FalseValue = ...
704   //   # fallthrough to sinkMBB
705   BB = copy0MBB;
706   
707   // Update machine-CFG edges
708   BB->addSuccessor(sinkMBB);
709   
710   //  sinkMBB:
711   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
712   //  ...
713   BB = sinkMBB;
714   BuildMI(BB, PPC::PHI, 4, MI->getOperand(0).getReg())
715     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB)
716     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB);
717
718   delete MI;   // The pseudo instruction is gone now.
719   return BB;
720 }
721