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