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