MipsISelLowering.cpp revision f09a03776dbbc882c9b15eeccb8ec847058fbfa0
1//===-- MipsISelLowering.cpp - Mips 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 defines the interfaces that Mips uses to lower LLVM code into a
11// selection DAG.
12//
13//===----------------------------------------------------------------------===//
14
15#define DEBUG_TYPE "mips-lower"
16#include "MipsISelLowering.h"
17#include "MipsMachineFunction.h"
18#include "MipsTargetMachine.h"
19#include "MipsTargetObjectFile.h"
20#include "MipsSubtarget.h"
21#include "InstPrinter/MipsInstPrinter.h"
22#include "MCTargetDesc/MipsBaseInfo.h"
23#include "llvm/DerivedTypes.h"
24#include "llvm/Function.h"
25#include "llvm/GlobalVariable.h"
26#include "llvm/Intrinsics.h"
27#include "llvm/CallingConv.h"
28#include "llvm/ADT/Statistic.h"
29#include "llvm/CodeGen/CallingConvLower.h"
30#include "llvm/CodeGen/MachineFrameInfo.h"
31#include "llvm/CodeGen/MachineFunction.h"
32#include "llvm/CodeGen/MachineInstrBuilder.h"
33#include "llvm/CodeGen/MachineRegisterInfo.h"
34#include "llvm/CodeGen/SelectionDAGISel.h"
35#include "llvm/CodeGen/ValueTypes.h"
36#include "llvm/Support/CommandLine.h"
37#include "llvm/Support/Debug.h"
38#include "llvm/Support/ErrorHandling.h"
39#include "llvm/Support/raw_ostream.h"
40
41using namespace llvm;
42
43STATISTIC(NumTailCalls, "Number of tail calls");
44
45static cl::opt<bool>
46EnableMipsTailCalls("enable-mips-tail-calls", cl::Hidden,
47                    cl::desc("MIPS: Enable tail calls."), cl::init(false));
48
49static cl::opt<bool>
50LargeGOT("mxgot", cl::Hidden,
51         cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
52
53static const uint16_t O32IntRegs[4] = {
54  Mips::A0, Mips::A1, Mips::A2, Mips::A3
55};
56
57static const uint16_t Mips64IntRegs[8] = {
58  Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
59  Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
60};
61
62static const uint16_t Mips64DPRegs[8] = {
63  Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
64  Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
65};
66
67// If I is a shifted mask, set the size (Size) and the first bit of the
68// mask (Pos), and return true.
69// For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
70static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
71  if (!isShiftedMask_64(I))
72     return false;
73
74  Size = CountPopulation_64(I);
75  Pos = CountTrailingZeros_64(I);
76  return true;
77}
78
79static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
80  MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
81  return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
82}
83
84static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
85  EVT Ty = Op.getValueType();
86
87  if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
88    return DAG.getTargetGlobalAddress(N->getGlobal(), Op.getDebugLoc(), Ty, 0,
89                                      Flag);
90  if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
91    return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
92  if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
93    return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
94  if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
95    return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
96  if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
97    return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
98                                     N->getOffset(), Flag);
99
100  llvm_unreachable("Unexpected node type.");
101  return SDValue();
102}
103
104static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
105  DebugLoc DL = Op.getDebugLoc();
106  EVT Ty = Op.getValueType();
107  SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
108  SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
109  return DAG.getNode(ISD::ADD, DL, Ty,
110                     DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
111                     DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
112}
113
114static SDValue getAddrLocal(SDValue Op, SelectionDAG &DAG, bool HasMips64) {
115  DebugLoc DL = Op.getDebugLoc();
116  EVT Ty = Op.getValueType();
117  unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
118  SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
119                            getTargetNode(Op, DAG, GOTFlag));
120  SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
121                             MachinePointerInfo::getGOT(), false, false, false,
122                             0);
123  unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
124  SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
125  return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
126}
127
128static SDValue getAddrGlobal(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
129  DebugLoc DL = Op.getDebugLoc();
130  EVT Ty = Op.getValueType();
131  SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
132                            getTargetNode(Op, DAG, Flag));
133  return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
134                     MachinePointerInfo::getGOT(), false, false, false, 0);
135}
136
137static SDValue getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
138                                     unsigned HiFlag, unsigned LoFlag) {
139  DebugLoc DL = Op.getDebugLoc();
140  EVT Ty = Op.getValueType();
141  SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
142  Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, GetGlobalReg(DAG, Ty));
143  SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
144                                getTargetNode(Op, DAG, LoFlag));
145  return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
146                     MachinePointerInfo::getGOT(), false, false, false, 0);
147}
148
149const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
150  switch (Opcode) {
151  case MipsISD::JmpLink:           return "MipsISD::JmpLink";
152  case MipsISD::TailCall:          return "MipsISD::TailCall";
153  case MipsISD::Hi:                return "MipsISD::Hi";
154  case MipsISD::Lo:                return "MipsISD::Lo";
155  case MipsISD::GPRel:             return "MipsISD::GPRel";
156  case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
157  case MipsISD::Ret:               return "MipsISD::Ret";
158  case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
159  case MipsISD::FPCmp:             return "MipsISD::FPCmp";
160  case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
161  case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
162  case MipsISD::FPRound:           return "MipsISD::FPRound";
163  case MipsISD::MAdd:              return "MipsISD::MAdd";
164  case MipsISD::MAddu:             return "MipsISD::MAddu";
165  case MipsISD::MSub:              return "MipsISD::MSub";
166  case MipsISD::MSubu:             return "MipsISD::MSubu";
167  case MipsISD::DivRem:            return "MipsISD::DivRem";
168  case MipsISD::DivRemU:           return "MipsISD::DivRemU";
169  case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
170  case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
171  case MipsISD::Wrapper:           return "MipsISD::Wrapper";
172  case MipsISD::DynAlloc:          return "MipsISD::DynAlloc";
173  case MipsISD::Sync:              return "MipsISD::Sync";
174  case MipsISD::Ext:               return "MipsISD::Ext";
175  case MipsISD::Ins:               return "MipsISD::Ins";
176  case MipsISD::LWL:               return "MipsISD::LWL";
177  case MipsISD::LWR:               return "MipsISD::LWR";
178  case MipsISD::SWL:               return "MipsISD::SWL";
179  case MipsISD::SWR:               return "MipsISD::SWR";
180  case MipsISD::LDL:               return "MipsISD::LDL";
181  case MipsISD::LDR:               return "MipsISD::LDR";
182  case MipsISD::SDL:               return "MipsISD::SDL";
183  case MipsISD::SDR:               return "MipsISD::SDR";
184  case MipsISD::EXTP:              return "MipsISD::EXTP";
185  case MipsISD::EXTPDP:            return "MipsISD::EXTPDP";
186  case MipsISD::EXTR_S_H:          return "MipsISD::EXTR_S_H";
187  case MipsISD::EXTR_W:            return "MipsISD::EXTR_W";
188  case MipsISD::EXTR_R_W:          return "MipsISD::EXTR_R_W";
189  case MipsISD::EXTR_RS_W:         return "MipsISD::EXTR_RS_W";
190  case MipsISD::SHILO:             return "MipsISD::SHILO";
191  case MipsISD::MTHLIP:            return "MipsISD::MTHLIP";
192  case MipsISD::MULT:              return "MipsISD::MULT";
193  case MipsISD::MULTU:             return "MipsISD::MULTU";
194  case MipsISD::MADD_DSP:          return "MipsISD::MADD_DSPDSP";
195  case MipsISD::MADDU_DSP:         return "MipsISD::MADDU_DSP";
196  case MipsISD::MSUB_DSP:          return "MipsISD::MSUB_DSP";
197  case MipsISD::MSUBU_DSP:         return "MipsISD::MSUBU_DSP";
198  default:                         return NULL;
199  }
200}
201
202MipsTargetLowering::
203MipsTargetLowering(MipsTargetMachine &TM)
204  : TargetLowering(TM, new MipsTargetObjectFile()),
205    Subtarget(&TM.getSubtarget<MipsSubtarget>()),
206    HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
207    IsO32(Subtarget->isABI_O32()) {
208
209  // Mips does not have i1 type, so use i32 for
210  // setcc operations results (slt, sgt, ...).
211  setBooleanContents(ZeroOrOneBooleanContent);
212  setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
213
214  // Set up the register classes
215  addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
216
217  if (HasMips64)
218    addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
219
220  if (Subtarget->inMips16Mode()) {
221    addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
222  }
223
224  if (Subtarget->hasDSP()) {
225    MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
226
227    for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
228      addRegisterClass(VecTys[i], &Mips::DSPRegsRegClass);
229
230      // Expand all builtin opcodes.
231      for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
232        setOperationAction(Opc, VecTys[i], Expand);
233
234      setOperationAction(ISD::LOAD, VecTys[i], Legal);
235      setOperationAction(ISD::STORE, VecTys[i], Legal);
236      setOperationAction(ISD::BITCAST, VecTys[i], Legal);
237    }
238  }
239
240  if (!TM.Options.UseSoftFloat) {
241    addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
242
243    // When dealing with single precision only, use libcalls
244    if (!Subtarget->isSingleFloat()) {
245      if (HasMips64)
246        addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
247      else
248        addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
249    }
250  }
251
252  // Load extented operations for i1 types must be promoted
253  setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
254  setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
255  setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
256
257  // MIPS doesn't have extending float->double load/store
258  setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
259  setTruncStoreAction(MVT::f64, MVT::f32, Expand);
260
261  // Used by legalize types to correctly generate the setcc result.
262  // Without this, every float setcc comes with a AND/OR with the result,
263  // we don't want this, since the fpcmp result goes to a flag register,
264  // which is used implicitly by brcond and select operations.
265  AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
266
267  // Mips Custom Operations
268  setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
269  setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
270  setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
271  setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
272  setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
273  setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
274  setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
275  setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
276  setOperationAction(ISD::SELECT_CC,          MVT::f32,   Custom);
277  setOperationAction(ISD::SELECT_CC,          MVT::f64,   Custom);
278  setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
279  setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
280  setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
281  setOperationAction(ISD::VASTART,            MVT::Other, Custom);
282  setOperationAction(ISD::FCOPYSIGN,          MVT::f32,   Custom);
283  setOperationAction(ISD::FCOPYSIGN,          MVT::f64,   Custom);
284  if (Subtarget->inMips16Mode()) {
285    setOperationAction(ISD::MEMBARRIER,         MVT::Other, Expand);
286    setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Expand);
287  }
288  else {
289    setOperationAction(ISD::MEMBARRIER,         MVT::Other, Custom);
290    setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Custom);
291  }
292  if (!Subtarget->inMips16Mode()) {
293    setOperationAction(ISD::LOAD,               MVT::i32, Custom);
294    setOperationAction(ISD::STORE,              MVT::i32, Custom);
295  }
296
297  if (!TM.Options.NoNaNsFPMath) {
298    setOperationAction(ISD::FABS,             MVT::f32,   Custom);
299    setOperationAction(ISD::FABS,             MVT::f64,   Custom);
300  }
301
302  if (HasMips64) {
303    setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
304    setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
305    setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
306    setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
307    setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
308    setOperationAction(ISD::SELECT,             MVT::i64,   Custom);
309    setOperationAction(ISD::LOAD,               MVT::i64,   Custom);
310    setOperationAction(ISD::STORE,              MVT::i64,   Custom);
311  }
312
313  if (!HasMips64) {
314    setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Custom);
315    setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Custom);
316    setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Custom);
317  }
318
319  setOperationAction(ISD::ADD,                MVT::i32,   Custom);
320  if (HasMips64)
321    setOperationAction(ISD::ADD,                MVT::i64,   Custom);
322
323  setOperationAction(ISD::SDIV, MVT::i32, Expand);
324  setOperationAction(ISD::SREM, MVT::i32, Expand);
325  setOperationAction(ISD::UDIV, MVT::i32, Expand);
326  setOperationAction(ISD::UREM, MVT::i32, Expand);
327  setOperationAction(ISD::SDIV, MVT::i64, Expand);
328  setOperationAction(ISD::SREM, MVT::i64, Expand);
329  setOperationAction(ISD::UDIV, MVT::i64, Expand);
330  setOperationAction(ISD::UREM, MVT::i64, Expand);
331
332  // Operations not directly supported by Mips.
333  setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
334  setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
335  setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
336  setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
337  setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
338  setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
339  setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
340  setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
341  setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
342  setOperationAction(ISD::CTPOP,             MVT::i64,   Expand);
343  setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
344  setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
345  setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i32,   Expand);
346  setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i64,   Expand);
347  setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i32,   Expand);
348  setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i64,   Expand);
349  setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
350  setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
351  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,  Expand);
352  setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,  Expand);
353
354  if (!Subtarget->hasMips32r2())
355    setOperationAction(ISD::ROTR, MVT::i32,   Expand);
356
357  if (!Subtarget->hasMips64r2())
358    setOperationAction(ISD::ROTR, MVT::i64,   Expand);
359
360  setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
361  setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
362  setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
363  setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
364  setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
365  setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
366  setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
367  setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
368  setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
369  setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
370  setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
371  setOperationAction(ISD::FMA,               MVT::f32,   Expand);
372  setOperationAction(ISD::FMA,               MVT::f64,   Expand);
373  setOperationAction(ISD::FREM,              MVT::f32,   Expand);
374  setOperationAction(ISD::FREM,              MVT::f64,   Expand);
375
376  if (!TM.Options.NoNaNsFPMath) {
377    setOperationAction(ISD::FNEG,             MVT::f32,   Expand);
378    setOperationAction(ISD::FNEG,             MVT::f64,   Expand);
379  }
380
381  setOperationAction(ISD::EXCEPTIONADDR,     MVT::i32, Expand);
382  setOperationAction(ISD::EXCEPTIONADDR,     MVT::i64, Expand);
383  setOperationAction(ISD::EHSELECTION,       MVT::i32, Expand);
384  setOperationAction(ISD::EHSELECTION,       MVT::i64, Expand);
385
386  setOperationAction(ISD::VAARG,             MVT::Other, Expand);
387  setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
388  setOperationAction(ISD::VAEND,             MVT::Other, Expand);
389
390  setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
391  setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
392
393  // Use the default for now
394  setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
395  setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
396
397  setOperationAction(ISD::ATOMIC_LOAD,       MVT::i32,    Expand);
398  setOperationAction(ISD::ATOMIC_LOAD,       MVT::i64,    Expand);
399  setOperationAction(ISD::ATOMIC_STORE,      MVT::i32,    Expand);
400  setOperationAction(ISD::ATOMIC_STORE,      MVT::i64,    Expand);
401
402  if (Subtarget->inMips16Mode()) {
403    setOperationAction(ISD::ATOMIC_CMP_SWAP,       MVT::i32,    Expand);
404    setOperationAction(ISD::ATOMIC_SWAP,           MVT::i32,    Expand);
405    setOperationAction(ISD::ATOMIC_LOAD_ADD,       MVT::i32,    Expand);
406    setOperationAction(ISD::ATOMIC_LOAD_SUB,       MVT::i32,    Expand);
407    setOperationAction(ISD::ATOMIC_LOAD_AND,       MVT::i32,    Expand);
408    setOperationAction(ISD::ATOMIC_LOAD_OR,        MVT::i32,    Expand);
409    setOperationAction(ISD::ATOMIC_LOAD_XOR,       MVT::i32,    Expand);
410    setOperationAction(ISD::ATOMIC_LOAD_NAND,      MVT::i32,    Expand);
411    setOperationAction(ISD::ATOMIC_LOAD_MIN,       MVT::i32,    Expand);
412    setOperationAction(ISD::ATOMIC_LOAD_MAX,       MVT::i32,    Expand);
413    setOperationAction(ISD::ATOMIC_LOAD_UMIN,      MVT::i32,    Expand);
414    setOperationAction(ISD::ATOMIC_LOAD_UMAX,      MVT::i32,    Expand);
415  }
416
417  setInsertFencesForAtomic(true);
418
419  if (!Subtarget->hasSEInReg()) {
420    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
421    setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
422  }
423
424  if (!Subtarget->hasBitCount()) {
425    setOperationAction(ISD::CTLZ, MVT::i32, Expand);
426    setOperationAction(ISD::CTLZ, MVT::i64, Expand);
427  }
428
429  if (!Subtarget->hasSwap()) {
430    setOperationAction(ISD::BSWAP, MVT::i32, Expand);
431    setOperationAction(ISD::BSWAP, MVT::i64, Expand);
432  }
433
434  if (HasMips64) {
435    setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
436    setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
437    setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
438    setTruncStoreAction(MVT::i64, MVT::i32, Custom);
439  }
440
441  setTargetDAGCombine(ISD::ADDE);
442  setTargetDAGCombine(ISD::SUBE);
443  setTargetDAGCombine(ISD::SDIVREM);
444  setTargetDAGCombine(ISD::UDIVREM);
445  setTargetDAGCombine(ISD::SELECT);
446  setTargetDAGCombine(ISD::AND);
447  setTargetDAGCombine(ISD::OR);
448  setTargetDAGCombine(ISD::ADD);
449
450  setMinFunctionAlignment(HasMips64 ? 3 : 2);
451
452  setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
453  computeRegisterProperties();
454
455  setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
456  setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
457
458  maxStoresPerMemcpy = 16;
459}
460
461bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
462  MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
463
464  if (Subtarget->inMips16Mode())
465    return false;
466
467  switch (SVT) {
468  case MVT::i64:
469  case MVT::i32:
470    return true;
471  default:
472    return false;
473  }
474}
475
476EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
477  return MVT::i32;
478}
479
480// SelectMadd -
481// Transforms a subgraph in CurDAG if the following pattern is found:
482//  (addc multLo, Lo0), (adde multHi, Hi0),
483// where,
484//  multHi/Lo: product of multiplication
485//  Lo0: initial value of Lo register
486//  Hi0: initial value of Hi register
487// Return true if pattern matching was successful.
488static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
489  // ADDENode's second operand must be a flag output of an ADDC node in order
490  // for the matching to be successful.
491  SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
492
493  if (ADDCNode->getOpcode() != ISD::ADDC)
494    return false;
495
496  SDValue MultHi = ADDENode->getOperand(0);
497  SDValue MultLo = ADDCNode->getOperand(0);
498  SDNode *MultNode = MultHi.getNode();
499  unsigned MultOpc = MultHi.getOpcode();
500
501  // MultHi and MultLo must be generated by the same node,
502  if (MultLo.getNode() != MultNode)
503    return false;
504
505  // and it must be a multiplication.
506  if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
507    return false;
508
509  // MultLo amd MultHi must be the first and second output of MultNode
510  // respectively.
511  if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
512    return false;
513
514  // Transform this to a MADD only if ADDENode and ADDCNode are the only users
515  // of the values of MultNode, in which case MultNode will be removed in later
516  // phases.
517  // If there exist users other than ADDENode or ADDCNode, this function returns
518  // here, which will result in MultNode being mapped to a single MULT
519  // instruction node rather than a pair of MULT and MADD instructions being
520  // produced.
521  if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
522    return false;
523
524  SDValue Chain = CurDAG->getEntryNode();
525  DebugLoc dl = ADDENode->getDebugLoc();
526
527  // create MipsMAdd(u) node
528  MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
529
530  SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
531                                 MultNode->getOperand(0),// Factor 0
532                                 MultNode->getOperand(1),// Factor 1
533                                 ADDCNode->getOperand(1),// Lo0
534                                 ADDENode->getOperand(1));// Hi0
535
536  // create CopyFromReg nodes
537  SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
538                                              MAdd);
539  SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
540                                              Mips::HI, MVT::i32,
541                                              CopyFromLo.getValue(2));
542
543  // replace uses of adde and addc here
544  if (!SDValue(ADDCNode, 0).use_empty())
545    CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
546
547  if (!SDValue(ADDENode, 0).use_empty())
548    CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
549
550  return true;
551}
552
553// SelectMsub -
554// Transforms a subgraph in CurDAG if the following pattern is found:
555//  (addc Lo0, multLo), (sube Hi0, multHi),
556// where,
557//  multHi/Lo: product of multiplication
558//  Lo0: initial value of Lo register
559//  Hi0: initial value of Hi register
560// Return true if pattern matching was successful.
561static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
562  // SUBENode's second operand must be a flag output of an SUBC node in order
563  // for the matching to be successful.
564  SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
565
566  if (SUBCNode->getOpcode() != ISD::SUBC)
567    return false;
568
569  SDValue MultHi = SUBENode->getOperand(1);
570  SDValue MultLo = SUBCNode->getOperand(1);
571  SDNode *MultNode = MultHi.getNode();
572  unsigned MultOpc = MultHi.getOpcode();
573
574  // MultHi and MultLo must be generated by the same node,
575  if (MultLo.getNode() != MultNode)
576    return false;
577
578  // and it must be a multiplication.
579  if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
580    return false;
581
582  // MultLo amd MultHi must be the first and second output of MultNode
583  // respectively.
584  if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
585    return false;
586
587  // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
588  // of the values of MultNode, in which case MultNode will be removed in later
589  // phases.
590  // If there exist users other than SUBENode or SUBCNode, this function returns
591  // here, which will result in MultNode being mapped to a single MULT
592  // instruction node rather than a pair of MULT and MSUB instructions being
593  // produced.
594  if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
595    return false;
596
597  SDValue Chain = CurDAG->getEntryNode();
598  DebugLoc dl = SUBENode->getDebugLoc();
599
600  // create MipsSub(u) node
601  MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
602
603  SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
604                                 MultNode->getOperand(0),// Factor 0
605                                 MultNode->getOperand(1),// Factor 1
606                                 SUBCNode->getOperand(0),// Lo0
607                                 SUBENode->getOperand(0));// Hi0
608
609  // create CopyFromReg nodes
610  SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
611                                              MSub);
612  SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
613                                              Mips::HI, MVT::i32,
614                                              CopyFromLo.getValue(2));
615
616  // replace uses of sube and subc here
617  if (!SDValue(SUBCNode, 0).use_empty())
618    CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
619
620  if (!SDValue(SUBENode, 0).use_empty())
621    CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
622
623  return true;
624}
625
626static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
627                                  TargetLowering::DAGCombinerInfo &DCI,
628                                  const MipsSubtarget *Subtarget) {
629  if (DCI.isBeforeLegalize())
630    return SDValue();
631
632  if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
633      SelectMadd(N, &DAG))
634    return SDValue(N, 0);
635
636  return SDValue();
637}
638
639static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
640                                  TargetLowering::DAGCombinerInfo &DCI,
641                                  const MipsSubtarget *Subtarget) {
642  if (DCI.isBeforeLegalize())
643    return SDValue();
644
645  if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
646      SelectMsub(N, &DAG))
647    return SDValue(N, 0);
648
649  return SDValue();
650}
651
652static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
653                                    TargetLowering::DAGCombinerInfo &DCI,
654                                    const MipsSubtarget *Subtarget) {
655  if (DCI.isBeforeLegalizeOps())
656    return SDValue();
657
658  EVT Ty = N->getValueType(0);
659  unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
660  unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
661  unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
662                                                  MipsISD::DivRemU;
663  DebugLoc dl = N->getDebugLoc();
664
665  SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
666                               N->getOperand(0), N->getOperand(1));
667  SDValue InChain = DAG.getEntryNode();
668  SDValue InGlue = DivRem;
669
670  // insert MFLO
671  if (N->hasAnyUseOfValue(0)) {
672    SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
673                                            InGlue);
674    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
675    InChain = CopyFromLo.getValue(1);
676    InGlue = CopyFromLo.getValue(2);
677  }
678
679  // insert MFHI
680  if (N->hasAnyUseOfValue(1)) {
681    SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
682                                            HI, Ty, InGlue);
683    DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
684  }
685
686  return SDValue();
687}
688
689static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
690  switch (CC) {
691  default: llvm_unreachable("Unknown fp condition code!");
692  case ISD::SETEQ:
693  case ISD::SETOEQ: return Mips::FCOND_OEQ;
694  case ISD::SETUNE: return Mips::FCOND_UNE;
695  case ISD::SETLT:
696  case ISD::SETOLT: return Mips::FCOND_OLT;
697  case ISD::SETGT:
698  case ISD::SETOGT: return Mips::FCOND_OGT;
699  case ISD::SETLE:
700  case ISD::SETOLE: return Mips::FCOND_OLE;
701  case ISD::SETGE:
702  case ISD::SETOGE: return Mips::FCOND_OGE;
703  case ISD::SETULT: return Mips::FCOND_ULT;
704  case ISD::SETULE: return Mips::FCOND_ULE;
705  case ISD::SETUGT: return Mips::FCOND_UGT;
706  case ISD::SETUGE: return Mips::FCOND_UGE;
707  case ISD::SETUO:  return Mips::FCOND_UN;
708  case ISD::SETO:   return Mips::FCOND_OR;
709  case ISD::SETNE:
710  case ISD::SETONE: return Mips::FCOND_ONE;
711  case ISD::SETUEQ: return Mips::FCOND_UEQ;
712  }
713}
714
715
716// Returns true if condition code has to be inverted.
717static bool InvertFPCondCode(Mips::CondCode CC) {
718  if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
719    return false;
720
721  assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
722         "Illegal Condition Code");
723
724  return true;
725}
726
727// Creates and returns an FPCmp node from a setcc node.
728// Returns Op if setcc is not a floating point comparison.
729static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
730  // must be a SETCC node
731  if (Op.getOpcode() != ISD::SETCC)
732    return Op;
733
734  SDValue LHS = Op.getOperand(0);
735
736  if (!LHS.getValueType().isFloatingPoint())
737    return Op;
738
739  SDValue RHS = Op.getOperand(1);
740  DebugLoc dl = Op.getDebugLoc();
741
742  // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
743  // node if necessary.
744  ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
745
746  return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
747                     DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
748}
749
750// Creates and returns a CMovFPT/F node.
751static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
752                            SDValue False, DebugLoc DL) {
753  bool invert = InvertFPCondCode((Mips::CondCode)
754                                 cast<ConstantSDNode>(Cond.getOperand(2))
755                                 ->getSExtValue());
756
757  return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
758                     True.getValueType(), True, False, Cond);
759}
760
761static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
762                                    TargetLowering::DAGCombinerInfo &DCI,
763                                    const MipsSubtarget *Subtarget) {
764  if (DCI.isBeforeLegalizeOps())
765    return SDValue();
766
767  SDValue SetCC = N->getOperand(0);
768
769  if ((SetCC.getOpcode() != ISD::SETCC) ||
770      !SetCC.getOperand(0).getValueType().isInteger())
771    return SDValue();
772
773  SDValue False = N->getOperand(2);
774  EVT FalseTy = False.getValueType();
775
776  if (!FalseTy.isInteger())
777    return SDValue();
778
779  ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
780
781  if (!CN || CN->getZExtValue())
782    return SDValue();
783
784  const DebugLoc DL = N->getDebugLoc();
785  ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
786  SDValue True = N->getOperand(1);
787
788  SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
789                       SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
790
791  return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
792}
793
794static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
795                                 TargetLowering::DAGCombinerInfo &DCI,
796                                 const MipsSubtarget *Subtarget) {
797  // Pattern match EXT.
798  //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
799  //  => ext $dst, $src, size, pos
800  if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
801    return SDValue();
802
803  SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
804  unsigned ShiftRightOpc = ShiftRight.getOpcode();
805
806  // Op's first operand must be a shift right.
807  if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
808    return SDValue();
809
810  // The second operand of the shift must be an immediate.
811  ConstantSDNode *CN;
812  if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
813    return SDValue();
814
815  uint64_t Pos = CN->getZExtValue();
816  uint64_t SMPos, SMSize;
817
818  // Op's second operand must be a shifted mask.
819  if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
820      !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
821    return SDValue();
822
823  // Return if the shifted mask does not start at bit 0 or the sum of its size
824  // and Pos exceeds the word's size.
825  EVT ValTy = N->getValueType(0);
826  if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
827    return SDValue();
828
829  return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
830                     ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
831                     DAG.getConstant(SMSize, MVT::i32));
832}
833
834static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
835                                TargetLowering::DAGCombinerInfo &DCI,
836                                const MipsSubtarget *Subtarget) {
837  // Pattern match INS.
838  //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
839  //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1
840  //  => ins $dst, $src, size, pos, $src1
841  if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
842    return SDValue();
843
844  SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
845  uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
846  ConstantSDNode *CN;
847
848  // See if Op's first operand matches (and $src1 , mask0).
849  if (And0.getOpcode() != ISD::AND)
850    return SDValue();
851
852  if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
853      !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
854    return SDValue();
855
856  // See if Op's second operand matches (and (shl $src, pos), mask1).
857  if (And1.getOpcode() != ISD::AND)
858    return SDValue();
859
860  if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
861      !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
862    return SDValue();
863
864  // The shift masks must have the same position and size.
865  if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
866    return SDValue();
867
868  SDValue Shl = And1.getOperand(0);
869  if (Shl.getOpcode() != ISD::SHL)
870    return SDValue();
871
872  if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
873    return SDValue();
874
875  unsigned Shamt = CN->getZExtValue();
876
877  // Return if the shift amount and the first bit position of mask are not the
878  // same.
879  EVT ValTy = N->getValueType(0);
880  if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
881    return SDValue();
882
883  return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
884                     DAG.getConstant(SMPos0, MVT::i32),
885                     DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
886}
887
888static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
889                                 TargetLowering::DAGCombinerInfo &DCI,
890                                 const MipsSubtarget *Subtarget) {
891  // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
892
893  if (DCI.isBeforeLegalizeOps())
894    return SDValue();
895
896  SDValue Add = N->getOperand(1);
897
898  if (Add.getOpcode() != ISD::ADD)
899    return SDValue();
900
901  SDValue Lo = Add.getOperand(1);
902
903  if ((Lo.getOpcode() != MipsISD::Lo) ||
904      (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
905    return SDValue();
906
907  EVT ValTy = N->getValueType(0);
908  DebugLoc DL = N->getDebugLoc();
909
910  SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
911                             Add.getOperand(0));
912  return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
913}
914
915SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
916  const {
917  SelectionDAG &DAG = DCI.DAG;
918  unsigned opc = N->getOpcode();
919
920  switch (opc) {
921  default: break;
922  case ISD::ADDE:
923    return PerformADDECombine(N, DAG, DCI, Subtarget);
924  case ISD::SUBE:
925    return PerformSUBECombine(N, DAG, DCI, Subtarget);
926  case ISD::SDIVREM:
927  case ISD::UDIVREM:
928    return PerformDivRemCombine(N, DAG, DCI, Subtarget);
929  case ISD::SELECT:
930    return PerformSELECTCombine(N, DAG, DCI, Subtarget);
931  case ISD::AND:
932    return PerformANDCombine(N, DAG, DCI, Subtarget);
933  case ISD::OR:
934    return PerformORCombine(N, DAG, DCI, Subtarget);
935  case ISD::ADD:
936    return PerformADDCombine(N, DAG, DCI, Subtarget);
937  }
938
939  return SDValue();
940}
941
942void
943MipsTargetLowering::LowerOperationWrapper(SDNode *N,
944                                          SmallVectorImpl<SDValue> &Results,
945                                          SelectionDAG &DAG) const {
946  SDValue Res = LowerOperation(SDValue(N, 0), DAG);
947
948  for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
949    Results.push_back(Res.getValue(I));
950}
951
952void
953MipsTargetLowering::ReplaceNodeResults(SDNode *N,
954                                       SmallVectorImpl<SDValue> &Results,
955                                       SelectionDAG &DAG) const {
956  SDValue Res = LowerOperation(SDValue(N, 0), DAG);
957
958  for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
959    Results.push_back(Res.getValue(I));
960}
961
962SDValue MipsTargetLowering::
963LowerOperation(SDValue Op, SelectionDAG &DAG) const
964{
965  switch (Op.getOpcode())
966  {
967    case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
968    case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
969    case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
970    case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
971    case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
972    case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
973    case ISD::SELECT:             return LowerSELECT(Op, DAG);
974    case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
975    case ISD::SETCC:              return LowerSETCC(Op, DAG);
976    case ISD::VASTART:            return LowerVASTART(Op, DAG);
977    case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
978    case ISD::FABS:               return LowerFABS(Op, DAG);
979    case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
980    case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
981    case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, DAG);
982    case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
983    case ISD::SHL_PARTS:          return LowerShiftLeftParts(Op, DAG);
984    case ISD::SRA_PARTS:          return LowerShiftRightParts(Op, DAG, true);
985    case ISD::SRL_PARTS:          return LowerShiftRightParts(Op, DAG, false);
986    case ISD::LOAD:               return LowerLOAD(Op, DAG);
987    case ISD::STORE:              return LowerSTORE(Op, DAG);
988    case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
989    case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
990    case ISD::ADD:                return LowerADD(Op, DAG);
991  }
992  return SDValue();
993}
994
995//===----------------------------------------------------------------------===//
996//  Lower helper functions
997//===----------------------------------------------------------------------===//
998
999// AddLiveIn - This helper function adds the specified physical register to the
1000// MachineFunction as a live in value.  It also creates a corresponding
1001// virtual register for it.
1002static unsigned
1003AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1004{
1005  assert(RC->contains(PReg) && "Not the correct regclass!");
1006  unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1007  MF.getRegInfo().addLiveIn(PReg, VReg);
1008  return VReg;
1009}
1010
1011// Get fp branch code (not opcode) from condition code.
1012static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
1013  if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
1014    return Mips::BRANCH_T;
1015
1016  assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
1017         "Invalid CondCode.");
1018
1019  return Mips::BRANCH_F;
1020}
1021
1022/*
1023static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
1024                                        DebugLoc dl,
1025                                        const MipsSubtarget *Subtarget,
1026                                        const TargetInstrInfo *TII,
1027                                        bool isFPCmp, unsigned Opc) {
1028  // There is no need to expand CMov instructions if target has
1029  // conditional moves.
1030  if (Subtarget->hasCondMov())
1031    return BB;
1032
1033  // To "insert" a SELECT_CC instruction, we actually have to insert the
1034  // diamond control-flow pattern.  The incoming instruction knows the
1035  // destination vreg to set, the condition code register to branch on, the
1036  // true/false values to select between, and a branch opcode to use.
1037  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1038  MachineFunction::iterator It = BB;
1039  ++It;
1040
1041  //  thisMBB:
1042  //  ...
1043  //   TrueVal = ...
1044  //   setcc r1, r2, r3
1045  //   bNE   r1, r0, copy1MBB
1046  //   fallthrough --> copy0MBB
1047  MachineBasicBlock *thisMBB  = BB;
1048  MachineFunction *F = BB->getParent();
1049  MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1050  MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
1051  F->insert(It, copy0MBB);
1052  F->insert(It, sinkMBB);
1053
1054  // Transfer the remainder of BB and its successor edges to sinkMBB.
1055  sinkMBB->splice(sinkMBB->begin(), BB,
1056                  llvm::next(MachineBasicBlock::iterator(MI)),
1057                  BB->end());
1058  sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1059
1060  // Next, add the true and fallthrough blocks as its successors.
1061  BB->addSuccessor(copy0MBB);
1062  BB->addSuccessor(sinkMBB);
1063
1064  // Emit the right instruction according to the type of the operands compared
1065  if (isFPCmp)
1066    BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
1067  else
1068    BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
1069      .addReg(Mips::ZERO).addMBB(sinkMBB);
1070
1071  //  copy0MBB:
1072  //   %FalseValue = ...
1073  //   # fallthrough to sinkMBB
1074  BB = copy0MBB;
1075
1076  // Update machine-CFG edges
1077  BB->addSuccessor(sinkMBB);
1078
1079  //  sinkMBB:
1080  //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1081  //  ...
1082  BB = sinkMBB;
1083
1084  if (isFPCmp)
1085    BuildMI(*BB, BB->begin(), dl,
1086            TII->get(Mips::PHI), MI->getOperand(0).getReg())
1087      .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
1088      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1089  else
1090    BuildMI(*BB, BB->begin(), dl,
1091            TII->get(Mips::PHI), MI->getOperand(0).getReg())
1092      .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
1093      .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1094
1095  MI->eraseFromParent();   // The pseudo instruction is gone now.
1096  return BB;
1097}
1098*/
1099
1100MachineBasicBlock *
1101MipsTargetLowering::EmitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
1102  // $bb:
1103  //  bposge32_pseudo $vr0
1104  //  =>
1105  // $bb:
1106  //  bposge32 $tbb
1107  // $fbb:
1108  //  li $vr2, 0
1109  //  b $sink
1110  // $tbb:
1111  //  li $vr1, 1
1112  // $sink:
1113  //  $vr0 = phi($vr2, $fbb, $vr1, $tbb)
1114
1115  MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
1116  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1117  const TargetRegisterClass *RC = &Mips::CPURegsRegClass;
1118  DebugLoc DL = MI->getDebugLoc();
1119  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1120  MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
1121  MachineFunction *F = BB->getParent();
1122  MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
1123  MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
1124  MachineBasicBlock *Sink  = F->CreateMachineBasicBlock(LLVM_BB);
1125  F->insert(It, FBB);
1126  F->insert(It, TBB);
1127  F->insert(It, Sink);
1128
1129  // Transfer the remainder of BB and its successor edges to Sink.
1130  Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
1131               BB->end());
1132  Sink->transferSuccessorsAndUpdatePHIs(BB);
1133
1134  // Add successors.
1135  BB->addSuccessor(FBB);
1136  BB->addSuccessor(TBB);
1137  FBB->addSuccessor(Sink);
1138  TBB->addSuccessor(Sink);
1139
1140  // Insert the real bposge32 instruction to $BB.
1141  BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
1142
1143  // Fill $FBB.
1144  unsigned VR2 = RegInfo.createVirtualRegister(RC);
1145  BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
1146    .addReg(Mips::ZERO).addImm(0);
1147  BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
1148
1149  // Fill $TBB.
1150  unsigned VR1 = RegInfo.createVirtualRegister(RC);
1151  BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
1152    .addReg(Mips::ZERO).addImm(1);
1153
1154  // Insert phi function to $Sink.
1155  BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
1156          MI->getOperand(0).getReg())
1157    .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
1158
1159  MI->eraseFromParent();   // The pseudo instruction is gone now.
1160  return Sink;
1161}
1162
1163MachineBasicBlock *
1164MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1165                                                MachineBasicBlock *BB) const {
1166  switch (MI->getOpcode()) {
1167  default: llvm_unreachable("Unexpected instr type to insert");
1168  case Mips::ATOMIC_LOAD_ADD_I8:
1169  case Mips::ATOMIC_LOAD_ADD_I8_P8:
1170    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1171  case Mips::ATOMIC_LOAD_ADD_I16:
1172  case Mips::ATOMIC_LOAD_ADD_I16_P8:
1173    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1174  case Mips::ATOMIC_LOAD_ADD_I32:
1175  case Mips::ATOMIC_LOAD_ADD_I32_P8:
1176    return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
1177  case Mips::ATOMIC_LOAD_ADD_I64:
1178  case Mips::ATOMIC_LOAD_ADD_I64_P8:
1179    return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
1180
1181  case Mips::ATOMIC_LOAD_AND_I8:
1182  case Mips::ATOMIC_LOAD_AND_I8_P8:
1183    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1184  case Mips::ATOMIC_LOAD_AND_I16:
1185  case Mips::ATOMIC_LOAD_AND_I16_P8:
1186    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1187  case Mips::ATOMIC_LOAD_AND_I32:
1188  case Mips::ATOMIC_LOAD_AND_I32_P8:
1189    return EmitAtomicBinary(MI, BB, 4, Mips::AND);
1190  case Mips::ATOMIC_LOAD_AND_I64:
1191  case Mips::ATOMIC_LOAD_AND_I64_P8:
1192    return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
1193
1194  case Mips::ATOMIC_LOAD_OR_I8:
1195  case Mips::ATOMIC_LOAD_OR_I8_P8:
1196    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1197  case Mips::ATOMIC_LOAD_OR_I16:
1198  case Mips::ATOMIC_LOAD_OR_I16_P8:
1199    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1200  case Mips::ATOMIC_LOAD_OR_I32:
1201  case Mips::ATOMIC_LOAD_OR_I32_P8:
1202    return EmitAtomicBinary(MI, BB, 4, Mips::OR);
1203  case Mips::ATOMIC_LOAD_OR_I64:
1204  case Mips::ATOMIC_LOAD_OR_I64_P8:
1205    return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
1206
1207  case Mips::ATOMIC_LOAD_XOR_I8:
1208  case Mips::ATOMIC_LOAD_XOR_I8_P8:
1209    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1210  case Mips::ATOMIC_LOAD_XOR_I16:
1211  case Mips::ATOMIC_LOAD_XOR_I16_P8:
1212    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1213  case Mips::ATOMIC_LOAD_XOR_I32:
1214  case Mips::ATOMIC_LOAD_XOR_I32_P8:
1215    return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
1216  case Mips::ATOMIC_LOAD_XOR_I64:
1217  case Mips::ATOMIC_LOAD_XOR_I64_P8:
1218    return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
1219
1220  case Mips::ATOMIC_LOAD_NAND_I8:
1221  case Mips::ATOMIC_LOAD_NAND_I8_P8:
1222    return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
1223  case Mips::ATOMIC_LOAD_NAND_I16:
1224  case Mips::ATOMIC_LOAD_NAND_I16_P8:
1225    return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
1226  case Mips::ATOMIC_LOAD_NAND_I32:
1227  case Mips::ATOMIC_LOAD_NAND_I32_P8:
1228    return EmitAtomicBinary(MI, BB, 4, 0, true);
1229  case Mips::ATOMIC_LOAD_NAND_I64:
1230  case Mips::ATOMIC_LOAD_NAND_I64_P8:
1231    return EmitAtomicBinary(MI, BB, 8, 0, true);
1232
1233  case Mips::ATOMIC_LOAD_SUB_I8:
1234  case Mips::ATOMIC_LOAD_SUB_I8_P8:
1235    return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1236  case Mips::ATOMIC_LOAD_SUB_I16:
1237  case Mips::ATOMIC_LOAD_SUB_I16_P8:
1238    return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1239  case Mips::ATOMIC_LOAD_SUB_I32:
1240  case Mips::ATOMIC_LOAD_SUB_I32_P8:
1241    return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1242  case Mips::ATOMIC_LOAD_SUB_I64:
1243  case Mips::ATOMIC_LOAD_SUB_I64_P8:
1244    return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1245
1246  case Mips::ATOMIC_SWAP_I8:
1247  case Mips::ATOMIC_SWAP_I8_P8:
1248    return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1249  case Mips::ATOMIC_SWAP_I16:
1250  case Mips::ATOMIC_SWAP_I16_P8:
1251    return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1252  case Mips::ATOMIC_SWAP_I32:
1253  case Mips::ATOMIC_SWAP_I32_P8:
1254    return EmitAtomicBinary(MI, BB, 4, 0);
1255  case Mips::ATOMIC_SWAP_I64:
1256  case Mips::ATOMIC_SWAP_I64_P8:
1257    return EmitAtomicBinary(MI, BB, 8, 0);
1258
1259  case Mips::ATOMIC_CMP_SWAP_I8:
1260  case Mips::ATOMIC_CMP_SWAP_I8_P8:
1261    return EmitAtomicCmpSwapPartword(MI, BB, 1);
1262  case Mips::ATOMIC_CMP_SWAP_I16:
1263  case Mips::ATOMIC_CMP_SWAP_I16_P8:
1264    return EmitAtomicCmpSwapPartword(MI, BB, 2);
1265  case Mips::ATOMIC_CMP_SWAP_I32:
1266  case Mips::ATOMIC_CMP_SWAP_I32_P8:
1267    return EmitAtomicCmpSwap(MI, BB, 4);
1268  case Mips::ATOMIC_CMP_SWAP_I64:
1269  case Mips::ATOMIC_CMP_SWAP_I64_P8:
1270    return EmitAtomicCmpSwap(MI, BB, 8);
1271  case Mips::BPOSGE32_PSEUDO:
1272    return EmitBPOSGE32(MI, BB);
1273  }
1274}
1275
1276// This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1277// Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1278MachineBasicBlock *
1279MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1280                                     unsigned Size, unsigned BinOpcode,
1281                                     bool Nand) const {
1282  assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1283
1284  MachineFunction *MF = BB->getParent();
1285  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1286  const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1287  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1288  DebugLoc dl = MI->getDebugLoc();
1289  unsigned LL, SC, AND, NOR, ZERO, BEQ;
1290
1291  if (Size == 4) {
1292    LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1293    SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1294    AND = Mips::AND;
1295    NOR = Mips::NOR;
1296    ZERO = Mips::ZERO;
1297    BEQ = Mips::BEQ;
1298  }
1299  else {
1300    LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1301    SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1302    AND = Mips::AND64;
1303    NOR = Mips::NOR64;
1304    ZERO = Mips::ZERO_64;
1305    BEQ = Mips::BEQ64;
1306  }
1307
1308  unsigned OldVal = MI->getOperand(0).getReg();
1309  unsigned Ptr = MI->getOperand(1).getReg();
1310  unsigned Incr = MI->getOperand(2).getReg();
1311
1312  unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1313  unsigned AndRes = RegInfo.createVirtualRegister(RC);
1314  unsigned Success = RegInfo.createVirtualRegister(RC);
1315
1316  // insert new blocks after the current block
1317  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1318  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1319  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1320  MachineFunction::iterator It = BB;
1321  ++It;
1322  MF->insert(It, loopMBB);
1323  MF->insert(It, exitMBB);
1324
1325  // Transfer the remainder of BB and its successor edges to exitMBB.
1326  exitMBB->splice(exitMBB->begin(), BB,
1327                  llvm::next(MachineBasicBlock::iterator(MI)),
1328                  BB->end());
1329  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1330
1331  //  thisMBB:
1332  //    ...
1333  //    fallthrough --> loopMBB
1334  BB->addSuccessor(loopMBB);
1335  loopMBB->addSuccessor(loopMBB);
1336  loopMBB->addSuccessor(exitMBB);
1337
1338  //  loopMBB:
1339  //    ll oldval, 0(ptr)
1340  //    <binop> storeval, oldval, incr
1341  //    sc success, storeval, 0(ptr)
1342  //    beq success, $0, loopMBB
1343  BB = loopMBB;
1344  BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1345  if (Nand) {
1346    //  and andres, oldval, incr
1347    //  nor storeval, $0, andres
1348    BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1349    BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1350  } else if (BinOpcode) {
1351    //  <binop> storeval, oldval, incr
1352    BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1353  } else {
1354    StoreVal = Incr;
1355  }
1356  BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1357  BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1358
1359  MI->eraseFromParent();   // The instruction is gone now.
1360
1361  return exitMBB;
1362}
1363
1364MachineBasicBlock *
1365MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1366                                             MachineBasicBlock *BB,
1367                                             unsigned Size, unsigned BinOpcode,
1368                                             bool Nand) const {
1369  assert((Size == 1 || Size == 2) &&
1370      "Unsupported size for EmitAtomicBinaryPartial.");
1371
1372  MachineFunction *MF = BB->getParent();
1373  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1374  const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1375  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1376  DebugLoc dl = MI->getDebugLoc();
1377  unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1378  unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1379
1380  unsigned Dest = MI->getOperand(0).getReg();
1381  unsigned Ptr = MI->getOperand(1).getReg();
1382  unsigned Incr = MI->getOperand(2).getReg();
1383
1384  unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1385  unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1386  unsigned Mask = RegInfo.createVirtualRegister(RC);
1387  unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1388  unsigned NewVal = RegInfo.createVirtualRegister(RC);
1389  unsigned OldVal = RegInfo.createVirtualRegister(RC);
1390  unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1391  unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1392  unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1393  unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1394  unsigned AndRes = RegInfo.createVirtualRegister(RC);
1395  unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1396  unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1397  unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1398  unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1399  unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1400  unsigned SllRes = RegInfo.createVirtualRegister(RC);
1401  unsigned Success = RegInfo.createVirtualRegister(RC);
1402
1403  // insert new blocks after the current block
1404  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1405  MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1406  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1407  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1408  MachineFunction::iterator It = BB;
1409  ++It;
1410  MF->insert(It, loopMBB);
1411  MF->insert(It, sinkMBB);
1412  MF->insert(It, exitMBB);
1413
1414  // Transfer the remainder of BB and its successor edges to exitMBB.
1415  exitMBB->splice(exitMBB->begin(), BB,
1416                  llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1417  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1418
1419  BB->addSuccessor(loopMBB);
1420  loopMBB->addSuccessor(loopMBB);
1421  loopMBB->addSuccessor(sinkMBB);
1422  sinkMBB->addSuccessor(exitMBB);
1423
1424  //  thisMBB:
1425  //    addiu   masklsb2,$0,-4                # 0xfffffffc
1426  //    and     alignedaddr,ptr,masklsb2
1427  //    andi    ptrlsb2,ptr,3
1428  //    sll     shiftamt,ptrlsb2,3
1429  //    ori     maskupper,$0,255               # 0xff
1430  //    sll     mask,maskupper,shiftamt
1431  //    nor     mask2,$0,mask
1432  //    sll     incr2,incr,shiftamt
1433
1434  int64_t MaskImm = (Size == 1) ? 255 : 65535;
1435  BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1436    .addReg(Mips::ZERO).addImm(-4);
1437  BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1438    .addReg(Ptr).addReg(MaskLSB2);
1439  BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1440  BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1441  BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1442    .addReg(Mips::ZERO).addImm(MaskImm);
1443  BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1444    .addReg(ShiftAmt).addReg(MaskUpper);
1445  BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1446  BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1447
1448  // atomic.load.binop
1449  // loopMBB:
1450  //   ll      oldval,0(alignedaddr)
1451  //   binop   binopres,oldval,incr2
1452  //   and     newval,binopres,mask
1453  //   and     maskedoldval0,oldval,mask2
1454  //   or      storeval,maskedoldval0,newval
1455  //   sc      success,storeval,0(alignedaddr)
1456  //   beq     success,$0,loopMBB
1457
1458  // atomic.swap
1459  // loopMBB:
1460  //   ll      oldval,0(alignedaddr)
1461  //   and     newval,incr2,mask
1462  //   and     maskedoldval0,oldval,mask2
1463  //   or      storeval,maskedoldval0,newval
1464  //   sc      success,storeval,0(alignedaddr)
1465  //   beq     success,$0,loopMBB
1466
1467  BB = loopMBB;
1468  BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1469  if (Nand) {
1470    //  and andres, oldval, incr2
1471    //  nor binopres, $0, andres
1472    //  and newval, binopres, mask
1473    BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1474    BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1475      .addReg(Mips::ZERO).addReg(AndRes);
1476    BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1477  } else if (BinOpcode) {
1478    //  <binop> binopres, oldval, incr2
1479    //  and newval, binopres, mask
1480    BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1481    BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1482  } else {// atomic.swap
1483    //  and newval, incr2, mask
1484    BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1485  }
1486
1487  BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1488    .addReg(OldVal).addReg(Mask2);
1489  BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1490    .addReg(MaskedOldVal0).addReg(NewVal);
1491  BuildMI(BB, dl, TII->get(SC), Success)
1492    .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1493  BuildMI(BB, dl, TII->get(Mips::BEQ))
1494    .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1495
1496  //  sinkMBB:
1497  //    and     maskedoldval1,oldval,mask
1498  //    srl     srlres,maskedoldval1,shiftamt
1499  //    sll     sllres,srlres,24
1500  //    sra     dest,sllres,24
1501  BB = sinkMBB;
1502  int64_t ShiftImm = (Size == 1) ? 24 : 16;
1503
1504  BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1505    .addReg(OldVal).addReg(Mask);
1506  BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1507      .addReg(ShiftAmt).addReg(MaskedOldVal1);
1508  BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1509      .addReg(SrlRes).addImm(ShiftImm);
1510  BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1511      .addReg(SllRes).addImm(ShiftImm);
1512
1513  MI->eraseFromParent();   // The instruction is gone now.
1514
1515  return exitMBB;
1516}
1517
1518MachineBasicBlock *
1519MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1520                                      MachineBasicBlock *BB,
1521                                      unsigned Size) const {
1522  assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1523
1524  MachineFunction *MF = BB->getParent();
1525  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1526  const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1527  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1528  DebugLoc dl = MI->getDebugLoc();
1529  unsigned LL, SC, ZERO, BNE, BEQ;
1530
1531  if (Size == 4) {
1532    LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1533    SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1534    ZERO = Mips::ZERO;
1535    BNE = Mips::BNE;
1536    BEQ = Mips::BEQ;
1537  }
1538  else {
1539    LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1540    SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1541    ZERO = Mips::ZERO_64;
1542    BNE = Mips::BNE64;
1543    BEQ = Mips::BEQ64;
1544  }
1545
1546  unsigned Dest    = MI->getOperand(0).getReg();
1547  unsigned Ptr     = MI->getOperand(1).getReg();
1548  unsigned OldVal  = MI->getOperand(2).getReg();
1549  unsigned NewVal  = MI->getOperand(3).getReg();
1550
1551  unsigned Success = RegInfo.createVirtualRegister(RC);
1552
1553  // insert new blocks after the current block
1554  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1555  MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1556  MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1557  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1558  MachineFunction::iterator It = BB;
1559  ++It;
1560  MF->insert(It, loop1MBB);
1561  MF->insert(It, loop2MBB);
1562  MF->insert(It, exitMBB);
1563
1564  // Transfer the remainder of BB and its successor edges to exitMBB.
1565  exitMBB->splice(exitMBB->begin(), BB,
1566                  llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1567  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1568
1569  //  thisMBB:
1570  //    ...
1571  //    fallthrough --> loop1MBB
1572  BB->addSuccessor(loop1MBB);
1573  loop1MBB->addSuccessor(exitMBB);
1574  loop1MBB->addSuccessor(loop2MBB);
1575  loop2MBB->addSuccessor(loop1MBB);
1576  loop2MBB->addSuccessor(exitMBB);
1577
1578  // loop1MBB:
1579  //   ll dest, 0(ptr)
1580  //   bne dest, oldval, exitMBB
1581  BB = loop1MBB;
1582  BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1583  BuildMI(BB, dl, TII->get(BNE))
1584    .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1585
1586  // loop2MBB:
1587  //   sc success, newval, 0(ptr)
1588  //   beq success, $0, loop1MBB
1589  BB = loop2MBB;
1590  BuildMI(BB, dl, TII->get(SC), Success)
1591    .addReg(NewVal).addReg(Ptr).addImm(0);
1592  BuildMI(BB, dl, TII->get(BEQ))
1593    .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1594
1595  MI->eraseFromParent();   // The instruction is gone now.
1596
1597  return exitMBB;
1598}
1599
1600MachineBasicBlock *
1601MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1602                                              MachineBasicBlock *BB,
1603                                              unsigned Size) const {
1604  assert((Size == 1 || Size == 2) &&
1605      "Unsupported size for EmitAtomicCmpSwapPartial.");
1606
1607  MachineFunction *MF = BB->getParent();
1608  MachineRegisterInfo &RegInfo = MF->getRegInfo();
1609  const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1610  const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1611  DebugLoc dl = MI->getDebugLoc();
1612  unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1613  unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1614
1615  unsigned Dest    = MI->getOperand(0).getReg();
1616  unsigned Ptr     = MI->getOperand(1).getReg();
1617  unsigned CmpVal  = MI->getOperand(2).getReg();
1618  unsigned NewVal  = MI->getOperand(3).getReg();
1619
1620  unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1621  unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1622  unsigned Mask = RegInfo.createVirtualRegister(RC);
1623  unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1624  unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1625  unsigned OldVal = RegInfo.createVirtualRegister(RC);
1626  unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1627  unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1628  unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1629  unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1630  unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1631  unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1632  unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1633  unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1634  unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1635  unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1636  unsigned SllRes = RegInfo.createVirtualRegister(RC);
1637  unsigned Success = RegInfo.createVirtualRegister(RC);
1638
1639  // insert new blocks after the current block
1640  const BasicBlock *LLVM_BB = BB->getBasicBlock();
1641  MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1642  MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1643  MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1644  MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1645  MachineFunction::iterator It = BB;
1646  ++It;
1647  MF->insert(It, loop1MBB);
1648  MF->insert(It, loop2MBB);
1649  MF->insert(It, sinkMBB);
1650  MF->insert(It, exitMBB);
1651
1652  // Transfer the remainder of BB and its successor edges to exitMBB.
1653  exitMBB->splice(exitMBB->begin(), BB,
1654                  llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1655  exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1656
1657  BB->addSuccessor(loop1MBB);
1658  loop1MBB->addSuccessor(sinkMBB);
1659  loop1MBB->addSuccessor(loop2MBB);
1660  loop2MBB->addSuccessor(loop1MBB);
1661  loop2MBB->addSuccessor(sinkMBB);
1662  sinkMBB->addSuccessor(exitMBB);
1663
1664  // FIXME: computation of newval2 can be moved to loop2MBB.
1665  //  thisMBB:
1666  //    addiu   masklsb2,$0,-4                # 0xfffffffc
1667  //    and     alignedaddr,ptr,masklsb2
1668  //    andi    ptrlsb2,ptr,3
1669  //    sll     shiftamt,ptrlsb2,3
1670  //    ori     maskupper,$0,255               # 0xff
1671  //    sll     mask,maskupper,shiftamt
1672  //    nor     mask2,$0,mask
1673  //    andi    maskedcmpval,cmpval,255
1674  //    sll     shiftedcmpval,maskedcmpval,shiftamt
1675  //    andi    maskednewval,newval,255
1676  //    sll     shiftednewval,maskednewval,shiftamt
1677  int64_t MaskImm = (Size == 1) ? 255 : 65535;
1678  BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1679    .addReg(Mips::ZERO).addImm(-4);
1680  BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1681    .addReg(Ptr).addReg(MaskLSB2);
1682  BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1683  BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1684  BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1685    .addReg(Mips::ZERO).addImm(MaskImm);
1686  BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1687    .addReg(ShiftAmt).addReg(MaskUpper);
1688  BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1689  BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1690    .addReg(CmpVal).addImm(MaskImm);
1691  BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1692    .addReg(ShiftAmt).addReg(MaskedCmpVal);
1693  BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1694    .addReg(NewVal).addImm(MaskImm);
1695  BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1696    .addReg(ShiftAmt).addReg(MaskedNewVal);
1697
1698  //  loop1MBB:
1699  //    ll      oldval,0(alginedaddr)
1700  //    and     maskedoldval0,oldval,mask
1701  //    bne     maskedoldval0,shiftedcmpval,sinkMBB
1702  BB = loop1MBB;
1703  BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1704  BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1705    .addReg(OldVal).addReg(Mask);
1706  BuildMI(BB, dl, TII->get(Mips::BNE))
1707    .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1708
1709  //  loop2MBB:
1710  //    and     maskedoldval1,oldval,mask2
1711  //    or      storeval,maskedoldval1,shiftednewval
1712  //    sc      success,storeval,0(alignedaddr)
1713  //    beq     success,$0,loop1MBB
1714  BB = loop2MBB;
1715  BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1716    .addReg(OldVal).addReg(Mask2);
1717  BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1718    .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1719  BuildMI(BB, dl, TII->get(SC), Success)
1720      .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1721  BuildMI(BB, dl, TII->get(Mips::BEQ))
1722      .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1723
1724  //  sinkMBB:
1725  //    srl     srlres,maskedoldval0,shiftamt
1726  //    sll     sllres,srlres,24
1727  //    sra     dest,sllres,24
1728  BB = sinkMBB;
1729  int64_t ShiftImm = (Size == 1) ? 24 : 16;
1730
1731  BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1732      .addReg(ShiftAmt).addReg(MaskedOldVal0);
1733  BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1734      .addReg(SrlRes).addImm(ShiftImm);
1735  BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1736      .addReg(SllRes).addImm(ShiftImm);
1737
1738  MI->eraseFromParent();   // The instruction is gone now.
1739
1740  return exitMBB;
1741}
1742
1743//===----------------------------------------------------------------------===//
1744//  Misc Lower Operation implementation
1745//===----------------------------------------------------------------------===//
1746SDValue MipsTargetLowering::
1747LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1748{
1749  // The first operand is the chain, the second is the condition, the third is
1750  // the block to branch to if the condition is true.
1751  SDValue Chain = Op.getOperand(0);
1752  SDValue Dest = Op.getOperand(2);
1753  DebugLoc dl = Op.getDebugLoc();
1754
1755  SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1756
1757  // Return if flag is not set by a floating point comparison.
1758  if (CondRes.getOpcode() != MipsISD::FPCmp)
1759    return Op;
1760
1761  SDValue CCNode  = CondRes.getOperand(2);
1762  Mips::CondCode CC =
1763    (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1764  SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1765
1766  return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1767                     Dest, CondRes);
1768}
1769
1770SDValue MipsTargetLowering::
1771LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1772{
1773  SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1774
1775  // Return if flag is not set by a floating point comparison.
1776  if (Cond.getOpcode() != MipsISD::FPCmp)
1777    return Op;
1778
1779  return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1780                      Op.getDebugLoc());
1781}
1782
1783SDValue MipsTargetLowering::
1784LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1785{
1786  DebugLoc DL = Op.getDebugLoc();
1787  EVT Ty = Op.getOperand(0).getValueType();
1788  SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1789                             Op.getOperand(0), Op.getOperand(1),
1790                             Op.getOperand(4));
1791
1792  return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1793                     Op.getOperand(3));
1794}
1795
1796SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1797  SDValue Cond = CreateFPCmp(DAG, Op);
1798
1799  assert(Cond.getOpcode() == MipsISD::FPCmp &&
1800         "Floating point operand expected.");
1801
1802  SDValue True  = DAG.getConstant(1, MVT::i32);
1803  SDValue False = DAG.getConstant(0, MVT::i32);
1804
1805  return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1806}
1807
1808SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1809                                               SelectionDAG &DAG) const {
1810  // FIXME there isn't actually debug info here
1811  DebugLoc dl = Op.getDebugLoc();
1812  const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1813
1814  if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1815    const MipsTargetObjectFile &TLOF =
1816      (const MipsTargetObjectFile&)getObjFileLowering();
1817
1818    // %gp_rel relocation
1819    if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1820      SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1821                                              MipsII::MO_GPREL);
1822      SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl,
1823                                      DAG.getVTList(MVT::i32), &GA, 1);
1824      SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1825      return DAG.getNode(ISD::ADD, dl, MVT::i32, GPReg, GPRelNode);
1826    }
1827
1828    // %hi/%lo relocation
1829    return getAddrNonPIC(Op, DAG);
1830  }
1831
1832  if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1833    return getAddrLocal(Op, DAG, HasMips64);
1834
1835  if (LargeGOT)
1836    return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1837                                 MipsII::MO_GOT_LO16);
1838
1839  return getAddrGlobal(Op, DAG,
1840                       HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1841}
1842
1843SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1844                                              SelectionDAG &DAG) const {
1845  if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1846    return getAddrNonPIC(Op, DAG);
1847
1848  return getAddrLocal(Op, DAG, HasMips64);
1849}
1850
1851SDValue MipsTargetLowering::
1852LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1853{
1854  // If the relocation model is PIC, use the General Dynamic TLS Model or
1855  // Local Dynamic TLS model, otherwise use the Initial Exec or
1856  // Local Exec TLS Model.
1857
1858  GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1859  DebugLoc dl = GA->getDebugLoc();
1860  const GlobalValue *GV = GA->getGlobal();
1861  EVT PtrVT = getPointerTy();
1862
1863  TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1864
1865  if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1866    // General Dynamic and Local Dynamic TLS Model.
1867    unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1868                                                      : MipsII::MO_TLSGD;
1869
1870    SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1871    SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1872                                   GetGlobalReg(DAG, PtrVT), TGA);
1873    unsigned PtrSize = PtrVT.getSizeInBits();
1874    IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1875
1876    SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1877
1878    ArgListTy Args;
1879    ArgListEntry Entry;
1880    Entry.Node = Argument;
1881    Entry.Ty = PtrTy;
1882    Args.push_back(Entry);
1883
1884    TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1885                  false, false, false, false, 0, CallingConv::C,
1886                  /*isTailCall=*/false, /*doesNotRet=*/false,
1887                  /*isReturnValueUsed=*/true,
1888                  TlsGetAddr, Args, DAG, dl);
1889    std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1890
1891    SDValue Ret = CallResult.first;
1892
1893    if (model != TLSModel::LocalDynamic)
1894      return Ret;
1895
1896    SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1897                                               MipsII::MO_DTPREL_HI);
1898    SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1899    SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1900                                               MipsII::MO_DTPREL_LO);
1901    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1902    SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1903    return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1904  }
1905
1906  SDValue Offset;
1907  if (model == TLSModel::InitialExec) {
1908    // Initial Exec TLS Model
1909    SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1910                                             MipsII::MO_GOTTPREL);
1911    TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1912                      TGA);
1913    Offset = DAG.getLoad(PtrVT, dl,
1914                         DAG.getEntryNode(), TGA, MachinePointerInfo(),
1915                         false, false, false, 0);
1916  } else {
1917    // Local Exec TLS Model
1918    assert(model == TLSModel::LocalExec);
1919    SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1920                                               MipsII::MO_TPREL_HI);
1921    SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1922                                               MipsII::MO_TPREL_LO);
1923    SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1924    SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1925    Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1926  }
1927
1928  SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1929  return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1930}
1931
1932SDValue MipsTargetLowering::
1933LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1934{
1935  if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1936    return getAddrNonPIC(Op, DAG);
1937
1938  return getAddrLocal(Op, DAG, HasMips64);
1939}
1940
1941SDValue MipsTargetLowering::
1942LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1943{
1944  // gp_rel relocation
1945  // FIXME: we should reference the constant pool using small data sections,
1946  // but the asm printer currently doesn't support this feature without
1947  // hacking it. This feature should come soon so we can uncomment the
1948  // stuff below.
1949  //if (IsInSmallSection(C->getType())) {
1950  //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1951  //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1952  //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1953
1954  if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1955    return getAddrNonPIC(Op, DAG);
1956
1957  return getAddrLocal(Op, DAG, HasMips64);
1958}
1959
1960SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1961  MachineFunction &MF = DAG.getMachineFunction();
1962  MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1963
1964  DebugLoc dl = Op.getDebugLoc();
1965  SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1966                                 getPointerTy());
1967
1968  // vastart just stores the address of the VarArgsFrameIndex slot into the
1969  // memory location argument.
1970  const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1971  return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1972                      MachinePointerInfo(SV), false, false, 0);
1973}
1974
1975static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1976  EVT TyX = Op.getOperand(0).getValueType();
1977  EVT TyY = Op.getOperand(1).getValueType();
1978  SDValue Const1 = DAG.getConstant(1, MVT::i32);
1979  SDValue Const31 = DAG.getConstant(31, MVT::i32);
1980  DebugLoc DL = Op.getDebugLoc();
1981  SDValue Res;
1982
1983  // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1984  // to i32.
1985  SDValue X = (TyX == MVT::f32) ?
1986    DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1987    DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1988                Const1);
1989  SDValue Y = (TyY == MVT::f32) ?
1990    DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1991    DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1992                Const1);
1993
1994  if (HasR2) {
1995    // ext  E, Y, 31, 1  ; extract bit31 of Y
1996    // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
1997    SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1998    Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1999  } else {
2000    // sll SllX, X, 1
2001    // srl SrlX, SllX, 1
2002    // srl SrlY, Y, 31
2003    // sll SllY, SrlX, 31
2004    // or  Or, SrlX, SllY
2005    SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2006    SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2007    SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2008    SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2009    Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2010  }
2011
2012  if (TyX == MVT::f32)
2013    return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2014
2015  SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2016                             Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2017  return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2018}
2019
2020static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2021  unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2022  unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2023  EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2024  SDValue Const1 = DAG.getConstant(1, MVT::i32);
2025  DebugLoc DL = Op.getDebugLoc();
2026
2027  // Bitcast to integer nodes.
2028  SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2029  SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2030
2031  if (HasR2) {
2032    // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
2033    // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
2034    SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2035                            DAG.getConstant(WidthY - 1, MVT::i32), Const1);
2036
2037    if (WidthX > WidthY)
2038      E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2039    else if (WidthY > WidthX)
2040      E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2041
2042    SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2043                            DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2044    return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2045  }
2046
2047  // (d)sll SllX, X, 1
2048  // (d)srl SrlX, SllX, 1
2049  // (d)srl SrlY, Y, width(Y)-1
2050  // (d)sll SllY, SrlX, width(Y)-1
2051  // or     Or, SrlX, SllY
2052  SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2053  SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2054  SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2055                             DAG.getConstant(WidthY - 1, MVT::i32));
2056
2057  if (WidthX > WidthY)
2058    SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2059  else if (WidthY > WidthX)
2060    SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2061
2062  SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2063                             DAG.getConstant(WidthX - 1, MVT::i32));
2064  SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2065  return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2066}
2067
2068SDValue
2069MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2070  if (Subtarget->hasMips64())
2071    return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
2072
2073  return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
2074}
2075
2076static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2077  SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2078  DebugLoc DL = Op.getDebugLoc();
2079
2080  // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2081  // to i32.
2082  SDValue X = (Op.getValueType() == MVT::f32) ?
2083    DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2084    DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2085                Const1);
2086
2087  // Clear MSB.
2088  if (HasR2)
2089    Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2090                      DAG.getRegister(Mips::ZERO, MVT::i32),
2091                      DAG.getConstant(31, MVT::i32), Const1, X);
2092  else {
2093    SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2094    Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2095  }
2096
2097  if (Op.getValueType() == MVT::f32)
2098    return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2099
2100  SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2101                             Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2102  return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2103}
2104
2105static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2106  SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2107  DebugLoc DL = Op.getDebugLoc();
2108
2109  // Bitcast to integer node.
2110  SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2111
2112  // Clear MSB.
2113  if (HasR2)
2114    Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2115                      DAG.getRegister(Mips::ZERO_64, MVT::i64),
2116                      DAG.getConstant(63, MVT::i32), Const1, X);
2117  else {
2118    SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2119    Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2120  }
2121
2122  return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2123}
2124
2125SDValue
2126MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
2127  if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2128    return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2129
2130  return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2131}
2132
2133SDValue MipsTargetLowering::
2134LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2135  // check the depth
2136  assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2137         "Frame address can only be determined for current frame.");
2138
2139  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2140  MFI->setFrameAddressIsTaken(true);
2141  EVT VT = Op.getValueType();
2142  DebugLoc dl = Op.getDebugLoc();
2143  SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2144                                         IsN64 ? Mips::FP_64 : Mips::FP, VT);
2145  return FrameAddr;
2146}
2147
2148SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2149                                            SelectionDAG &DAG) const {
2150  // check the depth
2151  assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2152         "Return address can be determined only for current frame.");
2153
2154  MachineFunction &MF = DAG.getMachineFunction();
2155  MachineFrameInfo *MFI = MF.getFrameInfo();
2156  EVT VT = Op.getValueType();
2157  unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2158  MFI->setReturnAddressIsTaken(true);
2159
2160  // Return RA, which contains the return address. Mark it an implicit live-in.
2161  unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2162  return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2163}
2164
2165// TODO: set SType according to the desired memory barrier behavior.
2166SDValue
2167MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2168  unsigned SType = 0;
2169  DebugLoc dl = Op.getDebugLoc();
2170  return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2171                     DAG.getConstant(SType, MVT::i32));
2172}
2173
2174SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2175                                              SelectionDAG &DAG) const {
2176  // FIXME: Need pseudo-fence for 'singlethread' fences
2177  // FIXME: Set SType for weaker fences where supported/appropriate.
2178  unsigned SType = 0;
2179  DebugLoc dl = Op.getDebugLoc();
2180  return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2181                     DAG.getConstant(SType, MVT::i32));
2182}
2183
2184SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2185                                                SelectionDAG &DAG) const {
2186  DebugLoc DL = Op.getDebugLoc();
2187  SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2188  SDValue Shamt = Op.getOperand(2);
2189
2190  // if shamt < 32:
2191  //  lo = (shl lo, shamt)
2192  //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2193  // else:
2194  //  lo = 0
2195  //  hi = (shl lo, shamt[4:0])
2196  SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2197                            DAG.getConstant(-1, MVT::i32));
2198  SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2199                                      DAG.getConstant(1, MVT::i32));
2200  SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2201                                     Not);
2202  SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2203  SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2204  SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2205  SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2206                             DAG.getConstant(0x20, MVT::i32));
2207  Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2208                   DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2209  Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2210
2211  SDValue Ops[2] = {Lo, Hi};
2212  return DAG.getMergeValues(Ops, 2, DL);
2213}
2214
2215SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2216                                                 bool IsSRA) const {
2217  DebugLoc DL = Op.getDebugLoc();
2218  SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2219  SDValue Shamt = Op.getOperand(2);
2220
2221  // if shamt < 32:
2222  //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2223  //  if isSRA:
2224  //    hi = (sra hi, shamt)
2225  //  else:
2226  //    hi = (srl hi, shamt)
2227  // else:
2228  //  if isSRA:
2229  //   lo = (sra hi, shamt[4:0])
2230  //   hi = (sra hi, 31)
2231  //  else:
2232  //   lo = (srl hi, shamt[4:0])
2233  //   hi = 0
2234  SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2235                            DAG.getConstant(-1, MVT::i32));
2236  SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2237                                     DAG.getConstant(1, MVT::i32));
2238  SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2239  SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2240  SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2241  SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2242                                     Hi, Shamt);
2243  SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2244                             DAG.getConstant(0x20, MVT::i32));
2245  SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2246                                DAG.getConstant(31, MVT::i32));
2247  Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2248  Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2249                   IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2250                   ShiftRightHi);
2251
2252  SDValue Ops[2] = {Lo, Hi};
2253  return DAG.getMergeValues(Ops, 2, DL);
2254}
2255
2256static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2257                            SDValue Chain, SDValue Src, unsigned Offset) {
2258  SDValue Ptr = LD->getBasePtr();
2259  EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2260  EVT BasePtrVT = Ptr.getValueType();
2261  DebugLoc DL = LD->getDebugLoc();
2262  SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2263
2264  if (Offset)
2265    Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2266                      DAG.getConstant(Offset, BasePtrVT));
2267
2268  SDValue Ops[] = { Chain, Ptr, Src };
2269  return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2270                                 LD->getMemOperand());
2271}
2272
2273// Expand an unaligned 32 or 64-bit integer load node.
2274SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2275  LoadSDNode *LD = cast<LoadSDNode>(Op);
2276  EVT MemVT = LD->getMemoryVT();
2277
2278  // Return if load is aligned or if MemVT is neither i32 nor i64.
2279  if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2280      ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2281    return SDValue();
2282
2283  bool IsLittle = Subtarget->isLittle();
2284  EVT VT = Op.getValueType();
2285  ISD::LoadExtType ExtType = LD->getExtensionType();
2286  SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2287
2288  assert((VT == MVT::i32) || (VT == MVT::i64));
2289
2290  // Expand
2291  //  (set dst, (i64 (load baseptr)))
2292  // to
2293  //  (set tmp, (ldl (add baseptr, 7), undef))
2294  //  (set dst, (ldr baseptr, tmp))
2295  if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2296    SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2297                               IsLittle ? 7 : 0);
2298    return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2299                        IsLittle ? 0 : 7);
2300  }
2301
2302  SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2303                             IsLittle ? 3 : 0);
2304  SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2305                             IsLittle ? 0 : 3);
2306
2307  // Expand
2308  //  (set dst, (i32 (load baseptr))) or
2309  //  (set dst, (i64 (sextload baseptr))) or
2310  //  (set dst, (i64 (extload baseptr)))
2311  // to
2312  //  (set tmp, (lwl (add baseptr, 3), undef))
2313  //  (set dst, (lwr baseptr, tmp))
2314  if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2315      (ExtType == ISD::EXTLOAD))
2316    return LWR;
2317
2318  assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2319
2320  // Expand
2321  //  (set dst, (i64 (zextload baseptr)))
2322  // to
2323  //  (set tmp0, (lwl (add baseptr, 3), undef))
2324  //  (set tmp1, (lwr baseptr, tmp0))
2325  //  (set tmp2, (shl tmp1, 32))
2326  //  (set dst, (srl tmp2, 32))
2327  DebugLoc DL = LD->getDebugLoc();
2328  SDValue Const32 = DAG.getConstant(32, MVT::i32);
2329  SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2330  SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2331  SDValue Ops[] = { SRL, LWR.getValue(1) };
2332  return DAG.getMergeValues(Ops, 2, DL);
2333}
2334
2335static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2336                             SDValue Chain, unsigned Offset) {
2337  SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2338  EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2339  DebugLoc DL = SD->getDebugLoc();
2340  SDVTList VTList = DAG.getVTList(MVT::Other);
2341
2342  if (Offset)
2343    Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2344                      DAG.getConstant(Offset, BasePtrVT));
2345
2346  SDValue Ops[] = { Chain, Value, Ptr };
2347  return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2348                                 SD->getMemOperand());
2349}
2350
2351// Expand an unaligned 32 or 64-bit integer store node.
2352SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2353  StoreSDNode *SD = cast<StoreSDNode>(Op);
2354  EVT MemVT = SD->getMemoryVT();
2355
2356  // Return if store is aligned or if MemVT is neither i32 nor i64.
2357  if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2358      ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2359    return SDValue();
2360
2361  bool IsLittle = Subtarget->isLittle();
2362  SDValue Value = SD->getValue(), Chain = SD->getChain();
2363  EVT VT = Value.getValueType();
2364
2365  // Expand
2366  //  (store val, baseptr) or
2367  //  (truncstore val, baseptr)
2368  // to
2369  //  (swl val, (add baseptr, 3))
2370  //  (swr val, baseptr)
2371  if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2372    SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2373                                IsLittle ? 3 : 0);
2374    return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2375  }
2376
2377  assert(VT == MVT::i64);
2378
2379  // Expand
2380  //  (store val, baseptr)
2381  // to
2382  //  (sdl val, (add baseptr, 7))
2383  //  (sdr val, baseptr)
2384  SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2385  return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2386}
2387
2388// This function expands mips intrinsic nodes which have 64-bit input operands
2389// or output values.
2390//
2391// out64 = intrinsic-node in64
2392// =>
2393// lo = copy (extract-element (in64, 0))
2394// hi = copy (extract-element (in64, 1))
2395// mips-specific-node
2396// v0 = copy lo
2397// v1 = copy hi
2398// out64 = merge-values (v0, v1)
2399//
2400static SDValue LowerDSPIntr(SDValue Op, SelectionDAG &DAG,
2401                            unsigned Opc, bool HasI64In, bool HasI64Out) {
2402  DebugLoc DL = Op.getDebugLoc();
2403  bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
2404  SDValue Chain = HasChainIn ? Op->getOperand(0) : DAG.getEntryNode();
2405  SmallVector<SDValue, 3> Ops;
2406
2407  if (HasI64In) {
2408    SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2409                               Op->getOperand(1 + HasChainIn),
2410                               DAG.getConstant(0, MVT::i32));
2411    SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2412                               Op->getOperand(1 + HasChainIn),
2413                               DAG.getConstant(1, MVT::i32));
2414
2415    Chain = DAG.getCopyToReg(Chain, DL, Mips::LO, InLo, SDValue());
2416    Chain = DAG.getCopyToReg(Chain, DL, Mips::HI, InHi, Chain.getValue(1));
2417
2418    Ops.push_back(Chain);
2419    Ops.append(Op->op_begin() + HasChainIn + 2, Op->op_end());
2420    Ops.push_back(Chain.getValue(1));
2421  } else {
2422    Ops.push_back(Chain);
2423    Ops.append(Op->op_begin() + HasChainIn + 1, Op->op_end());
2424  }
2425
2426  if (!HasI64Out)
2427    return DAG.getNode(Opc, DL, Op->value_begin(), Op->getNumValues(),
2428                       Ops.begin(), Ops.size());
2429
2430  SDValue Intr = DAG.getNode(Opc, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2431                             Ops.begin(), Ops.size());
2432  SDValue OutLo = DAG.getCopyFromReg(Intr.getValue(0), DL, Mips::LO, MVT::i32,
2433                                     Intr.getValue(1));
2434  SDValue OutHi = DAG.getCopyFromReg(OutLo.getValue(1), DL, Mips::HI, MVT::i32,
2435                                     OutLo.getValue(2));
2436  SDValue Out = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, OutLo, OutHi);
2437
2438  if (!HasChainIn)
2439    return Out;
2440
2441  SDValue Vals[] = { Out, OutHi.getValue(1) };
2442  return DAG.getMergeValues(Vals, 2, DL);
2443}
2444
2445SDValue MipsTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2446                                                    SelectionDAG &DAG) const {
2447  switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
2448  default:
2449    return SDValue();
2450  case Intrinsic::mips_shilo:
2451    return LowerDSPIntr(Op, DAG, MipsISD::SHILO, true, true);
2452  case Intrinsic::mips_dpau_h_qbl:
2453    return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL, true, true);
2454  case Intrinsic::mips_dpau_h_qbr:
2455    return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR, true, true);
2456  case Intrinsic::mips_dpsu_h_qbl:
2457    return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL, true, true);
2458  case Intrinsic::mips_dpsu_h_qbr:
2459    return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR, true, true);
2460  case Intrinsic::mips_dpa_w_ph:
2461    return LowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH, true, true);
2462  case Intrinsic::mips_dps_w_ph:
2463    return LowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH, true, true);
2464  case Intrinsic::mips_dpax_w_ph:
2465    return LowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH, true, true);
2466  case Intrinsic::mips_dpsx_w_ph:
2467    return LowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH, true, true);
2468  case Intrinsic::mips_mulsa_w_ph:
2469    return LowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH, true, true);
2470  case Intrinsic::mips_mult:
2471    return LowerDSPIntr(Op, DAG, MipsISD::MULT, false, true);
2472  case Intrinsic::mips_multu:
2473    return LowerDSPIntr(Op, DAG, MipsISD::MULTU, false, true);
2474  case Intrinsic::mips_madd:
2475    return LowerDSPIntr(Op, DAG, MipsISD::MADD_DSP, true, true);
2476  case Intrinsic::mips_maddu:
2477    return LowerDSPIntr(Op, DAG, MipsISD::MADDU_DSP, true, true);
2478  case Intrinsic::mips_msub:
2479    return LowerDSPIntr(Op, DAG, MipsISD::MSUB_DSP, true, true);
2480  case Intrinsic::mips_msubu:
2481    return LowerDSPIntr(Op, DAG, MipsISD::MSUBU_DSP, true, true);
2482  }
2483}
2484
2485SDValue MipsTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2486                                                   SelectionDAG &DAG) const {
2487  switch (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue()) {
2488  default:
2489    return SDValue();
2490  case Intrinsic::mips_extp:
2491    return LowerDSPIntr(Op, DAG, MipsISD::EXTP, true, false);
2492  case Intrinsic::mips_extpdp:
2493    return LowerDSPIntr(Op, DAG, MipsISD::EXTPDP, true, false);
2494  case Intrinsic::mips_extr_w:
2495    return LowerDSPIntr(Op, DAG, MipsISD::EXTR_W, true, false);
2496  case Intrinsic::mips_extr_r_w:
2497    return LowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W, true, false);
2498  case Intrinsic::mips_extr_rs_w:
2499    return LowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W, true, false);
2500  case Intrinsic::mips_extr_s_h:
2501    return LowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H, true, false);
2502  case Intrinsic::mips_mthlip:
2503    return LowerDSPIntr(Op, DAG, MipsISD::MTHLIP, true, true);
2504  case Intrinsic::mips_mulsaq_s_w_ph:
2505    return LowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH, true, true);
2506  case Intrinsic::mips_maq_s_w_phl:
2507    return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL, true, true);
2508  case Intrinsic::mips_maq_s_w_phr:
2509    return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR, true, true);
2510  case Intrinsic::mips_maq_sa_w_phl:
2511    return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL, true, true);
2512  case Intrinsic::mips_maq_sa_w_phr:
2513    return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR, true, true);
2514  case Intrinsic::mips_dpaq_s_w_ph:
2515    return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH, true, true);
2516  case Intrinsic::mips_dpsq_s_w_ph:
2517    return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH, true, true);
2518  case Intrinsic::mips_dpaq_sa_l_w:
2519    return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W, true, true);
2520  case Intrinsic::mips_dpsq_sa_l_w:
2521    return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W, true, true);
2522  case Intrinsic::mips_dpaqx_s_w_ph:
2523    return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH, true, true);
2524  case Intrinsic::mips_dpaqx_sa_w_ph:
2525    return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH, true, true);
2526  case Intrinsic::mips_dpsqx_s_w_ph:
2527    return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH, true, true);
2528  case Intrinsic::mips_dpsqx_sa_w_ph:
2529    return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH, true, true);
2530  }
2531}
2532
2533SDValue MipsTargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
2534  if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2535      || cast<ConstantSDNode>
2536        (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2537      || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2538    return SDValue();
2539
2540  // The pattern
2541  //   (add (frameaddr 0), (frame_to_args_offset))
2542  // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2543  //   (add FrameObject, 0)
2544  // where FrameObject is a fixed StackObject with offset 0 which points to
2545  // the old stack pointer.
2546  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2547  EVT ValTy = Op->getValueType(0);
2548  int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2549  SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2550  return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2551                     DAG.getConstant(0, ValTy));
2552}
2553
2554//===----------------------------------------------------------------------===//
2555//                      Calling Convention Implementation
2556//===----------------------------------------------------------------------===//
2557
2558//===----------------------------------------------------------------------===//
2559// TODO: Implement a generic logic using tblgen that can support this.
2560// Mips O32 ABI rules:
2561// ---
2562// i32 - Passed in A0, A1, A2, A3 and stack
2563// f32 - Only passed in f32 registers if no int reg has been used yet to hold
2564//       an argument. Otherwise, passed in A1, A2, A3 and stack.
2565// f64 - Only passed in two aliased f32 registers if no int reg has been used
2566//       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2567//       not used, it must be shadowed. If only A3 is avaiable, shadow it and
2568//       go to stack.
2569//
2570//  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2571//===----------------------------------------------------------------------===//
2572
2573static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2574                       MVT LocVT, CCValAssign::LocInfo LocInfo,
2575                       ISD::ArgFlagsTy ArgFlags, CCState &State) {
2576
2577  static const unsigned IntRegsSize=4, FloatRegsSize=2;
2578
2579  static const uint16_t IntRegs[] = {
2580      Mips::A0, Mips::A1, Mips::A2, Mips::A3
2581  };
2582  static const uint16_t F32Regs[] = {
2583      Mips::F12, Mips::F14
2584  };
2585  static const uint16_t F64Regs[] = {
2586      Mips::D6, Mips::D7
2587  };
2588
2589  // Do not process byval args here.
2590  if (ArgFlags.isByVal())
2591    return true;
2592
2593  // Promote i8 and i16
2594  if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2595    LocVT = MVT::i32;
2596    if (ArgFlags.isSExt())
2597      LocInfo = CCValAssign::SExt;
2598    else if (ArgFlags.isZExt())
2599      LocInfo = CCValAssign::ZExt;
2600    else
2601      LocInfo = CCValAssign::AExt;
2602  }
2603
2604  unsigned Reg;
2605
2606  // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2607  // is true: function is vararg, argument is 3rd or higher, there is previous
2608  // argument which is not f32 or f64.
2609  bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2610      || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2611  unsigned OrigAlign = ArgFlags.getOrigAlign();
2612  bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2613
2614  if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2615    Reg = State.AllocateReg(IntRegs, IntRegsSize);
2616    // If this is the first part of an i64 arg,
2617    // the allocated register must be either A0 or A2.
2618    if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2619      Reg = State.AllocateReg(IntRegs, IntRegsSize);
2620    LocVT = MVT::i32;
2621  } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2622    // Allocate int register and shadow next int register. If first
2623    // available register is Mips::A1 or Mips::A3, shadow it too.
2624    Reg = State.AllocateReg(IntRegs, IntRegsSize);
2625    if (Reg == Mips::A1 || Reg == Mips::A3)
2626      Reg = State.AllocateReg(IntRegs, IntRegsSize);
2627    State.AllocateReg(IntRegs, IntRegsSize);
2628    LocVT = MVT::i32;
2629  } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2630    // we are guaranteed to find an available float register
2631    if (ValVT == MVT::f32) {
2632      Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2633      // Shadow int register
2634      State.AllocateReg(IntRegs, IntRegsSize);
2635    } else {
2636      Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2637      // Shadow int registers
2638      unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2639      if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2640        State.AllocateReg(IntRegs, IntRegsSize);
2641      State.AllocateReg(IntRegs, IntRegsSize);
2642    }
2643  } else
2644    llvm_unreachable("Cannot handle this ValVT.");
2645
2646  if (!Reg) {
2647    unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2648                                          OrigAlign);
2649    State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2650  } else
2651    State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2652
2653  return false;
2654}
2655
2656#include "MipsGenCallingConv.inc"
2657
2658//===----------------------------------------------------------------------===//
2659//                  Call Calling Convention Implementation
2660//===----------------------------------------------------------------------===//
2661
2662static const unsigned O32IntRegsSize = 4;
2663
2664// Return next O32 integer argument register.
2665static unsigned getNextIntArgReg(unsigned Reg) {
2666  assert((Reg == Mips::A0) || (Reg == Mips::A2));
2667  return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2668}
2669
2670/// IsEligibleForTailCallOptimization - Check whether the call is eligible
2671/// for tail call optimization.
2672bool MipsTargetLowering::
2673IsEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
2674                                  unsigned NextStackOffset,
2675                                  const MipsFunctionInfo& FI) const {
2676  if (!EnableMipsTailCalls)
2677    return false;
2678
2679  // No tail call optimization for mips16.
2680  if (Subtarget->inMips16Mode())
2681    return false;
2682
2683  // Return false if either the callee or caller has a byval argument.
2684  if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
2685    return false;
2686
2687  // Return true if the callee's argument area is no larger than the
2688  // caller's.
2689  return NextStackOffset <= FI.getIncomingArgSize();
2690}
2691
2692SDValue
2693MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2694                                   SDValue Chain, SDValue Arg, DebugLoc DL,
2695                                   bool IsTailCall, SelectionDAG &DAG) const {
2696  if (!IsTailCall) {
2697    SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2698                                 DAG.getIntPtrConstant(Offset));
2699    return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2700                        false, 0);
2701  }
2702
2703  MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2704  int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2705  SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2706  return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2707                      /*isVolatile=*/ true, false, 0);
2708}
2709
2710/// LowerCall - functions arguments are copied from virtual regs to
2711/// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2712SDValue
2713MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2714                              SmallVectorImpl<SDValue> &InVals) const {
2715  SelectionDAG &DAG                     = CLI.DAG;
2716  DebugLoc &dl                          = CLI.DL;
2717  SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2718  SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
2719  SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
2720  SDValue Chain                         = CLI.Chain;
2721  SDValue Callee                        = CLI.Callee;
2722  bool &isTailCall                      = CLI.IsTailCall;
2723  CallingConv::ID CallConv              = CLI.CallConv;
2724  bool isVarArg                         = CLI.IsVarArg;
2725
2726  MachineFunction &MF = DAG.getMachineFunction();
2727  MachineFrameInfo *MFI = MF.getFrameInfo();
2728  const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2729  bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2730
2731  // Analyze operands of the call, assigning locations to each operand.
2732  SmallVector<CCValAssign, 16> ArgLocs;
2733  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2734                 getTargetMachine(), ArgLocs, *DAG.getContext());
2735  MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
2736
2737  MipsCCInfo.analyzeCallOperands(Outs);
2738
2739  // Get a count of how many bytes are to be pushed on the stack.
2740  unsigned NextStackOffset = CCInfo.getNextStackOffset();
2741
2742  // Check if it's really possible to do a tail call.
2743  if (isTailCall)
2744    isTailCall =
2745      IsEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2746                                        *MF.getInfo<MipsFunctionInfo>());
2747
2748  if (isTailCall)
2749    ++NumTailCalls;
2750
2751  // Chain is the output chain of the last Load/Store or CopyToReg node.
2752  // ByValChain is the output chain of the last Memcpy node created for copying
2753  // byval arguments to the stack.
2754  unsigned StackAlignment = TFL->getStackAlignment();
2755  NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2756  SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2757
2758  if (!isTailCall)
2759    Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
2760
2761  SDValue StackPtr = DAG.getCopyFromReg(Chain, dl,
2762                                        IsN64 ? Mips::SP_64 : Mips::SP,
2763                                        getPointerTy());
2764
2765  // With EABI is it possible to have 16 args on registers.
2766  SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2767  SmallVector<SDValue, 8> MemOpChains;
2768  MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2769
2770  // Walk the register/memloc assignments, inserting copies/loads.
2771  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2772    SDValue Arg = OutVals[i];
2773    CCValAssign &VA = ArgLocs[i];
2774    MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2775    ISD::ArgFlagsTy Flags = Outs[i].Flags;
2776
2777    // ByVal Arg.
2778    if (Flags.isByVal()) {
2779      assert(Flags.getByValSize() &&
2780             "ByVal args of size 0 should have been ignored by front-end.");
2781      assert(ByValArg != MipsCCInfo.byval_end());
2782      assert(!isTailCall &&
2783             "Do not tail-call optimize if there is a byval argument.");
2784      passByValArg(Chain, dl, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2785                   MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2786      ++ByValArg;
2787      continue;
2788    }
2789
2790    // Promote the value if needed.
2791    switch (VA.getLocInfo()) {
2792    default: llvm_unreachable("Unknown loc info!");
2793    case CCValAssign::Full:
2794      if (VA.isRegLoc()) {
2795        if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2796            (ValVT == MVT::f64 && LocVT == MVT::i64))
2797          Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2798        else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2799          SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2800                                   Arg, DAG.getConstant(0, MVT::i32));
2801          SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2802                                   Arg, DAG.getConstant(1, MVT::i32));
2803          if (!Subtarget->isLittle())
2804            std::swap(Lo, Hi);
2805          unsigned LocRegLo = VA.getLocReg();
2806          unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2807          RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2808          RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2809          continue;
2810        }
2811      }
2812      break;
2813    case CCValAssign::SExt:
2814      Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2815      break;
2816    case CCValAssign::ZExt:
2817      Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2818      break;
2819    case CCValAssign::AExt:
2820      Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2821      break;
2822    }
2823
2824    // Arguments that can be passed on register must be kept at
2825    // RegsToPass vector
2826    if (VA.isRegLoc()) {
2827      RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2828      continue;
2829    }
2830
2831    // Register can't get to this point...
2832    assert(VA.isMemLoc());
2833
2834    // emit ISD::STORE whichs stores the
2835    // parameter value to a stack Location
2836    MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2837                                         Chain, Arg, dl, isTailCall, DAG));
2838  }
2839
2840  // Transform all store nodes into one single node because all store
2841  // nodes are independent of each other.
2842  if (!MemOpChains.empty())
2843    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2844                        &MemOpChains[0], MemOpChains.size());
2845
2846  // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2847  // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2848  // node so that legalize doesn't hack it.
2849  bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2850  bool GlobalOrExternal = false;
2851  SDValue CalleeLo;
2852
2853  if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2854    if (IsPICCall) {
2855      if (G->getGlobal()->hasInternalLinkage())
2856        Callee = getAddrLocal(Callee, DAG, HasMips64);
2857      else if (LargeGOT)
2858        Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2859                                       MipsII::MO_CALL_LO16);
2860      else
2861        Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2862    } else
2863      Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2864                                          MipsII::MO_NO_FLAG);
2865    GlobalOrExternal = true;
2866  }
2867  else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2868    if (!IsN64 && !IsPIC) // !N64 && static
2869      Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2870                                            MipsII::MO_NO_FLAG);
2871    else if (LargeGOT)
2872      Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2873                                     MipsII::MO_CALL_LO16);
2874    else if (HasMips64)
2875      Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_DISP);
2876    else // O32 & PIC
2877      Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2878
2879    GlobalOrExternal = true;
2880  }
2881
2882  SDValue InFlag;
2883
2884  // T9 register operand.
2885  SDValue T9;
2886
2887  // T9 should contain the address of the callee function if
2888  // -reloction-model=pic or it is an indirect call.
2889  if (IsPICCall || !GlobalOrExternal) {
2890    // copy to T9
2891    unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2892    Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2893    InFlag = Chain.getValue(1);
2894
2895    if (Subtarget->inMips16Mode())
2896      T9 = DAG.getRegister(T9Reg, getPointerTy());
2897    else
2898      Callee = DAG.getRegister(T9Reg, getPointerTy());
2899  }
2900
2901  // Insert node "GP copy globalreg" before call to function.
2902  // Lazy-binding stubs require GP to point to the GOT.
2903  if (IsPICCall) {
2904    unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2905    EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2906    RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
2907  }
2908
2909  // Build a sequence of copy-to-reg nodes chained together with token
2910  // chain and flag operands which copy the outgoing args into registers.
2911  // The InFlag in necessary since all emitted instructions must be
2912  // stuck together.
2913  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2914    Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2915                             RegsToPass[i].second, InFlag);
2916    InFlag = Chain.getValue(1);
2917  }
2918
2919  // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2920  //             = Chain, Callee, Reg#1, Reg#2, ...
2921  //
2922  // Returns a chain & a flag for retval copy to use.
2923  SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2924  SmallVector<SDValue, 8> Ops;
2925  Ops.push_back(Chain);
2926  Ops.push_back(Callee);
2927
2928  // Add argument registers to the end of the list so that they are
2929  // known live into the call.
2930  for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2931    Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2932                                  RegsToPass[i].second.getValueType()));
2933
2934  // Add T9 register operand.
2935  if (T9.getNode())
2936    Ops.push_back(T9);
2937
2938  // Add a register mask operand representing the call-preserved registers.
2939  const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2940  const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2941  assert(Mask && "Missing call preserved mask for calling convention");
2942  Ops.push_back(DAG.getRegisterMask(Mask));
2943
2944  if (InFlag.getNode())
2945    Ops.push_back(InFlag);
2946
2947  if (isTailCall)
2948    return DAG.getNode(MipsISD::TailCall, dl, MVT::Other, &Ops[0], Ops.size());
2949
2950  Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2951  InFlag = Chain.getValue(1);
2952
2953  // Create the CALLSEQ_END node.
2954  Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2955                             DAG.getIntPtrConstant(0, true), InFlag);
2956  InFlag = Chain.getValue(1);
2957
2958  // Handle result values, copying them out of physregs into vregs that we
2959  // return.
2960  return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2961                         Ins, dl, DAG, InVals);
2962}
2963
2964/// LowerCallResult - Lower the result values of a call into the
2965/// appropriate copies out of appropriate physical registers.
2966SDValue
2967MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2968                                    CallingConv::ID CallConv, bool isVarArg,
2969                                    const SmallVectorImpl<ISD::InputArg> &Ins,
2970                                    DebugLoc dl, SelectionDAG &DAG,
2971                                    SmallVectorImpl<SDValue> &InVals) const {
2972  // Assign locations to each value returned by this call.
2973  SmallVector<CCValAssign, 16> RVLocs;
2974  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2975                 getTargetMachine(), RVLocs, *DAG.getContext());
2976
2977  CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2978
2979  // Copy all of the result registers out of their specified physreg.
2980  for (unsigned i = 0; i != RVLocs.size(); ++i) {
2981    Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2982                               RVLocs[i].getValVT(), InFlag).getValue(1);
2983    InFlag = Chain.getValue(2);
2984    InVals.push_back(Chain.getValue(0));
2985  }
2986
2987  return Chain;
2988}
2989
2990//===----------------------------------------------------------------------===//
2991//             Formal Arguments Calling Convention Implementation
2992//===----------------------------------------------------------------------===//
2993/// LowerFormalArguments - transform physical registers into virtual registers
2994/// and generate load operations for arguments places on the stack.
2995SDValue
2996MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2997                                         CallingConv::ID CallConv,
2998                                         bool isVarArg,
2999                                      const SmallVectorImpl<ISD::InputArg> &Ins,
3000                                         DebugLoc dl, SelectionDAG &DAG,
3001                                         SmallVectorImpl<SDValue> &InVals)
3002                                          const {
3003  MachineFunction &MF = DAG.getMachineFunction();
3004  MachineFrameInfo *MFI = MF.getFrameInfo();
3005  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3006
3007  MipsFI->setVarArgsFrameIndex(0);
3008
3009  // Used with vargs to acumulate store chains.
3010  std::vector<SDValue> OutChains;
3011
3012  // Assign locations to all of the incoming arguments.
3013  SmallVector<CCValAssign, 16> ArgLocs;
3014  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3015                 getTargetMachine(), ArgLocs, *DAG.getContext());
3016  MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
3017
3018  MipsCCInfo.analyzeFormalArguments(Ins);
3019  MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3020                           MipsCCInfo.hasByValArg());
3021
3022  Function::const_arg_iterator FuncArg =
3023    DAG.getMachineFunction().getFunction()->arg_begin();
3024  unsigned CurArgIdx = 0;
3025  MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3026
3027  for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3028    CCValAssign &VA = ArgLocs[i];
3029    std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
3030    CurArgIdx = Ins[i].OrigArgIndex;
3031    EVT ValVT = VA.getValVT();
3032    ISD::ArgFlagsTy Flags = Ins[i].Flags;
3033    bool IsRegLoc = VA.isRegLoc();
3034
3035    if (Flags.isByVal()) {
3036      assert(Flags.getByValSize() &&
3037             "ByVal args of size 0 should have been ignored by front-end.");
3038      assert(ByValArg != MipsCCInfo.byval_end());
3039      copyByValRegs(Chain, dl, OutChains, DAG, Flags, InVals, &*FuncArg,
3040                    MipsCCInfo, *ByValArg);
3041      ++ByValArg;
3042      continue;
3043    }
3044
3045    // Arguments stored on registers
3046    if (IsRegLoc) {
3047      EVT RegVT = VA.getLocVT();
3048      unsigned ArgReg = VA.getLocReg();
3049      const TargetRegisterClass *RC;
3050
3051      if (RegVT == MVT::i32)
3052        RC = &Mips::CPURegsRegClass;
3053      else if (RegVT == MVT::i64)
3054        RC = &Mips::CPU64RegsRegClass;
3055      else if (RegVT == MVT::f32)
3056        RC = &Mips::FGR32RegClass;
3057      else if (RegVT == MVT::f64)
3058        RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3059      else
3060        llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3061
3062      // Transform the arguments stored on
3063      // physical registers into virtual ones
3064      unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3065      SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3066
3067      // If this is an 8 or 16-bit value, it has been passed promoted
3068      // to 32 bits.  Insert an assert[sz]ext to capture this, then
3069      // truncate to the right size.
3070      if (VA.getLocInfo() != CCValAssign::Full) {
3071        unsigned Opcode = 0;
3072        if (VA.getLocInfo() == CCValAssign::SExt)
3073          Opcode = ISD::AssertSext;
3074        else if (VA.getLocInfo() == CCValAssign::ZExt)
3075          Opcode = ISD::AssertZext;
3076        if (Opcode)
3077          ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3078                                 DAG.getValueType(ValVT));
3079        ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3080      }
3081
3082      // Handle floating point arguments passed in integer registers.
3083      if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3084          (RegVT == MVT::i64 && ValVT == MVT::f64))
3085        ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3086      else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3087        unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3088                                  getNextIntArgReg(ArgReg), RC);
3089        SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3090        if (!Subtarget->isLittle())
3091          std::swap(ArgValue, ArgValue2);
3092        ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3093                               ArgValue, ArgValue2);
3094      }
3095
3096      InVals.push_back(ArgValue);
3097    } else { // VA.isRegLoc()
3098
3099      // sanity check
3100      assert(VA.isMemLoc());
3101
3102      // The stack pointer offset is relative to the caller stack frame.
3103      int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3104                                      VA.getLocMemOffset(), true);
3105
3106      // Create load nodes to retrieve arguments from the stack
3107      SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3108      InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3109                                   MachinePointerInfo::getFixedStack(FI),
3110                                   false, false, false, 0));
3111    }
3112  }
3113
3114  // The mips ABIs for returning structs by value requires that we copy
3115  // the sret argument into $v0 for the return. Save the argument into
3116  // a virtual register so that we can access it from the return points.
3117  if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3118    unsigned Reg = MipsFI->getSRetReturnReg();
3119    if (!Reg) {
3120      Reg = MF.getRegInfo().
3121        createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
3122      MipsFI->setSRetReturnReg(Reg);
3123    }
3124    SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3125    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3126  }
3127
3128  if (isVarArg)
3129    writeVarArgRegs(OutChains, MipsCCInfo, Chain, dl, DAG);
3130
3131  // All stores are grouped in one node to allow the matching between
3132  // the size of Ins and InVals. This only happens when on varg functions
3133  if (!OutChains.empty()) {
3134    OutChains.push_back(Chain);
3135    Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3136                        &OutChains[0], OutChains.size());
3137  }
3138
3139  return Chain;
3140}
3141
3142//===----------------------------------------------------------------------===//
3143//               Return Value Calling Convention Implementation
3144//===----------------------------------------------------------------------===//
3145
3146bool
3147MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3148                                   MachineFunction &MF, bool isVarArg,
3149                                   const SmallVectorImpl<ISD::OutputArg> &Outs,
3150                                   LLVMContext &Context) const {
3151  SmallVector<CCValAssign, 16> RVLocs;
3152  CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
3153                 RVLocs, Context);
3154  return CCInfo.CheckReturn(Outs, RetCC_Mips);
3155}
3156
3157SDValue
3158MipsTargetLowering::LowerReturn(SDValue Chain,
3159                                CallingConv::ID CallConv, bool isVarArg,
3160                                const SmallVectorImpl<ISD::OutputArg> &Outs,
3161                                const SmallVectorImpl<SDValue> &OutVals,
3162                                DebugLoc dl, SelectionDAG &DAG) const {
3163
3164  // CCValAssign - represent the assignment of
3165  // the return value to a location
3166  SmallVector<CCValAssign, 16> RVLocs;
3167
3168  // CCState - Info about the registers and stack slot.
3169  CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3170                 getTargetMachine(), RVLocs, *DAG.getContext());
3171
3172  // Analize return values.
3173  CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3174
3175  // If this is the first return lowered for this function, add
3176  // the regs to the liveout set for the function.
3177  if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3178    for (unsigned i = 0; i != RVLocs.size(); ++i)
3179      if (RVLocs[i].isRegLoc())
3180        DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3181  }
3182
3183  SDValue Flag;
3184
3185  // Copy the result values into the output registers.
3186  for (unsigned i = 0; i != RVLocs.size(); ++i) {
3187    CCValAssign &VA = RVLocs[i];
3188    assert(VA.isRegLoc() && "Can only return in registers!");
3189
3190    Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3191
3192    // guarantee that all emitted copies are
3193    // stuck together, avoiding something bad
3194    Flag = Chain.getValue(1);
3195  }
3196
3197  // The mips ABIs for returning structs by value requires that we copy
3198  // the sret argument into $v0 for the return. We saved the argument into
3199  // a virtual register in the entry block, so now we copy the value out
3200  // and into $v0.
3201  if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3202    MachineFunction &MF      = DAG.getMachineFunction();
3203    MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3204    unsigned Reg = MipsFI->getSRetReturnReg();
3205
3206    if (!Reg)
3207      llvm_unreachable("sret virtual register not created in the entry block");
3208    SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3209    unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
3210
3211    Chain = DAG.getCopyToReg(Chain, dl, V0, Val, Flag);
3212    Flag = Chain.getValue(1);
3213    MF.getRegInfo().addLiveOut(V0);
3214  }
3215
3216  // Return on Mips is always a "jr $ra"
3217  if (Flag.getNode())
3218    return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain, Flag);
3219
3220  // Return Void
3221  return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain);
3222}
3223
3224//===----------------------------------------------------------------------===//
3225//                           Mips Inline Assembly Support
3226//===----------------------------------------------------------------------===//
3227
3228/// getConstraintType - Given a constraint letter, return the type of
3229/// constraint it is for this target.
3230MipsTargetLowering::ConstraintType MipsTargetLowering::
3231getConstraintType(const std::string &Constraint) const
3232{
3233  // Mips specific constrainy
3234  // GCC config/mips/constraints.md
3235  //
3236  // 'd' : An address register. Equivalent to r
3237  //       unless generating MIPS16 code.
3238  // 'y' : Equivalent to r; retained for
3239  //       backwards compatibility.
3240  // 'c' : A register suitable for use in an indirect
3241  //       jump. This will always be $25 for -mabicalls.
3242  // 'l' : The lo register. 1 word storage.
3243  // 'x' : The hilo register pair. Double word storage.
3244  if (Constraint.size() == 1) {
3245    switch (Constraint[0]) {
3246      default : break;
3247      case 'd':
3248      case 'y':
3249      case 'f':
3250      case 'c':
3251      case 'l':
3252      case 'x':
3253        return C_RegisterClass;
3254    }
3255  }
3256  return TargetLowering::getConstraintType(Constraint);
3257}
3258
3259/// Examine constraint type and operand type and determine a weight value.
3260/// This object must already have been set up with the operand type
3261/// and the current alternative constraint selected.
3262TargetLowering::ConstraintWeight
3263MipsTargetLowering::getSingleConstraintMatchWeight(
3264    AsmOperandInfo &info, const char *constraint) const {
3265  ConstraintWeight weight = CW_Invalid;
3266  Value *CallOperandVal = info.CallOperandVal;
3267    // If we don't have a value, we can't do a match,
3268    // but allow it at the lowest weight.
3269  if (CallOperandVal == NULL)
3270    return CW_Default;
3271  Type *type = CallOperandVal->getType();
3272  // Look at the constraint type.
3273  switch (*constraint) {
3274  default:
3275    weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3276    break;
3277  case 'd':
3278  case 'y':
3279    if (type->isIntegerTy())
3280      weight = CW_Register;
3281    break;
3282  case 'f':
3283    if (type->isFloatTy())
3284      weight = CW_Register;
3285    break;
3286  case 'c': // $25 for indirect jumps
3287  case 'l': // lo register
3288  case 'x': // hilo register pair
3289      if (type->isIntegerTy())
3290      weight = CW_SpecificReg;
3291      break;
3292  case 'I': // signed 16 bit immediate
3293  case 'J': // integer zero
3294  case 'K': // unsigned 16 bit immediate
3295  case 'L': // signed 32 bit immediate where lower 16 bits are 0
3296  case 'N': // immediate in the range of -65535 to -1 (inclusive)
3297  case 'O': // signed 15 bit immediate (+- 16383)
3298  case 'P': // immediate in the range of 65535 to 1 (inclusive)
3299    if (isa<ConstantInt>(CallOperandVal))
3300      weight = CW_Constant;
3301    break;
3302  }
3303  return weight;
3304}
3305
3306/// Given a register class constraint, like 'r', if this corresponds directly
3307/// to an LLVM register class, return a register of 0 and the register class
3308/// pointer.
3309std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3310getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3311{
3312  if (Constraint.size() == 1) {
3313    switch (Constraint[0]) {
3314    case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3315    case 'y': // Same as 'r'. Exists for compatibility.
3316    case 'r':
3317      if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3318        if (Subtarget->inMips16Mode())
3319          return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3320        return std::make_pair(0U, &Mips::CPURegsRegClass);
3321      }
3322      if (VT == MVT::i64 && !HasMips64)
3323        return std::make_pair(0U, &Mips::CPURegsRegClass);
3324      if (VT == MVT::i64 && HasMips64)
3325        return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3326      // This will generate an error message
3327      return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3328    case 'f':
3329      if (VT == MVT::f32)
3330        return std::make_pair(0U, &Mips::FGR32RegClass);
3331      if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3332        if (Subtarget->isFP64bit())
3333          return std::make_pair(0U, &Mips::FGR64RegClass);
3334        return std::make_pair(0U, &Mips::AFGR64RegClass);
3335      }
3336      break;
3337    case 'c': // register suitable for indirect jump
3338      if (VT == MVT::i32)
3339        return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3340      assert(VT == MVT::i64 && "Unexpected type.");
3341      return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3342    case 'l': // register suitable for indirect jump
3343      if (VT == MVT::i32)
3344        return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3345      return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3346    case 'x': // register suitable for indirect jump
3347      // Fixme: Not triggering the use of both hi and low
3348      // This will generate an error message
3349      return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3350    }
3351  }
3352  return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3353}
3354
3355/// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3356/// vector.  If it is invalid, don't add anything to Ops.
3357void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3358                                                     std::string &Constraint,
3359                                                     std::vector<SDValue>&Ops,
3360                                                     SelectionDAG &DAG) const {
3361  SDValue Result(0, 0);
3362
3363  // Only support length 1 constraints for now.
3364  if (Constraint.length() > 1) return;
3365
3366  char ConstraintLetter = Constraint[0];
3367  switch (ConstraintLetter) {
3368  default: break; // This will fall through to the generic implementation
3369  case 'I': // Signed 16 bit constant
3370    // If this fails, the parent routine will give an error
3371    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3372      EVT Type = Op.getValueType();
3373      int64_t Val = C->getSExtValue();
3374      if (isInt<16>(Val)) {
3375        Result = DAG.getTargetConstant(Val, Type);
3376        break;
3377      }
3378    }
3379    return;
3380  case 'J': // integer zero
3381    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3382      EVT Type = Op.getValueType();
3383      int64_t Val = C->getZExtValue();
3384      if (Val == 0) {
3385        Result = DAG.getTargetConstant(0, Type);
3386        break;
3387      }
3388    }
3389    return;
3390  case 'K': // unsigned 16 bit immediate
3391    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3392      EVT Type = Op.getValueType();
3393      uint64_t Val = (uint64_t)C->getZExtValue();
3394      if (isUInt<16>(Val)) {
3395        Result = DAG.getTargetConstant(Val, Type);
3396        break;
3397      }
3398    }
3399    return;
3400  case 'L': // signed 32 bit immediate where lower 16 bits are 0
3401    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3402      EVT Type = Op.getValueType();
3403      int64_t Val = C->getSExtValue();
3404      if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3405        Result = DAG.getTargetConstant(Val, Type);
3406        break;
3407      }
3408    }
3409    return;
3410  case 'N': // immediate in the range of -65535 to -1 (inclusive)
3411    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3412      EVT Type = Op.getValueType();
3413      int64_t Val = C->getSExtValue();
3414      if ((Val >= -65535) && (Val <= -1)) {
3415        Result = DAG.getTargetConstant(Val, Type);
3416        break;
3417      }
3418    }
3419    return;
3420  case 'O': // signed 15 bit immediate
3421    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3422      EVT Type = Op.getValueType();
3423      int64_t Val = C->getSExtValue();
3424      if ((isInt<15>(Val))) {
3425        Result = DAG.getTargetConstant(Val, Type);
3426        break;
3427      }
3428    }
3429    return;
3430  case 'P': // immediate in the range of 1 to 65535 (inclusive)
3431    if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3432      EVT Type = Op.getValueType();
3433      int64_t Val = C->getSExtValue();
3434      if ((Val <= 65535) && (Val >= 1)) {
3435        Result = DAG.getTargetConstant(Val, Type);
3436        break;
3437      }
3438    }
3439    return;
3440  }
3441
3442  if (Result.getNode()) {
3443    Ops.push_back(Result);
3444    return;
3445  }
3446
3447  TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3448}
3449
3450bool
3451MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3452  // No global is ever allowed as a base.
3453  if (AM.BaseGV)
3454    return false;
3455
3456  switch (AM.Scale) {
3457  case 0: // "r+i" or just "i", depending on HasBaseReg.
3458    break;
3459  case 1:
3460    if (!AM.HasBaseReg) // allow "r+i".
3461      break;
3462    return false; // disallow "r+r" or "r+r+i".
3463  default:
3464    return false;
3465  }
3466
3467  return true;
3468}
3469
3470bool
3471MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3472  // The Mips target isn't yet aware of offsets.
3473  return false;
3474}
3475
3476EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3477                                            unsigned SrcAlign, bool IsZeroVal,
3478                                            bool MemcpyStrSrc,
3479                                            MachineFunction &MF) const {
3480  if (Subtarget->hasMips64())
3481    return MVT::i64;
3482
3483  return MVT::i32;
3484}
3485
3486bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3487  if (VT != MVT::f32 && VT != MVT::f64)
3488    return false;
3489  if (Imm.isNegZero())
3490    return false;
3491  return Imm.isZero();
3492}
3493
3494unsigned MipsTargetLowering::getJumpTableEncoding() const {
3495  if (IsN64)
3496    return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3497
3498  return TargetLowering::getJumpTableEncoding();
3499}
3500
3501MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CallConv, bool IsVarArg,
3502                                   bool IsO32, CCState &Info) : CCInfo(Info) {
3503  UseRegsForByval = true;
3504
3505  if (IsO32) {
3506    RegSize = 4;
3507    NumIntArgRegs = array_lengthof(O32IntRegs);
3508    ReservedArgArea = 16;
3509    IntArgRegs = ShadowRegs = O32IntRegs;
3510    FixedFn = VarFn = CC_MipsO32;
3511  } else {
3512    RegSize = 8;
3513    NumIntArgRegs = array_lengthof(Mips64IntRegs);
3514    ReservedArgArea = 0;
3515    IntArgRegs = Mips64IntRegs;
3516    ShadowRegs = Mips64DPRegs;
3517    FixedFn = CC_MipsN;
3518    VarFn = CC_MipsN_VarArg;
3519  }
3520
3521  if (CallConv == CallingConv::Fast) {
3522    assert(!IsVarArg);
3523    UseRegsForByval = false;
3524    ReservedArgArea = 0;
3525    FixedFn = VarFn = CC_Mips_FastCC;
3526  }
3527
3528  // Pre-allocate reserved argument area.
3529  CCInfo.AllocateStack(ReservedArgArea, 1);
3530}
3531
3532void MipsTargetLowering::MipsCC::
3533analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args) {
3534  unsigned NumOpnds = Args.size();
3535
3536  for (unsigned I = 0; I != NumOpnds; ++I) {
3537    MVT ArgVT = Args[I].VT;
3538    ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3539    bool R;
3540
3541    if (ArgFlags.isByVal()) {
3542      handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3543      continue;
3544    }
3545
3546    if (Args[I].IsFixed)
3547      R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3548    else
3549      R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3550
3551    if (R) {
3552#ifndef NDEBUG
3553      dbgs() << "Call operand #" << I << " has unhandled type "
3554             << EVT(ArgVT).getEVTString();
3555#endif
3556      llvm_unreachable(0);
3557    }
3558  }
3559}
3560
3561void MipsTargetLowering::MipsCC::
3562analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args) {
3563  unsigned NumArgs = Args.size();
3564
3565  for (unsigned I = 0; I != NumArgs; ++I) {
3566    MVT ArgVT = Args[I].VT;
3567    ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3568
3569    if (ArgFlags.isByVal()) {
3570      handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3571      continue;
3572    }
3573
3574    if (!FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo))
3575      continue;
3576
3577#ifndef NDEBUG
3578    dbgs() << "Formal Arg #" << I << " has unhandled type "
3579           << EVT(ArgVT).getEVTString();
3580#endif
3581    llvm_unreachable(0);
3582  }
3583}
3584
3585void
3586MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3587                                           MVT LocVT,
3588                                           CCValAssign::LocInfo LocInfo,
3589                                           ISD::ArgFlagsTy ArgFlags) {
3590  assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3591
3592  struct ByValArgInfo ByVal;
3593  unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3594  unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3595                            RegSize * 2);
3596
3597  if (UseRegsForByval)
3598    allocateRegs(ByVal, ByValSize, Align);
3599
3600  // Allocate space on caller's stack.
3601  ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3602                                       Align);
3603  CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3604                                    LocInfo));
3605  ByValArgs.push_back(ByVal);
3606}
3607
3608void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3609                                              unsigned ByValSize,
3610                                              unsigned Align) {
3611  assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3612         "Byval argument's size and alignment should be a multiple of"
3613         "RegSize.");
3614
3615  ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3616
3617  // If Align > RegSize, the first arg register must be even.
3618  if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3619    CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3620    ++ByVal.FirstIdx;
3621  }
3622
3623  // Mark the registers allocated.
3624  for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3625       ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3626    CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3627}
3628
3629void MipsTargetLowering::
3630copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
3631              SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3632              SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3633              const MipsCC &CC, const ByValArgInfo &ByVal) const {
3634  MachineFunction &MF = DAG.getMachineFunction();
3635  MachineFrameInfo *MFI = MF.getFrameInfo();
3636  unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3637  unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3638  int FrameObjOffset;
3639
3640  if (RegAreaSize)
3641    FrameObjOffset = (int)CC.reservedArgArea() -
3642      (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3643  else
3644    FrameObjOffset = ByVal.Address;
3645
3646  // Create frame object.
3647  EVT PtrTy = getPointerTy();
3648  int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3649  SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3650  InVals.push_back(FIN);
3651
3652  if (!ByVal.NumRegs)
3653    return;
3654
3655  // Copy arg registers.
3656  EVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3657  const TargetRegisterClass *RC = getRegClassFor(RegTy);
3658
3659  for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3660    unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3661    unsigned VReg = AddLiveIn(MF, ArgReg, RC);
3662    unsigned Offset = I * CC.regSize();
3663    SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3664                                   DAG.getConstant(Offset, PtrTy));
3665    SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3666                                 StorePtr, MachinePointerInfo(FuncArg, Offset),
3667                                 false, false, 0);
3668    OutChains.push_back(Store);
3669  }
3670}
3671
3672// Copy byVal arg to registers and stack.
3673void MipsTargetLowering::
3674passByValArg(SDValue Chain, DebugLoc DL,
3675             SmallVector<std::pair<unsigned, SDValue>, 16> &RegsToPass,
3676             SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3677             MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3678             const MipsCC &CC, const ByValArgInfo &ByVal,
3679             const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3680  unsigned ByValSize = Flags.getByValSize();
3681  unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3682  unsigned RegSize = CC.regSize();
3683  unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3684  EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3685
3686  if (ByVal.NumRegs) {
3687    const uint16_t *ArgRegs = CC.intArgRegs();
3688    bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3689    unsigned I = 0;
3690
3691    // Copy words to registers.
3692    for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3693      SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3694                                    DAG.getConstant(Offset, PtrTy));
3695      SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3696                                    MachinePointerInfo(), false, false, false,
3697                                    Alignment);
3698      MemOpChains.push_back(LoadVal.getValue(1));
3699      unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3700      RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3701    }
3702
3703    // Return if the struct has been fully copied.
3704    if (ByValSize == Offset)
3705      return;
3706
3707    // Copy the remainder of the byval argument with sub-word loads and shifts.
3708    if (LeftoverBytes) {
3709      assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3710             "Size of the remainder should be smaller than RegSize.");
3711      SDValue Val;
3712
3713      for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3714           Offset < ByValSize; LoadSize /= 2) {
3715        unsigned RemSize = ByValSize - Offset;
3716
3717        if (RemSize < LoadSize)
3718          continue;
3719
3720        // Load subword.
3721        SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3722                                      DAG.getConstant(Offset, PtrTy));
3723        SDValue LoadVal =
3724          DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3725                         MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3726                         false, false, Alignment);
3727        MemOpChains.push_back(LoadVal.getValue(1));
3728
3729        // Shift the loaded value.
3730        unsigned Shamt;
3731
3732        if (isLittle)
3733          Shamt = TotalSizeLoaded;
3734        else
3735          Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3736
3737        SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3738                                    DAG.getConstant(Shamt, MVT::i32));
3739
3740        if (Val.getNode())
3741          Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3742        else
3743          Val = Shift;
3744
3745        Offset += LoadSize;
3746        TotalSizeLoaded += LoadSize;
3747        Alignment = std::min(Alignment, LoadSize);
3748      }
3749
3750      unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3751      RegsToPass.push_back(std::make_pair(ArgReg, Val));
3752      return;
3753    }
3754  }
3755
3756  // Copy remainder of byval arg to it with memcpy.
3757  unsigned MemCpySize = ByValSize - Offset;
3758  SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3759                            DAG.getConstant(Offset, PtrTy));
3760  SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3761                            DAG.getIntPtrConstant(ByVal.Address));
3762  Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3763                        DAG.getConstant(MemCpySize, PtrTy), Alignment,
3764                        /*isVolatile=*/false, /*AlwaysInline=*/false,
3765                        MachinePointerInfo(0), MachinePointerInfo(0));
3766  MemOpChains.push_back(Chain);
3767}
3768
3769void
3770MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3771                                    const MipsCC &CC, SDValue Chain,
3772                                    DebugLoc DL, SelectionDAG &DAG) const {
3773  unsigned NumRegs = CC.numIntArgRegs();
3774  const uint16_t *ArgRegs = CC.intArgRegs();
3775  const CCState &CCInfo = CC.getCCInfo();
3776  unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3777  unsigned RegSize = CC.regSize();
3778  EVT RegTy = MVT::getIntegerVT(RegSize * 8);
3779  const TargetRegisterClass *RC = getRegClassFor(RegTy);
3780  MachineFunction &MF = DAG.getMachineFunction();
3781  MachineFrameInfo *MFI = MF.getFrameInfo();
3782  MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3783
3784  // Offset of the first variable argument from stack pointer.
3785  int VaArgOffset;
3786
3787  if (NumRegs == Idx)
3788    VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3789  else
3790    VaArgOffset =
3791      (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3792
3793  // Record the frame index of the first variable argument
3794  // which is a value necessary to VASTART.
3795  int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3796  MipsFI->setVarArgsFrameIndex(FI);
3797
3798  // Copy the integer registers that have not been used for argument passing
3799  // to the argument register save area. For O32, the save area is allocated
3800  // in the caller's stack frame, while for N32/64, it is allocated in the
3801  // callee's stack frame.
3802  for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3803    unsigned Reg = AddLiveIn(MF, ArgRegs[I], RC);
3804    SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3805    FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3806    SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3807    SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3808                                 MachinePointerInfo(), false, false, 0);
3809    cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3810    OutChains.push_back(Store);
3811  }
3812}
3813