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