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