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