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