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