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