SPARC backend fix: correctly passing arguments through stack
[oota-llvm.git] / lib / Target / Sparc / SparcISelLowering.cpp
1 //===-- SparcISelLowering.cpp - Sparc DAG Lowering Implementation ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the interfaces that Sparc uses to lower LLVM code into a
11 // selection DAG.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "SparcISelLowering.h"
16 #include "SparcTargetMachine.h"
17 #include "SparcMachineFunctionInfo.h"
18 #include "llvm/Function.h"
19 #include "llvm/CodeGen/CallingConvLower.h"
20 #include "llvm/CodeGen/MachineFrameInfo.h"
21 #include "llvm/CodeGen/MachineFunction.h"
22 #include "llvm/CodeGen/MachineInstrBuilder.h"
23 #include "llvm/CodeGen/MachineRegisterInfo.h"
24 #include "llvm/CodeGen/SelectionDAG.h"
25 #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
26 #include "llvm/ADT/VectorExtras.h"
27 #include "llvm/Support/ErrorHandling.h"
28 using namespace llvm;
29
30
31 //===----------------------------------------------------------------------===//
32 // Calling Convention Implementation
33 //===----------------------------------------------------------------------===//
34
35 #include "SparcGenCallingConv.inc"
36
37 SDValue
38 SparcTargetLowering::LowerReturn(SDValue Chain,
39                                  CallingConv::ID CallConv, bool isVarArg,
40                                  const SmallVectorImpl<ISD::OutputArg> &Outs,
41                                  const SmallVectorImpl<SDValue> &OutVals,
42                                  DebugLoc dl, SelectionDAG &DAG) const {
43
44   // CCValAssign - represent the assignment of the return value to locations.
45   SmallVector<CCValAssign, 16> RVLocs;
46
47   // CCState - Info about the registers and stack slot.
48   CCState CCInfo(CallConv, isVarArg, DAG.getTarget(),
49                  RVLocs, *DAG.getContext());
50
51   // Analize return values.
52   CCInfo.AnalyzeReturn(Outs, RetCC_Sparc32);
53
54   // If this is the first return lowered for this function, add the regs to the
55   // liveout set for the function.
56   if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
57     for (unsigned i = 0; i != RVLocs.size(); ++i)
58       if (RVLocs[i].isRegLoc())
59         DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
60   }
61
62   SDValue Flag;
63
64   // Copy the result values into the output registers.
65   for (unsigned i = 0; i != RVLocs.size(); ++i) {
66     CCValAssign &VA = RVLocs[i];
67     assert(VA.isRegLoc() && "Can only return in registers!");
68
69     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(),
70                              OutVals[i], Flag);
71
72     // Guarantee that all emitted copies are stuck together with flags.
73     Flag = Chain.getValue(1);
74   }
75
76   if (Flag.getNode())
77     return DAG.getNode(SPISD::RET_FLAG, dl, MVT::Other, Chain, Flag);
78   return DAG.getNode(SPISD::RET_FLAG, dl, MVT::Other, Chain);
79 }
80
81 /// LowerFormalArguments - V8 uses a very simple ABI, where all values are
82 /// passed in either one or two GPRs, including FP values.  TODO: we should
83 /// pass FP values in FP registers for fastcc functions.
84 SDValue
85 SparcTargetLowering::LowerFormalArguments(SDValue Chain,
86                                           CallingConv::ID CallConv, bool isVarArg,
87                                           const SmallVectorImpl<ISD::InputArg>
88                                             &Ins,
89                                           DebugLoc dl, SelectionDAG &DAG,
90                                           SmallVectorImpl<SDValue> &InVals)
91                                             const {
92
93   MachineFunction &MF = DAG.getMachineFunction();
94   MachineRegisterInfo &RegInfo = MF.getRegInfo();
95   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
96
97   // Assign locations to all of the incoming arguments.
98   SmallVector<CCValAssign, 16> ArgLocs;
99   CCState CCInfo(CallConv, isVarArg, getTargetMachine(),
100                  ArgLocs, *DAG.getContext());
101   CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc32);
102
103   static const unsigned ArgRegs[] = {
104     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
105   };
106   const unsigned *CurArgReg = ArgRegs, *ArgRegEnd = ArgRegs+6;
107   unsigned ArgOffset = 68;
108
109   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
110     SDValue ArgValue;
111     CCValAssign &VA = ArgLocs[i];
112     // FIXME: We ignore the register assignments of AnalyzeFormalArguments
113     // because it doesn't know how to split a double into two i32 registers.
114     EVT ObjectVT = VA.getValVT();
115     switch (ObjectVT.getSimpleVT().SimpleTy) {
116     default: llvm_unreachable("Unhandled argument type!");
117     case MVT::i1:
118     case MVT::i8:
119     case MVT::i16:
120     case MVT::i32:
121       if (!Ins[i].Used) {                  // Argument is dead.
122         if (CurArgReg < ArgRegEnd) ++CurArgReg;
123         InVals.push_back(DAG.getUNDEF(ObjectVT));
124       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
125         unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
126         MF.getRegInfo().addLiveIn(*CurArgReg++, VReg);
127         SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
128         if (ObjectVT != MVT::i32) {
129           unsigned AssertOp = ISD::AssertSext;
130           Arg = DAG.getNode(AssertOp, dl, MVT::i32, Arg,
131                             DAG.getValueType(ObjectVT));
132           Arg = DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, Arg);
133         }
134         InVals.push_back(Arg);
135       } else {
136         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
137                                                             true);
138         SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
139         SDValue Load;
140         if (ObjectVT == MVT::i32) {
141           Load = DAG.getLoad(MVT::i32, dl, Chain, FIPtr, MachinePointerInfo(),
142                              false, false, 0);
143         } else {
144           ISD::LoadExtType LoadOp = ISD::SEXTLOAD;
145
146           // Sparc is big endian, so add an offset based on the ObjectVT.
147           unsigned Offset = 4-std::max(1U, ObjectVT.getSizeInBits()/8);
148           FIPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIPtr,
149                               DAG.getConstant(Offset, MVT::i32));
150           Load = DAG.getExtLoad(LoadOp, MVT::i32, dl, Chain, FIPtr,
151                                 MachinePointerInfo(), ObjectVT, false, false,0);
152           Load = DAG.getNode(ISD::TRUNCATE, dl, ObjectVT, Load);
153         }
154         InVals.push_back(Load);
155       }
156
157       ArgOffset += 4;
158       break;
159     case MVT::f32:
160       if (!Ins[i].Used) {                  // Argument is dead.
161         if (CurArgReg < ArgRegEnd) ++CurArgReg;
162         InVals.push_back(DAG.getUNDEF(ObjectVT));
163       } else if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
164         // FP value is passed in an integer register.
165         unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
166         MF.getRegInfo().addLiveIn(*CurArgReg++, VReg);
167         SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
168
169         Arg = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Arg);
170         InVals.push_back(Arg);
171       } else {
172         int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
173                                                             true);
174         SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
175         SDValue Load = DAG.getLoad(MVT::f32, dl, Chain, FIPtr,
176                                    MachinePointerInfo(),
177                                    false, false, 0);
178         InVals.push_back(Load);
179       }
180       ArgOffset += 4;
181       break;
182
183     case MVT::i64:
184     case MVT::f64:
185       if (!Ins[i].Used) {                // Argument is dead.
186         if (CurArgReg < ArgRegEnd) ++CurArgReg;
187         if (CurArgReg < ArgRegEnd) ++CurArgReg;
188         InVals.push_back(DAG.getUNDEF(ObjectVT));
189       } else {
190         SDValue HiVal;
191         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
192           unsigned VRegHi = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
193           MF.getRegInfo().addLiveIn(*CurArgReg++, VRegHi);
194           HiVal = DAG.getCopyFromReg(Chain, dl, VRegHi, MVT::i32);
195         } else {
196           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
197                                                               true);
198           SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
199           HiVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr, MachinePointerInfo(),
200                               false, false, 0);
201         }
202
203         SDValue LoVal;
204         if (CurArgReg < ArgRegEnd) {  // Lives in an incoming GPR
205           unsigned VRegLo = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
206           MF.getRegInfo().addLiveIn(*CurArgReg++, VRegLo);
207           LoVal = DAG.getCopyFromReg(Chain, dl, VRegLo, MVT::i32);
208         } else {
209           int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset+4,
210                                                               true);
211           SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
212           LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr, MachinePointerInfo(),
213                               false, false, 0);
214         }
215
216         // Compose the two halves together into an i64 unit.
217         SDValue WholeValue =
218           DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
219
220         // If we want a double, do a bit convert.
221         if (ObjectVT == MVT::f64)
222           WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
223
224         InVals.push_back(WholeValue);
225       }
226       ArgOffset += 8;
227       break;
228     }
229   }
230
231   // Store remaining ArgRegs to the stack if this is a varargs function.
232   if (isVarArg) {
233     // Remember the vararg offset for the va_start implementation.
234     FuncInfo->setVarArgsFrameOffset(ArgOffset);
235
236     std::vector<SDValue> OutChains;
237
238     for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
239       unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
240       MF.getRegInfo().addLiveIn(*CurArgReg, VReg);
241       SDValue Arg = DAG.getCopyFromReg(DAG.getRoot(), dl, VReg, MVT::i32);
242
243       int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
244                                                           true);
245       SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
246
247       OutChains.push_back(DAG.getStore(DAG.getRoot(), dl, Arg, FIPtr,
248                                        MachinePointerInfo(),
249                                        false, false, 0));
250       ArgOffset += 4;
251     }
252
253     if (!OutChains.empty()) {
254       OutChains.push_back(Chain);
255       Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
256                           &OutChains[0], OutChains.size());
257     }
258   }
259
260   return Chain;
261 }
262
263 SDValue
264 SparcTargetLowering::LowerCall(SDValue Chain, SDValue Callee,
265                                CallingConv::ID CallConv, bool isVarArg,
266                                bool &isTailCall,
267                                const SmallVectorImpl<ISD::OutputArg> &Outs,
268                                const SmallVectorImpl<SDValue> &OutVals,
269                                const SmallVectorImpl<ISD::InputArg> &Ins,
270                                DebugLoc dl, SelectionDAG &DAG,
271                                SmallVectorImpl<SDValue> &InVals) const {
272   // Sparc target does not yet support tail call optimization.
273   isTailCall = false;
274
275 #if 0
276   // Analyze operands of the call, assigning locations to each operand.
277   SmallVector<CCValAssign, 16> ArgLocs;
278   CCState CCInfo(CallConv, isVarArg, DAG.getTarget(), ArgLocs);
279   CCInfo.AnalyzeCallOperands(Outs, CC_Sparc32);
280
281   // Get the size of the outgoing arguments stack space requirement.
282   unsigned ArgsSize = CCInfo.getNextStackOffset();
283   // FIXME: We can't use this until f64 is known to take two GPRs.
284 #else
285   (void)CC_Sparc32;
286
287   // Count the size of the outgoing arguments.
288   unsigned ArgsSize = 0;
289   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
290     switch (Outs[i].VT.SimpleTy) {
291       default: llvm_unreachable("Unknown value type!");
292       case MVT::i1:
293       case MVT::i8:
294       case MVT::i16:
295       case MVT::i32:
296       case MVT::f32:
297         ArgsSize += 4;
298         break;
299       case MVT::i64:
300       case MVT::f64:
301         ArgsSize += 8;
302         break;
303     }
304   }
305   if (ArgsSize > 4*6)
306     ArgsSize -= 4*6;    // Space for first 6 arguments is prereserved.
307   else
308     ArgsSize = 0;
309 #endif
310
311   // Keep stack frames 8-byte aligned.
312   ArgsSize = (ArgsSize+7) & ~7;
313
314   Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true));
315
316   SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
317   SmallVector<SDValue, 8> MemOpChains;
318
319 #if 0
320   // Walk the register/memloc assignments, inserting copies/loads.
321   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
322     CCValAssign &VA = ArgLocs[i];
323     SDValue Arg = OutVals[i];
324
325     // Promote the value if needed.
326     switch (VA.getLocInfo()) {
327     default: llvm_unreachable("Unknown loc info!");
328     case CCValAssign::Full: break;
329     case CCValAssign::SExt:
330       Arg = DAG.getNode(ISD::SIGN_EXTEND, VA.getLocVT(), Arg);
331       break;
332     case CCValAssign::ZExt:
333       Arg = DAG.getNode(ISD::ZERO_EXTEND, VA.getLocVT(), Arg);
334       break;
335     case CCValAssign::AExt:
336       Arg = DAG.getNode(ISD::ANY_EXTEND, VA.getLocVT(), Arg);
337       break;
338     }
339
340     // Arguments that can be passed on register must be kept at
341     // RegsToPass vector
342     if (VA.isRegLoc()) {
343       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
344       continue;
345     }
346
347     assert(VA.isMemLoc());
348
349     // Create a store off the stack pointer for this argument.
350     SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
351     // FIXME: VERIFY THAT 68 IS RIGHT.
352     SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset()+68);
353     PtrOff = DAG.getNode(ISD::ADD, MVT::i32, StackPtr, PtrOff);
354     MemOpChains.push_back(DAG.getStore(Chain, Arg, PtrOff, MachinePointerInfo(),
355                                        false, false, 0));
356   }
357
358 #else
359   static const unsigned ArgRegs[] = {
360     SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
361   };
362   unsigned ArgOffset = 68;
363
364   for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
365     SDValue Val = OutVals[i];
366     EVT ObjectVT = Outs[i].VT;
367     SDValue ValToStore(0, 0);
368     SDValue ValToStore2(0, 0);
369     unsigned ArgOffset1 = 0, ArgOffset2 = 0;
370     switch (ObjectVT.getSimpleVT().SimpleTy) {
371     default: llvm_unreachable("Unhandled argument type!");
372     case MVT::i32:
373       ArgOffset1 = ArgOffset;
374       ArgOffset += 4;
375
376       if (RegsToPass.size() >= 6) {
377         ValToStore = Val;
378       } else {
379         RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Val));
380       }
381
382       break;
383     case MVT::f32:
384       ArgOffset1 = ArgOffset;
385       ArgOffset += 4;
386       if (RegsToPass.size() >= 6) {
387         ValToStore = Val;
388       } else {
389         // Convert this to a FP value in an int reg.
390         Val = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Val);
391         RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Val));
392       }
393       break;
394     case MVT::f64: {
395
396       if (RegsToPass.size() >= 6) {
397         if (ArgOffset % 8 == 0) {
398           ArgOffset1 = ArgOffset;
399           ArgOffset += 8;
400           ValToStore = Val;    // Whole thing is passed in memory.
401           break;
402         }
403       }
404       // Break into top and bottom parts by storing to the stack and loading
405       // out the parts as integers.
406       SDValue StackPtr = DAG.CreateStackTemporary(MVT::f64, MVT::i32);
407       SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
408                                    Val, StackPtr, MachinePointerInfo(),
409                                    false, false, 0);
410       // Sparc is big-endian, so the high part comes first.
411       SDValue Hi = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
412                                MachinePointerInfo(), false, false, 0);
413       // Increment the pointer to the other half.
414       StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
415                              DAG.getIntPtrConstant(4));
416       // Load the low part.
417       SDValue Lo = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
418                                MachinePointerInfo(), false, false, 0);
419
420       if (RegsToPass.size() >= 6) {
421         ArgOffset1 = ArgOffset;
422         ValToStore = Hi;
423       } else {
424         RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Hi));
425       }
426       ArgOffset += 4;
427       if (RegsToPass.size() >= 6) {
428         ArgOffset2 = ArgOffset;
429         ValToStore2 = Lo;
430       } else {
431         RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Lo));
432       }
433       ArgOffset += 4;
434       break;
435     }
436     case MVT::i64: {
437
438       if (RegsToPass.size() >= 6) {
439         if (ArgOffset % 8 == 0) {
440           ArgOffset1 = ArgOffset;
441           ArgOffset += 8;
442           ValToStore = Val;    // Whole thing is passed in memory.
443           break;
444         }
445       }
446
447       // Split the value into top and bottom part.  Top part goes in a reg.
448       SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Val,
449                                  DAG.getConstant(1, MVT::i32));
450       SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, dl, MVT::i32, Val,
451                                  DAG.getConstant(0, MVT::i32));
452       if (RegsToPass.size() >= 6) {
453         ArgOffset1 = ArgOffset;
454         ValToStore = Hi;
455       } else {
456         RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Hi));
457       }
458       ArgOffset += 4;
459       if (RegsToPass.size() >= 6) {
460         ArgOffset2 = ArgOffset;
461         ValToStore2 = Lo;
462       } else {
463         RegsToPass.push_back(std::make_pair(ArgRegs[RegsToPass.size()], Lo));
464       }
465       ArgOffset += 4;
466       break;
467     }
468     }
469
470     if (ValToStore.getNode()) {
471       SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
472       SDValue PtrOff = DAG.getConstant(ArgOffset1, MVT::i32);
473       PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
474       MemOpChains.push_back(DAG.getStore(Chain, dl, ValToStore,
475                                          PtrOff, MachinePointerInfo(),
476                                          false, false, 0));
477     }
478     if (ValToStore2.getNode()) {
479       SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
480       SDValue PtrOff = DAG.getConstant(ArgOffset2, MVT::i32);
481       PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
482       MemOpChains.push_back(DAG.getStore(Chain, dl, ValToStore2,
483                                          PtrOff, MachinePointerInfo(),
484                                          false, false, 0));
485     }
486   }
487 #endif
488
489   // Emit all stores, make sure the occur before any copies into physregs.
490   if (!MemOpChains.empty())
491     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
492                         &MemOpChains[0], MemOpChains.size());
493
494   // Build a sequence of copy-to-reg nodes chained together with token
495   // chain and flag operands which copy the outgoing args into registers.
496   // The InFlag in necessary since all emited instructions must be
497   // stuck together.
498   SDValue InFlag;
499   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
500     unsigned Reg = RegsToPass[i].first;
501     // Remap I0->I7 -> O0->O7.
502     if (Reg >= SP::I0 && Reg <= SP::I7)
503       Reg = Reg-SP::I0+SP::O0;
504
505     Chain = DAG.getCopyToReg(Chain, dl, Reg, RegsToPass[i].second, InFlag);
506     InFlag = Chain.getValue(1);
507   }
508
509   // If the callee is a GlobalAddress node (quite common, every direct call is)
510   // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
511   // Likewise ExternalSymbol -> TargetExternalSymbol.
512   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
513     Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
514   else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
515     Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
516
517   std::vector<EVT> NodeTys;
518   NodeTys.push_back(MVT::Other);   // Returns a chain
519   NodeTys.push_back(MVT::Glue);    // Returns a flag for retval copy to use.
520   SDValue Ops[] = { Chain, Callee, InFlag };
521   Chain = DAG.getNode(SPISD::CALL, dl, NodeTys, Ops, InFlag.getNode() ? 3 : 2);
522   InFlag = Chain.getValue(1);
523
524   Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
525                              DAG.getIntPtrConstant(0, true), InFlag);
526   InFlag = Chain.getValue(1);
527
528   // Assign locations to each value returned by this call.
529   SmallVector<CCValAssign, 16> RVLocs;
530   CCState RVInfo(CallConv, isVarArg, DAG.getTarget(),
531                  RVLocs, *DAG.getContext());
532
533   RVInfo.AnalyzeCallResult(Ins, RetCC_Sparc32);
534
535   // Copy all of the result registers out of their specified physreg.
536   for (unsigned i = 0; i != RVLocs.size(); ++i) {
537     unsigned Reg = RVLocs[i].getLocReg();
538
539     // Remap I0->I7 -> O0->O7.
540     if (Reg >= SP::I0 && Reg <= SP::I7)
541       Reg = Reg-SP::I0+SP::O0;
542
543     Chain = DAG.getCopyFromReg(Chain, dl, Reg,
544                                RVLocs[i].getValVT(), InFlag).getValue(1);
545     InFlag = Chain.getValue(2);
546     InVals.push_back(Chain.getValue(0));
547   }
548
549   return Chain;
550 }
551
552
553
554 //===----------------------------------------------------------------------===//
555 // TargetLowering Implementation
556 //===----------------------------------------------------------------------===//
557
558 /// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
559 /// condition.
560 static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
561   switch (CC) {
562   default: llvm_unreachable("Unknown integer condition code!");
563   case ISD::SETEQ:  return SPCC::ICC_E;
564   case ISD::SETNE:  return SPCC::ICC_NE;
565   case ISD::SETLT:  return SPCC::ICC_L;
566   case ISD::SETGT:  return SPCC::ICC_G;
567   case ISD::SETLE:  return SPCC::ICC_LE;
568   case ISD::SETGE:  return SPCC::ICC_GE;
569   case ISD::SETULT: return SPCC::ICC_CS;
570   case ISD::SETULE: return SPCC::ICC_LEU;
571   case ISD::SETUGT: return SPCC::ICC_GU;
572   case ISD::SETUGE: return SPCC::ICC_CC;
573   }
574 }
575
576 /// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
577 /// FCC condition.
578 static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
579   switch (CC) {
580   default: llvm_unreachable("Unknown fp condition code!");
581   case ISD::SETEQ:
582   case ISD::SETOEQ: return SPCC::FCC_E;
583   case ISD::SETNE:
584   case ISD::SETUNE: return SPCC::FCC_NE;
585   case ISD::SETLT:
586   case ISD::SETOLT: return SPCC::FCC_L;
587   case ISD::SETGT:
588   case ISD::SETOGT: return SPCC::FCC_G;
589   case ISD::SETLE:
590   case ISD::SETOLE: return SPCC::FCC_LE;
591   case ISD::SETGE:
592   case ISD::SETOGE: return SPCC::FCC_GE;
593   case ISD::SETULT: return SPCC::FCC_UL;
594   case ISD::SETULE: return SPCC::FCC_ULE;
595   case ISD::SETUGT: return SPCC::FCC_UG;
596   case ISD::SETUGE: return SPCC::FCC_UGE;
597   case ISD::SETUO:  return SPCC::FCC_U;
598   case ISD::SETO:   return SPCC::FCC_O;
599   case ISD::SETONE: return SPCC::FCC_LG;
600   case ISD::SETUEQ: return SPCC::FCC_UE;
601   }
602 }
603
604 SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
605   : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
606
607   // Set up the register classes.
608   addRegisterClass(MVT::i32, SP::IntRegsRegisterClass);
609   addRegisterClass(MVT::f32, SP::FPRegsRegisterClass);
610   addRegisterClass(MVT::f64, SP::DFPRegsRegisterClass);
611
612   // Turn FP extload into load/fextend
613   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
614   // Sparc doesn't have i1 sign extending load
615   setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
616   // Turn FP truncstore into trunc + store.
617   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
618
619   // Custom legalize GlobalAddress nodes into LO/HI parts.
620   setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
621   setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
622   setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
623
624   // Sparc doesn't have sext_inreg, replace them with shl/sra
625   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
626   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
627   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
628
629   // Sparc has no REM or DIVREM operations.
630   setOperationAction(ISD::UREM, MVT::i32, Expand);
631   setOperationAction(ISD::SREM, MVT::i32, Expand);
632   setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
633   setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
634
635   // Custom expand fp<->sint
636   setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
637   setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
638
639   // Expand fp<->uint
640   setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
641   setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
642
643   setOperationAction(ISD::BITCAST, MVT::f32, Expand);
644   setOperationAction(ISD::BITCAST, MVT::i32, Expand);
645
646   // Sparc has no select or setcc: expand to SELECT_CC.
647   setOperationAction(ISD::SELECT, MVT::i32, Expand);
648   setOperationAction(ISD::SELECT, MVT::f32, Expand);
649   setOperationAction(ISD::SELECT, MVT::f64, Expand);
650   setOperationAction(ISD::SETCC, MVT::i32, Expand);
651   setOperationAction(ISD::SETCC, MVT::f32, Expand);
652   setOperationAction(ISD::SETCC, MVT::f64, Expand);
653
654   // Sparc doesn't have BRCOND either, it has BR_CC.
655   setOperationAction(ISD::BRCOND, MVT::Other, Expand);
656   setOperationAction(ISD::BRIND, MVT::Other, Expand);
657   setOperationAction(ISD::BR_JT, MVT::Other, Expand);
658   setOperationAction(ISD::BR_CC, MVT::i32, Custom);
659   setOperationAction(ISD::BR_CC, MVT::f32, Custom);
660   setOperationAction(ISD::BR_CC, MVT::f64, Custom);
661
662   setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
663   setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
664   setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
665
666   // SPARC has no intrinsics for these particular operations.
667   setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
668
669   setOperationAction(ISD::FSIN , MVT::f64, Expand);
670   setOperationAction(ISD::FCOS , MVT::f64, Expand);
671   setOperationAction(ISD::FREM , MVT::f64, Expand);
672   setOperationAction(ISD::FSIN , MVT::f32, Expand);
673   setOperationAction(ISD::FCOS , MVT::f32, Expand);
674   setOperationAction(ISD::FREM , MVT::f32, Expand);
675   setOperationAction(ISD::CTPOP, MVT::i32, Expand);
676   setOperationAction(ISD::CTTZ , MVT::i32, Expand);
677   setOperationAction(ISD::CTLZ , MVT::i32, Expand);
678   setOperationAction(ISD::ROTL , MVT::i32, Expand);
679   setOperationAction(ISD::ROTR , MVT::i32, Expand);
680   setOperationAction(ISD::BSWAP, MVT::i32, Expand);
681   setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
682   setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
683   setOperationAction(ISD::FPOW , MVT::f64, Expand);
684   setOperationAction(ISD::FPOW , MVT::f32, Expand);
685
686   setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
687   setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
688   setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
689
690   // FIXME: Sparc provides these multiplies, but we don't have them yet.
691   setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
692   setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
693
694   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
695
696   // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
697   setOperationAction(ISD::VASTART           , MVT::Other, Custom);
698   // VAARG needs to be lowered to not do unaligned accesses for doubles.
699   setOperationAction(ISD::VAARG             , MVT::Other, Custom);
700
701   // Use the default implementation.
702   setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
703   setOperationAction(ISD::VAEND             , MVT::Other, Expand);
704   setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
705   setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
706   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
707
708   // No debug info support yet.
709   setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
710
711   setStackPointerRegisterToSaveRestore(SP::O6);
712
713   if (TM.getSubtarget<SparcSubtarget>().isV9())
714     setOperationAction(ISD::CTPOP, MVT::i32, Legal);
715
716   computeRegisterProperties();
717 }
718
719 const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
720   switch (Opcode) {
721   default: return 0;
722   case SPISD::CMPICC:     return "SPISD::CMPICC";
723   case SPISD::CMPFCC:     return "SPISD::CMPFCC";
724   case SPISD::BRICC:      return "SPISD::BRICC";
725   case SPISD::BRFCC:      return "SPISD::BRFCC";
726   case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
727   case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
728   case SPISD::Hi:         return "SPISD::Hi";
729   case SPISD::Lo:         return "SPISD::Lo";
730   case SPISD::FTOI:       return "SPISD::FTOI";
731   case SPISD::ITOF:       return "SPISD::ITOF";
732   case SPISD::CALL:       return "SPISD::CALL";
733   case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
734   }
735 }
736
737 /// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
738 /// be zero. Op is expected to be a target specific node. Used by DAG
739 /// combiner.
740 void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
741                                                          const APInt &Mask,
742                                                          APInt &KnownZero,
743                                                          APInt &KnownOne,
744                                                          const SelectionDAG &DAG,
745                                                          unsigned Depth) const {
746   APInt KnownZero2, KnownOne2;
747   KnownZero = KnownOne = APInt(Mask.getBitWidth(), 0);   // Don't know anything.
748
749   switch (Op.getOpcode()) {
750   default: break;
751   case SPISD::SELECT_ICC:
752   case SPISD::SELECT_FCC:
753     DAG.ComputeMaskedBits(Op.getOperand(1), Mask, KnownZero, KnownOne,
754                           Depth+1);
755     DAG.ComputeMaskedBits(Op.getOperand(0), Mask, KnownZero2, KnownOne2,
756                           Depth+1);
757     assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
758     assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
759
760     // Only known if known in both the LHS and RHS.
761     KnownOne &= KnownOne2;
762     KnownZero &= KnownZero2;
763     break;
764   }
765 }
766
767 // Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
768 // set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
769 static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
770                              ISD::CondCode CC, unsigned &SPCC) {
771   if (isa<ConstantSDNode>(RHS) &&
772       cast<ConstantSDNode>(RHS)->isNullValue() &&
773       CC == ISD::SETNE &&
774       ((LHS.getOpcode() == SPISD::SELECT_ICC &&
775         LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
776        (LHS.getOpcode() == SPISD::SELECT_FCC &&
777         LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
778       isa<ConstantSDNode>(LHS.getOperand(0)) &&
779       isa<ConstantSDNode>(LHS.getOperand(1)) &&
780       cast<ConstantSDNode>(LHS.getOperand(0))->isOne() &&
781       cast<ConstantSDNode>(LHS.getOperand(1))->isNullValue()) {
782     SDValue CMPCC = LHS.getOperand(3);
783     SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
784     LHS = CMPCC.getOperand(0);
785     RHS = CMPCC.getOperand(1);
786   }
787 }
788
789 SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op,
790                                                 SelectionDAG &DAG) const {
791   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
792   // FIXME there isn't really any debug info here
793   DebugLoc dl = Op.getDebugLoc();
794   SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
795   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, GA);
796   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, GA);
797
798   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
799     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
800
801   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
802                                    getPointerTy());
803   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
804   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
805                                 GlobalBase, RelAddr);
806   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
807                      AbsAddr, MachinePointerInfo(), false, false, 0);
808 }
809
810 SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
811                                                SelectionDAG &DAG) const {
812   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
813   // FIXME there isn't really any debug info here
814   DebugLoc dl = Op.getDebugLoc();
815   const Constant *C = N->getConstVal();
816   SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
817   SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, CP);
818   SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, CP);
819   if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
820     return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
821
822   SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
823                                    getPointerTy());
824   SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
825   SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
826                                 GlobalBase, RelAddr);
827   return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
828                      AbsAddr, MachinePointerInfo(), false, false, 0);
829 }
830
831 static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
832   DebugLoc dl = Op.getDebugLoc();
833   // Convert the fp value to integer in an FP register.
834   assert(Op.getValueType() == MVT::i32);
835   Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
836   return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
837 }
838
839 static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
840   DebugLoc dl = Op.getDebugLoc();
841   assert(Op.getOperand(0).getValueType() == MVT::i32);
842   SDValue Tmp = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
843   // Convert the int value to FP in an FP register.
844   return DAG.getNode(SPISD::ITOF, dl, Op.getValueType(), Tmp);
845 }
846
847 static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
848   SDValue Chain = Op.getOperand(0);
849   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
850   SDValue LHS = Op.getOperand(2);
851   SDValue RHS = Op.getOperand(3);
852   SDValue Dest = Op.getOperand(4);
853   DebugLoc dl = Op.getDebugLoc();
854   unsigned Opc, SPCC = ~0U;
855
856   // If this is a br_cc of a "setcc", and if the setcc got lowered into
857   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
858   LookThroughSetCC(LHS, RHS, CC, SPCC);
859
860   // Get the condition flag.
861   SDValue CompareFlag;
862   if (LHS.getValueType() == MVT::i32) {
863     std::vector<EVT> VTs;
864     VTs.push_back(MVT::i32);
865     VTs.push_back(MVT::Glue);
866     SDValue Ops[2] = { LHS, RHS };
867     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
868     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
869     Opc = SPISD::BRICC;
870   } else {
871     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
872     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
873     Opc = SPISD::BRFCC;
874   }
875   return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
876                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
877 }
878
879 static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
880   SDValue LHS = Op.getOperand(0);
881   SDValue RHS = Op.getOperand(1);
882   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
883   SDValue TrueVal = Op.getOperand(2);
884   SDValue FalseVal = Op.getOperand(3);
885   DebugLoc dl = Op.getDebugLoc();
886   unsigned Opc, SPCC = ~0U;
887
888   // If this is a select_cc of a "setcc", and if the setcc got lowered into
889   // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
890   LookThroughSetCC(LHS, RHS, CC, SPCC);
891
892   SDValue CompareFlag;
893   if (LHS.getValueType() == MVT::i32) {
894     std::vector<EVT> VTs;
895     VTs.push_back(LHS.getValueType());   // subcc returns a value
896     VTs.push_back(MVT::Glue);
897     SDValue Ops[2] = { LHS, RHS };
898     CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
899     Opc = SPISD::SELECT_ICC;
900     if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
901   } else {
902     CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
903     Opc = SPISD::SELECT_FCC;
904     if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
905   }
906   return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
907                      DAG.getConstant(SPCC, MVT::i32), CompareFlag);
908 }
909
910 static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
911                             const SparcTargetLowering &TLI) {
912   MachineFunction &MF = DAG.getMachineFunction();
913   SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
914
915   // vastart just stores the address of the VarArgsFrameIndex slot into the
916   // memory location argument.
917   DebugLoc dl = Op.getDebugLoc();
918   SDValue Offset =
919     DAG.getNode(ISD::ADD, dl, MVT::i32,
920                 DAG.getRegister(SP::I6, MVT::i32),
921                 DAG.getConstant(FuncInfo->getVarArgsFrameOffset(),
922                                 MVT::i32));
923   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
924   return DAG.getStore(Op.getOperand(0), dl, Offset, Op.getOperand(1),
925                       MachinePointerInfo(SV), false, false, 0);
926 }
927
928 static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
929   SDNode *Node = Op.getNode();
930   EVT VT = Node->getValueType(0);
931   SDValue InChain = Node->getOperand(0);
932   SDValue VAListPtr = Node->getOperand(1);
933   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
934   DebugLoc dl = Node->getDebugLoc();
935   SDValue VAList = DAG.getLoad(MVT::i32, dl, InChain, VAListPtr,
936                                MachinePointerInfo(SV), false, false, 0);
937   // Increment the pointer, VAList, to the next vaarg
938   SDValue NextPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, VAList,
939                                   DAG.getConstant(VT.getSizeInBits()/8,
940                                                   MVT::i32));
941   // Store the incremented VAList to the legalized pointer
942   InChain = DAG.getStore(VAList.getValue(1), dl, NextPtr,
943                          VAListPtr, MachinePointerInfo(SV), false, false, 0);
944   // Load the actual argument out of the pointer VAList, unless this is an
945   // f64 load.
946   if (VT != MVT::f64)
947     return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
948                        false, false, 0);
949
950   // Otherwise, load it as i64, then do a bitconvert.
951   SDValue V = DAG.getLoad(MVT::i64, dl, InChain, VAList, MachinePointerInfo(),
952                           false, false, 0);
953
954   // Bit-Convert the value to f64.
955   SDValue Ops[2] = {
956     DAG.getNode(ISD::BITCAST, dl, MVT::f64, V),
957     V.getValue(1)
958   };
959   return DAG.getMergeValues(Ops, 2, dl);
960 }
961
962 static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
963   SDValue Chain = Op.getOperand(0);  // Legalize the chain.
964   SDValue Size  = Op.getOperand(1);  // Legalize the size.
965   DebugLoc dl = Op.getDebugLoc();
966
967   unsigned SPReg = SP::O6;
968   SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
969   SDValue NewSP = DAG.getNode(ISD::SUB, dl, MVT::i32, SP, Size); // Value
970   Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
971
972   // The resultant pointer is actually 16 words from the bottom of the stack,
973   // to provide a register spill area.
974   SDValue NewVal = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
975                                  DAG.getConstant(96, MVT::i32));
976   SDValue Ops[2] = { NewVal, Chain };
977   return DAG.getMergeValues(Ops, 2, dl);
978 }
979
980
981 SDValue SparcTargetLowering::
982 LowerOperation(SDValue Op, SelectionDAG &DAG) const {
983   switch (Op.getOpcode()) {
984   default: llvm_unreachable("Should not custom lower this!");
985   // Frame & Return address.  Currently unimplemented
986   case ISD::RETURNADDR: return SDValue();
987   case ISD::FRAMEADDR:  return SDValue();
988   case ISD::GlobalTLSAddress:
989     llvm_unreachable("TLS not implemented for Sparc.");
990   case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
991   case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
992   case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
993   case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
994   case ISD::BR_CC:              return LowerBR_CC(Op, DAG);
995   case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
996   case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
997   case ISD::VAARG:              return LowerVAARG(Op, DAG);
998   case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
999   }
1000 }
1001
1002 MachineBasicBlock *
1003 SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1004                                                  MachineBasicBlock *BB) const {
1005   const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1006   unsigned BROpcode;
1007   unsigned CC;
1008   DebugLoc dl = MI->getDebugLoc();
1009   // Figure out the conditional branch opcode to use for this select_cc.
1010   switch (MI->getOpcode()) {
1011   default: llvm_unreachable("Unknown SELECT_CC!");
1012   case SP::SELECT_CC_Int_ICC:
1013   case SP::SELECT_CC_FP_ICC:
1014   case SP::SELECT_CC_DFP_ICC:
1015     BROpcode = SP::BCOND;
1016     break;
1017   case SP::SELECT_CC_Int_FCC:
1018   case SP::SELECT_CC_FP_FCC:
1019   case SP::SELECT_CC_DFP_FCC:
1020     BROpcode = SP::FBCOND;
1021     break;
1022   }
1023
1024   CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
1025
1026   // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1027   // control-flow pattern.  The incoming instruction knows the destination vreg
1028   // to set, the condition code register to branch on, the true/false values to
1029   // select between, and a branch opcode to use.
1030   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1031   MachineFunction::iterator It = BB;
1032   ++It;
1033
1034   //  thisMBB:
1035   //  ...
1036   //   TrueVal = ...
1037   //   [f]bCC copy1MBB
1038   //   fallthrough --> copy0MBB
1039   MachineBasicBlock *thisMBB = BB;
1040   MachineFunction *F = BB->getParent();
1041   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1042   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1043   F->insert(It, copy0MBB);
1044   F->insert(It, sinkMBB);
1045
1046   // Transfer the remainder of BB and its successor edges to sinkMBB.
1047   sinkMBB->splice(sinkMBB->begin(), BB,
1048                   llvm::next(MachineBasicBlock::iterator(MI)),
1049                   BB->end());
1050   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1051
1052   // Add the true and fallthrough blocks as its successors.
1053   BB->addSuccessor(copy0MBB);
1054   BB->addSuccessor(sinkMBB);
1055
1056   BuildMI(BB, dl, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
1057
1058   //  copy0MBB:
1059   //   %FalseValue = ...
1060   //   # fallthrough to sinkMBB
1061   BB = copy0MBB;
1062
1063   // Update machine-CFG edges
1064   BB->addSuccessor(sinkMBB);
1065
1066   //  sinkMBB:
1067   //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1068   //  ...
1069   BB = sinkMBB;
1070   BuildMI(*BB, BB->begin(), dl, TII.get(SP::PHI), MI->getOperand(0).getReg())
1071     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1072     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1073
1074   MI->eraseFromParent();   // The pseudo instruction is gone now.
1075   return BB;
1076 }
1077
1078 //===----------------------------------------------------------------------===//
1079 //                         Sparc Inline Assembly Support
1080 //===----------------------------------------------------------------------===//
1081
1082 /// getConstraintType - Given a constraint letter, return the type of
1083 /// constraint it is for this target.
1084 SparcTargetLowering::ConstraintType
1085 SparcTargetLowering::getConstraintType(const std::string &Constraint) const {
1086   if (Constraint.size() == 1) {
1087     switch (Constraint[0]) {
1088     default:  break;
1089     case 'r': return C_RegisterClass;
1090     }
1091   }
1092
1093   return TargetLowering::getConstraintType(Constraint);
1094 }
1095
1096 std::pair<unsigned, const TargetRegisterClass*>
1097 SparcTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1098                                                   EVT VT) const {
1099   if (Constraint.size() == 1) {
1100     switch (Constraint[0]) {
1101     case 'r':
1102       return std::make_pair(0U, SP::IntRegsRegisterClass);
1103     }
1104   }
1105
1106   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1107 }
1108
1109 std::vector<unsigned> SparcTargetLowering::
1110 getRegClassForInlineAsmConstraint(const std::string &Constraint,
1111                                   EVT VT) const {
1112   if (Constraint.size() != 1)
1113     return std::vector<unsigned>();
1114
1115   switch (Constraint[0]) {
1116   default: break;
1117   case 'r':
1118     return make_vector<unsigned>(SP::L0, SP::L1, SP::L2, SP::L3,
1119                                  SP::L4, SP::L5, SP::L6, SP::L7,
1120                                  SP::I0, SP::I1, SP::I2, SP::I3,
1121                                  SP::I4, SP::I5,
1122                                  SP::O0, SP::O1, SP::O2, SP::O3,
1123                                  SP::O4, SP::O5, SP::O7, 0);
1124   }
1125
1126   return std::vector<unsigned>();
1127 }
1128
1129 bool
1130 SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1131   // The Sparc target isn't yet aware of offsets.
1132   return false;
1133 }
1134
1135 /// getFunctionAlignment - Return the Log2 alignment of this function.
1136 unsigned SparcTargetLowering::getFunctionAlignment(const Function *) const {
1137   return 2;
1138 }