SparcISelLowering.cpp revision 18fdb398ea94c7ddee40bec49f63491922c5b110
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// Allocate a full-sized argument for the 64-bit ABI.
78static bool CC_Sparc64_Full(unsigned &ValNo, MVT &ValVT,
79                            MVT &LocVT, CCValAssign::LocInfo &LocInfo,
80                            ISD::ArgFlagsTy &ArgFlags, CCState &State) {
81  assert((LocVT == MVT::f32 || LocVT.getSizeInBits() == 64) &&
82         "Can't handle non-64 bits locations");
83
84  // Stack space is allocated for all arguments starting from [%fp+BIAS+128].
85  unsigned Offset = State.AllocateStack(8, 8);
86  unsigned Reg = 0;
87
88  if (LocVT == MVT::i64 && Offset < 6*8)
89    // Promote integers to %i0-%i5.
90    Reg = SP::I0 + Offset/8;
91  else if (LocVT == MVT::f64 && Offset < 16*8)
92    // Promote doubles to %d0-%d30. (Which LLVM calls D0-D15).
93    Reg = SP::D0 + Offset/8;
94  else if (LocVT == MVT::f32 && Offset < 16*8)
95    // Promote floats to %f1, %f3, ...
96    Reg = SP::F1 + Offset/4;
97
98  // Promote to register when possible, otherwise use the stack slot.
99  if (Reg) {
100    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
101    return true;
102  }
103
104  // This argument goes on the stack in an 8-byte slot.
105  // When passing floats, LocVT is smaller than 8 bytes. Adjust the offset to
106  // the right-aligned float. The first 4 bytes of the stack slot are undefined.
107  if (LocVT == MVT::f32)
108    Offset += 4;
109
110  State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
111  return true;
112}
113
114// Allocate a half-sized argument for the 64-bit ABI.
115//
116// This is used when passing { float, int } structs by value in registers.
117static bool CC_Sparc64_Half(unsigned &ValNo, MVT &ValVT,
118                            MVT &LocVT, CCValAssign::LocInfo &LocInfo,
119                            ISD::ArgFlagsTy &ArgFlags, CCState &State) {
120  assert(LocVT.getSizeInBits() == 32 && "Can't handle non-32 bits locations");
121  unsigned Offset = State.AllocateStack(4, 4);
122
123  if (LocVT == MVT::f32 && Offset < 16*8) {
124    // Promote floats to %f0-%f31.
125    State.addLoc(CCValAssign::getReg(ValNo, ValVT, SP::F0 + Offset/4,
126                                     LocVT, LocInfo));
127    return true;
128  }
129
130  if (LocVT == MVT::i32 && Offset < 6*8) {
131    // Promote integers to %i0-%i5, using half the register.
132    unsigned Reg = SP::I0 + Offset/8;
133    LocVT = MVT::i64;
134    LocInfo = CCValAssign::AExt;
135
136    // Set the Custom bit if this i32 goes in the high bits of a register.
137    if (Offset % 8 == 0)
138      State.addLoc(CCValAssign::getCustomReg(ValNo, ValVT, Reg,
139                                             LocVT, LocInfo));
140    else
141      State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
142    return true;
143  }
144
145  State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
146  return true;
147}
148
149#include "SparcGenCallingConv.inc"
150
151SDValue
152SparcTargetLowering::LowerReturn(SDValue Chain,
153                                 CallingConv::ID CallConv, bool IsVarArg,
154                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
155                                 const SmallVectorImpl<SDValue> &OutVals,
156                                 DebugLoc DL, SelectionDAG &DAG) const {
157  if (Subtarget->is64Bit())
158    return LowerReturn_64(Chain, CallConv, IsVarArg, Outs, OutVals, DL, DAG);
159  return LowerReturn_32(Chain, CallConv, IsVarArg, Outs, OutVals, DL, DAG);
160}
161
162SDValue
163SparcTargetLowering::LowerReturn_32(SDValue Chain,
164                                    CallingConv::ID CallConv, bool IsVarArg,
165                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
166                                    const SmallVectorImpl<SDValue> &OutVals,
167                                    DebugLoc DL, SelectionDAG &DAG) const {
168  MachineFunction &MF = DAG.getMachineFunction();
169
170  // CCValAssign - represent the assignment of the return value to locations.
171  SmallVector<CCValAssign, 16> RVLocs;
172
173  // CCState - Info about the registers and stack slot.
174  CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
175                 DAG.getTarget(), RVLocs, *DAG.getContext());
176
177  // Analyze return values.
178  CCInfo.AnalyzeReturn(Outs, RetCC_Sparc32);
179
180  SDValue Flag;
181  SmallVector<SDValue, 4> RetOps(1, Chain);
182  // Make room for the return address offset.
183  RetOps.push_back(SDValue());
184
185  // Copy the result values into the output registers.
186  for (unsigned i = 0; i != RVLocs.size(); ++i) {
187    CCValAssign &VA = RVLocs[i];
188    assert(VA.isRegLoc() && "Can only return in registers!");
189
190    Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(),
191                             OutVals[i], Flag);
192
193    // Guarantee that all emitted copies are stuck together with flags.
194    Flag = Chain.getValue(1);
195    RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
196  }
197
198  unsigned RetAddrOffset = 8; //Call Inst + Delay Slot
199  // If the function returns a struct, copy the SRetReturnReg to I0
200  if (MF.getFunction()->hasStructRetAttr()) {
201    SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
202    unsigned Reg = SFI->getSRetReturnReg();
203    if (!Reg)
204      llvm_unreachable("sret virtual register not created in the entry block");
205    SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
206    Chain = DAG.getCopyToReg(Chain, DL, SP::I0, Val, Flag);
207    Flag = Chain.getValue(1);
208    RetOps.push_back(DAG.getRegister(SP::I0, getPointerTy()));
209    RetAddrOffset = 12; // CallInst + Delay Slot + Unimp
210  }
211
212  RetOps[0] = Chain;  // Update chain.
213  RetOps[1] = DAG.getConstant(RetAddrOffset, MVT::i32);
214
215  // Add the flag if we have it.
216  if (Flag.getNode())
217    RetOps.push_back(Flag);
218
219  return DAG.getNode(SPISD::RET_FLAG, DL, MVT::Other,
220                     &RetOps[0], RetOps.size());
221}
222
223// Lower return values for the 64-bit ABI.
224// Return values are passed the exactly the same way as function arguments.
225SDValue
226SparcTargetLowering::LowerReturn_64(SDValue Chain,
227                                    CallingConv::ID CallConv, bool IsVarArg,
228                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
229                                    const SmallVectorImpl<SDValue> &OutVals,
230                                    DebugLoc DL, SelectionDAG &DAG) const {
231  // CCValAssign - represent the assignment of the return value to locations.
232  SmallVector<CCValAssign, 16> RVLocs;
233
234  // CCState - Info about the registers and stack slot.
235  CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
236                 DAG.getTarget(), RVLocs, *DAG.getContext());
237
238  // Analyze return values.
239  CCInfo.AnalyzeReturn(Outs, CC_Sparc64);
240
241  SDValue Flag;
242  SmallVector<SDValue, 4> RetOps(1, Chain);
243
244  // The second operand on the return instruction is the return address offset.
245  // The return address is always %i7+8 with the 64-bit ABI.
246  RetOps.push_back(DAG.getConstant(8, MVT::i32));
247
248  // Copy the result values into the output registers.
249  for (unsigned i = 0; i != RVLocs.size(); ++i) {
250    CCValAssign &VA = RVLocs[i];
251    assert(VA.isRegLoc() && "Can only return in registers!");
252    SDValue OutVal = OutVals[i];
253
254    // Integer return values must be sign or zero extended by the callee.
255    switch (VA.getLocInfo()) {
256    case CCValAssign::SExt:
257      OutVal = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), OutVal);
258      break;
259    case CCValAssign::ZExt:
260      OutVal = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), OutVal);
261      break;
262    case CCValAssign::AExt:
263      OutVal = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), OutVal);
264    default:
265      break;
266    }
267
268    // The custom bit on an i32 return value indicates that it should be passed
269    // in the high bits of the register.
270    if (VA.getValVT() == MVT::i32 && VA.needsCustom()) {
271      OutVal = DAG.getNode(ISD::SHL, DL, MVT::i64, OutVal,
272                           DAG.getConstant(32, MVT::i32));
273
274      // The next value may go in the low bits of the same register.
275      // Handle both at once.
276      if (i+1 < RVLocs.size() && RVLocs[i+1].getLocReg() == VA.getLocReg()) {
277        SDValue NV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, OutVals[i+1]);
278        OutVal = DAG.getNode(ISD::OR, DL, MVT::i64, OutVal, NV);
279        // Skip the next value, it's already done.
280        ++i;
281      }
282    }
283
284    Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), OutVal, Flag);
285
286    // Guarantee that all emitted copies are stuck together with flags.
287    Flag = Chain.getValue(1);
288    RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
289  }
290
291  RetOps[0] = Chain;  // Update chain.
292
293  // Add the flag if we have it.
294  if (Flag.getNode())
295    RetOps.push_back(Flag);
296
297  return DAG.getNode(SPISD::RET_FLAG, DL, MVT::Other,
298                     &RetOps[0], RetOps.size());
299}
300
301SDValue SparcTargetLowering::
302LowerFormalArguments(SDValue Chain,
303                     CallingConv::ID CallConv,
304                     bool IsVarArg,
305                     const SmallVectorImpl<ISD::InputArg> &Ins,
306                     DebugLoc DL,
307                     SelectionDAG &DAG,
308                     SmallVectorImpl<SDValue> &InVals) const {
309  if (Subtarget->is64Bit())
310    return LowerFormalArguments_64(Chain, CallConv, IsVarArg, Ins,
311                                   DL, DAG, InVals);
312  return LowerFormalArguments_32(Chain, CallConv, IsVarArg, Ins,
313                                 DL, DAG, InVals);
314}
315
316/// LowerFormalArguments32 - V8 uses a very simple ABI, where all values are
317/// passed in either one or two GPRs, including FP values.  TODO: we should
318/// pass FP values in FP registers for fastcc functions.
319SDValue SparcTargetLowering::
320LowerFormalArguments_32(SDValue Chain,
321                        CallingConv::ID CallConv,
322                        bool isVarArg,
323                        const SmallVectorImpl<ISD::InputArg> &Ins,
324                        DebugLoc dl,
325                        SelectionDAG &DAG,
326                        SmallVectorImpl<SDValue> &InVals) const {
327  MachineFunction &MF = DAG.getMachineFunction();
328  MachineRegisterInfo &RegInfo = MF.getRegInfo();
329  SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
330
331  // Assign locations to all of the incoming arguments.
332  SmallVector<CCValAssign, 16> ArgLocs;
333  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
334                 getTargetMachine(), ArgLocs, *DAG.getContext());
335  CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc32);
336
337  const unsigned StackOffset = 92;
338
339  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
340    CCValAssign &VA = ArgLocs[i];
341
342    if (i == 0  && Ins[i].Flags.isSRet()) {
343      //Get SRet from [%fp+64]
344      int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, 64, true);
345      SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
346      SDValue Arg = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
347                                MachinePointerInfo(),
348                                false, false, false, 0);
349      InVals.push_back(Arg);
350      continue;
351    }
352
353    if (VA.isRegLoc()) {
354      if (VA.needsCustom()) {
355        assert(VA.getLocVT() == MVT::f64);
356        unsigned VRegHi = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
357        MF.getRegInfo().addLiveIn(VA.getLocReg(), VRegHi);
358        SDValue HiVal = DAG.getCopyFromReg(Chain, dl, VRegHi, MVT::i32);
359
360        assert(i+1 < e);
361        CCValAssign &NextVA = ArgLocs[++i];
362
363        SDValue LoVal;
364        if (NextVA.isMemLoc()) {
365          int FrameIdx = MF.getFrameInfo()->
366            CreateFixedObject(4, StackOffset+NextVA.getLocMemOffset(),true);
367          SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
368          LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
369                              MachinePointerInfo(),
370                              false, false, false, 0);
371        } else {
372          unsigned loReg = MF.addLiveIn(NextVA.getLocReg(),
373                                        &SP::IntRegsRegClass);
374          LoVal = DAG.getCopyFromReg(Chain, dl, loReg, MVT::i32);
375        }
376        SDValue WholeValue =
377          DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
378        WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
379        InVals.push_back(WholeValue);
380        continue;
381      }
382      unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
383      MF.getRegInfo().addLiveIn(VA.getLocReg(), VReg);
384      SDValue Arg = DAG.getCopyFromReg(Chain, dl, VReg, MVT::i32);
385      if (VA.getLocVT() == MVT::f32)
386        Arg = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Arg);
387      else if (VA.getLocVT() != MVT::i32) {
388        Arg = DAG.getNode(ISD::AssertSext, dl, MVT::i32, Arg,
389                          DAG.getValueType(VA.getLocVT()));
390        Arg = DAG.getNode(ISD::TRUNCATE, dl, VA.getLocVT(), Arg);
391      }
392      InVals.push_back(Arg);
393      continue;
394    }
395
396    assert(VA.isMemLoc());
397
398    unsigned Offset = VA.getLocMemOffset()+StackOffset;
399
400    if (VA.needsCustom()) {
401      assert(VA.getValVT() == MVT::f64);
402      //If it is double-word aligned, just load.
403      if (Offset % 8 == 0) {
404        int FI = MF.getFrameInfo()->CreateFixedObject(8,
405                                                      Offset,
406                                                      true);
407        SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
408        SDValue Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
409                                   MachinePointerInfo(),
410                                   false,false, false, 0);
411        InVals.push_back(Load);
412        continue;
413      }
414
415      int FI = MF.getFrameInfo()->CreateFixedObject(4,
416                                                    Offset,
417                                                    true);
418      SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
419      SDValue HiVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr,
420                                  MachinePointerInfo(),
421                                  false, false, false, 0);
422      int FI2 = MF.getFrameInfo()->CreateFixedObject(4,
423                                                     Offset+4,
424                                                     true);
425      SDValue FIPtr2 = DAG.getFrameIndex(FI2, getPointerTy());
426
427      SDValue LoVal = DAG.getLoad(MVT::i32, dl, Chain, FIPtr2,
428                                  MachinePointerInfo(),
429                                  false, false, false, 0);
430
431      SDValue WholeValue =
432        DAG.getNode(ISD::BUILD_PAIR, dl, MVT::i64, LoVal, HiVal);
433      WholeValue = DAG.getNode(ISD::BITCAST, dl, MVT::f64, WholeValue);
434      InVals.push_back(WholeValue);
435      continue;
436    }
437
438    int FI = MF.getFrameInfo()->CreateFixedObject(4,
439                                                  Offset,
440                                                  true);
441    SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
442    SDValue Load ;
443    if (VA.getValVT() == MVT::i32 || VA.getValVT() == MVT::f32) {
444      Load = DAG.getLoad(VA.getValVT(), dl, Chain, FIPtr,
445                         MachinePointerInfo(),
446                         false, false, false, 0);
447    } else {
448      ISD::LoadExtType LoadOp = ISD::SEXTLOAD;
449      // Sparc is big endian, so add an offset based on the ObjectVT.
450      unsigned Offset = 4-std::max(1U, VA.getValVT().getSizeInBits()/8);
451      FIPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIPtr,
452                          DAG.getConstant(Offset, MVT::i32));
453      Load = DAG.getExtLoad(LoadOp, dl, MVT::i32, Chain, FIPtr,
454                            MachinePointerInfo(),
455                            VA.getValVT(), false, false,0);
456      Load = DAG.getNode(ISD::TRUNCATE, dl, VA.getValVT(), Load);
457    }
458    InVals.push_back(Load);
459  }
460
461  if (MF.getFunction()->hasStructRetAttr()) {
462    //Copy the SRet Argument to SRetReturnReg
463    SparcMachineFunctionInfo *SFI = MF.getInfo<SparcMachineFunctionInfo>();
464    unsigned Reg = SFI->getSRetReturnReg();
465    if (!Reg) {
466      Reg = MF.getRegInfo().createVirtualRegister(&SP::IntRegsRegClass);
467      SFI->setSRetReturnReg(Reg);
468    }
469    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
470    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
471  }
472
473  // Store remaining ArgRegs to the stack if this is a varargs function.
474  if (isVarArg) {
475    static const uint16_t ArgRegs[] = {
476      SP::I0, SP::I1, SP::I2, SP::I3, SP::I4, SP::I5
477    };
478    unsigned NumAllocated = CCInfo.getFirstUnallocated(ArgRegs, 6);
479    const uint16_t *CurArgReg = ArgRegs+NumAllocated, *ArgRegEnd = ArgRegs+6;
480    unsigned ArgOffset = CCInfo.getNextStackOffset();
481    if (NumAllocated == 6)
482      ArgOffset += StackOffset;
483    else {
484      assert(!ArgOffset);
485      ArgOffset = 68+4*NumAllocated;
486    }
487
488    // Remember the vararg offset for the va_start implementation.
489    FuncInfo->setVarArgsFrameOffset(ArgOffset);
490
491    std::vector<SDValue> OutChains;
492
493    for (; CurArgReg != ArgRegEnd; ++CurArgReg) {
494      unsigned VReg = RegInfo.createVirtualRegister(&SP::IntRegsRegClass);
495      MF.getRegInfo().addLiveIn(*CurArgReg, VReg);
496      SDValue Arg = DAG.getCopyFromReg(DAG.getRoot(), dl, VReg, MVT::i32);
497
498      int FrameIdx = MF.getFrameInfo()->CreateFixedObject(4, ArgOffset,
499                                                          true);
500      SDValue FIPtr = DAG.getFrameIndex(FrameIdx, MVT::i32);
501
502      OutChains.push_back(DAG.getStore(DAG.getRoot(), dl, Arg, FIPtr,
503                                       MachinePointerInfo(),
504                                       false, false, 0));
505      ArgOffset += 4;
506    }
507
508    if (!OutChains.empty()) {
509      OutChains.push_back(Chain);
510      Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
511                          &OutChains[0], OutChains.size());
512    }
513  }
514
515  return Chain;
516}
517
518// Lower formal arguments for the 64 bit ABI.
519SDValue SparcTargetLowering::
520LowerFormalArguments_64(SDValue Chain,
521                        CallingConv::ID CallConv,
522                        bool IsVarArg,
523                        const SmallVectorImpl<ISD::InputArg> &Ins,
524                        DebugLoc DL,
525                        SelectionDAG &DAG,
526                        SmallVectorImpl<SDValue> &InVals) const {
527  MachineFunction &MF = DAG.getMachineFunction();
528
529  // Analyze arguments according to CC_Sparc64.
530  SmallVector<CCValAssign, 16> ArgLocs;
531  CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
532                 getTargetMachine(), ArgLocs, *DAG.getContext());
533  CCInfo.AnalyzeFormalArguments(Ins, CC_Sparc64);
534
535  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
536    CCValAssign &VA = ArgLocs[i];
537    if (VA.isRegLoc()) {
538      // This argument is passed in a register.
539      // All integer register arguments are promoted by the caller to i64.
540
541      // Create a virtual register for the promoted live-in value.
542      unsigned VReg = MF.addLiveIn(VA.getLocReg(),
543                                   getRegClassFor(VA.getLocVT()));
544      SDValue Arg = DAG.getCopyFromReg(Chain, DL, VReg, VA.getLocVT());
545
546      // Get the high bits for i32 struct elements.
547      if (VA.getValVT() == MVT::i32 && VA.needsCustom())
548        Arg = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Arg,
549                          DAG.getConstant(32, MVT::i32));
550
551      // The caller promoted the argument, so insert an Assert?ext SDNode so we
552      // won't promote the value again in this function.
553      switch (VA.getLocInfo()) {
554      case CCValAssign::SExt:
555        Arg = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Arg,
556                          DAG.getValueType(VA.getValVT()));
557        break;
558      case CCValAssign::ZExt:
559        Arg = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Arg,
560                          DAG.getValueType(VA.getValVT()));
561        break;
562      default:
563        break;
564      }
565
566      // Truncate the register down to the argument type.
567      if (VA.isExtInLoc())
568        Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
569
570      InVals.push_back(Arg);
571      continue;
572    }
573
574    // The registers are exhausted. This argument was passed on the stack.
575    assert(VA.isMemLoc());
576    // The CC_Sparc64_Full/Half functions compute stack offsets relative to the
577    // beginning of the arguments area at %fp+BIAS+128.
578    unsigned Offset = VA.getLocMemOffset() + 128;
579    unsigned ValSize = VA.getValVT().getSizeInBits() / 8;
580    // Adjust offset for extended arguments, SPARC is big-endian.
581    // The caller will have written the full slot with extended bytes, but we
582    // prefer our own extending loads.
583    if (VA.isExtInLoc())
584      Offset += 8 - ValSize;
585    int FI = MF.getFrameInfo()->CreateFixedObject(ValSize, Offset, true);
586    InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain,
587                                 DAG.getFrameIndex(FI, getPointerTy()),
588                                 MachinePointerInfo::getFixedStack(FI),
589                                 false, false, false, 0));
590  }
591  return Chain;
592}
593
594SDValue
595SparcTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
596                               SmallVectorImpl<SDValue> &InVals) const {
597  if (Subtarget->is64Bit())
598    return LowerCall_64(CLI, InVals);
599  return LowerCall_32(CLI, InVals);
600}
601
602// Lower a call for the 32-bit ABI.
603SDValue
604SparcTargetLowering::LowerCall_32(TargetLowering::CallLoweringInfo &CLI,
605                                  SmallVectorImpl<SDValue> &InVals) const {
606  SelectionDAG &DAG                     = CLI.DAG;
607  DebugLoc &dl                          = CLI.DL;
608  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
609  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
610  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
611  SDValue Chain                         = CLI.Chain;
612  SDValue Callee                        = CLI.Callee;
613  bool &isTailCall                      = CLI.IsTailCall;
614  CallingConv::ID CallConv              = CLI.CallConv;
615  bool isVarArg                         = CLI.IsVarArg;
616
617  // Sparc target does not yet support tail call optimization.
618  isTailCall = false;
619
620  // Analyze operands of the call, assigning locations to each operand.
621  SmallVector<CCValAssign, 16> ArgLocs;
622  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
623                 DAG.getTarget(), ArgLocs, *DAG.getContext());
624  CCInfo.AnalyzeCallOperands(Outs, CC_Sparc32);
625
626  // Get the size of the outgoing arguments stack space requirement.
627  unsigned ArgsSize = CCInfo.getNextStackOffset();
628
629  // Keep stack frames 8-byte aligned.
630  ArgsSize = (ArgsSize+7) & ~7;
631
632  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
633
634  //Create local copies for byval args.
635  SmallVector<SDValue, 8> ByValArgs;
636  for (unsigned i = 0,  e = Outs.size(); i != e; ++i) {
637    ISD::ArgFlagsTy Flags = Outs[i].Flags;
638    if (!Flags.isByVal())
639      continue;
640
641    SDValue Arg = OutVals[i];
642    unsigned Size = Flags.getByValSize();
643    unsigned Align = Flags.getByValAlign();
644
645    int FI = MFI->CreateStackObject(Size, Align, false);
646    SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy());
647    SDValue SizeNode = DAG.getConstant(Size, MVT::i32);
648
649    Chain = DAG.getMemcpy(Chain, dl, FIPtr, Arg, SizeNode, Align,
650                          false,        //isVolatile,
651                          (Size <= 32), //AlwaysInline if size <= 32
652                          MachinePointerInfo(), MachinePointerInfo());
653    ByValArgs.push_back(FIPtr);
654  }
655
656  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true));
657
658  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
659  SmallVector<SDValue, 8> MemOpChains;
660
661  const unsigned StackOffset = 92;
662  bool hasStructRetAttr = false;
663  // Walk the register/memloc assignments, inserting copies/loads.
664  for (unsigned i = 0, realArgIdx = 0, byvalArgIdx = 0, e = ArgLocs.size();
665       i != e;
666       ++i, ++realArgIdx) {
667    CCValAssign &VA = ArgLocs[i];
668    SDValue Arg = OutVals[realArgIdx];
669
670    ISD::ArgFlagsTy Flags = Outs[realArgIdx].Flags;
671
672    //Use local copy if it is a byval arg.
673    if (Flags.isByVal())
674      Arg = ByValArgs[byvalArgIdx++];
675
676    // Promote the value if needed.
677    switch (VA.getLocInfo()) {
678    default: llvm_unreachable("Unknown loc info!");
679    case CCValAssign::Full: break;
680    case CCValAssign::SExt:
681      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, VA.getLocVT(), Arg);
682      break;
683    case CCValAssign::ZExt:
684      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, VA.getLocVT(), Arg);
685      break;
686    case CCValAssign::AExt:
687      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, VA.getLocVT(), Arg);
688      break;
689    case CCValAssign::BCvt:
690      Arg = DAG.getNode(ISD::BITCAST, dl, VA.getLocVT(), Arg);
691      break;
692    }
693
694    if (Flags.isSRet()) {
695      assert(VA.needsCustom());
696      // store SRet argument in %sp+64
697      SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
698      SDValue PtrOff = DAG.getIntPtrConstant(64);
699      PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
700      MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
701                                         MachinePointerInfo(),
702                                         false, false, 0));
703      hasStructRetAttr = true;
704      continue;
705    }
706
707    if (VA.needsCustom()) {
708      assert(VA.getLocVT() == MVT::f64);
709
710      if (VA.isMemLoc()) {
711        unsigned Offset = VA.getLocMemOffset() + StackOffset;
712        //if it is double-word aligned, just store.
713        if (Offset % 8 == 0) {
714          SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
715          SDValue PtrOff = DAG.getIntPtrConstant(Offset);
716          PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
717          MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
718                                             MachinePointerInfo(),
719                                             false, false, 0));
720          continue;
721        }
722      }
723
724      SDValue StackPtr = DAG.CreateStackTemporary(MVT::f64, MVT::i32);
725      SDValue Store = DAG.getStore(DAG.getEntryNode(), dl,
726                                   Arg, StackPtr, MachinePointerInfo(),
727                                   false, false, 0);
728      // Sparc is big-endian, so the high part comes first.
729      SDValue Hi = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
730                               MachinePointerInfo(), false, false, false, 0);
731      // Increment the pointer to the other half.
732      StackPtr = DAG.getNode(ISD::ADD, dl, StackPtr.getValueType(), StackPtr,
733                             DAG.getIntPtrConstant(4));
734      // Load the low part.
735      SDValue Lo = DAG.getLoad(MVT::i32, dl, Store, StackPtr,
736                               MachinePointerInfo(), false, false, false, 0);
737
738      if (VA.isRegLoc()) {
739        RegsToPass.push_back(std::make_pair(VA.getLocReg(), Hi));
740        assert(i+1 != e);
741        CCValAssign &NextVA = ArgLocs[++i];
742        if (NextVA.isRegLoc()) {
743          RegsToPass.push_back(std::make_pair(NextVA.getLocReg(), Lo));
744        } else {
745          //Store the low part in stack.
746          unsigned Offset = NextVA.getLocMemOffset() + StackOffset;
747          SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
748          SDValue PtrOff = DAG.getIntPtrConstant(Offset);
749          PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
750          MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
751                                             MachinePointerInfo(),
752                                             false, false, 0));
753        }
754      } else {
755        unsigned Offset = VA.getLocMemOffset() + StackOffset;
756        // Store the high part.
757        SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
758        SDValue PtrOff = DAG.getIntPtrConstant(Offset);
759        PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
760        MemOpChains.push_back(DAG.getStore(Chain, dl, Hi, PtrOff,
761                                           MachinePointerInfo(),
762                                           false, false, 0));
763        // Store the low part.
764        PtrOff = DAG.getIntPtrConstant(Offset+4);
765        PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
766        MemOpChains.push_back(DAG.getStore(Chain, dl, Lo, PtrOff,
767                                           MachinePointerInfo(),
768                                           false, false, 0));
769      }
770      continue;
771    }
772
773    // Arguments that can be passed on register must be kept at
774    // RegsToPass vector
775    if (VA.isRegLoc()) {
776      if (VA.getLocVT() != MVT::f32) {
777        RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
778        continue;
779      }
780      Arg = DAG.getNode(ISD::BITCAST, dl, MVT::i32, Arg);
781      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
782      continue;
783    }
784
785    assert(VA.isMemLoc());
786
787    // Create a store off the stack pointer for this argument.
788    SDValue StackPtr = DAG.getRegister(SP::O6, MVT::i32);
789    SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset()+StackOffset);
790    PtrOff = DAG.getNode(ISD::ADD, dl, MVT::i32, StackPtr, PtrOff);
791    MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
792                                       MachinePointerInfo(),
793                                       false, false, 0));
794  }
795
796
797  // Emit all stores, make sure the occur before any copies into physregs.
798  if (!MemOpChains.empty())
799    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
800                        &MemOpChains[0], MemOpChains.size());
801
802  // Build a sequence of copy-to-reg nodes chained together with token
803  // chain and flag operands which copy the outgoing args into registers.
804  // The InFlag in necessary since all emitted instructions must be
805  // stuck together.
806  SDValue InFlag;
807  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
808    unsigned Reg = RegsToPass[i].first;
809    // Remap I0->I7 -> O0->O7.
810    if (Reg >= SP::I0 && Reg <= SP::I7)
811      Reg = Reg-SP::I0+SP::O0;
812
813    Chain = DAG.getCopyToReg(Chain, dl, Reg, RegsToPass[i].second, InFlag);
814    InFlag = Chain.getValue(1);
815  }
816
817  unsigned SRetArgSize = (hasStructRetAttr)? getSRetArgSize(DAG, Callee):0;
818
819  // If the callee is a GlobalAddress node (quite common, every direct call is)
820  // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
821  // Likewise ExternalSymbol -> TargetExternalSymbol.
822  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
823    Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, MVT::i32);
824  else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
825    Callee = DAG.getTargetExternalSymbol(E->getSymbol(), MVT::i32);
826
827  // Returns a chain & a flag for retval copy to use
828  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
829  SmallVector<SDValue, 8> Ops;
830  Ops.push_back(Chain);
831  Ops.push_back(Callee);
832  if (hasStructRetAttr)
833    Ops.push_back(DAG.getTargetConstant(SRetArgSize, MVT::i32));
834  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
835    unsigned Reg = RegsToPass[i].first;
836    if (Reg >= SP::I0 && Reg <= SP::I7)
837      Reg = Reg-SP::I0+SP::O0;
838
839    Ops.push_back(DAG.getRegister(Reg, RegsToPass[i].second.getValueType()));
840  }
841  if (InFlag.getNode())
842    Ops.push_back(InFlag);
843
844  Chain = DAG.getNode(SPISD::CALL, dl, NodeTys, &Ops[0], Ops.size());
845  InFlag = Chain.getValue(1);
846
847  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
848                             DAG.getIntPtrConstant(0, true), InFlag);
849  InFlag = Chain.getValue(1);
850
851  // Assign locations to each value returned by this call.
852  SmallVector<CCValAssign, 16> RVLocs;
853  CCState RVInfo(CallConv, isVarArg, DAG.getMachineFunction(),
854                 DAG.getTarget(), RVLocs, *DAG.getContext());
855
856  RVInfo.AnalyzeCallResult(Ins, RetCC_Sparc32);
857
858  // Copy all of the result registers out of their specified physreg.
859  for (unsigned i = 0; i != RVLocs.size(); ++i) {
860    unsigned Reg = RVLocs[i].getLocReg();
861
862    // Remap I0->I7 -> O0->O7.
863    if (Reg >= SP::I0 && Reg <= SP::I7)
864      Reg = Reg-SP::I0+SP::O0;
865
866    Chain = DAG.getCopyFromReg(Chain, dl, Reg,
867                               RVLocs[i].getValVT(), InFlag).getValue(1);
868    InFlag = Chain.getValue(2);
869    InVals.push_back(Chain.getValue(0));
870  }
871
872  return Chain;
873}
874
875unsigned
876SparcTargetLowering::getSRetArgSize(SelectionDAG &DAG, SDValue Callee) const
877{
878  const Function *CalleeFn = 0;
879  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
880    CalleeFn = dyn_cast<Function>(G->getGlobal());
881  } else if (ExternalSymbolSDNode *E =
882             dyn_cast<ExternalSymbolSDNode>(Callee)) {
883    const Function *Fn = DAG.getMachineFunction().getFunction();
884    const Module *M = Fn->getParent();
885    CalleeFn = M->getFunction(E->getSymbol());
886  }
887
888  if (!CalleeFn)
889    return 0;
890
891  assert(CalleeFn->hasStructRetAttr() &&
892         "Callee does not have the StructRet attribute.");
893
894  PointerType *Ty = cast<PointerType>(CalleeFn->arg_begin()->getType());
895  Type *ElementTy = Ty->getElementType();
896  return getDataLayout()->getTypeAllocSize(ElementTy);
897}
898
899// Lower a call for the 64-bit ABI.
900SDValue
901SparcTargetLowering::LowerCall_64(TargetLowering::CallLoweringInfo &CLI,
902                                  SmallVectorImpl<SDValue> &InVals) const {
903  SelectionDAG &DAG = CLI.DAG;
904  DebugLoc DL = CLI.DL;
905  SDValue Chain = CLI.Chain;
906
907  // Analyze operands of the call, assigning locations to each operand.
908  SmallVector<CCValAssign, 16> ArgLocs;
909  CCState CCInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(),
910                 DAG.getTarget(), ArgLocs, *DAG.getContext());
911  CCInfo.AnalyzeCallOperands(CLI.Outs, CC_Sparc64);
912
913  // Get the size of the outgoing arguments stack space requirement.
914  // The stack offset computed by CC_Sparc64 includes all arguments.
915  // We always allocate space for 6 arguments in the prolog.
916  unsigned ArgsSize = std::max(6*8u, CCInfo.getNextStackOffset()) - 6*8u;
917
918  // Keep stack frames 16-byte aligned.
919  ArgsSize = RoundUpToAlignment(ArgsSize, 16);
920
921  // Adjust the stack pointer to make room for the arguments.
922  // FIXME: Use hasReservedCallFrame to avoid %sp adjustments around all calls
923  // with more than 6 arguments.
924  Chain = DAG.getCALLSEQ_START(Chain, DAG.getIntPtrConstant(ArgsSize, true));
925
926  // Collect the set of registers to pass to the function and their values.
927  // This will be emitted as a sequence of CopyToReg nodes glued to the call
928  // instruction.
929  SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
930
931  // Collect chains from all the memory opeations that copy arguments to the
932  // stack. They must follow the stack pointer adjustment above and precede the
933  // call instruction itself.
934  SmallVector<SDValue, 8> MemOpChains;
935
936  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
937    const CCValAssign &VA = ArgLocs[i];
938    SDValue Arg = CLI.OutVals[i];
939
940    // Promote the value if needed.
941    switch (VA.getLocInfo()) {
942    default:
943      llvm_unreachable("Unknown location info!");
944    case CCValAssign::Full:
945      break;
946    case CCValAssign::SExt:
947      Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
948      break;
949    case CCValAssign::ZExt:
950      Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
951      break;
952    case CCValAssign::AExt:
953      Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
954      break;
955    case CCValAssign::BCvt:
956      Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
957      break;
958    }
959
960    if (VA.isRegLoc()) {
961      // The custom bit on an i32 return value indicates that it should be
962      // passed in the high bits of the register.
963      if (VA.getValVT() == MVT::i32 && VA.needsCustom()) {
964        Arg = DAG.getNode(ISD::SHL, DL, MVT::i64, Arg,
965                          DAG.getConstant(32, MVT::i32));
966
967        // The next value may go in the low bits of the same register.
968        // Handle both at once.
969        if (i+1 < ArgLocs.size() && ArgLocs[i+1].isRegLoc() &&
970            ArgLocs[i+1].getLocReg() == VA.getLocReg()) {
971          SDValue NV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64,
972                                   CLI.OutVals[i+1]);
973          Arg = DAG.getNode(ISD::OR, DL, MVT::i64, Arg, NV);
974          // Skip the next value, it's already done.
975          ++i;
976        }
977      }
978
979      // The argument registers are described in term of the callee's register
980      // window, so translate I0-I7 -> O0-O7.
981      unsigned Reg = VA.getLocReg();
982      if (Reg >= SP::I0 && Reg <= SP::I7)
983        Reg = Reg - SP::I0 + SP::O0;
984      RegsToPass.push_back(std::make_pair(Reg, Arg));
985      continue;
986    }
987
988    assert(VA.isMemLoc());
989
990    // Create a store off the stack pointer for this argument.
991    SDValue StackPtr = DAG.getRegister(SP::O6, getPointerTy());
992    // The argument area starts at %fp+BIAS+128 in the callee frame,
993    // %sp+BIAS+128 in ours.
994    SDValue PtrOff = DAG.getIntPtrConstant(VA.getLocMemOffset() +
995                                           Subtarget->getStackPointerBias() +
996                                           128);
997    PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr, PtrOff);
998    MemOpChains.push_back(DAG.getStore(Chain, DL, Arg, PtrOff,
999                                       MachinePointerInfo(),
1000                                       false, false, 0));
1001  }
1002
1003  // Emit all stores, make sure they occur before the call.
1004  if (!MemOpChains.empty())
1005    Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
1006                        &MemOpChains[0], MemOpChains.size());
1007
1008  // Build a sequence of CopyToReg nodes glued together with token chain and
1009  // glue operands which copy the outgoing args into registers. The InGlue is
1010  // necessary since all emitted instructions must be stuck together in order
1011  // to pass the live physical registers.
1012  SDValue InGlue;
1013  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
1014    Chain = DAG.getCopyToReg(Chain, DL,
1015                             RegsToPass[i].first, RegsToPass[i].second, InGlue);
1016    InGlue = Chain.getValue(1);
1017  }
1018
1019  // If the callee is a GlobalAddress node (quite common, every direct call is)
1020  // turn it into a TargetGlobalAddress node so that legalize doesn't hack it.
1021  // Likewise ExternalSymbol -> TargetExternalSymbol.
1022  SDValue Callee = CLI.Callee;
1023  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee))
1024    Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy());
1025  else if (ExternalSymbolSDNode *E = dyn_cast<ExternalSymbolSDNode>(Callee))
1026    Callee = DAG.getTargetExternalSymbol(E->getSymbol(), getPointerTy());
1027
1028  // Build the operands for the call instruction itself.
1029  SmallVector<SDValue, 8> Ops;
1030  Ops.push_back(Chain);
1031  Ops.push_back(Callee);
1032  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
1033    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
1034                                  RegsToPass[i].second.getValueType()));
1035
1036  // Make sure the CopyToReg nodes are glued to the call instruction which
1037  // consumes the registers.
1038  if (InGlue.getNode())
1039    Ops.push_back(InGlue);
1040
1041  // Now the call itself.
1042  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
1043  Chain = DAG.getNode(SPISD::CALL, DL, NodeTys, &Ops[0], Ops.size());
1044  InGlue = Chain.getValue(1);
1045
1046  // Revert the stack pointer immediately after the call.
1047  Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(ArgsSize, true),
1048                             DAG.getIntPtrConstant(0, true), InGlue);
1049  InGlue = Chain.getValue(1);
1050
1051  // Now extract the return values. This is more or less the same as
1052  // LowerFormalArguments_64.
1053
1054  // Assign locations to each value returned by this call.
1055  SmallVector<CCValAssign, 16> RVLocs;
1056  CCState RVInfo(CLI.CallConv, CLI.IsVarArg, DAG.getMachineFunction(),
1057                 DAG.getTarget(), RVLocs, *DAG.getContext());
1058  RVInfo.AnalyzeCallResult(CLI.Ins, CC_Sparc64);
1059
1060  // Copy all of the result registers out of their specified physreg.
1061  for (unsigned i = 0; i != RVLocs.size(); ++i) {
1062    CCValAssign &VA = RVLocs[i];
1063    unsigned Reg = VA.getLocReg();
1064
1065    // Remap I0-I7 -> O0-O7.
1066    if (Reg >= SP::I0 && Reg <= SP::I7)
1067      Reg = Reg - SP::I0 + SP::O0;
1068
1069    // When returning 'inreg {i32, i32 }', two consecutive i32 arguments can
1070    // reside in the same register in the high and low bits. Reuse the
1071    // CopyFromReg previous node to avoid duplicate copies.
1072    SDValue RV;
1073    if (RegisterSDNode *SrcReg = dyn_cast<RegisterSDNode>(Chain.getOperand(1)))
1074      if (SrcReg->getReg() == Reg && Chain->getOpcode() == ISD::CopyFromReg)
1075        RV = Chain.getValue(0);
1076
1077    // But usually we'll create a new CopyFromReg for a different register.
1078    if (!RV.getNode()) {
1079      RV = DAG.getCopyFromReg(Chain, DL, Reg, RVLocs[i].getLocVT(), InGlue);
1080      Chain = RV.getValue(1);
1081      InGlue = Chain.getValue(2);
1082    }
1083
1084    // Get the high bits for i32 struct elements.
1085    if (VA.getValVT() == MVT::i32 && VA.needsCustom())
1086      RV = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), RV,
1087                       DAG.getConstant(32, MVT::i32));
1088
1089    // The callee promoted the return value, so insert an Assert?ext SDNode so
1090    // we won't promote the value again in this function.
1091    switch (VA.getLocInfo()) {
1092    case CCValAssign::SExt:
1093      RV = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), RV,
1094                       DAG.getValueType(VA.getValVT()));
1095      break;
1096    case CCValAssign::ZExt:
1097      RV = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), RV,
1098                       DAG.getValueType(VA.getValVT()));
1099      break;
1100    default:
1101      break;
1102    }
1103
1104    // Truncate the register down to the return value type.
1105    if (VA.isExtInLoc())
1106      RV = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), RV);
1107
1108    InVals.push_back(RV);
1109  }
1110
1111  return Chain;
1112}
1113
1114//===----------------------------------------------------------------------===//
1115// TargetLowering Implementation
1116//===----------------------------------------------------------------------===//
1117
1118/// IntCondCCodeToICC - Convert a DAG integer condition code to a SPARC ICC
1119/// condition.
1120static SPCC::CondCodes IntCondCCodeToICC(ISD::CondCode CC) {
1121  switch (CC) {
1122  default: llvm_unreachable("Unknown integer condition code!");
1123  case ISD::SETEQ:  return SPCC::ICC_E;
1124  case ISD::SETNE:  return SPCC::ICC_NE;
1125  case ISD::SETLT:  return SPCC::ICC_L;
1126  case ISD::SETGT:  return SPCC::ICC_G;
1127  case ISD::SETLE:  return SPCC::ICC_LE;
1128  case ISD::SETGE:  return SPCC::ICC_GE;
1129  case ISD::SETULT: return SPCC::ICC_CS;
1130  case ISD::SETULE: return SPCC::ICC_LEU;
1131  case ISD::SETUGT: return SPCC::ICC_GU;
1132  case ISD::SETUGE: return SPCC::ICC_CC;
1133  }
1134}
1135
1136/// FPCondCCodeToFCC - Convert a DAG floatingp oint condition code to a SPARC
1137/// FCC condition.
1138static SPCC::CondCodes FPCondCCodeToFCC(ISD::CondCode CC) {
1139  switch (CC) {
1140  default: llvm_unreachable("Unknown fp condition code!");
1141  case ISD::SETEQ:
1142  case ISD::SETOEQ: return SPCC::FCC_E;
1143  case ISD::SETNE:
1144  case ISD::SETUNE: return SPCC::FCC_NE;
1145  case ISD::SETLT:
1146  case ISD::SETOLT: return SPCC::FCC_L;
1147  case ISD::SETGT:
1148  case ISD::SETOGT: return SPCC::FCC_G;
1149  case ISD::SETLE:
1150  case ISD::SETOLE: return SPCC::FCC_LE;
1151  case ISD::SETGE:
1152  case ISD::SETOGE: return SPCC::FCC_GE;
1153  case ISD::SETULT: return SPCC::FCC_UL;
1154  case ISD::SETULE: return SPCC::FCC_ULE;
1155  case ISD::SETUGT: return SPCC::FCC_UG;
1156  case ISD::SETUGE: return SPCC::FCC_UGE;
1157  case ISD::SETUO:  return SPCC::FCC_U;
1158  case ISD::SETO:   return SPCC::FCC_O;
1159  case ISD::SETONE: return SPCC::FCC_LG;
1160  case ISD::SETUEQ: return SPCC::FCC_UE;
1161  }
1162}
1163
1164SparcTargetLowering::SparcTargetLowering(TargetMachine &TM)
1165  : TargetLowering(TM, new TargetLoweringObjectFileELF()) {
1166  Subtarget = &TM.getSubtarget<SparcSubtarget>();
1167
1168  // Set up the register classes.
1169  addRegisterClass(MVT::i32, &SP::IntRegsRegClass);
1170  addRegisterClass(MVT::f32, &SP::FPRegsRegClass);
1171  addRegisterClass(MVT::f64, &SP::DFPRegsRegClass);
1172  if (Subtarget->is64Bit())
1173    addRegisterClass(MVT::i64, &SP::I64RegsRegClass);
1174
1175  // Turn FP extload into load/fextend
1176  setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
1177  // Sparc doesn't have i1 sign extending load
1178  setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
1179  // Turn FP truncstore into trunc + store.
1180  setTruncStoreAction(MVT::f64, MVT::f32, Expand);
1181
1182  // Custom legalize GlobalAddress nodes into LO/HI parts.
1183  setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
1184  setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
1185  setOperationAction(ISD::ConstantPool , MVT::i32, Custom);
1186
1187  // Sparc doesn't have sext_inreg, replace them with shl/sra
1188  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
1189  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8 , Expand);
1190  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1 , Expand);
1191
1192  // Sparc has no REM or DIVREM operations.
1193  setOperationAction(ISD::UREM, MVT::i32, Expand);
1194  setOperationAction(ISD::SREM, MVT::i32, Expand);
1195  setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
1196  setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
1197
1198  // Custom expand fp<->sint
1199  setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
1200  setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
1201
1202  // Expand fp<->uint
1203  setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
1204  setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
1205
1206  setOperationAction(ISD::BITCAST, MVT::f32, Expand);
1207  setOperationAction(ISD::BITCAST, MVT::i32, Expand);
1208
1209  // Sparc has no select or setcc: expand to SELECT_CC.
1210  setOperationAction(ISD::SELECT, MVT::i32, Expand);
1211  setOperationAction(ISD::SELECT, MVT::f32, Expand);
1212  setOperationAction(ISD::SELECT, MVT::f64, Expand);
1213  setOperationAction(ISD::SETCC, MVT::i32, Expand);
1214  setOperationAction(ISD::SETCC, MVT::f32, Expand);
1215  setOperationAction(ISD::SETCC, MVT::f64, Expand);
1216
1217  // Sparc doesn't have BRCOND either, it has BR_CC.
1218  setOperationAction(ISD::BRCOND, MVT::Other, Expand);
1219  setOperationAction(ISD::BRIND, MVT::Other, Expand);
1220  setOperationAction(ISD::BR_JT, MVT::Other, Expand);
1221  setOperationAction(ISD::BR_CC, MVT::i32, Custom);
1222  setOperationAction(ISD::BR_CC, MVT::f32, Custom);
1223  setOperationAction(ISD::BR_CC, MVT::f64, Custom);
1224
1225  setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
1226  setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
1227  setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
1228
1229  if (Subtarget->is64Bit()) {
1230    setOperationAction(ISD::BR_CC, MVT::i64, Custom);
1231    setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
1232  }
1233
1234  // FIXME: There are instructions available for ATOMIC_FENCE
1235  // on SparcV8 and later.
1236  setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
1237  setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
1238
1239  setOperationAction(ISD::FSIN , MVT::f64, Expand);
1240  setOperationAction(ISD::FCOS , MVT::f64, Expand);
1241  setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
1242  setOperationAction(ISD::FREM , MVT::f64, Expand);
1243  setOperationAction(ISD::FMA  , MVT::f64, Expand);
1244  setOperationAction(ISD::FSIN , MVT::f32, Expand);
1245  setOperationAction(ISD::FCOS , MVT::f32, Expand);
1246  setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
1247  setOperationAction(ISD::FREM , MVT::f32, Expand);
1248  setOperationAction(ISD::FMA  , MVT::f32, Expand);
1249  setOperationAction(ISD::CTPOP, MVT::i32, Expand);
1250  setOperationAction(ISD::CTTZ , MVT::i32, Expand);
1251  setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
1252  setOperationAction(ISD::CTLZ , MVT::i32, Expand);
1253  setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
1254  setOperationAction(ISD::ROTL , MVT::i32, Expand);
1255  setOperationAction(ISD::ROTR , MVT::i32, Expand);
1256  setOperationAction(ISD::BSWAP, MVT::i32, Expand);
1257  setOperationAction(ISD::FCOPYSIGN, MVT::f64, Expand);
1258  setOperationAction(ISD::FCOPYSIGN, MVT::f32, Expand);
1259  setOperationAction(ISD::FPOW , MVT::f64, Expand);
1260  setOperationAction(ISD::FPOW , MVT::f32, Expand);
1261
1262  setOperationAction(ISD::SHL_PARTS, MVT::i32, Expand);
1263  setOperationAction(ISD::SRA_PARTS, MVT::i32, Expand);
1264  setOperationAction(ISD::SRL_PARTS, MVT::i32, Expand);
1265
1266  // FIXME: Sparc provides these multiplies, but we don't have them yet.
1267  setOperationAction(ISD::UMUL_LOHI, MVT::i32, Expand);
1268  setOperationAction(ISD::SMUL_LOHI, MVT::i32, Expand);
1269
1270  setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
1271
1272  // VASTART needs to be custom lowered to use the VarArgsFrameIndex.
1273  setOperationAction(ISD::VASTART           , MVT::Other, Custom);
1274  // VAARG needs to be lowered to not do unaligned accesses for doubles.
1275  setOperationAction(ISD::VAARG             , MVT::Other, Custom);
1276
1277  // Use the default implementation.
1278  setOperationAction(ISD::VACOPY            , MVT::Other, Expand);
1279  setOperationAction(ISD::VAEND             , MVT::Other, Expand);
1280  setOperationAction(ISD::STACKSAVE         , MVT::Other, Expand);
1281  setOperationAction(ISD::STACKRESTORE      , MVT::Other, Expand);
1282  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32  , Custom);
1283
1284  // No debug info support yet.
1285  setOperationAction(ISD::EH_LABEL, MVT::Other, Expand);
1286
1287  setStackPointerRegisterToSaveRestore(SP::O6);
1288
1289  if (TM.getSubtarget<SparcSubtarget>().isV9())
1290    setOperationAction(ISD::CTPOP, MVT::i32, Legal);
1291
1292  setMinFunctionAlignment(2);
1293
1294  computeRegisterProperties();
1295}
1296
1297const char *SparcTargetLowering::getTargetNodeName(unsigned Opcode) const {
1298  switch (Opcode) {
1299  default: return 0;
1300  case SPISD::CMPICC:     return "SPISD::CMPICC";
1301  case SPISD::CMPFCC:     return "SPISD::CMPFCC";
1302  case SPISD::BRICC:      return "SPISD::BRICC";
1303  case SPISD::BRXCC:      return "SPISD::BRXCC";
1304  case SPISD::BRFCC:      return "SPISD::BRFCC";
1305  case SPISD::SELECT_ICC: return "SPISD::SELECT_ICC";
1306  case SPISD::SELECT_XCC: return "SPISD::SELECT_XCC";
1307  case SPISD::SELECT_FCC: return "SPISD::SELECT_FCC";
1308  case SPISD::Hi:         return "SPISD::Hi";
1309  case SPISD::Lo:         return "SPISD::Lo";
1310  case SPISD::FTOI:       return "SPISD::FTOI";
1311  case SPISD::ITOF:       return "SPISD::ITOF";
1312  case SPISD::CALL:       return "SPISD::CALL";
1313  case SPISD::RET_FLAG:   return "SPISD::RET_FLAG";
1314  case SPISD::GLOBAL_BASE_REG: return "SPISD::GLOBAL_BASE_REG";
1315  case SPISD::FLUSHW:     return "SPISD::FLUSHW";
1316  }
1317}
1318
1319/// isMaskedValueZeroForTargetNode - Return true if 'Op & Mask' is known to
1320/// be zero. Op is expected to be a target specific node. Used by DAG
1321/// combiner.
1322void SparcTargetLowering::computeMaskedBitsForTargetNode(const SDValue Op,
1323                                                         APInt &KnownZero,
1324                                                         APInt &KnownOne,
1325                                                         const SelectionDAG &DAG,
1326                                                         unsigned Depth) const {
1327  APInt KnownZero2, KnownOne2;
1328  KnownZero = KnownOne = APInt(KnownZero.getBitWidth(), 0);
1329
1330  switch (Op.getOpcode()) {
1331  default: break;
1332  case SPISD::SELECT_ICC:
1333  case SPISD::SELECT_XCC:
1334  case SPISD::SELECT_FCC:
1335    DAG.ComputeMaskedBits(Op.getOperand(1), KnownZero, KnownOne, Depth+1);
1336    DAG.ComputeMaskedBits(Op.getOperand(0), KnownZero2, KnownOne2, Depth+1);
1337    assert((KnownZero & KnownOne) == 0 && "Bits known to be one AND zero?");
1338    assert((KnownZero2 & KnownOne2) == 0 && "Bits known to be one AND zero?");
1339
1340    // Only known if known in both the LHS and RHS.
1341    KnownOne &= KnownOne2;
1342    KnownZero &= KnownZero2;
1343    break;
1344  }
1345}
1346
1347// Look at LHS/RHS/CC and see if they are a lowered setcc instruction.  If so
1348// set LHS/RHS and SPCC to the LHS/RHS of the setcc and SPCC to the condition.
1349static void LookThroughSetCC(SDValue &LHS, SDValue &RHS,
1350                             ISD::CondCode CC, unsigned &SPCC) {
1351  if (isa<ConstantSDNode>(RHS) &&
1352      cast<ConstantSDNode>(RHS)->isNullValue() &&
1353      CC == ISD::SETNE &&
1354      (((LHS.getOpcode() == SPISD::SELECT_ICC ||
1355         LHS.getOpcode() == SPISD::SELECT_XCC) &&
1356        LHS.getOperand(3).getOpcode() == SPISD::CMPICC) ||
1357       (LHS.getOpcode() == SPISD::SELECT_FCC &&
1358        LHS.getOperand(3).getOpcode() == SPISD::CMPFCC)) &&
1359      isa<ConstantSDNode>(LHS.getOperand(0)) &&
1360      isa<ConstantSDNode>(LHS.getOperand(1)) &&
1361      cast<ConstantSDNode>(LHS.getOperand(0))->isOne() &&
1362      cast<ConstantSDNode>(LHS.getOperand(1))->isNullValue()) {
1363    SDValue CMPCC = LHS.getOperand(3);
1364    SPCC = cast<ConstantSDNode>(LHS.getOperand(2))->getZExtValue();
1365    LHS = CMPCC.getOperand(0);
1366    RHS = CMPCC.getOperand(1);
1367  }
1368}
1369
1370SDValue SparcTargetLowering::LowerGlobalAddress(SDValue Op,
1371                                                SelectionDAG &DAG) const {
1372  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1373  // FIXME there isn't really any debug info here
1374  DebugLoc dl = Op.getDebugLoc();
1375  SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32);
1376  SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, GA);
1377  SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, GA);
1378
1379  if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
1380    return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1381
1382  SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
1383                                   getPointerTy());
1384  SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1385  SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
1386                                GlobalBase, RelAddr);
1387  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1388                     AbsAddr, MachinePointerInfo(), false, false, false, 0);
1389}
1390
1391SDValue SparcTargetLowering::LowerConstantPool(SDValue Op,
1392                                               SelectionDAG &DAG) const {
1393  ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1394  // FIXME there isn't really any debug info here
1395  DebugLoc dl = Op.getDebugLoc();
1396  const Constant *C = N->getConstVal();
1397  SDValue CP = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment());
1398  SDValue Hi = DAG.getNode(SPISD::Hi, dl, MVT::i32, CP);
1399  SDValue Lo = DAG.getNode(SPISD::Lo, dl, MVT::i32, CP);
1400  if (getTargetMachine().getRelocationModel() != Reloc::PIC_)
1401    return DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1402
1403  SDValue GlobalBase = DAG.getNode(SPISD::GLOBAL_BASE_REG, dl,
1404                                   getPointerTy());
1405  SDValue RelAddr = DAG.getNode(ISD::ADD, dl, MVT::i32, Lo, Hi);
1406  SDValue AbsAddr = DAG.getNode(ISD::ADD, dl, MVT::i32,
1407                                GlobalBase, RelAddr);
1408  return DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
1409                     AbsAddr, MachinePointerInfo(), false, false, false, 0);
1410}
1411
1412static SDValue LowerFP_TO_SINT(SDValue Op, SelectionDAG &DAG) {
1413  DebugLoc dl = Op.getDebugLoc();
1414  // Convert the fp value to integer in an FP register.
1415  assert(Op.getValueType() == MVT::i32);
1416  Op = DAG.getNode(SPISD::FTOI, dl, MVT::f32, Op.getOperand(0));
1417  return DAG.getNode(ISD::BITCAST, dl, MVT::i32, Op);
1418}
1419
1420static SDValue LowerSINT_TO_FP(SDValue Op, SelectionDAG &DAG) {
1421  DebugLoc dl = Op.getDebugLoc();
1422  assert(Op.getOperand(0).getValueType() == MVT::i32);
1423  SDValue Tmp = DAG.getNode(ISD::BITCAST, dl, MVT::f32, Op.getOperand(0));
1424  // Convert the int value to FP in an FP register.
1425  return DAG.getNode(SPISD::ITOF, dl, Op.getValueType(), Tmp);
1426}
1427
1428static SDValue LowerBR_CC(SDValue Op, SelectionDAG &DAG) {
1429  SDValue Chain = Op.getOperand(0);
1430  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
1431  SDValue LHS = Op.getOperand(2);
1432  SDValue RHS = Op.getOperand(3);
1433  SDValue Dest = Op.getOperand(4);
1434  DebugLoc dl = Op.getDebugLoc();
1435  unsigned Opc, SPCC = ~0U;
1436
1437  // If this is a br_cc of a "setcc", and if the setcc got lowered into
1438  // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1439  LookThroughSetCC(LHS, RHS, CC, SPCC);
1440
1441  // Get the condition flag.
1442  SDValue CompareFlag;
1443  if (LHS.getValueType().isInteger()) {
1444    EVT VTs[] = { LHS.getValueType(), MVT::Glue };
1445    SDValue Ops[2] = { LHS, RHS };
1446    CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
1447    if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
1448    // 32-bit compares use the icc flags, 64-bit uses the xcc flags.
1449    Opc = LHS.getValueType() == MVT::i32 ? SPISD::BRICC : SPISD::BRXCC;
1450  } else {
1451    CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
1452    if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
1453    Opc = SPISD::BRFCC;
1454  }
1455  return DAG.getNode(Opc, dl, MVT::Other, Chain, Dest,
1456                     DAG.getConstant(SPCC, MVT::i32), CompareFlag);
1457}
1458
1459static SDValue LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) {
1460  SDValue LHS = Op.getOperand(0);
1461  SDValue RHS = Op.getOperand(1);
1462  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
1463  SDValue TrueVal = Op.getOperand(2);
1464  SDValue FalseVal = Op.getOperand(3);
1465  DebugLoc dl = Op.getDebugLoc();
1466  unsigned Opc, SPCC = ~0U;
1467
1468  // If this is a select_cc of a "setcc", and if the setcc got lowered into
1469  // an CMP[IF]CC/SELECT_[IF]CC pair, find the original compared values.
1470  LookThroughSetCC(LHS, RHS, CC, SPCC);
1471
1472  SDValue CompareFlag;
1473  if (LHS.getValueType().isInteger()) {
1474    // subcc returns a value
1475    EVT VTs[] = { LHS.getValueType(), MVT::Glue };
1476    SDValue Ops[2] = { LHS, RHS };
1477    CompareFlag = DAG.getNode(SPISD::CMPICC, dl, VTs, Ops, 2).getValue(1);
1478    Opc = LHS.getValueType() == MVT::i32 ?
1479          SPISD::SELECT_ICC : SPISD::SELECT_XCC;
1480    if (SPCC == ~0U) SPCC = IntCondCCodeToICC(CC);
1481  } else {
1482    CompareFlag = DAG.getNode(SPISD::CMPFCC, dl, MVT::Glue, LHS, RHS);
1483    Opc = SPISD::SELECT_FCC;
1484    if (SPCC == ~0U) SPCC = FPCondCCodeToFCC(CC);
1485  }
1486  return DAG.getNode(Opc, dl, TrueVal.getValueType(), TrueVal, FalseVal,
1487                     DAG.getConstant(SPCC, MVT::i32), CompareFlag);
1488}
1489
1490static SDValue LowerVASTART(SDValue Op, SelectionDAG &DAG,
1491                            const SparcTargetLowering &TLI) {
1492  MachineFunction &MF = DAG.getMachineFunction();
1493  SparcMachineFunctionInfo *FuncInfo = MF.getInfo<SparcMachineFunctionInfo>();
1494
1495  // vastart just stores the address of the VarArgsFrameIndex slot into the
1496  // memory location argument.
1497  DebugLoc dl = Op.getDebugLoc();
1498  SDValue Offset =
1499    DAG.getNode(ISD::ADD, dl, MVT::i32,
1500                DAG.getRegister(SP::I6, MVT::i32),
1501                DAG.getConstant(FuncInfo->getVarArgsFrameOffset(),
1502                                MVT::i32));
1503  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1504  return DAG.getStore(Op.getOperand(0), dl, Offset, Op.getOperand(1),
1505                      MachinePointerInfo(SV), false, false, 0);
1506}
1507
1508static SDValue LowerVAARG(SDValue Op, SelectionDAG &DAG) {
1509  SDNode *Node = Op.getNode();
1510  EVT VT = Node->getValueType(0);
1511  SDValue InChain = Node->getOperand(0);
1512  SDValue VAListPtr = Node->getOperand(1);
1513  const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1514  DebugLoc dl = Node->getDebugLoc();
1515  SDValue VAList = DAG.getLoad(MVT::i32, dl, InChain, VAListPtr,
1516                               MachinePointerInfo(SV), false, false, false, 0);
1517  // Increment the pointer, VAList, to the next vaarg
1518  SDValue NextPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, VAList,
1519                                  DAG.getConstant(VT.getSizeInBits()/8,
1520                                                  MVT::i32));
1521  // Store the incremented VAList to the legalized pointer
1522  InChain = DAG.getStore(VAList.getValue(1), dl, NextPtr,
1523                         VAListPtr, MachinePointerInfo(SV), false, false, 0);
1524  // Load the actual argument out of the pointer VAList, unless this is an
1525  // f64 load.
1526  if (VT != MVT::f64)
1527    return DAG.getLoad(VT, dl, InChain, VAList, MachinePointerInfo(),
1528                       false, false, false, 0);
1529
1530  // Otherwise, load it as i64, then do a bitconvert.
1531  SDValue V = DAG.getLoad(MVT::i64, dl, InChain, VAList, MachinePointerInfo(),
1532                          false, false, false, 0);
1533
1534  // Bit-Convert the value to f64.
1535  SDValue Ops[2] = {
1536    DAG.getNode(ISD::BITCAST, dl, MVT::f64, V),
1537    V.getValue(1)
1538  };
1539  return DAG.getMergeValues(Ops, 2, dl);
1540}
1541
1542static SDValue LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) {
1543  SDValue Chain = Op.getOperand(0);  // Legalize the chain.
1544  SDValue Size  = Op.getOperand(1);  // Legalize the size.
1545  DebugLoc dl = Op.getDebugLoc();
1546
1547  unsigned SPReg = SP::O6;
1548  SDValue SP = DAG.getCopyFromReg(Chain, dl, SPReg, MVT::i32);
1549  SDValue NewSP = DAG.getNode(ISD::SUB, dl, MVT::i32, SP, Size); // Value
1550  Chain = DAG.getCopyToReg(SP.getValue(1), dl, SPReg, NewSP);    // Output chain
1551
1552  // The resultant pointer is actually 16 words from the bottom of the stack,
1553  // to provide a register spill area.
1554  SDValue NewVal = DAG.getNode(ISD::ADD, dl, MVT::i32, NewSP,
1555                                 DAG.getConstant(96, MVT::i32));
1556  SDValue Ops[2] = { NewVal, Chain };
1557  return DAG.getMergeValues(Ops, 2, dl);
1558}
1559
1560
1561static SDValue getFLUSHW(SDValue Op, SelectionDAG &DAG) {
1562  DebugLoc dl = Op.getDebugLoc();
1563  SDValue Chain = DAG.getNode(SPISD::FLUSHW,
1564                              dl, MVT::Other, DAG.getEntryNode());
1565  return Chain;
1566}
1567
1568static SDValue LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) {
1569  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1570  MFI->setFrameAddressIsTaken(true);
1571
1572  EVT VT = Op.getValueType();
1573  DebugLoc dl = Op.getDebugLoc();
1574  unsigned FrameReg = SP::I6;
1575
1576  uint64_t depth = Op.getConstantOperandVal(0);
1577
1578  SDValue FrameAddr;
1579  if (depth == 0)
1580    FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, FrameReg, VT);
1581  else {
1582    // flush first to make sure the windowed registers' values are in stack
1583    SDValue Chain = getFLUSHW(Op, DAG);
1584    FrameAddr = DAG.getCopyFromReg(Chain, dl, FrameReg, VT);
1585
1586    for (uint64_t i = 0; i != depth; ++i) {
1587      SDValue Ptr = DAG.getNode(ISD::ADD,
1588                                dl, MVT::i32,
1589                                FrameAddr, DAG.getIntPtrConstant(56));
1590      FrameAddr = DAG.getLoad(MVT::i32, dl,
1591                              Chain,
1592                              Ptr,
1593                              MachinePointerInfo(), false, false, false, 0);
1594    }
1595  }
1596  return FrameAddr;
1597}
1598
1599static SDValue LowerRETURNADDR(SDValue Op, SelectionDAG &DAG) {
1600  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1601  MFI->setReturnAddressIsTaken(true);
1602
1603  EVT VT = Op.getValueType();
1604  DebugLoc dl = Op.getDebugLoc();
1605  unsigned RetReg = SP::I7;
1606
1607  uint64_t depth = Op.getConstantOperandVal(0);
1608
1609  SDValue RetAddr;
1610  if (depth == 0)
1611    RetAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl, RetReg, VT);
1612  else {
1613    // flush first to make sure the windowed registers' values are in stack
1614    SDValue Chain = getFLUSHW(Op, DAG);
1615    RetAddr = DAG.getCopyFromReg(Chain, dl, SP::I6, VT);
1616
1617    for (uint64_t i = 0; i != depth; ++i) {
1618      SDValue Ptr = DAG.getNode(ISD::ADD,
1619                                dl, MVT::i32,
1620                                RetAddr,
1621                                DAG.getIntPtrConstant((i == depth-1)?60:56));
1622      RetAddr = DAG.getLoad(MVT::i32, dl,
1623                            Chain,
1624                            Ptr,
1625                            MachinePointerInfo(), false, false, false, 0);
1626    }
1627  }
1628  return RetAddr;
1629}
1630
1631SDValue SparcTargetLowering::
1632LowerOperation(SDValue Op, SelectionDAG &DAG) const {
1633  switch (Op.getOpcode()) {
1634  default: llvm_unreachable("Should not custom lower this!");
1635  case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
1636  case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
1637  case ISD::GlobalTLSAddress:
1638    llvm_unreachable("TLS not implemented for Sparc.");
1639  case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
1640  case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1641  case ISD::FP_TO_SINT:         return LowerFP_TO_SINT(Op, DAG);
1642  case ISD::SINT_TO_FP:         return LowerSINT_TO_FP(Op, DAG);
1643  case ISD::BR_CC:              return LowerBR_CC(Op, DAG);
1644  case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
1645  case ISD::VASTART:            return LowerVASTART(Op, DAG, *this);
1646  case ISD::VAARG:              return LowerVAARG(Op, DAG);
1647  case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
1648  }
1649}
1650
1651MachineBasicBlock *
1652SparcTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1653                                                 MachineBasicBlock *BB) const {
1654  const TargetInstrInfo &TII = *getTargetMachine().getInstrInfo();
1655  unsigned BROpcode;
1656  unsigned CC;
1657  DebugLoc dl = MI->getDebugLoc();
1658  // Figure out the conditional branch opcode to use for this select_cc.
1659  switch (MI->getOpcode()) {
1660  default: llvm_unreachable("Unknown SELECT_CC!");
1661  case SP::SELECT_CC_Int_ICC:
1662  case SP::SELECT_CC_FP_ICC:
1663  case SP::SELECT_CC_DFP_ICC:
1664    BROpcode = SP::BCOND;
1665    break;
1666  case SP::SELECT_CC_Int_FCC:
1667  case SP::SELECT_CC_FP_FCC:
1668  case SP::SELECT_CC_DFP_FCC:
1669    BROpcode = SP::FBCOND;
1670    break;
1671  }
1672
1673  CC = (SPCC::CondCodes)MI->getOperand(3).getImm();
1674
1675  // To "insert" a SELECT_CC instruction, we actually have to insert the diamond
1676  // control-flow pattern.  The incoming instruction knows the destination vreg
1677  // to set, the condition code register to branch on, the true/false values to
1678  // select between, and a branch opcode to use.
1679  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1680  MachineFunction::iterator It = BB;
1681  ++It;
1682
1683  //  thisMBB:
1684  //  ...
1685  //   TrueVal = ...
1686  //   [f]bCC copy1MBB
1687  //   fallthrough --> copy0MBB
1688  MachineBasicBlock *thisMBB = BB;
1689  MachineFunction *F = BB->getParent();
1690  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1691  MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1692  F->insert(It, copy0MBB);
1693  F->insert(It, sinkMBB);
1694
1695  // Transfer the remainder of BB and its successor edges to sinkMBB.
1696  sinkMBB->splice(sinkMBB->begin(), BB,
1697                  llvm::next(MachineBasicBlock::iterator(MI)),
1698                  BB->end());
1699  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1700
1701  // Add the true and fallthrough blocks as its successors.
1702  BB->addSuccessor(copy0MBB);
1703  BB->addSuccessor(sinkMBB);
1704
1705  BuildMI(BB, dl, TII.get(BROpcode)).addMBB(sinkMBB).addImm(CC);
1706
1707  //  copy0MBB:
1708  //   %FalseValue = ...
1709  //   # fallthrough to sinkMBB
1710  BB = copy0MBB;
1711
1712  // Update machine-CFG edges
1713  BB->addSuccessor(sinkMBB);
1714
1715  //  sinkMBB:
1716  //   %Result = phi [ %FalseValue, copy0MBB ], [ %TrueValue, thisMBB ]
1717  //  ...
1718  BB = sinkMBB;
1719  BuildMI(*BB, BB->begin(), dl, TII.get(SP::PHI), MI->getOperand(0).getReg())
1720    .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB)
1721    .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB);
1722
1723  MI->eraseFromParent();   // The pseudo instruction is gone now.
1724  return BB;
1725}
1726
1727//===----------------------------------------------------------------------===//
1728//                         Sparc Inline Assembly Support
1729//===----------------------------------------------------------------------===//
1730
1731/// getConstraintType - Given a constraint letter, return the type of
1732/// constraint it is for this target.
1733SparcTargetLowering::ConstraintType
1734SparcTargetLowering::getConstraintType(const std::string &Constraint) const {
1735  if (Constraint.size() == 1) {
1736    switch (Constraint[0]) {
1737    default:  break;
1738    case 'r': return C_RegisterClass;
1739    }
1740  }
1741
1742  return TargetLowering::getConstraintType(Constraint);
1743}
1744
1745std::pair<unsigned, const TargetRegisterClass*>
1746SparcTargetLowering::getRegForInlineAsmConstraint(const std::string &Constraint,
1747                                                  EVT VT) const {
1748  if (Constraint.size() == 1) {
1749    switch (Constraint[0]) {
1750    case 'r':
1751      return std::make_pair(0U, &SP::IntRegsRegClass);
1752    }
1753  }
1754
1755  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
1756}
1757
1758bool
1759SparcTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
1760  // The Sparc target isn't yet aware of offsets.
1761  return false;
1762}
1763