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