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