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