]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Target/Mips/MipsISelLowering.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r305575, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / 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 "MipsCCState.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include <cctype>
41
42 using namespace llvm;
43
44 #define DEBUG_TYPE "mips-lower"
45
46 STATISTIC(NumTailCalls, "Number of tail calls");
47
48 static cl::opt<bool>
49 LargeGOT("mxgot", cl::Hidden,
50          cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
51
52 static cl::opt<bool>
53 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
54                cl::desc("MIPS: Don't trap on integer division by zero."),
55                cl::init(false));
56
57 static const MCPhysReg Mips64DPRegs[8] = {
58   Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
59   Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
60 };
61
62 // If I is a shifted mask, set the size (Size) and the first bit of the
63 // mask (Pos), and return true.
64 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
65 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
66   if (!isShiftedMask_64(I))
67     return false;
68
69   Size = countPopulation(I);
70   Pos = countTrailingZeros(I);
71   return true;
72 }
73
74 // The MIPS MSA ABI passes vector arguments in the integer register set.
75 // The number of integer registers used is dependant on the ABI used.
76 MVT MipsTargetLowering::getRegisterTypeForCallingConv(MVT VT) const {
77   if (VT.isVector() && Subtarget.hasMSA())
78     return Subtarget.isABI_O32() ? MVT::i32 : MVT::i64;
79   return MipsTargetLowering::getRegisterType(VT);
80 }
81
82 MVT MipsTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
83                                                       EVT VT) const {
84   if (VT.isVector()) {
85       if (Subtarget.isABI_O32()) {
86         return MVT::i32;
87       } else {
88         return (VT.getSizeInBits() == 32) ? MVT::i32 : MVT::i64;
89       }
90   }
91   return MipsTargetLowering::getRegisterType(Context, VT);
92 }
93
94 unsigned MipsTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
95                                                            EVT VT) const {
96   if (VT.isVector())
97     return std::max((VT.getSizeInBits() / (Subtarget.isABI_O32() ? 32 : 64)),
98                     1U);
99   return MipsTargetLowering::getNumRegisters(Context, VT);
100 }
101
102 unsigned MipsTargetLowering::getVectorTypeBreakdownForCallingConv(
103     LLVMContext &Context, EVT VT, EVT &IntermediateVT,
104     unsigned &NumIntermediates, MVT &RegisterVT) const {
105
106   // Break down vector types to either 2 i64s or 4 i32s.
107   RegisterVT = getRegisterTypeForCallingConv(Context, VT) ;
108   IntermediateVT = RegisterVT;
109   NumIntermediates = VT.getSizeInBits() < RegisterVT.getSizeInBits()
110                          ? VT.getVectorNumElements()
111                          : VT.getSizeInBits() / RegisterVT.getSizeInBits();
112
113   return NumIntermediates;
114 }
115
116 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
117   MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
118   return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
119 }
120
121 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
122                                           SelectionDAG &DAG,
123                                           unsigned Flag) const {
124   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
125 }
126
127 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
128                                           SelectionDAG &DAG,
129                                           unsigned Flag) const {
130   return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
131 }
132
133 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
134                                           SelectionDAG &DAG,
135                                           unsigned Flag) const {
136   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
137 }
138
139 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
140                                           SelectionDAG &DAG,
141                                           unsigned Flag) const {
142   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
143 }
144
145 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
146                                           SelectionDAG &DAG,
147                                           unsigned Flag) const {
148   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
149                                    N->getOffset(), Flag);
150 }
151
152 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
153   switch ((MipsISD::NodeType)Opcode) {
154   case MipsISD::FIRST_NUMBER:      break;
155   case MipsISD::JmpLink:           return "MipsISD::JmpLink";
156   case MipsISD::TailCall:          return "MipsISD::TailCall";
157   case MipsISD::Highest:           return "MipsISD::Highest";
158   case MipsISD::Higher:            return "MipsISD::Higher";
159   case MipsISD::Hi:                return "MipsISD::Hi";
160   case MipsISD::Lo:                return "MipsISD::Lo";
161   case MipsISD::GotHi:             return "MipsISD::GotHi";
162   case MipsISD::GPRel:             return "MipsISD::GPRel";
163   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
164   case MipsISD::Ret:               return "MipsISD::Ret";
165   case MipsISD::ERet:              return "MipsISD::ERet";
166   case MipsISD::EH_RETURN:         return "MipsISD::EH_RETURN";
167   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
168   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
169   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
170   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
171   case MipsISD::TruncIntFP:        return "MipsISD::TruncIntFP";
172   case MipsISD::MFHI:              return "MipsISD::MFHI";
173   case MipsISD::MFLO:              return "MipsISD::MFLO";
174   case MipsISD::MTLOHI:            return "MipsISD::MTLOHI";
175   case MipsISD::Mult:              return "MipsISD::Mult";
176   case MipsISD::Multu:             return "MipsISD::Multu";
177   case MipsISD::MAdd:              return "MipsISD::MAdd";
178   case MipsISD::MAddu:             return "MipsISD::MAddu";
179   case MipsISD::MSub:              return "MipsISD::MSub";
180   case MipsISD::MSubu:             return "MipsISD::MSubu";
181   case MipsISD::DivRem:            return "MipsISD::DivRem";
182   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
183   case MipsISD::DivRem16:          return "MipsISD::DivRem16";
184   case MipsISD::DivRemU16:         return "MipsISD::DivRemU16";
185   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
186   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
187   case MipsISD::Wrapper:           return "MipsISD::Wrapper";
188   case MipsISD::DynAlloc:          return "MipsISD::DynAlloc";
189   case MipsISD::Sync:              return "MipsISD::Sync";
190   case MipsISD::Ext:               return "MipsISD::Ext";
191   case MipsISD::Ins:               return "MipsISD::Ins";
192   case MipsISD::CIns:              return "MipsISD::CIns";
193   case MipsISD::LWL:               return "MipsISD::LWL";
194   case MipsISD::LWR:               return "MipsISD::LWR";
195   case MipsISD::SWL:               return "MipsISD::SWL";
196   case MipsISD::SWR:               return "MipsISD::SWR";
197   case MipsISD::LDL:               return "MipsISD::LDL";
198   case MipsISD::LDR:               return "MipsISD::LDR";
199   case MipsISD::SDL:               return "MipsISD::SDL";
200   case MipsISD::SDR:               return "MipsISD::SDR";
201   case MipsISD::EXTP:              return "MipsISD::EXTP";
202   case MipsISD::EXTPDP:            return "MipsISD::EXTPDP";
203   case MipsISD::EXTR_S_H:          return "MipsISD::EXTR_S_H";
204   case MipsISD::EXTR_W:            return "MipsISD::EXTR_W";
205   case MipsISD::EXTR_R_W:          return "MipsISD::EXTR_R_W";
206   case MipsISD::EXTR_RS_W:         return "MipsISD::EXTR_RS_W";
207   case MipsISD::SHILO:             return "MipsISD::SHILO";
208   case MipsISD::MTHLIP:            return "MipsISD::MTHLIP";
209   case MipsISD::MULSAQ_S_W_PH:     return "MipsISD::MULSAQ_S_W_PH";
210   case MipsISD::MAQ_S_W_PHL:       return "MipsISD::MAQ_S_W_PHL";
211   case MipsISD::MAQ_S_W_PHR:       return "MipsISD::MAQ_S_W_PHR";
212   case MipsISD::MAQ_SA_W_PHL:      return "MipsISD::MAQ_SA_W_PHL";
213   case MipsISD::MAQ_SA_W_PHR:      return "MipsISD::MAQ_SA_W_PHR";
214   case MipsISD::DPAU_H_QBL:        return "MipsISD::DPAU_H_QBL";
215   case MipsISD::DPAU_H_QBR:        return "MipsISD::DPAU_H_QBR";
216   case MipsISD::DPSU_H_QBL:        return "MipsISD::DPSU_H_QBL";
217   case MipsISD::DPSU_H_QBR:        return "MipsISD::DPSU_H_QBR";
218   case MipsISD::DPAQ_S_W_PH:       return "MipsISD::DPAQ_S_W_PH";
219   case MipsISD::DPSQ_S_W_PH:       return "MipsISD::DPSQ_S_W_PH";
220   case MipsISD::DPAQ_SA_L_W:       return "MipsISD::DPAQ_SA_L_W";
221   case MipsISD::DPSQ_SA_L_W:       return "MipsISD::DPSQ_SA_L_W";
222   case MipsISD::DPA_W_PH:          return "MipsISD::DPA_W_PH";
223   case MipsISD::DPS_W_PH:          return "MipsISD::DPS_W_PH";
224   case MipsISD::DPAQX_S_W_PH:      return "MipsISD::DPAQX_S_W_PH";
225   case MipsISD::DPAQX_SA_W_PH:     return "MipsISD::DPAQX_SA_W_PH";
226   case MipsISD::DPAX_W_PH:         return "MipsISD::DPAX_W_PH";
227   case MipsISD::DPSX_W_PH:         return "MipsISD::DPSX_W_PH";
228   case MipsISD::DPSQX_S_W_PH:      return "MipsISD::DPSQX_S_W_PH";
229   case MipsISD::DPSQX_SA_W_PH:     return "MipsISD::DPSQX_SA_W_PH";
230   case MipsISD::MULSA_W_PH:        return "MipsISD::MULSA_W_PH";
231   case MipsISD::MULT:              return "MipsISD::MULT";
232   case MipsISD::MULTU:             return "MipsISD::MULTU";
233   case MipsISD::MADD_DSP:          return "MipsISD::MADD_DSP";
234   case MipsISD::MADDU_DSP:         return "MipsISD::MADDU_DSP";
235   case MipsISD::MSUB_DSP:          return "MipsISD::MSUB_DSP";
236   case MipsISD::MSUBU_DSP:         return "MipsISD::MSUBU_DSP";
237   case MipsISD::SHLL_DSP:          return "MipsISD::SHLL_DSP";
238   case MipsISD::SHRA_DSP:          return "MipsISD::SHRA_DSP";
239   case MipsISD::SHRL_DSP:          return "MipsISD::SHRL_DSP";
240   case MipsISD::SETCC_DSP:         return "MipsISD::SETCC_DSP";
241   case MipsISD::SELECT_CC_DSP:     return "MipsISD::SELECT_CC_DSP";
242   case MipsISD::VALL_ZERO:         return "MipsISD::VALL_ZERO";
243   case MipsISD::VANY_ZERO:         return "MipsISD::VANY_ZERO";
244   case MipsISD::VALL_NONZERO:      return "MipsISD::VALL_NONZERO";
245   case MipsISD::VANY_NONZERO:      return "MipsISD::VANY_NONZERO";
246   case MipsISD::VCEQ:              return "MipsISD::VCEQ";
247   case MipsISD::VCLE_S:            return "MipsISD::VCLE_S";
248   case MipsISD::VCLE_U:            return "MipsISD::VCLE_U";
249   case MipsISD::VCLT_S:            return "MipsISD::VCLT_S";
250   case MipsISD::VCLT_U:            return "MipsISD::VCLT_U";
251   case MipsISD::VSMAX:             return "MipsISD::VSMAX";
252   case MipsISD::VSMIN:             return "MipsISD::VSMIN";
253   case MipsISD::VUMAX:             return "MipsISD::VUMAX";
254   case MipsISD::VUMIN:             return "MipsISD::VUMIN";
255   case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
256   case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
257   case MipsISD::VNOR:              return "MipsISD::VNOR";
258   case MipsISD::VSHF:              return "MipsISD::VSHF";
259   case MipsISD::SHF:               return "MipsISD::SHF";
260   case MipsISD::ILVEV:             return "MipsISD::ILVEV";
261   case MipsISD::ILVOD:             return "MipsISD::ILVOD";
262   case MipsISD::ILVL:              return "MipsISD::ILVL";
263   case MipsISD::ILVR:              return "MipsISD::ILVR";
264   case MipsISD::PCKEV:             return "MipsISD::PCKEV";
265   case MipsISD::PCKOD:             return "MipsISD::PCKOD";
266   case MipsISD::INSVE:             return "MipsISD::INSVE";
267   }
268   return nullptr;
269 }
270
271 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
272                                        const MipsSubtarget &STI)
273     : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
274   // Mips does not have i1 type, so use i32 for
275   // setcc operations results (slt, sgt, ...).
276   setBooleanContents(ZeroOrOneBooleanContent);
277   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
278   // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
279   // does. Integer booleans still use 0 and 1.
280   if (Subtarget.hasMips32r6())
281     setBooleanContents(ZeroOrOneBooleanContent,
282                        ZeroOrNegativeOneBooleanContent);
283
284   // Load extented operations for i1 types must be promoted
285   for (MVT VT : MVT::integer_valuetypes()) {
286     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1,  Promote);
287     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1,  Promote);
288     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1,  Promote);
289   }
290
291   // MIPS doesn't have extending float->double load/store.  Set LoadExtAction
292   // for f32, f16
293   for (MVT VT : MVT::fp_valuetypes()) {
294     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
295     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
296   }
297
298   // Set LoadExtAction for f16 vectors to Expand
299   for (MVT VT : MVT::fp_vector_valuetypes()) {
300     MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
301     if (F16VT.isValid())
302       setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
303   }
304
305   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
306   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
307
308   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
309
310   // Used by legalize types to correctly generate the setcc result.
311   // Without this, every float setcc comes with a AND/OR with the result,
312   // we don't want this, since the fpcmp result goes to a flag register,
313   // which is used implicitly by brcond and select operations.
314   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
315
316   // Mips Custom Operations
317   setOperationAction(ISD::BR_JT,              MVT::Other, Expand);
318   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
319   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
320   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
321   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
322   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
323   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
324   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
325   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
326   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
327   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
328   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
329   setOperationAction(ISD::FCOPYSIGN,          MVT::f32,   Custom);
330   setOperationAction(ISD::FCOPYSIGN,          MVT::f64,   Custom);
331   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
332
333   if (Subtarget.isGP64bit()) {
334     setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
335     setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
336     setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
337     setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
338     setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
339     setOperationAction(ISD::SELECT,             MVT::i64,   Custom);
340     setOperationAction(ISD::LOAD,               MVT::i64,   Custom);
341     setOperationAction(ISD::STORE,              MVT::i64,   Custom);
342     setOperationAction(ISD::FP_TO_SINT,         MVT::i64,   Custom);
343     setOperationAction(ISD::SHL_PARTS,          MVT::i64,   Custom);
344     setOperationAction(ISD::SRA_PARTS,          MVT::i64,   Custom);
345     setOperationAction(ISD::SRL_PARTS,          MVT::i64,   Custom);
346   }
347
348   if (!Subtarget.isGP64bit()) {
349     setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Custom);
350     setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Custom);
351     setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Custom);
352   }
353
354   setOperationAction(ISD::EH_DWARF_CFA,         MVT::i32,   Custom);
355   if (Subtarget.isGP64bit())
356     setOperationAction(ISD::EH_DWARF_CFA,       MVT::i64,   Custom);
357
358   setOperationAction(ISD::SDIV, MVT::i32, Expand);
359   setOperationAction(ISD::SREM, MVT::i32, Expand);
360   setOperationAction(ISD::UDIV, MVT::i32, Expand);
361   setOperationAction(ISD::UREM, MVT::i32, Expand);
362   setOperationAction(ISD::SDIV, MVT::i64, Expand);
363   setOperationAction(ISD::SREM, MVT::i64, Expand);
364   setOperationAction(ISD::UDIV, MVT::i64, Expand);
365   setOperationAction(ISD::UREM, MVT::i64, Expand);
366
367   if (!(Subtarget.hasDSP() && Subtarget.hasMips32r2())) {
368     setOperationAction(ISD::ADDC, MVT::i32, Expand);
369     setOperationAction(ISD::ADDE, MVT::i32, Expand);
370   }
371
372   setOperationAction(ISD::ADDC, MVT::i64, Expand);
373   setOperationAction(ISD::ADDE, MVT::i64, Expand);
374   setOperationAction(ISD::SUBC, MVT::i32, Expand);
375   setOperationAction(ISD::SUBE, MVT::i32, Expand);
376   setOperationAction(ISD::SUBC, MVT::i64, Expand);
377   setOperationAction(ISD::SUBE, MVT::i64, Expand);
378
379   // Operations not directly supported by Mips.
380   setOperationAction(ISD::BR_CC,             MVT::f32,   Expand);
381   setOperationAction(ISD::BR_CC,             MVT::f64,   Expand);
382   setOperationAction(ISD::BR_CC,             MVT::i32,   Expand);
383   setOperationAction(ISD::BR_CC,             MVT::i64,   Expand);
384   setOperationAction(ISD::SELECT_CC,         MVT::i32,   Expand);
385   setOperationAction(ISD::SELECT_CC,         MVT::i64,   Expand);
386   setOperationAction(ISD::SELECT_CC,         MVT::f32,   Expand);
387   setOperationAction(ISD::SELECT_CC,         MVT::f64,   Expand);
388   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
389   setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
390   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
391   setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
392   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
393   if (Subtarget.hasCnMips()) {
394     setOperationAction(ISD::CTPOP,           MVT::i32,   Legal);
395     setOperationAction(ISD::CTPOP,           MVT::i64,   Legal);
396   } else {
397     setOperationAction(ISD::CTPOP,           MVT::i32,   Expand);
398     setOperationAction(ISD::CTPOP,           MVT::i64,   Expand);
399   }
400   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
401   setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
402   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
403   setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
404   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,  Expand);
405   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,  Expand);
406
407   if (!Subtarget.hasMips32r2())
408     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
409
410   if (!Subtarget.hasMips64r2())
411     setOperationAction(ISD::ROTR, MVT::i64,   Expand);
412
413   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
414   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
415   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
416   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
417   setOperationAction(ISD::FSINCOS,           MVT::f32,   Expand);
418   setOperationAction(ISD::FSINCOS,           MVT::f64,   Expand);
419   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
420   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
421   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
422   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
423   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
424   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
425   setOperationAction(ISD::FMA,               MVT::f32,   Expand);
426   setOperationAction(ISD::FMA,               MVT::f64,   Expand);
427   setOperationAction(ISD::FREM,              MVT::f32,   Expand);
428   setOperationAction(ISD::FREM,              MVT::f64,   Expand);
429
430   // Lower f16 conversion operations into library calls
431   setOperationAction(ISD::FP16_TO_FP,        MVT::f32,   Expand);
432   setOperationAction(ISD::FP_TO_FP16,        MVT::f32,   Expand);
433   setOperationAction(ISD::FP16_TO_FP,        MVT::f64,   Expand);
434   setOperationAction(ISD::FP_TO_FP16,        MVT::f64,   Expand);
435
436   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
437
438   setOperationAction(ISD::VASTART,           MVT::Other, Custom);
439   setOperationAction(ISD::VAARG,             MVT::Other, Custom);
440   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
441   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
442
443   // Use the default for now
444   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
445   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
446
447   if (!Subtarget.isGP64bit()) {
448     setOperationAction(ISD::ATOMIC_LOAD,     MVT::i64,   Expand);
449     setOperationAction(ISD::ATOMIC_STORE,    MVT::i64,   Expand);
450   }
451
452
453   if (!Subtarget.hasMips32r2()) {
454     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
455     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
456   }
457
458   // MIPS16 lacks MIPS32's clz and clo instructions.
459   if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
460     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
461   if (!Subtarget.hasMips64())
462     setOperationAction(ISD::CTLZ, MVT::i64, Expand);
463
464   if (!Subtarget.hasMips32r2())
465     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
466   if (!Subtarget.hasMips64r2())
467     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
468
469   if (Subtarget.isGP64bit()) {
470     setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
471     setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
472     setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
473     setTruncStoreAction(MVT::i64, MVT::i32, Custom);
474   }
475
476   setOperationAction(ISD::TRAP, MVT::Other, Legal);
477
478   setTargetDAGCombine(ISD::SDIVREM);
479   setTargetDAGCombine(ISD::UDIVREM);
480   setTargetDAGCombine(ISD::SELECT);
481   setTargetDAGCombine(ISD::AND);
482   setTargetDAGCombine(ISD::OR);
483   setTargetDAGCombine(ISD::ADD);
484   setTargetDAGCombine(ISD::SUB);
485   setTargetDAGCombine(ISD::AssertZext);
486   setTargetDAGCombine(ISD::SHL);
487
488   if (ABI.IsO32()) {
489     // These libcalls are not available in 32-bit.
490     setLibcallName(RTLIB::SHL_I128, nullptr);
491     setLibcallName(RTLIB::SRL_I128, nullptr);
492     setLibcallName(RTLIB::SRA_I128, nullptr);
493   }
494
495   setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
496
497   // The arguments on the stack are defined in terms of 4-byte slots on O32
498   // and 8-byte slots on N32/N64.
499   setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
500
501   setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
502
503   MaxStoresPerMemcpy = 16;
504
505   isMicroMips = Subtarget.inMicroMipsMode();
506 }
507
508 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
509                                                      const MipsSubtarget &STI) {
510   if (STI.inMips16Mode())
511     return llvm::createMips16TargetLowering(TM, STI);
512
513   return llvm::createMipsSETargetLowering(TM, STI);
514 }
515
516 // Create a fast isel object.
517 FastISel *
518 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
519                                   const TargetLibraryInfo *libInfo) const {
520   const MipsTargetMachine &TM =
521       static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
522
523   // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
524   bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
525                      !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() &&
526                      !Subtarget.inMicroMipsMode();
527
528   // Disable if either of the following is true:
529   // We do not generate PIC, the ABI is not O32, LargeGOT is being used.
530   if (!TM.isPositionIndependent() || !TM.getABI().IsO32() || LargeGOT)
531     UseFastISel = false;
532
533   return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr;
534 }
535
536 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
537                                            EVT VT) const {
538   if (!VT.isVector())
539     return MVT::i32;
540   return VT.changeVectorElementTypeToInteger();
541 }
542
543 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
544                                     TargetLowering::DAGCombinerInfo &DCI,
545                                     const MipsSubtarget &Subtarget) {
546   if (DCI.isBeforeLegalizeOps())
547     return SDValue();
548
549   EVT Ty = N->getValueType(0);
550   unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
551   unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
552   unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
553                                                   MipsISD::DivRemU16;
554   SDLoc DL(N);
555
556   SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
557                                N->getOperand(0), N->getOperand(1));
558   SDValue InChain = DAG.getEntryNode();
559   SDValue InGlue = DivRem;
560
561   // insert MFLO
562   if (N->hasAnyUseOfValue(0)) {
563     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
564                                             InGlue);
565     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
566     InChain = CopyFromLo.getValue(1);
567     InGlue = CopyFromLo.getValue(2);
568   }
569
570   // insert MFHI
571   if (N->hasAnyUseOfValue(1)) {
572     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
573                                             HI, Ty, InGlue);
574     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
575   }
576
577   return SDValue();
578 }
579
580 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
581   switch (CC) {
582   default: llvm_unreachable("Unknown fp condition code!");
583   case ISD::SETEQ:
584   case ISD::SETOEQ: return Mips::FCOND_OEQ;
585   case ISD::SETUNE: return Mips::FCOND_UNE;
586   case ISD::SETLT:
587   case ISD::SETOLT: return Mips::FCOND_OLT;
588   case ISD::SETGT:
589   case ISD::SETOGT: return Mips::FCOND_OGT;
590   case ISD::SETLE:
591   case ISD::SETOLE: return Mips::FCOND_OLE;
592   case ISD::SETGE:
593   case ISD::SETOGE: return Mips::FCOND_OGE;
594   case ISD::SETULT: return Mips::FCOND_ULT;
595   case ISD::SETULE: return Mips::FCOND_ULE;
596   case ISD::SETUGT: return Mips::FCOND_UGT;
597   case ISD::SETUGE: return Mips::FCOND_UGE;
598   case ISD::SETUO:  return Mips::FCOND_UN;
599   case ISD::SETO:   return Mips::FCOND_OR;
600   case ISD::SETNE:
601   case ISD::SETONE: return Mips::FCOND_ONE;
602   case ISD::SETUEQ: return Mips::FCOND_UEQ;
603   }
604 }
605
606
607 /// This function returns true if the floating point conditional branches and
608 /// conditional moves which use condition code CC should be inverted.
609 static bool invertFPCondCodeUser(Mips::CondCode CC) {
610   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
611     return false;
612
613   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
614          "Illegal Condition Code");
615
616   return true;
617 }
618
619 // Creates and returns an FPCmp node from a setcc node.
620 // Returns Op if setcc is not a floating point comparison.
621 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
622   // must be a SETCC node
623   if (Op.getOpcode() != ISD::SETCC)
624     return Op;
625
626   SDValue LHS = Op.getOperand(0);
627
628   if (!LHS.getValueType().isFloatingPoint())
629     return Op;
630
631   SDValue RHS = Op.getOperand(1);
632   SDLoc DL(Op);
633
634   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
635   // node if necessary.
636   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
637
638   return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
639                      DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
640 }
641
642 // Creates and returns a CMovFPT/F node.
643 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
644                             SDValue False, const SDLoc &DL) {
645   ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
646   bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
647   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
648
649   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
650                      True.getValueType(), True, FCC0, False, Cond);
651 }
652
653 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
654                                     TargetLowering::DAGCombinerInfo &DCI,
655                                     const MipsSubtarget &Subtarget) {
656   if (DCI.isBeforeLegalizeOps())
657     return SDValue();
658
659   SDValue SetCC = N->getOperand(0);
660
661   if ((SetCC.getOpcode() != ISD::SETCC) ||
662       !SetCC.getOperand(0).getValueType().isInteger())
663     return SDValue();
664
665   SDValue False = N->getOperand(2);
666   EVT FalseTy = False.getValueType();
667
668   if (!FalseTy.isInteger())
669     return SDValue();
670
671   ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
672
673   // If the RHS (False) is 0, we swap the order of the operands
674   // of ISD::SELECT (obviously also inverting the condition) so that we can
675   // take advantage of conditional moves using the $0 register.
676   // Example:
677   //   return (a != 0) ? x : 0;
678   //     load $reg, x
679   //     movz $reg, $0, a
680   if (!FalseC)
681     return SDValue();
682
683   const SDLoc DL(N);
684
685   if (!FalseC->getZExtValue()) {
686     ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
687     SDValue True = N->getOperand(1);
688
689     SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
690                          SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
691
692     return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
693   }
694
695   // If both operands are integer constants there's a possibility that we
696   // can do some interesting optimizations.
697   SDValue True = N->getOperand(1);
698   ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
699
700   if (!TrueC || !True.getValueType().isInteger())
701     return SDValue();
702
703   // We'll also ignore MVT::i64 operands as this optimizations proves
704   // to be ineffective because of the required sign extensions as the result
705   // of a SETCC operator is always MVT::i32 for non-vector types.
706   if (True.getValueType() == MVT::i64)
707     return SDValue();
708
709   int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
710
711   // 1)  (a < x) ? y : y-1
712   //  slti $reg1, a, x
713   //  addiu $reg2, $reg1, y-1
714   if (Diff == 1)
715     return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
716
717   // 2)  (a < x) ? y-1 : y
718   //  slti $reg1, a, x
719   //  xor $reg1, $reg1, 1
720   //  addiu $reg2, $reg1, y-1
721   if (Diff == -1) {
722     ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
723     SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
724                          SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
725     return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
726   }
727
728   // Couldn't optimize.
729   return SDValue();
730 }
731
732 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
733                                     TargetLowering::DAGCombinerInfo &DCI,
734                                     const MipsSubtarget &Subtarget) {
735   if (DCI.isBeforeLegalizeOps())
736     return SDValue();
737
738   SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
739
740   ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
741   if (!FalseC || FalseC->getZExtValue())
742     return SDValue();
743
744   // Since RHS (False) is 0, we swap the order of the True/False operands
745   // (obviously also inverting the condition) so that we can
746   // take advantage of conditional moves using the $0 register.
747   // Example:
748   //   return (a != 0) ? x : 0;
749   //     load $reg, x
750   //     movz $reg, $0, a
751   unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
752                                                          MipsISD::CMovFP_T;
753
754   SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
755   return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
756                      ValueIfFalse, FCC, ValueIfTrue, Glue);
757 }
758
759 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
760                                  TargetLowering::DAGCombinerInfo &DCI,
761                                  const MipsSubtarget &Subtarget) {
762   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
763     return SDValue();
764
765   SDValue FirstOperand = N->getOperand(0);
766   unsigned FirstOperandOpc = FirstOperand.getOpcode();
767   SDValue Mask = N->getOperand(1);
768   EVT ValTy = N->getValueType(0);
769   SDLoc DL(N);
770
771   uint64_t Pos = 0, SMPos, SMSize;
772   ConstantSDNode *CN;
773   SDValue NewOperand;
774   unsigned Opc;
775
776   // Op's second operand must be a shifted mask.
777   if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
778       !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
779     return SDValue();
780
781   if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
782     // Pattern match EXT.
783     //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
784     //  => ext $dst, $src, pos, size
785
786     // The second operand of the shift must be an immediate.
787     if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
788       return SDValue();
789
790     Pos = CN->getZExtValue();
791
792     // Return if the shifted mask does not start at bit 0 or the sum of its size
793     // and Pos exceeds the word's size.
794     if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
795       return SDValue();
796
797     Opc = MipsISD::Ext;
798     NewOperand = FirstOperand.getOperand(0);
799   } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
800     // Pattern match CINS.
801     //  $dst = and (shl $src , pos), mask
802     //  => cins $dst, $src, pos, size
803     // mask is a shifted mask with consecutive 1's, pos = shift amount,
804     // size = population count.
805
806     // The second operand of the shift must be an immediate.
807     if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
808       return SDValue();
809
810     Pos = CN->getZExtValue();
811
812     if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
813         Pos + SMSize > ValTy.getSizeInBits())
814       return SDValue();
815
816     NewOperand = FirstOperand.getOperand(0);
817     // SMSize is 'location' (position) in this case, not size.
818     SMSize--;
819     Opc = MipsISD::CIns;
820   } else {
821     // Pattern match EXT.
822     //  $dst = and $src, (2**size - 1) , if size > 16
823     //  => ext $dst, $src, pos, size , pos = 0
824
825     // If the mask is <= 0xffff, andi can be used instead.
826     if (CN->getZExtValue() <= 0xffff)
827       return SDValue();
828
829     // Return if the mask doesn't start at position 0.
830     if (SMPos)
831       return SDValue();
832
833     Opc = MipsISD::Ext;
834     NewOperand = FirstOperand;
835   }
836   return DAG.getNode(Opc, DL, ValTy, NewOperand,
837                      DAG.getConstant(Pos, DL, MVT::i32),
838                      DAG.getConstant(SMSize, DL, MVT::i32));
839 }
840
841 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
842                                 TargetLowering::DAGCombinerInfo &DCI,
843                                 const MipsSubtarget &Subtarget) {
844   // Pattern match INS.
845   //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
846   //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1
847   //  => ins $dst, $src, size, pos, $src1
848   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
849     return SDValue();
850
851   SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
852   uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
853   ConstantSDNode *CN, *CN1;
854
855   // See if Op's first operand matches (and $src1 , mask0).
856   if (And0.getOpcode() != ISD::AND)
857     return SDValue();
858
859   if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
860       !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
861     return SDValue();
862
863   // See if Op's second operand matches (and (shl $src, pos), mask1).
864   if (And1.getOpcode() == ISD::AND &&
865       And1.getOperand(0).getOpcode() == ISD::SHL) {
866
867     if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
868         !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
869       return SDValue();
870
871     // The shift masks must have the same position and size.
872     if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
873       return SDValue();
874
875     SDValue Shl = And1.getOperand(0);
876
877     if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
878       return SDValue();
879
880     unsigned Shamt = CN->getZExtValue();
881
882     // Return if the shift amount and the first bit position of mask are not the
883     // same.
884     EVT ValTy = N->getValueType(0);
885     if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
886       return SDValue();
887
888     SDLoc DL(N);
889     return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
890                        DAG.getConstant(SMPos0, DL, MVT::i32),
891                        DAG.getConstant(SMSize0, DL, MVT::i32),
892                        And0.getOperand(0));
893   } else {
894     // Pattern match DINS.
895     //  $dst = or (and $src, mask0), mask1
896     //  where mask0 = ((1 << SMSize0) -1) << SMPos0
897     //  => dins $dst, $src, pos, size
898     if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) &&
899         ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
900          (SMSize0 + SMPos0 <= 32))) {
901       // Check if AND instruction has constant as argument
902       bool isConstCase = And1.getOpcode() != ISD::AND;
903       if (And1.getOpcode() == ISD::AND) {
904         if (!(CN1 = dyn_cast<ConstantSDNode>(And1->getOperand(1))))
905           return SDValue();
906       } else {
907         if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
908           return SDValue();
909       }
910       SDLoc DL(N);
911       EVT ValTy = N->getOperand(0)->getValueType(0);
912       SDValue Const1;
913       SDValue SrlX;
914       if (!isConstCase) {
915         Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
916         SrlX = DAG.getNode(ISD::SRL, DL, And1->getValueType(0), And1, Const1);
917       }
918       return DAG.getNode(
919           MipsISD::Ins, DL, N->getValueType(0),
920           isConstCase
921               ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
922               : SrlX,
923           DAG.getConstant(SMPos0, DL, MVT::i32),
924           DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
925                                                         : SMSize0,
926                           DL, MVT::i32),
927           And0->getOperand(0));
928
929     }
930     return SDValue();
931   }
932 }
933
934 static SDValue performMADD_MSUBCombine(SDNode *ROOTNode, SelectionDAG &CurDAG,
935                                        const MipsSubtarget &Subtarget) {
936   // ROOTNode must have a multiplication as an operand for the match to be
937   // successful.
938   if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL &&
939       ROOTNode->getOperand(1).getOpcode() != ISD::MUL)
940     return SDValue();
941
942   // We don't handle vector types here.
943   if (ROOTNode->getValueType(0).isVector())
944     return SDValue();
945
946   // For MIPS64, madd / msub instructions are inefficent to use with 64 bit
947   // arithmetic. E.g.
948   // (add (mul a b) c) =>
949   //   let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in
950   //   MIPS64:   (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32)
951   //   or
952   //   MIPS64R2: (dins (mflo res) (mfhi res) 32 32)
953   //
954   // The overhead of setting up the Hi/Lo registers and reassembling the
955   // result makes this a dubious optimzation for MIPS64. The core of the
956   // problem is that Hi/Lo contain the upper and lower 32 bits of the
957   // operand and result.
958   //
959   // It requires a chain of 4 add/mul for MIPS64R2 to get better code
960   // density than doing it naively, 5 for MIPS64. Additionally, using
961   // madd/msub on MIPS64 requires the operands actually be 32 bit sign
962   // extended operands, not true 64 bit values.
963   //
964   // FIXME: For the moment, disable this completely for MIPS64.
965   if (Subtarget.hasMips64())
966     return SDValue();
967
968   SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
969                      ? ROOTNode->getOperand(0)
970                      : ROOTNode->getOperand(1);
971
972   SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
973                      ? ROOTNode->getOperand(1)
974                      : ROOTNode->getOperand(0);
975
976   // Transform this to a MADD only if the user of this node is the add.
977   // If there are other users of the mul, this function returns here.
978   if (!Mult.hasOneUse())
979     return SDValue();
980
981   // maddu and madd are unusual instructions in that on MIPS64 bits 63..31
982   // must be in canonical form, i.e. sign extended. For MIPS32, the operands
983   // of the multiply must have 32 or more sign bits, otherwise we cannot
984   // perform this optimization. We have to check this here as we're performing
985   // this optimization pre-legalization.
986   SDValue MultLHS = Mult->getOperand(0);
987   SDValue MultRHS = Mult->getOperand(1);
988   unsigned LHSSB = CurDAG.ComputeNumSignBits(MultLHS);
989   unsigned RHSSB = CurDAG.ComputeNumSignBits(MultRHS);
990
991   if (LHSSB < 32 || RHSSB < 32)
992     return SDValue();
993
994   APInt HighMask =
995       APInt::getHighBitsSet(Mult->getValueType(0).getScalarSizeInBits(), 32);
996   bool IsUnsigned = CurDAG.MaskedValueIsZero(Mult->getOperand(0), HighMask) &&
997                     CurDAG.MaskedValueIsZero(Mult->getOperand(1), HighMask) &&
998                     CurDAG.MaskedValueIsZero(AddOperand, HighMask);
999
1000   // Initialize accumulator.
1001   SDLoc DL(ROOTNode);
1002   SDValue TopHalf;
1003   SDValue BottomHalf;
1004   BottomHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1005                               CurDAG.getIntPtrConstant(0, DL));
1006
1007   TopHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1008                            CurDAG.getIntPtrConstant(1, DL));
1009   SDValue ACCIn = CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped,
1010                                   BottomHalf,
1011                                   TopHalf);
1012
1013   // Create MipsMAdd(u) / MipsMSub(u) node.
1014   bool IsAdd = ROOTNode->getOpcode() == ISD::ADD;
1015   unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd)
1016                           : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub);
1017   SDValue MAddOps[3] = {
1018       CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)),
1019       CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn};
1020   EVT VTs[2] = {MVT::i32, MVT::i32};
1021   SDValue MAdd = CurDAG.getNode(Opcode, DL, VTs, MAddOps);
1022
1023   SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
1024   SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
1025   SDValue Combined =
1026       CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi);
1027   return Combined;
1028 }
1029
1030 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG,
1031                                  TargetLowering::DAGCombinerInfo &DCI,
1032                                  const MipsSubtarget &Subtarget) {
1033   // (sub v0 (mul v1, v2)) => (msub v1, v2, v0)
1034   if (DCI.isBeforeLegalizeOps()) {
1035     if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1036         !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1037       return performMADD_MSUBCombine(N, DAG, Subtarget);
1038
1039     return SDValue();
1040   }
1041
1042   return SDValue();
1043 }
1044
1045 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
1046                                  TargetLowering::DAGCombinerInfo &DCI,
1047                                  const MipsSubtarget &Subtarget) {
1048   // (add v0 (mul v1, v2)) => (madd v1, v2, v0)
1049   if (DCI.isBeforeLegalizeOps()) {
1050     if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1051         !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1052       return performMADD_MSUBCombine(N, DAG, Subtarget);
1053
1054     return SDValue();
1055   }
1056
1057   // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
1058   SDValue Add = N->getOperand(1);
1059
1060   if (Add.getOpcode() != ISD::ADD)
1061     return SDValue();
1062
1063   SDValue Lo = Add.getOperand(1);
1064
1065   if ((Lo.getOpcode() != MipsISD::Lo) ||
1066       (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
1067     return SDValue();
1068
1069   EVT ValTy = N->getValueType(0);
1070   SDLoc DL(N);
1071
1072   SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
1073                              Add.getOperand(0));
1074   return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
1075 }
1076
1077 static SDValue performAssertZextCombine(SDNode *N, SelectionDAG &DAG,
1078                                         TargetLowering::DAGCombinerInfo &DCI,
1079                                         const MipsSubtarget &Subtarget) {
1080   SDValue N0 = N->getOperand(0);
1081   EVT NarrowerVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1082
1083   if (N0.getOpcode() != ISD::TRUNCATE)
1084     return SDValue();
1085
1086   if (N0.getOperand(0).getOpcode() != ISD::AssertZext)
1087     return SDValue();
1088
1089   // fold (AssertZext (trunc (AssertZext x))) -> (trunc (AssertZext x))
1090   // if the type of the extension of the innermost AssertZext node is
1091   // smaller from that of the outermost node, eg:
1092   // (AssertZext:i32 (trunc:i32 (AssertZext:i64 X, i32)), i8)
1093   //   -> (trunc:i32 (AssertZext X, i8))
1094   SDValue WiderAssertZext = N0.getOperand(0);
1095   EVT WiderVT = cast<VTSDNode>(WiderAssertZext->getOperand(1))->getVT();
1096
1097   if (NarrowerVT.bitsLT(WiderVT)) {
1098     SDValue NewAssertZext = DAG.getNode(
1099         ISD::AssertZext, SDLoc(N), WiderAssertZext.getValueType(),
1100         WiderAssertZext.getOperand(0), DAG.getValueType(NarrowerVT));
1101     return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0),
1102                        NewAssertZext);
1103   }
1104
1105   return SDValue();
1106 }
1107
1108
1109 static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG,
1110                                  TargetLowering::DAGCombinerInfo &DCI,
1111                                  const MipsSubtarget &Subtarget) {
1112   // Pattern match CINS.
1113   //  $dst = shl (and $src , imm), pos
1114   //  => cins $dst, $src, pos, size
1115
1116   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
1117     return SDValue();
1118
1119   SDValue FirstOperand = N->getOperand(0);
1120   unsigned FirstOperandOpc = FirstOperand.getOpcode();
1121   SDValue SecondOperand = N->getOperand(1);
1122   EVT ValTy = N->getValueType(0);
1123   SDLoc DL(N);
1124
1125   uint64_t Pos = 0, SMPos, SMSize;
1126   ConstantSDNode *CN;
1127   SDValue NewOperand;
1128
1129   // The second operand of the shift must be an immediate.
1130   if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
1131     return SDValue();
1132
1133   Pos = CN->getZExtValue();
1134
1135   if (Pos >= ValTy.getSizeInBits())
1136     return SDValue();
1137
1138   if (FirstOperandOpc != ISD::AND)
1139     return SDValue();
1140
1141   // AND's second operand must be a shifted mask.
1142   if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
1143       !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
1144     return SDValue();
1145
1146   // Return if the shifted mask does not start at bit 0 or the sum of its size
1147   // and Pos exceeds the word's size.
1148   if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
1149     return SDValue();
1150
1151   NewOperand = FirstOperand.getOperand(0);
1152   // SMSize is 'location' (position) in this case, not size.
1153   SMSize--;
1154
1155   return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
1156                      DAG.getConstant(Pos, DL, MVT::i32),
1157                      DAG.getConstant(SMSize, DL, MVT::i32));
1158 }
1159
1160 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
1161   const {
1162   SelectionDAG &DAG = DCI.DAG;
1163   unsigned Opc = N->getOpcode();
1164
1165   switch (Opc) {
1166   default: break;
1167   case ISD::SDIVREM:
1168   case ISD::UDIVREM:
1169     return performDivRemCombine(N, DAG, DCI, Subtarget);
1170   case ISD::SELECT:
1171     return performSELECTCombine(N, DAG, DCI, Subtarget);
1172   case MipsISD::CMovFP_F:
1173   case MipsISD::CMovFP_T:
1174     return performCMovFPCombine(N, DAG, DCI, Subtarget);
1175   case ISD::AND:
1176     return performANDCombine(N, DAG, DCI, Subtarget);
1177   case ISD::OR:
1178     return performORCombine(N, DAG, DCI, Subtarget);
1179   case ISD::ADD:
1180     return performADDCombine(N, DAG, DCI, Subtarget);
1181   case ISD::AssertZext:
1182     return performAssertZextCombine(N, DAG, DCI, Subtarget);
1183   case ISD::SHL:
1184     return performSHLCombine(N, DAG, DCI, Subtarget);
1185   case ISD::SUB:
1186     return performSUBCombine(N, DAG, DCI, Subtarget);
1187   }
1188
1189   return SDValue();
1190 }
1191
1192 bool MipsTargetLowering::isCheapToSpeculateCttz() const {
1193   return Subtarget.hasMips32();
1194 }
1195
1196 bool MipsTargetLowering::isCheapToSpeculateCtlz() const {
1197   return Subtarget.hasMips32();
1198 }
1199
1200 void
1201 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1202                                           SmallVectorImpl<SDValue> &Results,
1203                                           SelectionDAG &DAG) const {
1204   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1205
1206   for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1207     Results.push_back(Res.getValue(I));
1208 }
1209
1210 void
1211 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1212                                        SmallVectorImpl<SDValue> &Results,
1213                                        SelectionDAG &DAG) const {
1214   return LowerOperationWrapper(N, Results, DAG);
1215 }
1216
1217 SDValue MipsTargetLowering::
1218 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1219 {
1220   switch (Op.getOpcode())
1221   {
1222   case ISD::BRCOND:             return lowerBRCOND(Op, DAG);
1223   case ISD::ConstantPool:       return lowerConstantPool(Op, DAG);
1224   case ISD::GlobalAddress:      return lowerGlobalAddress(Op, DAG);
1225   case ISD::BlockAddress:       return lowerBlockAddress(Op, DAG);
1226   case ISD::GlobalTLSAddress:   return lowerGlobalTLSAddress(Op, DAG);
1227   case ISD::JumpTable:          return lowerJumpTable(Op, DAG);
1228   case ISD::SELECT:             return lowerSELECT(Op, DAG);
1229   case ISD::SETCC:              return lowerSETCC(Op, DAG);
1230   case ISD::VASTART:            return lowerVASTART(Op, DAG);
1231   case ISD::VAARG:              return lowerVAARG(Op, DAG);
1232   case ISD::FCOPYSIGN:          return lowerFCOPYSIGN(Op, DAG);
1233   case ISD::FRAMEADDR:          return lowerFRAMEADDR(Op, DAG);
1234   case ISD::RETURNADDR:         return lowerRETURNADDR(Op, DAG);
1235   case ISD::EH_RETURN:          return lowerEH_RETURN(Op, DAG);
1236   case ISD::ATOMIC_FENCE:       return lowerATOMIC_FENCE(Op, DAG);
1237   case ISD::SHL_PARTS:          return lowerShiftLeftParts(Op, DAG);
1238   case ISD::SRA_PARTS:          return lowerShiftRightParts(Op, DAG, true);
1239   case ISD::SRL_PARTS:          return lowerShiftRightParts(Op, DAG, false);
1240   case ISD::LOAD:               return lowerLOAD(Op, DAG);
1241   case ISD::STORE:              return lowerSTORE(Op, DAG);
1242   case ISD::EH_DWARF_CFA:       return lowerEH_DWARF_CFA(Op, DAG);
1243   case ISD::FP_TO_SINT:         return lowerFP_TO_SINT(Op, DAG);
1244   }
1245   return SDValue();
1246 }
1247
1248 //===----------------------------------------------------------------------===//
1249 //  Lower helper functions
1250 //===----------------------------------------------------------------------===//
1251
1252 // addLiveIn - This helper function adds the specified physical register to the
1253 // MachineFunction as a live in value.  It also creates a corresponding
1254 // virtual register for it.
1255 static unsigned
1256 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1257 {
1258   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1259   MF.getRegInfo().addLiveIn(PReg, VReg);
1260   return VReg;
1261 }
1262
1263 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr &MI,
1264                                               MachineBasicBlock &MBB,
1265                                               const TargetInstrInfo &TII,
1266                                               bool Is64Bit, bool IsMicroMips) {
1267   if (NoZeroDivCheck)
1268     return &MBB;
1269
1270   // Insert instruction "teq $divisor_reg, $zero, 7".
1271   MachineBasicBlock::iterator I(MI);
1272   MachineInstrBuilder MIB;
1273   MachineOperand &Divisor = MI.getOperand(2);
1274   MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1275                 TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ))
1276             .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1277             .addReg(Mips::ZERO)
1278             .addImm(7);
1279
1280   // Use the 32-bit sub-register if this is a 64-bit division.
1281   if (Is64Bit)
1282     MIB->getOperand(0).setSubReg(Mips::sub_32);
1283
1284   // Clear Divisor's kill flag.
1285   Divisor.setIsKill(false);
1286
1287   // We would normally delete the original instruction here but in this case
1288   // we only needed to inject an additional instruction rather than replace it.
1289
1290   return &MBB;
1291 }
1292
1293 MachineBasicBlock *
1294 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1295                                                 MachineBasicBlock *BB) const {
1296   switch (MI.getOpcode()) {
1297   default:
1298     llvm_unreachable("Unexpected instr type to insert");
1299   case Mips::ATOMIC_LOAD_ADD_I8:
1300     return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1301   case Mips::ATOMIC_LOAD_ADD_I16:
1302     return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1303   case Mips::ATOMIC_LOAD_ADD_I32:
1304     return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
1305   case Mips::ATOMIC_LOAD_ADD_I64:
1306     return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
1307
1308   case Mips::ATOMIC_LOAD_AND_I8:
1309     return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1310   case Mips::ATOMIC_LOAD_AND_I16:
1311     return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1312   case Mips::ATOMIC_LOAD_AND_I32:
1313     return emitAtomicBinary(MI, BB, 4, Mips::AND);
1314   case Mips::ATOMIC_LOAD_AND_I64:
1315     return emitAtomicBinary(MI, BB, 8, Mips::AND64);
1316
1317   case Mips::ATOMIC_LOAD_OR_I8:
1318     return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1319   case Mips::ATOMIC_LOAD_OR_I16:
1320     return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1321   case Mips::ATOMIC_LOAD_OR_I32:
1322     return emitAtomicBinary(MI, BB, 4, Mips::OR);
1323   case Mips::ATOMIC_LOAD_OR_I64:
1324     return emitAtomicBinary(MI, BB, 8, Mips::OR64);
1325
1326   case Mips::ATOMIC_LOAD_XOR_I8:
1327     return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1328   case Mips::ATOMIC_LOAD_XOR_I16:
1329     return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1330   case Mips::ATOMIC_LOAD_XOR_I32:
1331     return emitAtomicBinary(MI, BB, 4, Mips::XOR);
1332   case Mips::ATOMIC_LOAD_XOR_I64:
1333     return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
1334
1335   case Mips::ATOMIC_LOAD_NAND_I8:
1336     return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
1337   case Mips::ATOMIC_LOAD_NAND_I16:
1338     return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
1339   case Mips::ATOMIC_LOAD_NAND_I32:
1340     return emitAtomicBinary(MI, BB, 4, 0, true);
1341   case Mips::ATOMIC_LOAD_NAND_I64:
1342     return emitAtomicBinary(MI, BB, 8, 0, true);
1343
1344   case Mips::ATOMIC_LOAD_SUB_I8:
1345     return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1346   case Mips::ATOMIC_LOAD_SUB_I16:
1347     return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1348   case Mips::ATOMIC_LOAD_SUB_I32:
1349     return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
1350   case Mips::ATOMIC_LOAD_SUB_I64:
1351     return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1352
1353   case Mips::ATOMIC_SWAP_I8:
1354     return emitAtomicBinaryPartword(MI, BB, 1, 0);
1355   case Mips::ATOMIC_SWAP_I16:
1356     return emitAtomicBinaryPartword(MI, BB, 2, 0);
1357   case Mips::ATOMIC_SWAP_I32:
1358     return emitAtomicBinary(MI, BB, 4, 0);
1359   case Mips::ATOMIC_SWAP_I64:
1360     return emitAtomicBinary(MI, BB, 8, 0);
1361
1362   case Mips::ATOMIC_CMP_SWAP_I8:
1363     return emitAtomicCmpSwapPartword(MI, BB, 1);
1364   case Mips::ATOMIC_CMP_SWAP_I16:
1365     return emitAtomicCmpSwapPartword(MI, BB, 2);
1366   case Mips::ATOMIC_CMP_SWAP_I32:
1367     return emitAtomicCmpSwap(MI, BB, 4);
1368   case Mips::ATOMIC_CMP_SWAP_I64:
1369     return emitAtomicCmpSwap(MI, BB, 8);
1370   case Mips::PseudoSDIV:
1371   case Mips::PseudoUDIV:
1372   case Mips::DIV:
1373   case Mips::DIVU:
1374   case Mips::MOD:
1375   case Mips::MODU:
1376     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1377                                false);
1378   case Mips::SDIV_MM_Pseudo:
1379   case Mips::UDIV_MM_Pseudo:
1380   case Mips::SDIV_MM:
1381   case Mips::UDIV_MM:
1382   case Mips::DIV_MMR6:
1383   case Mips::DIVU_MMR6:
1384   case Mips::MOD_MMR6:
1385   case Mips::MODU_MMR6:
1386     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true);
1387   case Mips::PseudoDSDIV:
1388   case Mips::PseudoDUDIV:
1389   case Mips::DDIV:
1390   case Mips::DDIVU:
1391   case Mips::DMOD:
1392   case Mips::DMODU:
1393     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false);
1394   case Mips::DDIV_MM64R6:
1395   case Mips::DDIVU_MM64R6:
1396   case Mips::DMOD_MM64R6:
1397   case Mips::DMODU_MM64R6:
1398     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, true);
1399   case Mips::SEL_D:
1400   case Mips::SEL_D_MMR6:
1401     return emitSEL_D(MI, BB);
1402
1403   case Mips::PseudoSELECT_I:
1404   case Mips::PseudoSELECT_I64:
1405   case Mips::PseudoSELECT_S:
1406   case Mips::PseudoSELECT_D32:
1407   case Mips::PseudoSELECT_D64:
1408     return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1409   case Mips::PseudoSELECTFP_F_I:
1410   case Mips::PseudoSELECTFP_F_I64:
1411   case Mips::PseudoSELECTFP_F_S:
1412   case Mips::PseudoSELECTFP_F_D32:
1413   case Mips::PseudoSELECTFP_F_D64:
1414     return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1415   case Mips::PseudoSELECTFP_T_I:
1416   case Mips::PseudoSELECTFP_T_I64:
1417   case Mips::PseudoSELECTFP_T_S:
1418   case Mips::PseudoSELECTFP_T_D32:
1419   case Mips::PseudoSELECTFP_T_D64:
1420     return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1421   }
1422 }
1423
1424 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1425 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1426 MachineBasicBlock *MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1427                                                         MachineBasicBlock *BB,
1428                                                         unsigned Size,
1429                                                         unsigned BinOpcode,
1430                                                         bool Nand) const {
1431   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1432
1433   MachineFunction *MF = BB->getParent();
1434   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1435   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1436   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1437   const bool ArePtrs64bit = ABI.ArePtrs64bit();
1438   DebugLoc DL = MI.getDebugLoc();
1439   unsigned LL, SC, AND, NOR, ZERO, BEQ;
1440
1441   if (Size == 4) {
1442     if (isMicroMips) {
1443       LL = Mips::LL_MM;
1444       SC = Mips::SC_MM;
1445     } else {
1446       LL = Subtarget.hasMips32r6()
1447                ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1448                : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1449       SC = Subtarget.hasMips32r6()
1450                ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1451                : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1452     }
1453
1454     AND = Mips::AND;
1455     NOR = Mips::NOR;
1456     ZERO = Mips::ZERO;
1457     BEQ = Mips::BEQ;
1458   } else {
1459     LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1460     SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1461     AND = Mips::AND64;
1462     NOR = Mips::NOR64;
1463     ZERO = Mips::ZERO_64;
1464     BEQ = Mips::BEQ64;
1465   }
1466
1467   unsigned OldVal = MI.getOperand(0).getReg();
1468   unsigned Ptr = MI.getOperand(1).getReg();
1469   unsigned Incr = MI.getOperand(2).getReg();
1470
1471   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1472   unsigned AndRes = RegInfo.createVirtualRegister(RC);
1473   unsigned Success = RegInfo.createVirtualRegister(RC);
1474
1475   // insert new blocks after the current block
1476   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1477   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1478   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1479   MachineFunction::iterator It = ++BB->getIterator();
1480   MF->insert(It, loopMBB);
1481   MF->insert(It, exitMBB);
1482
1483   // Transfer the remainder of BB and its successor edges to exitMBB.
1484   exitMBB->splice(exitMBB->begin(), BB,
1485                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1486   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1487
1488   //  thisMBB:
1489   //    ...
1490   //    fallthrough --> loopMBB
1491   BB->addSuccessor(loopMBB);
1492   loopMBB->addSuccessor(loopMBB);
1493   loopMBB->addSuccessor(exitMBB);
1494
1495   //  loopMBB:
1496   //    ll oldval, 0(ptr)
1497   //    <binop> storeval, oldval, incr
1498   //    sc success, storeval, 0(ptr)
1499   //    beq success, $0, loopMBB
1500   BB = loopMBB;
1501   BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1502   if (Nand) {
1503     //  and andres, oldval, incr
1504     //  nor storeval, $0, andres
1505     BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1506     BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1507   } else if (BinOpcode) {
1508     //  <binop> storeval, oldval, incr
1509     BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1510   } else {
1511     StoreVal = Incr;
1512   }
1513   BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1514   BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1515
1516   MI.eraseFromParent(); // The instruction is gone now.
1517
1518   return exitMBB;
1519 }
1520
1521 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1522     MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1523     unsigned SrcReg) const {
1524   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1525   const DebugLoc &DL = MI.getDebugLoc();
1526
1527   if (Subtarget.hasMips32r2() && Size == 1) {
1528     BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1529     return BB;
1530   }
1531
1532   if (Subtarget.hasMips32r2() && Size == 2) {
1533     BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1534     return BB;
1535   }
1536
1537   MachineFunction *MF = BB->getParent();
1538   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1539   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1540   unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1541
1542   assert(Size < 32);
1543   int64_t ShiftImm = 32 - (Size * 8);
1544
1545   BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1546   BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1547
1548   return BB;
1549 }
1550
1551 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1552     MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1553     bool Nand) const {
1554   assert((Size == 1 || Size == 2) &&
1555          "Unsupported size for EmitAtomicBinaryPartial.");
1556
1557   MachineFunction *MF = BB->getParent();
1558   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1559   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1560   const bool ArePtrs64bit = ABI.ArePtrs64bit();
1561   const TargetRegisterClass *RCp =
1562     getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1563   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1564   DebugLoc DL = MI.getDebugLoc();
1565
1566   unsigned Dest = MI.getOperand(0).getReg();
1567   unsigned Ptr = MI.getOperand(1).getReg();
1568   unsigned Incr = MI.getOperand(2).getReg();
1569
1570   unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1571   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1572   unsigned Mask = RegInfo.createVirtualRegister(RC);
1573   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1574   unsigned NewVal = RegInfo.createVirtualRegister(RC);
1575   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1576   unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1577   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1578   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1579   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1580   unsigned AndRes = RegInfo.createVirtualRegister(RC);
1581   unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1582   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1583   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1584   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1585   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1586   unsigned Success = RegInfo.createVirtualRegister(RC);
1587
1588   unsigned LL, SC;
1589   if (isMicroMips) {
1590     LL = Mips::LL_MM;
1591     SC = Mips::SC_MM;
1592   } else {
1593     LL = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1594                                  : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1595     SC = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1596                                  : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1597   }
1598
1599   // insert new blocks after the current block
1600   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1601   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1602   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1603   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1604   MachineFunction::iterator It = ++BB->getIterator();
1605   MF->insert(It, loopMBB);
1606   MF->insert(It, sinkMBB);
1607   MF->insert(It, exitMBB);
1608
1609   // Transfer the remainder of BB and its successor edges to exitMBB.
1610   exitMBB->splice(exitMBB->begin(), BB,
1611                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1612   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1613
1614   BB->addSuccessor(loopMBB);
1615   loopMBB->addSuccessor(loopMBB);
1616   loopMBB->addSuccessor(sinkMBB);
1617   sinkMBB->addSuccessor(exitMBB);
1618
1619   //  thisMBB:
1620   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1621   //    and     alignedaddr,ptr,masklsb2
1622   //    andi    ptrlsb2,ptr,3
1623   //    sll     shiftamt,ptrlsb2,3
1624   //    ori     maskupper,$0,255               # 0xff
1625   //    sll     mask,maskupper,shiftamt
1626   //    nor     mask2,$0,mask
1627   //    sll     incr2,incr,shiftamt
1628
1629   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1630   BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1631     .addReg(ABI.GetNullPtr()).addImm(-4);
1632   BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1633     .addReg(Ptr).addReg(MaskLSB2);
1634   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1635       .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1636   if (Subtarget.isLittle()) {
1637     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1638   } else {
1639     unsigned Off = RegInfo.createVirtualRegister(RC);
1640     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1641       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1642     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1643   }
1644   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1645     .addReg(Mips::ZERO).addImm(MaskImm);
1646   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1647     .addReg(MaskUpper).addReg(ShiftAmt);
1648   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1649   BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1650
1651   // atomic.load.binop
1652   // loopMBB:
1653   //   ll      oldval,0(alignedaddr)
1654   //   binop   binopres,oldval,incr2
1655   //   and     newval,binopres,mask
1656   //   and     maskedoldval0,oldval,mask2
1657   //   or      storeval,maskedoldval0,newval
1658   //   sc      success,storeval,0(alignedaddr)
1659   //   beq     success,$0,loopMBB
1660
1661   // atomic.swap
1662   // loopMBB:
1663   //   ll      oldval,0(alignedaddr)
1664   //   and     newval,incr2,mask
1665   //   and     maskedoldval0,oldval,mask2
1666   //   or      storeval,maskedoldval0,newval
1667   //   sc      success,storeval,0(alignedaddr)
1668   //   beq     success,$0,loopMBB
1669
1670   BB = loopMBB;
1671   BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1672   if (Nand) {
1673     //  and andres, oldval, incr2
1674     //  nor binopres, $0, andres
1675     //  and newval, binopres, mask
1676     BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1677     BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1678       .addReg(Mips::ZERO).addReg(AndRes);
1679     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1680   } else if (BinOpcode) {
1681     //  <binop> binopres, oldval, incr2
1682     //  and newval, binopres, mask
1683     BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1684     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1685   } else { // atomic.swap
1686     //  and newval, incr2, mask
1687     BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1688   }
1689
1690   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1691     .addReg(OldVal).addReg(Mask2);
1692   BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1693     .addReg(MaskedOldVal0).addReg(NewVal);
1694   BuildMI(BB, DL, TII->get(SC), Success)
1695     .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1696   BuildMI(BB, DL, TII->get(Mips::BEQ))
1697     .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1698
1699   //  sinkMBB:
1700   //    and     maskedoldval1,oldval,mask
1701   //    srl     srlres,maskedoldval1,shiftamt
1702   //    sign_extend dest,srlres
1703   BB = sinkMBB;
1704
1705   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1706     .addReg(OldVal).addReg(Mask);
1707   BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1708       .addReg(MaskedOldVal1).addReg(ShiftAmt);
1709   BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1710
1711   MI.eraseFromParent(); // The instruction is gone now.
1712
1713   return exitMBB;
1714 }
1715
1716 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1717                                                          MachineBasicBlock *BB,
1718                                                          unsigned Size) const {
1719   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1720
1721   MachineFunction *MF = BB->getParent();
1722   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1723   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1724   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1725   const bool ArePtrs64bit = ABI.ArePtrs64bit();
1726   DebugLoc DL = MI.getDebugLoc();
1727   unsigned LL, SC, ZERO, BNE, BEQ;
1728
1729   if (Size == 4) {
1730     if (isMicroMips) {
1731       LL = Mips::LL_MM;
1732       SC = Mips::SC_MM;
1733     } else {
1734       LL = Subtarget.hasMips32r6()
1735                ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1736                : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1737       SC = Subtarget.hasMips32r6()
1738                ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1739                : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1740     }
1741
1742     ZERO = Mips::ZERO;
1743     BNE = Mips::BNE;
1744     BEQ = Mips::BEQ;
1745   } else {
1746     LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1747     SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1748     ZERO = Mips::ZERO_64;
1749     BNE = Mips::BNE64;
1750     BEQ = Mips::BEQ64;
1751   }
1752
1753   unsigned Dest = MI.getOperand(0).getReg();
1754   unsigned Ptr = MI.getOperand(1).getReg();
1755   unsigned OldVal = MI.getOperand(2).getReg();
1756   unsigned NewVal = MI.getOperand(3).getReg();
1757
1758   unsigned Success = RegInfo.createVirtualRegister(RC);
1759
1760   // insert new blocks after the current block
1761   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1762   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1763   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1764   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1765   MachineFunction::iterator It = ++BB->getIterator();
1766   MF->insert(It, loop1MBB);
1767   MF->insert(It, loop2MBB);
1768   MF->insert(It, exitMBB);
1769
1770   // Transfer the remainder of BB and its successor edges to exitMBB.
1771   exitMBB->splice(exitMBB->begin(), BB,
1772                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1773   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1774
1775   //  thisMBB:
1776   //    ...
1777   //    fallthrough --> loop1MBB
1778   BB->addSuccessor(loop1MBB);
1779   loop1MBB->addSuccessor(exitMBB);
1780   loop1MBB->addSuccessor(loop2MBB);
1781   loop2MBB->addSuccessor(loop1MBB);
1782   loop2MBB->addSuccessor(exitMBB);
1783
1784   // loop1MBB:
1785   //   ll dest, 0(ptr)
1786   //   bne dest, oldval, exitMBB
1787   BB = loop1MBB;
1788   BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1789   BuildMI(BB, DL, TII->get(BNE))
1790     .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1791
1792   // loop2MBB:
1793   //   sc success, newval, 0(ptr)
1794   //   beq success, $0, loop1MBB
1795   BB = loop2MBB;
1796   BuildMI(BB, DL, TII->get(SC), Success)
1797     .addReg(NewVal).addReg(Ptr).addImm(0);
1798   BuildMI(BB, DL, TII->get(BEQ))
1799     .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1800
1801   MI.eraseFromParent(); // The instruction is gone now.
1802
1803   return exitMBB;
1804 }
1805
1806 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1807     MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1808   assert((Size == 1 || Size == 2) &&
1809       "Unsupported size for EmitAtomicCmpSwapPartial.");
1810
1811   MachineFunction *MF = BB->getParent();
1812   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1813   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1814   const bool ArePtrs64bit = ABI.ArePtrs64bit();
1815   const TargetRegisterClass *RCp =
1816     getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1817   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1818   DebugLoc DL = MI.getDebugLoc();
1819
1820   unsigned Dest = MI.getOperand(0).getReg();
1821   unsigned Ptr = MI.getOperand(1).getReg();
1822   unsigned CmpVal = MI.getOperand(2).getReg();
1823   unsigned NewVal = MI.getOperand(3).getReg();
1824
1825   unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1826   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1827   unsigned Mask = RegInfo.createVirtualRegister(RC);
1828   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1829   unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1830   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1831   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1832   unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1833   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1834   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1835   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1836   unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1837   unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1838   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1839   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1840   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1841   unsigned Success = RegInfo.createVirtualRegister(RC);
1842   unsigned LL, SC;
1843
1844   if (isMicroMips) {
1845     LL = Mips::LL_MM;
1846     SC = Mips::SC_MM;
1847   } else {
1848     LL = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1849                                  : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1850     SC = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1851                                  : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1852   }
1853
1854   // insert new blocks after the current block
1855   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1856   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1857   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1858   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1859   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1860   MachineFunction::iterator It = ++BB->getIterator();
1861   MF->insert(It, loop1MBB);
1862   MF->insert(It, loop2MBB);
1863   MF->insert(It, sinkMBB);
1864   MF->insert(It, exitMBB);
1865
1866   // Transfer the remainder of BB and its successor edges to exitMBB.
1867   exitMBB->splice(exitMBB->begin(), BB,
1868                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1869   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1870
1871   BB->addSuccessor(loop1MBB);
1872   loop1MBB->addSuccessor(sinkMBB);
1873   loop1MBB->addSuccessor(loop2MBB);
1874   loop2MBB->addSuccessor(loop1MBB);
1875   loop2MBB->addSuccessor(sinkMBB);
1876   sinkMBB->addSuccessor(exitMBB);
1877
1878   // FIXME: computation of newval2 can be moved to loop2MBB.
1879   //  thisMBB:
1880   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1881   //    and     alignedaddr,ptr,masklsb2
1882   //    andi    ptrlsb2,ptr,3
1883   //    xori    ptrlsb2,ptrlsb2,3              # Only for BE
1884   //    sll     shiftamt,ptrlsb2,3
1885   //    ori     maskupper,$0,255               # 0xff
1886   //    sll     mask,maskupper,shiftamt
1887   //    nor     mask2,$0,mask
1888   //    andi    maskedcmpval,cmpval,255
1889   //    sll     shiftedcmpval,maskedcmpval,shiftamt
1890   //    andi    maskednewval,newval,255
1891   //    sll     shiftednewval,maskednewval,shiftamt
1892   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1893   BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1894     .addReg(ABI.GetNullPtr()).addImm(-4);
1895   BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1896     .addReg(Ptr).addReg(MaskLSB2);
1897   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1898       .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1899   if (Subtarget.isLittle()) {
1900     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1901   } else {
1902     unsigned Off = RegInfo.createVirtualRegister(RC);
1903     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1904       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1905     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1906   }
1907   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1908     .addReg(Mips::ZERO).addImm(MaskImm);
1909   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1910     .addReg(MaskUpper).addReg(ShiftAmt);
1911   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1912   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1913     .addReg(CmpVal).addImm(MaskImm);
1914   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1915     .addReg(MaskedCmpVal).addReg(ShiftAmt);
1916   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1917     .addReg(NewVal).addImm(MaskImm);
1918   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1919     .addReg(MaskedNewVal).addReg(ShiftAmt);
1920
1921   //  loop1MBB:
1922   //    ll      oldval,0(alginedaddr)
1923   //    and     maskedoldval0,oldval,mask
1924   //    bne     maskedoldval0,shiftedcmpval,sinkMBB
1925   BB = loop1MBB;
1926   BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1927   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1928     .addReg(OldVal).addReg(Mask);
1929   BuildMI(BB, DL, TII->get(Mips::BNE))
1930     .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1931
1932   //  loop2MBB:
1933   //    and     maskedoldval1,oldval,mask2
1934   //    or      storeval,maskedoldval1,shiftednewval
1935   //    sc      success,storeval,0(alignedaddr)
1936   //    beq     success,$0,loop1MBB
1937   BB = loop2MBB;
1938   BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1939     .addReg(OldVal).addReg(Mask2);
1940   BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1941     .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1942   BuildMI(BB, DL, TII->get(SC), Success)
1943       .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1944   BuildMI(BB, DL, TII->get(Mips::BEQ))
1945       .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1946
1947   //  sinkMBB:
1948   //    srl     srlres,maskedoldval0,shiftamt
1949   //    sign_extend dest,srlres
1950   BB = sinkMBB;
1951
1952   BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1953       .addReg(MaskedOldVal0).addReg(ShiftAmt);
1954   BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1955
1956   MI.eraseFromParent(); // The instruction is gone now.
1957
1958   return exitMBB;
1959 }
1960
1961 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr &MI,
1962                                                  MachineBasicBlock *BB) const {
1963   MachineFunction *MF = BB->getParent();
1964   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1965   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1966   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1967   DebugLoc DL = MI.getDebugLoc();
1968   MachineBasicBlock::iterator II(MI);
1969
1970   unsigned Fc = MI.getOperand(1).getReg();
1971   const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1972
1973   unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1974
1975   BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1976       .addImm(0)
1977       .addReg(Fc)
1978       .addImm(Mips::sub_lo);
1979
1980   // We don't erase the original instruction, we just replace the condition
1981   // register with the 64-bit super-register.
1982   MI.getOperand(1).setReg(Fc2);
1983
1984   return BB;
1985 }
1986
1987 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1988   // The first operand is the chain, the second is the condition, the third is
1989   // the block to branch to if the condition is true.
1990   SDValue Chain = Op.getOperand(0);
1991   SDValue Dest = Op.getOperand(2);
1992   SDLoc DL(Op);
1993
1994   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1995   SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1996
1997   // Return if flag is not set by a floating point comparison.
1998   if (CondRes.getOpcode() != MipsISD::FPCmp)
1999     return Op;
2000
2001   SDValue CCNode  = CondRes.getOperand(2);
2002   Mips::CondCode CC =
2003     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
2004   unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
2005   SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
2006   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
2007   return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
2008                      FCC0, Dest, CondRes);
2009 }
2010
2011 SDValue MipsTargetLowering::
2012 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
2013 {
2014   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2015   SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
2016
2017   // Return if flag is not set by a floating point comparison.
2018   if (Cond.getOpcode() != MipsISD::FPCmp)
2019     return Op;
2020
2021   return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2022                       SDLoc(Op));
2023 }
2024
2025 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2026   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2027   SDValue Cond = createFPCmp(DAG, Op);
2028
2029   assert(Cond.getOpcode() == MipsISD::FPCmp &&
2030          "Floating point operand expected.");
2031
2032   SDLoc DL(Op);
2033   SDValue True  = DAG.getConstant(1, DL, MVT::i32);
2034   SDValue False = DAG.getConstant(0, DL, MVT::i32);
2035
2036   return createCMovFP(DAG, Cond, True, False, DL);
2037 }
2038
2039 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
2040                                                SelectionDAG &DAG) const {
2041   EVT Ty = Op.getValueType();
2042   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2043   const GlobalValue *GV = N->getGlobal();
2044
2045   if (!isPositionIndependent()) {
2046     const MipsTargetObjectFile *TLOF =
2047         static_cast<const MipsTargetObjectFile *>(
2048             getTargetMachine().getObjFileLowering());
2049     const GlobalObject *GO = GV->getBaseObject();
2050     if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
2051       // %gp_rel relocation
2052       return getAddrGPRel(N, SDLoc(N), Ty, DAG);
2053
2054                                  // %hi/%lo relocation
2055     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2056                                  // %highest/%higher/%hi/%lo relocation
2057                                  : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2058   }
2059
2060   // Every other architecture would use shouldAssumeDSOLocal in here, but
2061   // mips is special.
2062   // * In PIC code mips requires got loads even for local statics!
2063   // * To save on got entries, for local statics the got entry contains the
2064   //   page and an additional add instruction takes care of the low bits.
2065   // * It is legal to access a hidden symbol with a non hidden undefined,
2066   //   so one cannot guarantee that all access to a hidden symbol will know
2067   //   it is hidden.
2068   // * Mips linkers don't support creating a page and a full got entry for
2069   //   the same symbol.
2070   // * Given all that, we have to use a full got entry for hidden symbols :-(
2071   if (GV->hasLocalLinkage())
2072     return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2073
2074   if (LargeGOT)
2075     return getAddrGlobalLargeGOT(
2076         N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
2077         DAG.getEntryNode(),
2078         MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2079
2080   return getAddrGlobal(
2081       N, SDLoc(N), Ty, DAG,
2082       (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT,
2083       DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2084 }
2085
2086 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2087                                               SelectionDAG &DAG) const {
2088   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2089   EVT Ty = Op.getValueType();
2090
2091   if (!isPositionIndependent())
2092     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2093                                 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2094
2095   return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2096 }
2097
2098 SDValue MipsTargetLowering::
2099 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2100 {
2101   // If the relocation model is PIC, use the General Dynamic TLS Model or
2102   // Local Dynamic TLS model, otherwise use the Initial Exec or
2103   // Local Exec TLS Model.
2104
2105   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2106   if (DAG.getTarget().Options.EmulatedTLS)
2107     return LowerToTLSEmulatedModel(GA, DAG);
2108
2109   SDLoc DL(GA);
2110   const GlobalValue *GV = GA->getGlobal();
2111   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2112
2113   TLSModel::Model model = getTargetMachine().getTLSModel(GV);
2114
2115   if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2116     // General Dynamic and Local Dynamic TLS Model.
2117     unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2118                                                       : MipsII::MO_TLSGD;
2119
2120     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2121     SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2122                                    getGlobalReg(DAG, PtrVT), TGA);
2123     unsigned PtrSize = PtrVT.getSizeInBits();
2124     IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2125
2126     SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2127
2128     ArgListTy Args;
2129     ArgListEntry Entry;
2130     Entry.Node = Argument;
2131     Entry.Ty = PtrTy;
2132     Args.push_back(Entry);
2133
2134     TargetLowering::CallLoweringInfo CLI(DAG);
2135     CLI.setDebugLoc(DL)
2136         .setChain(DAG.getEntryNode())
2137         .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2138     std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2139
2140     SDValue Ret = CallResult.first;
2141
2142     if (model != TLSModel::LocalDynamic)
2143       return Ret;
2144
2145     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2146                                                MipsII::MO_DTPREL_HI);
2147     SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
2148     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2149                                                MipsII::MO_DTPREL_LO);
2150     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2151     SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2152     return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2153   }
2154
2155   SDValue Offset;
2156   if (model == TLSModel::InitialExec) {
2157     // Initial Exec TLS Model
2158     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2159                                              MipsII::MO_GOTTPREL);
2160     TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2161                       TGA);
2162     Offset =
2163         DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2164   } else {
2165     // Local Exec TLS Model
2166     assert(model == TLSModel::LocalExec);
2167     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2168                                                MipsII::MO_TPREL_HI);
2169     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2170                                                MipsII::MO_TPREL_LO);
2171     SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
2172     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2173     Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2174   }
2175
2176   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2177   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2178 }
2179
2180 SDValue MipsTargetLowering::
2181 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2182 {
2183   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2184   EVT Ty = Op.getValueType();
2185
2186   if (!isPositionIndependent())
2187     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2188                                 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2189
2190   return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2191 }
2192
2193 SDValue MipsTargetLowering::
2194 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2195 {
2196   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2197   EVT Ty = Op.getValueType();
2198
2199   if (!isPositionIndependent()) {
2200     const MipsTargetObjectFile *TLOF =
2201         static_cast<const MipsTargetObjectFile *>(
2202             getTargetMachine().getObjFileLowering());
2203
2204     if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2205                                        getTargetMachine()))
2206       // %gp_rel relocation
2207       return getAddrGPRel(N, SDLoc(N), Ty, DAG);
2208
2209     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2210                                 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2211   }
2212
2213  return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2214 }
2215
2216 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2217   MachineFunction &MF = DAG.getMachineFunction();
2218   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2219
2220   SDLoc DL(Op);
2221   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2222                                  getPointerTy(MF.getDataLayout()));
2223
2224   // vastart just stores the address of the VarArgsFrameIndex slot into the
2225   // memory location argument.
2226   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2227   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2228                       MachinePointerInfo(SV));
2229 }
2230
2231 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2232   SDNode *Node = Op.getNode();
2233   EVT VT = Node->getValueType(0);
2234   SDValue Chain = Node->getOperand(0);
2235   SDValue VAListPtr = Node->getOperand(1);
2236   unsigned Align = Node->getConstantOperandVal(3);
2237   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2238   SDLoc DL(Node);
2239   unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2240
2241   SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2242                                    VAListPtr, MachinePointerInfo(SV));
2243   SDValue VAList = VAListLoad;
2244
2245   // Re-align the pointer if necessary.
2246   // It should only ever be necessary for 64-bit types on O32 since the minimum
2247   // argument alignment is the same as the maximum type alignment for N32/N64.
2248   //
2249   // FIXME: We currently align too often. The code generator doesn't notice
2250   //        when the pointer is still aligned from the last va_arg (or pair of
2251   //        va_args for the i64 on O32 case).
2252   if (Align > getMinStackArgumentAlignment()) {
2253     assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
2254
2255     VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2256                          DAG.getConstant(Align - 1, DL, VAList.getValueType()));
2257
2258     VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
2259                          DAG.getConstant(-(int64_t)Align, DL,
2260                                          VAList.getValueType()));
2261   }
2262
2263   // Increment the pointer, VAList, to the next vaarg.
2264   auto &TD = DAG.getDataLayout();
2265   unsigned ArgSizeInBytes =
2266       TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
2267   SDValue Tmp3 =
2268       DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2269                   DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2270                                   DL, VAList.getValueType()));
2271   // Store the incremented VAList to the legalized pointer
2272   Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2273                        MachinePointerInfo(SV));
2274
2275   // In big-endian mode we must adjust the pointer when the load size is smaller
2276   // than the argument slot size. We must also reduce the known alignment to
2277   // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2278   // the correct half of the slot, and reduce the alignment from 8 (slot
2279   // alignment) down to 4 (type alignment).
2280   if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2281     unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2282     VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2283                          DAG.getIntPtrConstant(Adjustment, DL));
2284   }
2285   // Load the actual argument out of the pointer VAList
2286   return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2287 }
2288
2289 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
2290                                 bool HasExtractInsert) {
2291   EVT TyX = Op.getOperand(0).getValueType();
2292   EVT TyY = Op.getOperand(1).getValueType();
2293   SDLoc DL(Op);
2294   SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2295   SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2296   SDValue Res;
2297
2298   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2299   // to i32.
2300   SDValue X = (TyX == MVT::f32) ?
2301     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2302     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2303                 Const1);
2304   SDValue Y = (TyY == MVT::f32) ?
2305     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2306     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2307                 Const1);
2308
2309   if (HasExtractInsert) {
2310     // ext  E, Y, 31, 1  ; extract bit31 of Y
2311     // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
2312     SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2313     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2314   } else {
2315     // sll SllX, X, 1
2316     // srl SrlX, SllX, 1
2317     // srl SrlY, Y, 31
2318     // sll SllY, SrlX, 31
2319     // or  Or, SrlX, SllY
2320     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2321     SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2322     SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2323     SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2324     Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2325   }
2326
2327   if (TyX == MVT::f32)
2328     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2329
2330   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2331                              Op.getOperand(0),
2332                              DAG.getConstant(0, DL, MVT::i32));
2333   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2334 }
2335
2336 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
2337                                 bool HasExtractInsert) {
2338   unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2339   unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2340   EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2341   SDLoc DL(Op);
2342   SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2343
2344   // Bitcast to integer nodes.
2345   SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2346   SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2347
2348   if (HasExtractInsert) {
2349     // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
2350     // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
2351     SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2352                             DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2353
2354     if (WidthX > WidthY)
2355       E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2356     else if (WidthY > WidthX)
2357       E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2358
2359     SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2360                             DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2361                             X);
2362     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2363   }
2364
2365   // (d)sll SllX, X, 1
2366   // (d)srl SrlX, SllX, 1
2367   // (d)srl SrlY, Y, width(Y)-1
2368   // (d)sll SllY, SrlX, width(Y)-1
2369   // or     Or, SrlX, SllY
2370   SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2371   SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2372   SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2373                              DAG.getConstant(WidthY - 1, DL, MVT::i32));
2374
2375   if (WidthX > WidthY)
2376     SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2377   else if (WidthY > WidthX)
2378     SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2379
2380   SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2381                              DAG.getConstant(WidthX - 1, DL, MVT::i32));
2382   SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2383   return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2384 }
2385
2386 SDValue
2387 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2388   if (Subtarget.isGP64bit())
2389     return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2390
2391   return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2392 }
2393
2394 SDValue MipsTargetLowering::
2395 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2396   // check the depth
2397   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2398          "Frame address can only be determined for current frame.");
2399
2400   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2401   MFI.setFrameAddressIsTaken(true);
2402   EVT VT = Op.getValueType();
2403   SDLoc DL(Op);
2404   SDValue FrameAddr = DAG.getCopyFromReg(
2405       DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2406   return FrameAddr;
2407 }
2408
2409 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2410                                             SelectionDAG &DAG) const {
2411   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2412     return SDValue();
2413
2414   // check the depth
2415   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2416          "Return address can be determined only for current frame.");
2417
2418   MachineFunction &MF = DAG.getMachineFunction();
2419   MachineFrameInfo &MFI = MF.getFrameInfo();
2420   MVT VT = Op.getSimpleValueType();
2421   unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2422   MFI.setReturnAddressIsTaken(true);
2423
2424   // Return RA, which contains the return address. Mark it an implicit live-in.
2425   unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2426   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2427 }
2428
2429 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2430 // generated from __builtin_eh_return (offset, handler)
2431 // The effect of this is to adjust the stack pointer by "offset"
2432 // and then branch to "handler".
2433 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2434                                                                      const {
2435   MachineFunction &MF = DAG.getMachineFunction();
2436   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2437
2438   MipsFI->setCallsEhReturn();
2439   SDValue Chain     = Op.getOperand(0);
2440   SDValue Offset    = Op.getOperand(1);
2441   SDValue Handler   = Op.getOperand(2);
2442   SDLoc DL(Op);
2443   EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2444
2445   // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2446   // EH_RETURN nodes, so that instructions are emitted back-to-back.
2447   unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2448   unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2449   Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2450   Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2451   return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2452                      DAG.getRegister(OffsetReg, Ty),
2453                      DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2454                      Chain.getValue(1));
2455 }
2456
2457 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2458                                               SelectionDAG &DAG) const {
2459   // FIXME: Need pseudo-fence for 'singlethread' fences
2460   // FIXME: Set SType for weaker fences where supported/appropriate.
2461   unsigned SType = 0;
2462   SDLoc DL(Op);
2463   return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2464                      DAG.getConstant(SType, DL, MVT::i32));
2465 }
2466
2467 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2468                                                 SelectionDAG &DAG) const {
2469   SDLoc DL(Op);
2470   MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2471
2472   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2473   SDValue Shamt = Op.getOperand(2);
2474   // if shamt < (VT.bits):
2475   //  lo = (shl lo, shamt)
2476   //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2477   // else:
2478   //  lo = 0
2479   //  hi = (shl lo, shamt[4:0])
2480   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2481                             DAG.getConstant(-1, DL, MVT::i32));
2482   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2483                                       DAG.getConstant(1, DL, VT));
2484   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2485   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2486   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2487   SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2488   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2489                              DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2490   Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2491                    DAG.getConstant(0, DL, VT), ShiftLeftLo);
2492   Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2493
2494   SDValue Ops[2] = {Lo, Hi};
2495   return DAG.getMergeValues(Ops, DL);
2496 }
2497
2498 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2499                                                  bool IsSRA) const {
2500   SDLoc DL(Op);
2501   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2502   SDValue Shamt = Op.getOperand(2);
2503   MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2504
2505   // if shamt < (VT.bits):
2506   //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2507   //  if isSRA:
2508   //    hi = (sra hi, shamt)
2509   //  else:
2510   //    hi = (srl hi, shamt)
2511   // else:
2512   //  if isSRA:
2513   //   lo = (sra hi, shamt[4:0])
2514   //   hi = (sra hi, 31)
2515   //  else:
2516   //   lo = (srl hi, shamt[4:0])
2517   //   hi = 0
2518   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2519                             DAG.getConstant(-1, DL, MVT::i32));
2520   SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2521                                      DAG.getConstant(1, DL, VT));
2522   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2523   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2524   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2525   SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2526                                      DL, VT, Hi, Shamt);
2527   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2528                              DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2529   SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2530                             DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2531   Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2532   Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2533                    IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2534
2535   SDValue Ops[2] = {Lo, Hi};
2536   return DAG.getMergeValues(Ops, DL);
2537 }
2538
2539 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2540                             SDValue Chain, SDValue Src, unsigned Offset) {
2541   SDValue Ptr = LD->getBasePtr();
2542   EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2543   EVT BasePtrVT = Ptr.getValueType();
2544   SDLoc DL(LD);
2545   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2546
2547   if (Offset)
2548     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2549                       DAG.getConstant(Offset, DL, BasePtrVT));
2550
2551   SDValue Ops[] = { Chain, Ptr, Src };
2552   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2553                                  LD->getMemOperand());
2554 }
2555
2556 // Expand an unaligned 32 or 64-bit integer load node.
2557 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2558   LoadSDNode *LD = cast<LoadSDNode>(Op);
2559   EVT MemVT = LD->getMemoryVT();
2560
2561   if (Subtarget.systemSupportsUnalignedAccess())
2562     return Op;
2563
2564   // Return if load is aligned or if MemVT is neither i32 nor i64.
2565   if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2566       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2567     return SDValue();
2568
2569   bool IsLittle = Subtarget.isLittle();
2570   EVT VT = Op.getValueType();
2571   ISD::LoadExtType ExtType = LD->getExtensionType();
2572   SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2573
2574   assert((VT == MVT::i32) || (VT == MVT::i64));
2575
2576   // Expand
2577   //  (set dst, (i64 (load baseptr)))
2578   // to
2579   //  (set tmp, (ldl (add baseptr, 7), undef))
2580   //  (set dst, (ldr baseptr, tmp))
2581   if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2582     SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2583                                IsLittle ? 7 : 0);
2584     return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2585                         IsLittle ? 0 : 7);
2586   }
2587
2588   SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2589                              IsLittle ? 3 : 0);
2590   SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2591                              IsLittle ? 0 : 3);
2592
2593   // Expand
2594   //  (set dst, (i32 (load baseptr))) or
2595   //  (set dst, (i64 (sextload baseptr))) or
2596   //  (set dst, (i64 (extload baseptr)))
2597   // to
2598   //  (set tmp, (lwl (add baseptr, 3), undef))
2599   //  (set dst, (lwr baseptr, tmp))
2600   if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2601       (ExtType == ISD::EXTLOAD))
2602     return LWR;
2603
2604   assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2605
2606   // Expand
2607   //  (set dst, (i64 (zextload baseptr)))
2608   // to
2609   //  (set tmp0, (lwl (add baseptr, 3), undef))
2610   //  (set tmp1, (lwr baseptr, tmp0))
2611   //  (set tmp2, (shl tmp1, 32))
2612   //  (set dst, (srl tmp2, 32))
2613   SDLoc DL(LD);
2614   SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2615   SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2616   SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2617   SDValue Ops[] = { SRL, LWR.getValue(1) };
2618   return DAG.getMergeValues(Ops, DL);
2619 }
2620
2621 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2622                              SDValue Chain, unsigned Offset) {
2623   SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2624   EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2625   SDLoc DL(SD);
2626   SDVTList VTList = DAG.getVTList(MVT::Other);
2627
2628   if (Offset)
2629     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2630                       DAG.getConstant(Offset, DL, BasePtrVT));
2631
2632   SDValue Ops[] = { Chain, Value, Ptr };
2633   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2634                                  SD->getMemOperand());
2635 }
2636
2637 // Expand an unaligned 32 or 64-bit integer store node.
2638 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2639                                       bool IsLittle) {
2640   SDValue Value = SD->getValue(), Chain = SD->getChain();
2641   EVT VT = Value.getValueType();
2642
2643   // Expand
2644   //  (store val, baseptr) or
2645   //  (truncstore val, baseptr)
2646   // to
2647   //  (swl val, (add baseptr, 3))
2648   //  (swr val, baseptr)
2649   if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2650     SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2651                                 IsLittle ? 3 : 0);
2652     return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2653   }
2654
2655   assert(VT == MVT::i64);
2656
2657   // Expand
2658   //  (store val, baseptr)
2659   // to
2660   //  (sdl val, (add baseptr, 7))
2661   //  (sdr val, baseptr)
2662   SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2663   return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2664 }
2665
2666 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2667 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2668   SDValue Val = SD->getValue();
2669
2670   if (Val.getOpcode() != ISD::FP_TO_SINT)
2671     return SDValue();
2672
2673   EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2674   SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2675                            Val.getOperand(0));
2676   return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2677                       SD->getPointerInfo(), SD->getAlignment(),
2678                       SD->getMemOperand()->getFlags());
2679 }
2680
2681 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2682   StoreSDNode *SD = cast<StoreSDNode>(Op);
2683   EVT MemVT = SD->getMemoryVT();
2684
2685   // Lower unaligned integer stores.
2686   if (!Subtarget.systemSupportsUnalignedAccess() &&
2687       (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2688       ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2689     return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2690
2691   return lowerFP_TO_SINT_STORE(SD, DAG);
2692 }
2693
2694 SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2695                                               SelectionDAG &DAG) const {
2696
2697   // Return a fixed StackObject with offset 0 which points to the old stack
2698   // pointer.
2699   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2700   EVT ValTy = Op->getValueType(0);
2701   int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2702   return DAG.getFrameIndex(FI, ValTy);
2703 }
2704
2705 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2706                                             SelectionDAG &DAG) const {
2707   EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2708   SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2709                               Op.getOperand(0));
2710   return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2711 }
2712
2713 //===----------------------------------------------------------------------===//
2714 //                      Calling Convention Implementation
2715 //===----------------------------------------------------------------------===//
2716
2717 //===----------------------------------------------------------------------===//
2718 // TODO: Implement a generic logic using tblgen that can support this.
2719 // Mips O32 ABI rules:
2720 // ---
2721 // i32 - Passed in A0, A1, A2, A3 and stack
2722 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2723 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
2724 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2725 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2726 //       not used, it must be shadowed. If only A3 is available, shadow it and
2727 //       go to stack.
2728 // vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
2729 // vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
2730 //         with the remainder spilled to the stack.
2731 // vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
2732 //         spilling the remainder to the stack.
2733 //
2734 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2735 //===----------------------------------------------------------------------===//
2736
2737 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2738                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2739                        CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2740   const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2741       State.getMachineFunction().getSubtarget());
2742
2743   static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2744
2745   const MipsCCState * MipsState = static_cast<MipsCCState *>(&State);
2746
2747   static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2748
2749   static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 };
2750
2751   // Do not process byval args here.
2752   if (ArgFlags.isByVal())
2753     return true;
2754
2755   // Promote i8 and i16
2756   if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2757     if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2758       LocVT = MVT::i32;
2759       if (ArgFlags.isSExt())
2760         LocInfo = CCValAssign::SExtUpper;
2761       else if (ArgFlags.isZExt())
2762         LocInfo = CCValAssign::ZExtUpper;
2763       else
2764         LocInfo = CCValAssign::AExtUpper;
2765     }
2766   }
2767
2768   // Promote i8 and i16
2769   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2770     LocVT = MVT::i32;
2771     if (ArgFlags.isSExt())
2772       LocInfo = CCValAssign::SExt;
2773     else if (ArgFlags.isZExt())
2774       LocInfo = CCValAssign::ZExt;
2775     else
2776       LocInfo = CCValAssign::AExt;
2777   }
2778
2779   unsigned Reg;
2780
2781   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2782   // is true: function is vararg, argument is 3rd or higher, there is previous
2783   // argument which is not f32 or f64.
2784   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2785                                 State.getFirstUnallocated(F32Regs) != ValNo;
2786   unsigned OrigAlign = ArgFlags.getOrigAlign();
2787   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2788   bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo);
2789
2790   // The MIPS vector ABI for floats passes them in a pair of registers
2791   if (ValVT == MVT::i32 && isVectorFloat) {
2792     // This is the start of an vector that was scalarized into an unknown number
2793     // of components. It doesn't matter how many there are. Allocate one of the
2794     // notional 8 byte aligned registers which map onto the argument stack, and
2795     // shadow the register lost to alignment requirements.
2796     if (ArgFlags.isSplit()) {
2797       Reg = State.AllocateReg(FloatVectorIntRegs);
2798       if (Reg == Mips::A2)
2799         State.AllocateReg(Mips::A1);
2800       else if (Reg == 0)
2801         State.AllocateReg(Mips::A3);
2802     } else {
2803       // If we're an intermediate component of the split, we can just attempt to
2804       // allocate a register directly.
2805       Reg = State.AllocateReg(IntRegs);
2806     }
2807   } else if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2808     Reg = State.AllocateReg(IntRegs);
2809     // If this is the first part of an i64 arg,
2810     // the allocated register must be either A0 or A2.
2811     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2812       Reg = State.AllocateReg(IntRegs);
2813     LocVT = MVT::i32;
2814   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2815     // Allocate int register and shadow next int register. If first
2816     // available register is Mips::A1 or Mips::A3, shadow it too.
2817     Reg = State.AllocateReg(IntRegs);
2818     if (Reg == Mips::A1 || Reg == Mips::A3)
2819       Reg = State.AllocateReg(IntRegs);
2820     State.AllocateReg(IntRegs);
2821     LocVT = MVT::i32;
2822   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2823     // we are guaranteed to find an available float register
2824     if (ValVT == MVT::f32) {
2825       Reg = State.AllocateReg(F32Regs);
2826       // Shadow int register
2827       State.AllocateReg(IntRegs);
2828     } else {
2829       Reg = State.AllocateReg(F64Regs);
2830       // Shadow int registers
2831       unsigned Reg2 = State.AllocateReg(IntRegs);
2832       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2833         State.AllocateReg(IntRegs);
2834       State.AllocateReg(IntRegs);
2835     }
2836   } else
2837     llvm_unreachable("Cannot handle this ValVT.");
2838
2839   if (!Reg) {
2840     unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2841                                           OrigAlign);
2842     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2843   } else
2844     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2845
2846   return false;
2847 }
2848
2849 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2850                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2851                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2852   static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2853
2854   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2855 }
2856
2857 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2858                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2859                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2860   static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2861
2862   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2863 }
2864
2865 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2866                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2867                        CCState &State) LLVM_ATTRIBUTE_UNUSED;
2868
2869 #include "MipsGenCallingConv.inc"
2870
2871 //===----------------------------------------------------------------------===//
2872 //                  Call Calling Convention Implementation
2873 //===----------------------------------------------------------------------===//
2874
2875 // Return next O32 integer argument register.
2876 static unsigned getNextIntArgReg(unsigned Reg) {
2877   assert((Reg == Mips::A0) || (Reg == Mips::A2));
2878   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2879 }
2880
2881 SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2882                                            SDValue Chain, SDValue Arg,
2883                                            const SDLoc &DL, bool IsTailCall,
2884                                            SelectionDAG &DAG) const {
2885   if (!IsTailCall) {
2886     SDValue PtrOff =
2887         DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2888                     DAG.getIntPtrConstant(Offset, DL));
2889     return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
2890   }
2891
2892   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2893   int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2894   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2895   return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2896                       /* Alignment = */ 0, MachineMemOperand::MOVolatile);
2897 }
2898
2899 void MipsTargetLowering::
2900 getOpndList(SmallVectorImpl<SDValue> &Ops,
2901             std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2902             bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2903             bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2904             SDValue Chain) const {
2905   // Insert node "GP copy globalreg" before call to function.
2906   //
2907   // R_MIPS_CALL* operators (emitted when non-internal functions are called
2908   // in PIC mode) allow symbols to be resolved via lazy binding.
2909   // The lazy binding stub requires GP to point to the GOT.
2910   // Note that we don't need GP to point to the GOT for indirect calls
2911   // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2912   // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2913   // used for the function (that is, Mips linker doesn't generate lazy binding
2914   // stub for a function whose address is taken in the program).
2915   if (IsPICCall && !InternalLinkage && IsCallReloc) {
2916     unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2917     EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2918     RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2919   }
2920
2921   // Build a sequence of copy-to-reg nodes chained together with token
2922   // chain and flag operands which copy the outgoing args into registers.
2923   // The InFlag in necessary since all emitted instructions must be
2924   // stuck together.
2925   SDValue InFlag;
2926
2927   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2928     Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2929                                  RegsToPass[i].second, InFlag);
2930     InFlag = Chain.getValue(1);
2931   }
2932
2933   // Add argument registers to the end of the list so that they are
2934   // known live into the call.
2935   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2936     Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2937                                       RegsToPass[i].second.getValueType()));
2938
2939   // Add a register mask operand representing the call-preserved registers.
2940   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2941   const uint32_t *Mask =
2942       TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2943   assert(Mask && "Missing call preserved mask for calling convention");
2944   if (Subtarget.inMips16HardFloat()) {
2945     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2946       llvm::StringRef Sym = G->getGlobal()->getName();
2947       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2948       if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2949         Mask = MipsRegisterInfo::getMips16RetHelperMask();
2950       }
2951     }
2952   }
2953   Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2954
2955   if (InFlag.getNode())
2956     Ops.push_back(InFlag);
2957 }
2958
2959 /// LowerCall - functions arguments are copied from virtual regs to
2960 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2961 SDValue
2962 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2963                               SmallVectorImpl<SDValue> &InVals) const {
2964   SelectionDAG &DAG                     = CLI.DAG;
2965   SDLoc DL                              = CLI.DL;
2966   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2967   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2968   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2969   SDValue Chain                         = CLI.Chain;
2970   SDValue Callee                        = CLI.Callee;
2971   bool &IsTailCall                      = CLI.IsTailCall;
2972   CallingConv::ID CallConv              = CLI.CallConv;
2973   bool IsVarArg                         = CLI.IsVarArg;
2974
2975   MachineFunction &MF = DAG.getMachineFunction();
2976   MachineFrameInfo &MFI = MF.getFrameInfo();
2977   const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2978   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2979   bool IsPIC = isPositionIndependent();
2980
2981   // Analyze operands of the call, assigning locations to each operand.
2982   SmallVector<CCValAssign, 16> ArgLocs;
2983   MipsCCState CCInfo(
2984       CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2985       MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2986
2987   // Allocate the reserved argument area. It seems strange to do this from the
2988   // caller side but removing it breaks the frame size calculation.
2989   CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2990
2991   const ExternalSymbolSDNode *ES =
2992       dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
2993   CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
2994                              ES ? ES->getSymbol() : nullptr);
2995
2996   // Get a count of how many bytes are to be pushed on the stack.
2997   unsigned NextStackOffset = CCInfo.getNextStackOffset();
2998
2999   // Check if it's really possible to do a tail call. Restrict it to functions
3000   // that are part of this compilation unit.
3001   bool InternalLinkage = false;
3002   if (IsTailCall) {
3003     IsTailCall = isEligibleForTailCallOptimization(
3004         CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
3005      if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3006       InternalLinkage = G->getGlobal()->hasInternalLinkage();
3007       IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
3008                      G->getGlobal()->hasPrivateLinkage() ||
3009                      G->getGlobal()->hasHiddenVisibility() ||
3010                      G->getGlobal()->hasProtectedVisibility());
3011      }
3012   }
3013   if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3014     report_fatal_error("failed to perform tail call elimination on a call "
3015                        "site marked musttail");
3016
3017   if (IsTailCall)
3018     ++NumTailCalls;
3019
3020   // Chain is the output chain of the last Load/Store or CopyToReg node.
3021   // ByValChain is the output chain of the last Memcpy node created for copying
3022   // byval arguments to the stack.
3023   unsigned StackAlignment = TFL->getStackAlignment();
3024   NextStackOffset = alignTo(NextStackOffset, StackAlignment);
3025   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
3026
3027   if (!IsTailCall)
3028     Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL);
3029
3030   SDValue StackPtr =
3031       DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
3032                          getPointerTy(DAG.getDataLayout()));
3033
3034   std::deque< std::pair<unsigned, SDValue> > RegsToPass;
3035   SmallVector<SDValue, 8> MemOpChains;
3036
3037   CCInfo.rewindByValRegsInfo();
3038
3039   // Walk the register/memloc assignments, inserting copies/loads.
3040   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3041     SDValue Arg = OutVals[i];
3042     CCValAssign &VA = ArgLocs[i];
3043     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3044     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3045     bool UseUpperBits = false;
3046
3047     // ByVal Arg.
3048     if (Flags.isByVal()) {
3049       unsigned FirstByValReg, LastByValReg;
3050       unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3051       CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3052
3053       assert(Flags.getByValSize() &&
3054              "ByVal args of size 0 should have been ignored by front-end.");
3055       assert(ByValIdx < CCInfo.getInRegsParamsCount());
3056       assert(!IsTailCall &&
3057              "Do not tail-call optimize if there is a byval argument.");
3058       passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3059                    FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3060                    VA);
3061       CCInfo.nextInRegsParam();
3062       continue;
3063     }
3064
3065     // Promote the value if needed.
3066     switch (VA.getLocInfo()) {
3067     default:
3068       llvm_unreachable("Unknown loc info!");
3069     case CCValAssign::Full:
3070       if (VA.isRegLoc()) {
3071         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3072             (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3073             (ValVT == MVT::i64 && LocVT == MVT::f64))
3074           Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3075         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3076           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3077                                    Arg, DAG.getConstant(0, DL, MVT::i32));
3078           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3079                                    Arg, DAG.getConstant(1, DL, MVT::i32));
3080           if (!Subtarget.isLittle())
3081             std::swap(Lo, Hi);
3082           unsigned LocRegLo = VA.getLocReg();
3083           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3084           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3085           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3086           continue;
3087         }
3088       }
3089       break;
3090     case CCValAssign::BCvt:
3091       Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3092       break;
3093     case CCValAssign::SExtUpper:
3094       UseUpperBits = true;
3095       LLVM_FALLTHROUGH;
3096     case CCValAssign::SExt:
3097       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3098       break;
3099     case CCValAssign::ZExtUpper:
3100       UseUpperBits = true;
3101       LLVM_FALLTHROUGH;
3102     case CCValAssign::ZExt:
3103       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3104       break;
3105     case CCValAssign::AExtUpper:
3106       UseUpperBits = true;
3107       LLVM_FALLTHROUGH;
3108     case CCValAssign::AExt:
3109       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3110       break;
3111     }
3112
3113     if (UseUpperBits) {
3114       unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3115       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3116       Arg = DAG.getNode(
3117           ISD::SHL, DL, VA.getLocVT(), Arg,
3118           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3119     }
3120
3121     // Arguments that can be passed on register must be kept at
3122     // RegsToPass vector
3123     if (VA.isRegLoc()) {
3124       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3125       continue;
3126     }
3127
3128     // Register can't get to this point...
3129     assert(VA.isMemLoc());
3130
3131     // emit ISD::STORE whichs stores the
3132     // parameter value to a stack Location
3133     MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3134                                          Chain, Arg, DL, IsTailCall, DAG));
3135   }
3136
3137   // Transform all store nodes into one single node because all store
3138   // nodes are independent of each other.
3139   if (!MemOpChains.empty())
3140     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3141
3142   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3143   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3144   // node so that legalize doesn't hack it.
3145
3146   SDValue CalleeLo;
3147   EVT Ty = Callee.getValueType();
3148   bool GlobalOrExternal = false, IsCallReloc = false;
3149
3150   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3151     if (IsPIC) {
3152       const GlobalValue *Val = G->getGlobal();
3153       InternalLinkage = Val->hasInternalLinkage();
3154
3155       if (InternalLinkage)
3156         Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3157       else if (LargeGOT) {
3158         Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3159                                        MipsII::MO_CALL_LO16, Chain,
3160                                        FuncInfo->callPtrInfo(Val));
3161         IsCallReloc = true;
3162       } else {
3163         Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3164                                FuncInfo->callPtrInfo(Val));
3165         IsCallReloc = true;
3166       }
3167     } else
3168       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3169                                           getPointerTy(DAG.getDataLayout()), 0,
3170                                           MipsII::MO_NO_FLAG);
3171     GlobalOrExternal = true;
3172   }
3173   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3174     const char *Sym = S->getSymbol();
3175
3176     if (!IsPIC) // static
3177       Callee = DAG.getTargetExternalSymbol(
3178           Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
3179     else if (LargeGOT) {
3180       Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3181                                      MipsII::MO_CALL_LO16, Chain,
3182                                      FuncInfo->callPtrInfo(Sym));
3183       IsCallReloc = true;
3184     } else { // PIC
3185       Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3186                              FuncInfo->callPtrInfo(Sym));
3187       IsCallReloc = true;
3188     }
3189
3190     GlobalOrExternal = true;
3191   }
3192
3193   SmallVector<SDValue, 8> Ops(1, Chain);
3194   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3195
3196   getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3197               IsCallReloc, CLI, Callee, Chain);
3198
3199   if (IsTailCall) {
3200     MF.getFrameInfo().setHasTailCall();
3201     return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3202   }
3203
3204   Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3205   SDValue InFlag = Chain.getValue(1);
3206
3207   // Create the CALLSEQ_END node.
3208   Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3209                              DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3210   InFlag = Chain.getValue(1);
3211
3212   // Handle result values, copying them out of physregs into vregs that we
3213   // return.
3214   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3215                          InVals, CLI);
3216 }
3217
3218 /// LowerCallResult - Lower the result values of a call into the
3219 /// appropriate copies out of appropriate physical registers.
3220 SDValue MipsTargetLowering::LowerCallResult(
3221     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
3222     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3223     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3224     TargetLowering::CallLoweringInfo &CLI) const {
3225   // Assign locations to each value returned by this call.
3226   SmallVector<CCValAssign, 16> RVLocs;
3227   MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3228                      *DAG.getContext());
3229
3230   const ExternalSymbolSDNode *ES =
3231       dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3232   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3233                            ES ? ES->getSymbol() : nullptr);
3234
3235   // Copy all of the result registers out of their specified physreg.
3236   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3237     CCValAssign &VA = RVLocs[i];
3238     assert(VA.isRegLoc() && "Can only return in registers!");
3239
3240     SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3241                                      RVLocs[i].getLocVT(), InFlag);
3242     Chain = Val.getValue(1);
3243     InFlag = Val.getValue(2);
3244
3245     if (VA.isUpperBitsInLoc()) {
3246       unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3247       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3248       unsigned Shift =
3249           VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3250       Val = DAG.getNode(
3251           Shift, DL, VA.getLocVT(), Val,
3252           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3253     }
3254
3255     switch (VA.getLocInfo()) {
3256     default:
3257       llvm_unreachable("Unknown loc info!");
3258     case CCValAssign::Full:
3259       break;
3260     case CCValAssign::BCvt:
3261       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3262       break;
3263     case CCValAssign::AExt:
3264     case CCValAssign::AExtUpper:
3265       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3266       break;
3267     case CCValAssign::ZExt:
3268     case CCValAssign::ZExtUpper:
3269       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3270                         DAG.getValueType(VA.getValVT()));
3271       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3272       break;
3273     case CCValAssign::SExt:
3274     case CCValAssign::SExtUpper:
3275       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3276                         DAG.getValueType(VA.getValVT()));
3277       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3278       break;
3279     }
3280
3281     InVals.push_back(Val);
3282   }
3283
3284   return Chain;
3285 }
3286
3287 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
3288                                       EVT ArgVT, const SDLoc &DL,
3289                                       SelectionDAG &DAG) {
3290   MVT LocVT = VA.getLocVT();
3291   EVT ValVT = VA.getValVT();
3292
3293   // Shift into the upper bits if necessary.
3294   switch (VA.getLocInfo()) {
3295   default:
3296     break;
3297   case CCValAssign::AExtUpper:
3298   case CCValAssign::SExtUpper:
3299   case CCValAssign::ZExtUpper: {
3300     unsigned ValSizeInBits = ArgVT.getSizeInBits();
3301     unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3302     unsigned Opcode =
3303         VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3304     Val = DAG.getNode(
3305         Opcode, DL, VA.getLocVT(), Val,
3306         DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3307     break;
3308   }
3309   }
3310
3311   // If this is an value smaller than the argument slot size (32-bit for O32,
3312   // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3313   // size. Extract the value and insert any appropriate assertions regarding
3314   // sign/zero extension.
3315   switch (VA.getLocInfo()) {
3316   default:
3317     llvm_unreachable("Unknown loc info!");
3318   case CCValAssign::Full:
3319     break;
3320   case CCValAssign::AExtUpper:
3321   case CCValAssign::AExt:
3322     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3323     break;
3324   case CCValAssign::SExtUpper:
3325   case CCValAssign::SExt:
3326     Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3327     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3328     break;
3329   case CCValAssign::ZExtUpper:
3330   case CCValAssign::ZExt:
3331     Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3332     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3333     break;
3334   case CCValAssign::BCvt:
3335     Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3336     break;
3337   }
3338
3339   return Val;
3340 }
3341
3342 //===----------------------------------------------------------------------===//
3343 //             Formal Arguments Calling Convention Implementation
3344 //===----------------------------------------------------------------------===//
3345 /// LowerFormalArguments - transform physical registers into virtual registers
3346 /// and generate load operations for arguments places on the stack.
3347 SDValue MipsTargetLowering::LowerFormalArguments(
3348     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3349     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3350     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3351   MachineFunction &MF = DAG.getMachineFunction();
3352   MachineFrameInfo &MFI = MF.getFrameInfo();
3353   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3354
3355   MipsFI->setVarArgsFrameIndex(0);
3356
3357   // Used with vargs to acumulate store chains.
3358   std::vector<SDValue> OutChains;
3359
3360   // Assign locations to all of the incoming arguments.
3361   SmallVector<CCValAssign, 16> ArgLocs;
3362   MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3363                      *DAG.getContext());
3364   CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
3365   const Function *Func = DAG.getMachineFunction().getFunction();
3366   Function::const_arg_iterator FuncArg = Func->arg_begin();
3367
3368   if (Func->hasFnAttribute("interrupt") && !Func->arg_empty())
3369     report_fatal_error(
3370         "Functions with the interrupt attribute cannot have arguments!");
3371
3372   CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3373   MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3374                            CCInfo.getInRegsParamsCount() > 0);
3375
3376   unsigned CurArgIdx = 0;
3377   CCInfo.rewindByValRegsInfo();
3378
3379   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3380     CCValAssign &VA = ArgLocs[i];
3381     if (Ins[i].isOrigArg()) {
3382       std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3383       CurArgIdx = Ins[i].getOrigArgIndex();
3384     }
3385     EVT ValVT = VA.getValVT();
3386     ISD::ArgFlagsTy Flags = Ins[i].Flags;
3387     bool IsRegLoc = VA.isRegLoc();
3388
3389     if (Flags.isByVal()) {
3390       assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
3391       unsigned FirstByValReg, LastByValReg;
3392       unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3393       CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3394
3395       assert(Flags.getByValSize() &&
3396              "ByVal args of size 0 should have been ignored by front-end.");
3397       assert(ByValIdx < CCInfo.getInRegsParamsCount());
3398       copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3399                     FirstByValReg, LastByValReg, VA, CCInfo);
3400       CCInfo.nextInRegsParam();
3401       continue;
3402     }
3403
3404     // Arguments stored on registers
3405     if (IsRegLoc) {
3406       MVT RegVT = VA.getLocVT();
3407       unsigned ArgReg = VA.getLocReg();
3408       const TargetRegisterClass *RC = getRegClassFor(RegVT);
3409
3410       // Transform the arguments stored on
3411       // physical registers into virtual ones
3412       unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3413       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3414
3415       ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3416
3417       // Handle floating point arguments passed in integer registers and
3418       // long double arguments passed in floating point registers.
3419       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3420           (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3421           (RegVT == MVT::f64 && ValVT == MVT::i64))
3422         ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3423       else if (ABI.IsO32() && RegVT == MVT::i32 &&
3424                ValVT == MVT::f64) {
3425         unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3426                                   getNextIntArgReg(ArgReg), RC);
3427         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3428         if (!Subtarget.isLittle())
3429           std::swap(ArgValue, ArgValue2);
3430         ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3431                                ArgValue, ArgValue2);
3432       }
3433
3434       InVals.push_back(ArgValue);
3435     } else { // VA.isRegLoc()
3436       MVT LocVT = VA.getLocVT();
3437
3438       if (ABI.IsO32()) {
3439         // We ought to be able to use LocVT directly but O32 sets it to i32
3440         // when allocating floating point values to integer registers.
3441         // This shouldn't influence how we load the value into registers unless
3442         // we are targeting softfloat.
3443         if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3444           LocVT = VA.getValVT();
3445       }
3446
3447       // sanity check
3448       assert(VA.isMemLoc());
3449
3450       // The stack pointer offset is relative to the caller stack frame.
3451       int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3452                                      VA.getLocMemOffset(), true);
3453
3454       // Create load nodes to retrieve arguments from the stack
3455       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3456       SDValue ArgValue = DAG.getLoad(
3457           LocVT, DL, Chain, FIN,
3458           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3459       OutChains.push_back(ArgValue.getValue(1));
3460
3461       ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3462
3463       InVals.push_back(ArgValue);
3464     }
3465   }
3466
3467   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3468     // The mips ABIs for returning structs by value requires that we copy
3469     // the sret argument into $v0 for the return. Save the argument into
3470     // a virtual register so that we can access it from the return points.
3471     if (Ins[i].Flags.isSRet()) {
3472       unsigned Reg = MipsFI->getSRetReturnReg();
3473       if (!Reg) {
3474         Reg = MF.getRegInfo().createVirtualRegister(
3475             getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3476         MipsFI->setSRetReturnReg(Reg);
3477       }
3478       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3479       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3480       break;
3481     }
3482   }
3483
3484   if (IsVarArg)
3485     writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3486
3487   // All stores are grouped in one node to allow the matching between
3488   // the size of Ins and InVals. This only happens when on varg functions
3489   if (!OutChains.empty()) {
3490     OutChains.push_back(Chain);
3491     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3492   }
3493
3494   return Chain;
3495 }
3496
3497 //===----------------------------------------------------------------------===//
3498 //               Return Value Calling Convention Implementation
3499 //===----------------------------------------------------------------------===//
3500
3501 bool
3502 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3503                                    MachineFunction &MF, bool IsVarArg,
3504                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3505                                    LLVMContext &Context) const {
3506   SmallVector<CCValAssign, 16> RVLocs;
3507   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3508   return CCInfo.CheckReturn(Outs, RetCC_Mips);
3509 }
3510
3511 bool
3512 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3513   if (Subtarget.hasMips3() && Subtarget.useSoftFloat()) {
3514     if (Type == MVT::i32)
3515       return true;
3516   }
3517   return IsSigned;
3518 }
3519
3520 SDValue
3521 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3522                                          const SDLoc &DL,
3523                                          SelectionDAG &DAG) const {
3524
3525   MachineFunction &MF = DAG.getMachineFunction();
3526   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3527
3528   MipsFI->setISR();
3529
3530   return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3531 }
3532
3533 SDValue
3534 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3535                                 bool IsVarArg,
3536                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
3537                                 const SmallVectorImpl<SDValue> &OutVals,
3538                                 const SDLoc &DL, SelectionDAG &DAG) const {
3539   // CCValAssign - represent the assignment of
3540   // the return value to a location
3541   SmallVector<CCValAssign, 16> RVLocs;
3542   MachineFunction &MF = DAG.getMachineFunction();
3543
3544   // CCState - Info about the registers and stack slot.
3545   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3546
3547   // Analyze return values.
3548   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3549
3550   SDValue Flag;
3551   SmallVector<SDValue, 4> RetOps(1, Chain);
3552
3553   // Copy the result values into the output registers.
3554   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3555     SDValue Val = OutVals[i];
3556     CCValAssign &VA = RVLocs[i];
3557     assert(VA.isRegLoc() && "Can only return in registers!");
3558     bool UseUpperBits = false;
3559
3560     switch (VA.getLocInfo()) {
3561     default:
3562       llvm_unreachable("Unknown loc info!");
3563     case CCValAssign::Full:
3564       break;
3565     case CCValAssign::BCvt:
3566       Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3567       break;
3568     case CCValAssign::AExtUpper:
3569       UseUpperBits = true;
3570       LLVM_FALLTHROUGH;
3571     case CCValAssign::AExt:
3572       Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3573       break;
3574     case CCValAssign::ZExtUpper:
3575       UseUpperBits = true;
3576       LLVM_FALLTHROUGH;
3577     case CCValAssign::ZExt:
3578       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3579       break;
3580     case CCValAssign::SExtUpper:
3581       UseUpperBits = true;
3582       LLVM_FALLTHROUGH;
3583     case CCValAssign::SExt:
3584       Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3585       break;
3586     }
3587
3588     if (UseUpperBits) {
3589       unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3590       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3591       Val = DAG.getNode(
3592           ISD::SHL, DL, VA.getLocVT(), Val,
3593           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3594     }
3595
3596     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3597
3598     // Guarantee that all emitted copies are stuck together with flags.
3599     Flag = Chain.getValue(1);
3600     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3601   }
3602
3603   // The mips ABIs for returning structs by value requires that we copy
3604   // the sret argument into $v0 for the return. We saved the argument into
3605   // a virtual register in the entry block, so now we copy the value out
3606   // and into $v0.
3607   if (MF.getFunction()->hasStructRetAttr()) {
3608     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3609     unsigned Reg = MipsFI->getSRetReturnReg();
3610
3611     if (!Reg)
3612       llvm_unreachable("sret virtual register not created in the entry block");
3613     SDValue Val =
3614         DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3615     unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3616
3617     Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3618     Flag = Chain.getValue(1);
3619     RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3620   }
3621
3622   RetOps[0] = Chain;  // Update chain.
3623
3624   // Add the flag if we have it.
3625   if (Flag.getNode())
3626     RetOps.push_back(Flag);
3627
3628   // ISRs must use "eret".
3629   if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt"))
3630     return LowerInterruptReturn(RetOps, DL, DAG);
3631
3632   // Standard return on Mips is a "jr $ra"
3633   return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3634 }
3635
3636 //===----------------------------------------------------------------------===//
3637 //                           Mips Inline Assembly Support
3638 //===----------------------------------------------------------------------===//
3639
3640 /// getConstraintType - Given a constraint letter, return the type of
3641 /// constraint it is for this target.
3642 MipsTargetLowering::ConstraintType
3643 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3644   // Mips specific constraints
3645   // GCC config/mips/constraints.md
3646   //
3647   // 'd' : An address register. Equivalent to r
3648   //       unless generating MIPS16 code.
3649   // 'y' : Equivalent to r; retained for
3650   //       backwards compatibility.
3651   // 'c' : A register suitable for use in an indirect
3652   //       jump. This will always be $25 for -mabicalls.
3653   // 'l' : The lo register. 1 word storage.
3654   // 'x' : The hilo register pair. Double word storage.
3655   if (Constraint.size() == 1) {
3656     switch (Constraint[0]) {
3657       default : break;
3658       case 'd':
3659       case 'y':
3660       case 'f':
3661       case 'c':
3662       case 'l':
3663       case 'x':
3664         return C_RegisterClass;
3665       case 'R':
3666         return C_Memory;
3667     }
3668   }
3669
3670   if (Constraint == "ZC")
3671     return C_Memory;
3672
3673   return TargetLowering::getConstraintType(Constraint);
3674 }
3675
3676 /// Examine constraint type and operand type and determine a weight value.
3677 /// This object must already have been set up with the operand type
3678 /// and the current alternative constraint selected.
3679 TargetLowering::ConstraintWeight
3680 MipsTargetLowering::getSingleConstraintMatchWeight(
3681     AsmOperandInfo &info, const char *constraint) const {
3682   ConstraintWeight weight = CW_Invalid;
3683   Value *CallOperandVal = info.CallOperandVal;
3684     // If we don't have a value, we can't do a match,
3685     // but allow it at the lowest weight.
3686   if (!CallOperandVal)
3687     return CW_Default;
3688   Type *type = CallOperandVal->getType();
3689   // Look at the constraint type.
3690   switch (*constraint) {
3691   default:
3692     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3693     break;
3694   case 'd':
3695   case 'y':
3696     if (type->isIntegerTy())
3697       weight = CW_Register;
3698     break;
3699   case 'f': // FPU or MSA register
3700     if (Subtarget.hasMSA() && type->isVectorTy() &&
3701         cast<VectorType>(type)->getBitWidth() == 128)
3702       weight = CW_Register;
3703     else if (type->isFloatTy())
3704       weight = CW_Register;
3705     break;
3706   case 'c': // $25 for indirect jumps
3707   case 'l': // lo register
3708   case 'x': // hilo register pair
3709     if (type->isIntegerTy())
3710       weight = CW_SpecificReg;
3711     break;
3712   case 'I': // signed 16 bit immediate
3713   case 'J': // integer zero
3714   case 'K': // unsigned 16 bit immediate
3715   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3716   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3717   case 'O': // signed 15 bit immediate (+- 16383)
3718   case 'P': // immediate in the range of 65535 to 1 (inclusive)
3719     if (isa<ConstantInt>(CallOperandVal))
3720       weight = CW_Constant;
3721     break;
3722   case 'R':
3723     weight = CW_Memory;
3724     break;
3725   }
3726   return weight;
3727 }
3728
3729 /// This is a helper function to parse a physical register string and split it
3730 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3731 /// that is returned indicates whether parsing was successful. The second flag
3732 /// is true if the numeric part exists.
3733 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3734                                               unsigned long long &Reg) {
3735   if (C.front() != '{' || C.back() != '}')
3736     return std::make_pair(false, false);
3737
3738   // Search for the first numeric character.
3739   StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3740   I = std::find_if(B, E, isdigit);
3741
3742   Prefix = StringRef(B, I - B);
3743
3744   // The second flag is set to false if no numeric characters were found.
3745   if (I == E)
3746     return std::make_pair(true, false);
3747
3748   // Parse the numeric characters.
3749   return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3750                         true);
3751 }
3752
3753 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3754 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3755   const TargetRegisterInfo *TRI =
3756       Subtarget.getRegisterInfo();
3757   const TargetRegisterClass *RC;
3758   StringRef Prefix;
3759   unsigned long long Reg;
3760
3761   std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3762
3763   if (!R.first)
3764     return std::make_pair(0U, nullptr);
3765
3766   if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3767     // No numeric characters follow "hi" or "lo".
3768     if (R.second)
3769       return std::make_pair(0U, nullptr);
3770
3771     RC = TRI->getRegClass(Prefix == "hi" ?
3772                           Mips::HI32RegClassID : Mips::LO32RegClassID);
3773     return std::make_pair(*(RC->begin()), RC);
3774   } else if (Prefix.startswith("$msa")) {
3775     // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3776
3777     // No numeric characters follow the name.
3778     if (R.second)
3779       return std::make_pair(0U, nullptr);
3780
3781     Reg = StringSwitch<unsigned long long>(Prefix)
3782               .Case("$msair", Mips::MSAIR)
3783               .Case("$msacsr", Mips::MSACSR)
3784               .Case("$msaaccess", Mips::MSAAccess)
3785               .Case("$msasave", Mips::MSASave)
3786               .Case("$msamodify", Mips::MSAModify)
3787               .Case("$msarequest", Mips::MSARequest)
3788               .Case("$msamap", Mips::MSAMap)
3789               .Case("$msaunmap", Mips::MSAUnmap)
3790               .Default(0);
3791
3792     if (!Reg)
3793       return std::make_pair(0U, nullptr);
3794
3795     RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3796     return std::make_pair(Reg, RC);
3797   }
3798
3799   if (!R.second)
3800     return std::make_pair(0U, nullptr);
3801
3802   if (Prefix == "$f") { // Parse $f0-$f31.
3803     // If the size of FP registers is 64-bit or Reg is an even number, select
3804     // the 64-bit register class. Otherwise, select the 32-bit register class.
3805     if (VT == MVT::Other)
3806       VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3807
3808     RC = getRegClassFor(VT);
3809
3810     if (RC == &Mips::AFGR64RegClass) {
3811       assert(Reg % 2 == 0);
3812       Reg >>= 1;
3813     }
3814   } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3815     RC = TRI->getRegClass(Mips::FCCRegClassID);
3816   else if (Prefix == "$w") { // Parse $w0-$w31.
3817     RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3818   } else { // Parse $0-$31.
3819     assert(Prefix == "$");
3820     RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3821   }
3822
3823   assert(Reg < RC->getNumRegs());
3824   return std::make_pair(*(RC->begin() + Reg), RC);
3825 }
3826
3827 /// Given a register class constraint, like 'r', if this corresponds directly
3828 /// to an LLVM register class, return a register of 0 and the register class
3829 /// pointer.
3830 std::pair<unsigned, const TargetRegisterClass *>
3831 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3832                                                  StringRef Constraint,
3833                                                  MVT VT) const {
3834   if (Constraint.size() == 1) {
3835     switch (Constraint[0]) {
3836     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3837     case 'y': // Same as 'r'. Exists for compatibility.
3838     case 'r':
3839       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3840         if (Subtarget.inMips16Mode())
3841           return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3842         return std::make_pair(0U, &Mips::GPR32RegClass);
3843       }
3844       if (VT == MVT::i64 && !Subtarget.isGP64bit())
3845         return std::make_pair(0U, &Mips::GPR32RegClass);
3846       if (VT == MVT::i64 && Subtarget.isGP64bit())
3847         return std::make_pair(0U, &Mips::GPR64RegClass);
3848       // This will generate an error message
3849       return std::make_pair(0U, nullptr);
3850     case 'f': // FPU or MSA register
3851       if (VT == MVT::v16i8)
3852         return std::make_pair(0U, &Mips::MSA128BRegClass);
3853       else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3854         return std::make_pair(0U, &Mips::MSA128HRegClass);
3855       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3856         return std::make_pair(0U, &Mips::MSA128WRegClass);
3857       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3858         return std::make_pair(0U, &Mips::MSA128DRegClass);
3859       else if (VT == MVT::f32)
3860         return std::make_pair(0U, &Mips::FGR32RegClass);
3861       else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3862         if (Subtarget.isFP64bit())
3863           return std::make_pair(0U, &Mips::FGR64RegClass);
3864         return std::make_pair(0U, &Mips::AFGR64RegClass);
3865       }
3866       break;
3867     case 'c': // register suitable for indirect jump
3868       if (VT == MVT::i32)
3869         return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3870       assert(VT == MVT::i64 && "Unexpected type.");
3871       return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3872     case 'l': // register suitable for indirect jump
3873       if (VT == MVT::i32)
3874         return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3875       return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3876     case 'x': // register suitable for indirect jump
3877       // Fixme: Not triggering the use of both hi and low
3878       // This will generate an error message
3879       return std::make_pair(0U, nullptr);
3880     }
3881   }
3882
3883   std::pair<unsigned, const TargetRegisterClass *> R;
3884   R = parseRegForInlineAsmConstraint(Constraint, VT);
3885
3886   if (R.second)
3887     return R;
3888
3889   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3890 }
3891
3892 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3893 /// vector.  If it is invalid, don't add anything to Ops.
3894 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3895                                                      std::string &Constraint,
3896                                                      std::vector<SDValue>&Ops,
3897                                                      SelectionDAG &DAG) const {
3898   SDLoc DL(Op);
3899   SDValue Result;
3900
3901   // Only support length 1 constraints for now.
3902   if (Constraint.length() > 1) return;
3903
3904   char ConstraintLetter = Constraint[0];
3905   switch (ConstraintLetter) {
3906   default: break; // This will fall through to the generic implementation
3907   case 'I': // Signed 16 bit constant
3908     // If this fails, the parent routine will give an error
3909     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3910       EVT Type = Op.getValueType();
3911       int64_t Val = C->getSExtValue();
3912       if (isInt<16>(Val)) {
3913         Result = DAG.getTargetConstant(Val, DL, Type);
3914         break;
3915       }
3916     }
3917     return;
3918   case 'J': // integer zero
3919     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3920       EVT Type = Op.getValueType();
3921       int64_t Val = C->getZExtValue();
3922       if (Val == 0) {
3923         Result = DAG.getTargetConstant(0, DL, Type);
3924         break;
3925       }
3926     }
3927     return;
3928   case 'K': // unsigned 16 bit immediate
3929     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3930       EVT Type = Op.getValueType();
3931       uint64_t Val = (uint64_t)C->getZExtValue();
3932       if (isUInt<16>(Val)) {
3933         Result = DAG.getTargetConstant(Val, DL, Type);
3934         break;
3935       }
3936     }
3937     return;
3938   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3939     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3940       EVT Type = Op.getValueType();
3941       int64_t Val = C->getSExtValue();
3942       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3943         Result = DAG.getTargetConstant(Val, DL, Type);
3944         break;
3945       }
3946     }
3947     return;
3948   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3949     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3950       EVT Type = Op.getValueType();
3951       int64_t Val = C->getSExtValue();
3952       if ((Val >= -65535) && (Val <= -1)) {
3953         Result = DAG.getTargetConstant(Val, DL, Type);
3954         break;
3955       }
3956     }
3957     return;
3958   case 'O': // signed 15 bit immediate
3959     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3960       EVT Type = Op.getValueType();
3961       int64_t Val = C->getSExtValue();
3962       if ((isInt<15>(Val))) {
3963         Result = DAG.getTargetConstant(Val, DL, Type);
3964         break;
3965       }
3966     }
3967     return;
3968   case 'P': // immediate in the range of 1 to 65535 (inclusive)
3969     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3970       EVT Type = Op.getValueType();
3971       int64_t Val = C->getSExtValue();
3972       if ((Val <= 65535) && (Val >= 1)) {
3973         Result = DAG.getTargetConstant(Val, DL, Type);
3974         break;
3975       }
3976     }
3977     return;
3978   }
3979
3980   if (Result.getNode()) {
3981     Ops.push_back(Result);
3982     return;
3983   }
3984
3985   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3986 }
3987
3988 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3989                                                const AddrMode &AM, Type *Ty,
3990                                                unsigned AS) const {
3991   // No global is ever allowed as a base.
3992   if (AM.BaseGV)
3993     return false;
3994
3995   switch (AM.Scale) {
3996   case 0: // "r+i" or just "i", depending on HasBaseReg.
3997     break;
3998   case 1:
3999     if (!AM.HasBaseReg) // allow "r+i".
4000       break;
4001     return false; // disallow "r+r" or "r+r+i".
4002   default:
4003     return false;
4004   }
4005
4006   return true;
4007 }
4008
4009 bool
4010 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4011   // The Mips target isn't yet aware of offsets.
4012   return false;
4013 }
4014
4015 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
4016                                             unsigned SrcAlign,
4017                                             bool IsMemset, bool ZeroMemset,
4018                                             bool MemcpyStrSrc,
4019                                             MachineFunction &MF) const {
4020   if (Subtarget.hasMips64())
4021     return MVT::i64;
4022
4023   return MVT::i32;
4024 }
4025
4026 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4027   if (VT != MVT::f32 && VT != MVT::f64)
4028     return false;
4029   if (Imm.isNegZero())
4030     return false;
4031   return Imm.isZero();
4032 }
4033
4034 unsigned MipsTargetLowering::getJumpTableEncoding() const {
4035
4036   // FIXME: For space reasons this should be: EK_GPRel32BlockAddress.
4037   if (ABI.IsN64() && isPositionIndependent())
4038     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
4039
4040   return TargetLowering::getJumpTableEncoding();
4041 }
4042
4043 bool MipsTargetLowering::useSoftFloat() const {
4044   return Subtarget.useSoftFloat();
4045 }
4046
4047 void MipsTargetLowering::copyByValRegs(
4048     SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4049     SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4050     SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4051     unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4052     MipsCCState &State) const {
4053   MachineFunction &MF = DAG.getMachineFunction();
4054   MachineFrameInfo &MFI = MF.getFrameInfo();
4055   unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4056   unsigned NumRegs = LastReg - FirstReg;
4057   unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4058   unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4059   int FrameObjOffset;
4060   ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4061
4062   if (RegAreaSize)
4063     FrameObjOffset =
4064         (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4065         (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4066   else
4067     FrameObjOffset = VA.getLocMemOffset();
4068
4069   // Create frame object.
4070   EVT PtrTy = getPointerTy(DAG.getDataLayout());
4071   int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, true);
4072   SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4073   InVals.push_back(FIN);
4074
4075   if (!NumRegs)
4076     return;
4077
4078   // Copy arg registers.
4079   MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4080   const TargetRegisterClass *RC = getRegClassFor(RegTy);
4081
4082   for (unsigned I = 0; I < NumRegs; ++I) {
4083     unsigned ArgReg = ByValArgRegs[FirstReg + I];
4084     unsigned VReg = addLiveIn(MF, ArgReg, RC);
4085     unsigned Offset = I * GPRSizeInBytes;
4086     SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4087                                    DAG.getConstant(Offset, DL, PtrTy));
4088     SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4089                                  StorePtr, MachinePointerInfo(FuncArg, Offset));
4090     OutChains.push_back(Store);
4091   }
4092 }
4093
4094 // Copy byVal arg to registers and stack.
4095 void MipsTargetLowering::passByValArg(
4096     SDValue Chain, const SDLoc &DL,
4097     std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4098     SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4099     MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4100     unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4101     const CCValAssign &VA) const {
4102   unsigned ByValSizeInBytes = Flags.getByValSize();
4103   unsigned OffsetInBytes = 0; // From beginning of struct
4104   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4105   unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
4106   EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4107       RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4108   unsigned NumRegs = LastReg - FirstReg;
4109
4110   if (NumRegs) {
4111     ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
4112     bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4113     unsigned I = 0;
4114
4115     // Copy words to registers.
4116     for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4117       SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4118                                     DAG.getConstant(OffsetInBytes, DL, PtrTy));
4119       SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4120                                     MachinePointerInfo(), Alignment);
4121       MemOpChains.push_back(LoadVal.getValue(1));
4122       unsigned ArgReg = ArgRegs[FirstReg + I];
4123       RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4124     }
4125
4126     // Return if the struct has been fully copied.
4127     if (ByValSizeInBytes == OffsetInBytes)
4128       return;
4129
4130     // Copy the remainder of the byval argument with sub-word loads and shifts.
4131     if (LeftoverBytes) {
4132       SDValue Val;
4133
4134       for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4135            OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4136         unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4137
4138         if (RemainingSizeInBytes < LoadSizeInBytes)
4139           continue;
4140
4141         // Load subword.
4142         SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4143                                       DAG.getConstant(OffsetInBytes, DL,
4144                                                       PtrTy));
4145         SDValue LoadVal = DAG.getExtLoad(
4146             ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4147             MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4148         MemOpChains.push_back(LoadVal.getValue(1));
4149
4150         // Shift the loaded value.
4151         unsigned Shamt;
4152
4153         if (isLittle)
4154           Shamt = TotalBytesLoaded * 8;
4155         else
4156           Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4157
4158         SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4159                                     DAG.getConstant(Shamt, DL, MVT::i32));
4160
4161         if (Val.getNode())
4162           Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4163         else
4164           Val = Shift;
4165
4166         OffsetInBytes += LoadSizeInBytes;
4167         TotalBytesLoaded += LoadSizeInBytes;
4168         Alignment = std::min(Alignment, LoadSizeInBytes);
4169       }
4170
4171       unsigned ArgReg = ArgRegs[FirstReg + I];
4172       RegsToPass.push_back(std::make_pair(ArgReg, Val));
4173       return;
4174     }
4175   }
4176
4177   // Copy remainder of byval arg to it with memcpy.
4178   unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4179   SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4180                             DAG.getConstant(OffsetInBytes, DL, PtrTy));
4181   SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4182                             DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
4183   Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4184                         DAG.getConstant(MemCpySize, DL, PtrTy),
4185                         Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
4186                         /*isTailCall=*/false,
4187                         MachinePointerInfo(), MachinePointerInfo());
4188   MemOpChains.push_back(Chain);
4189 }
4190
4191 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4192                                          SDValue Chain, const SDLoc &DL,
4193                                          SelectionDAG &DAG,
4194                                          CCState &State) const {
4195   ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
4196   unsigned Idx = State.getFirstUnallocated(ArgRegs);
4197   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4198   MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4199   const TargetRegisterClass *RC = getRegClassFor(RegTy);
4200   MachineFunction &MF = DAG.getMachineFunction();
4201   MachineFrameInfo &MFI = MF.getFrameInfo();
4202   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4203
4204   // Offset of the first variable argument from stack pointer.
4205   int VaArgOffset;
4206
4207   if (ArgRegs.size() == Idx)
4208     VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
4209   else {
4210     VaArgOffset =
4211         (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4212         (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4213   }
4214
4215   // Record the frame index of the first variable argument
4216   // which is a value necessary to VASTART.
4217   int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4218   MipsFI->setVarArgsFrameIndex(FI);
4219
4220   // Copy the integer registers that have not been used for argument passing
4221   // to the argument register save area. For O32, the save area is allocated
4222   // in the caller's stack frame, while for N32/64, it is allocated in the
4223   // callee's stack frame.
4224   for (unsigned I = Idx; I < ArgRegs.size();
4225        ++I, VaArgOffset += RegSizeInBytes) {
4226     unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4227     SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4228     FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4229     SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4230     SDValue Store =
4231         DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4232     cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4233         (Value *)nullptr);
4234     OutChains.push_back(Store);
4235   }
4236 }
4237
4238 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
4239                                      unsigned Align) const {
4240   const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4241
4242   assert(Size && "Byval argument's size shouldn't be 0.");
4243
4244   Align = std::min(Align, TFL->getStackAlignment());
4245
4246   unsigned FirstReg = 0;
4247   unsigned NumRegs = 0;
4248
4249   if (State->getCallingConv() != CallingConv::Fast) {
4250     unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4251     ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4252     // FIXME: The O32 case actually describes no shadow registers.
4253     const MCPhysReg *ShadowRegs =
4254         ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4255
4256     // We used to check the size as well but we can't do that anymore since
4257     // CCState::HandleByVal() rounds up the size after calling this function.
4258     assert(!(Align % RegSizeInBytes) &&
4259            "Byval argument's alignment should be a multiple of"
4260            "RegSizeInBytes.");
4261
4262     FirstReg = State->getFirstUnallocated(IntArgRegs);
4263
4264     // If Align > RegSizeInBytes, the first arg register must be even.
4265     // FIXME: This condition happens to do the right thing but it's not the
4266     //        right way to test it. We want to check that the stack frame offset
4267     //        of the register is aligned.
4268     if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
4269       State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4270       ++FirstReg;
4271     }
4272
4273     // Mark the registers allocated.
4274     Size = alignTo(Size, RegSizeInBytes);
4275     for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4276          Size -= RegSizeInBytes, ++I, ++NumRegs)
4277       State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4278   }
4279
4280   State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4281 }
4282
4283 MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4284                                                         MachineBasicBlock *BB,
4285                                                         bool isFPCmp,
4286                                                         unsigned Opc) const {
4287   assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4288          "Subtarget already supports SELECT nodes with the use of"
4289          "conditional-move instructions.");
4290
4291   const TargetInstrInfo *TII =
4292       Subtarget.getInstrInfo();
4293   DebugLoc DL = MI.getDebugLoc();
4294
4295   // To "insert" a SELECT instruction, we actually have to insert the
4296   // diamond control-flow pattern.  The incoming instruction knows the
4297   // destination vreg to set, the condition code register to branch on, the
4298   // true/false values to select between, and a branch opcode to use.
4299   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4300   MachineFunction::iterator It = ++BB->getIterator();
4301
4302   //  thisMBB:
4303   //  ...
4304   //   TrueVal = ...
4305   //   setcc r1, r2, r3
4306   //   bNE   r1, r0, copy1MBB
4307   //   fallthrough --> copy0MBB
4308   MachineBasicBlock *thisMBB  = BB;
4309   MachineFunction *F = BB->getParent();
4310   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4311   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
4312   F->insert(It, copy0MBB);
4313   F->insert(It, sinkMBB);
4314
4315   // Transfer the remainder of BB and its successor edges to sinkMBB.
4316   sinkMBB->splice(sinkMBB->begin(), BB,
4317                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
4318   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4319
4320   // Next, add the true and fallthrough blocks as its successors.
4321   BB->addSuccessor(copy0MBB);
4322   BB->addSuccessor(sinkMBB);
4323
4324   if (isFPCmp) {
4325     // bc1[tf] cc, sinkMBB
4326     BuildMI(BB, DL, TII->get(Opc))
4327         .addReg(MI.getOperand(1).getReg())
4328         .addMBB(sinkMBB);
4329   } else {
4330     // bne rs, $0, sinkMBB
4331     BuildMI(BB, DL, TII->get(Opc))
4332         .addReg(MI.getOperand(1).getReg())
4333         .addReg(Mips::ZERO)
4334         .addMBB(sinkMBB);
4335   }
4336
4337   //  copy0MBB:
4338   //   %FalseValue = ...
4339   //   # fallthrough to sinkMBB
4340   BB = copy0MBB;
4341
4342   // Update machine-CFG edges
4343   BB->addSuccessor(sinkMBB);
4344
4345   //  sinkMBB:
4346   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4347   //  ...
4348   BB = sinkMBB;
4349
4350   BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4351       .addReg(MI.getOperand(2).getReg())
4352       .addMBB(thisMBB)
4353       .addReg(MI.getOperand(3).getReg())
4354       .addMBB(copy0MBB);
4355
4356   MI.eraseFromParent(); // The pseudo instruction is gone now.
4357
4358   return BB;
4359 }
4360
4361 // FIXME? Maybe this could be a TableGen attribute on some registers and
4362 // this table could be generated automatically from RegInfo.
4363 unsigned MipsTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4364                                                SelectionDAG &DAG) const {
4365   // Named registers is expected to be fairly rare. For now, just support $28
4366   // since the linux kernel uses it.
4367   if (Subtarget.isGP64bit()) {
4368     unsigned Reg = StringSwitch<unsigned>(RegName)
4369                          .Case("$28", Mips::GP_64)
4370                          .Default(0);
4371     if (Reg)
4372       return Reg;
4373   } else {
4374     unsigned Reg = StringSwitch<unsigned>(RegName)
4375                          .Case("$28", Mips::GP)
4376                          .Default(0);
4377     if (Reg)
4378       return Reg;
4379   }
4380   report_fatal_error("Invalid register name global variable");
4381 }