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