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