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