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