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