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