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