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