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