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