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