[mips] Add CCValAssign::[ASZ]ExtUpper and CCPromoteToUpperBitsInType and handle struc...
[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(const 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(const 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 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode);
2377
2378 #include "MipsGenCallingConv.inc"
2379
2380 //===----------------------------------------------------------------------===//
2381 //                  Call Calling Convention Implementation
2382 //===----------------------------------------------------------------------===//
2383
2384 // Return next O32 integer argument register.
2385 static unsigned getNextIntArgReg(unsigned Reg) {
2386   assert((Reg == Mips::A0) || (Reg == Mips::A2));
2387   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2388 }
2389
2390 SDValue
2391 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2392                                    SDValue Chain, SDValue Arg, SDLoc DL,
2393                                    bool IsTailCall, SelectionDAG &DAG) const {
2394   if (!IsTailCall) {
2395     SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2396                                  DAG.getIntPtrConstant(Offset));
2397     return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2398                         false, 0);
2399   }
2400
2401   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2402   int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2403   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2404   return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2405                       /*isVolatile=*/ true, false, 0);
2406 }
2407
2408 void MipsTargetLowering::
2409 getOpndList(SmallVectorImpl<SDValue> &Ops,
2410             std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2411             bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2412             CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2413   // Insert node "GP copy globalreg" before call to function.
2414   //
2415   // R_MIPS_CALL* operators (emitted when non-internal functions are called
2416   // in PIC mode) allow symbols to be resolved via lazy binding.
2417   // The lazy binding stub requires GP to point to the GOT.
2418   if (IsPICCall && !InternalLinkage) {
2419     unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
2420     EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2421     RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2422   }
2423
2424   // Build a sequence of copy-to-reg nodes chained together with token
2425   // chain and flag operands which copy the outgoing args into registers.
2426   // The InFlag in necessary since all emitted instructions must be
2427   // stuck together.
2428   SDValue InFlag;
2429
2430   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2431     Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2432                                  RegsToPass[i].second, InFlag);
2433     InFlag = Chain.getValue(1);
2434   }
2435
2436   // Add argument registers to the end of the list so that they are
2437   // known live into the call.
2438   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2439     Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2440                                       RegsToPass[i].second.getValueType()));
2441
2442   // Add a register mask operand representing the call-preserved registers.
2443   const TargetRegisterInfo *TRI =
2444       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2445   const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2446   assert(Mask && "Missing call preserved mask for calling convention");
2447   if (Subtarget.inMips16HardFloat()) {
2448     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2449       llvm::StringRef Sym = G->getGlobal()->getName();
2450       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2451       if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2452         Mask = MipsRegisterInfo::getMips16RetHelperMask();
2453       }
2454     }
2455   }
2456   Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2457
2458   if (InFlag.getNode())
2459     Ops.push_back(InFlag);
2460 }
2461
2462 /// LowerCall - functions arguments are copied from virtual regs to
2463 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2464 SDValue
2465 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2466                               SmallVectorImpl<SDValue> &InVals) const {
2467   SelectionDAG &DAG                     = CLI.DAG;
2468   SDLoc DL                              = CLI.DL;
2469   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2470   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2471   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2472   SDValue Chain                         = CLI.Chain;
2473   SDValue Callee                        = CLI.Callee;
2474   bool &IsTailCall                      = CLI.IsTailCall;
2475   CallingConv::ID CallConv              = CLI.CallConv;
2476   bool IsVarArg                         = CLI.IsVarArg;
2477
2478   MachineFunction &MF = DAG.getMachineFunction();
2479   MachineFrameInfo *MFI = MF.getFrameInfo();
2480   const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
2481   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2482   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2483
2484   // Analyze operands of the call, assigning locations to each operand.
2485   SmallVector<CCValAssign, 16> ArgLocs;
2486   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2487                  *DAG.getContext());
2488   MipsCC::SpecialCallingConvType SpecialCallingConv =
2489     getSpecialCallingConv(Callee);
2490   MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo, SpecialCallingConv);
2491
2492   MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2493                                  Subtarget.abiUsesSoftFloat(),
2494                                  Callee.getNode(), CLI.getArgs());
2495
2496   // Get a count of how many bytes are to be pushed on the stack.
2497   unsigned NextStackOffset = CCInfo.getNextStackOffset();
2498
2499   // Check if it's really possible to do a tail call.
2500   if (IsTailCall)
2501     IsTailCall =
2502       isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2503                                         *MF.getInfo<MipsFunctionInfo>());
2504
2505   if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2506     report_fatal_error("failed to perform tail call elimination on a call "
2507                        "site marked musttail");
2508
2509   if (IsTailCall)
2510     ++NumTailCalls;
2511
2512   // Chain is the output chain of the last Load/Store or CopyToReg node.
2513   // ByValChain is the output chain of the last Memcpy node created for copying
2514   // byval arguments to the stack.
2515   unsigned StackAlignment = TFL->getStackAlignment();
2516   NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2517   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2518
2519   if (!IsTailCall)
2520     Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2521
2522   SDValue StackPtr = DAG.getCopyFromReg(
2523       Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
2524       getPointerTy());
2525
2526   // With EABI is it possible to have 16 args on registers.
2527   std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2528   SmallVector<SDValue, 8> MemOpChains;
2529   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2530
2531   // Walk the register/memloc assignments, inserting copies/loads.
2532   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2533     SDValue Arg = OutVals[i];
2534     CCValAssign &VA = ArgLocs[i];
2535     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2536     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2537
2538     // ByVal Arg.
2539     if (Flags.isByVal()) {
2540       assert(Flags.getByValSize() &&
2541              "ByVal args of size 0 should have been ignored by front-end.");
2542       assert(ByValArg != MipsCCInfo.byval_end());
2543       assert(!IsTailCall &&
2544              "Do not tail-call optimize if there is a byval argument.");
2545       passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2546                    MipsCCInfo, *ByValArg, Flags, Subtarget.isLittle());
2547       ++ByValArg;
2548       continue;
2549     }
2550
2551     // Promote the value if needed.
2552     switch (VA.getLocInfo()) {
2553     default: llvm_unreachable("Unknown loc info!");
2554     case CCValAssign::Full:
2555       if (VA.isRegLoc()) {
2556         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2557             (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2558             (ValVT == MVT::i64 && LocVT == MVT::f64))
2559           Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2560         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2561           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2562                                    Arg, DAG.getConstant(0, MVT::i32));
2563           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2564                                    Arg, DAG.getConstant(1, MVT::i32));
2565           if (!Subtarget.isLittle())
2566             std::swap(Lo, Hi);
2567           unsigned LocRegLo = VA.getLocReg();
2568           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2569           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2570           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2571           continue;
2572         }
2573       }
2574       break;
2575     case CCValAssign::SExt:
2576       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2577       break;
2578     case CCValAssign::ZExt:
2579       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2580       break;
2581     case CCValAssign::AExt:
2582       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2583       break;
2584     }
2585
2586     // Arguments that can be passed on register must be kept at
2587     // RegsToPass vector
2588     if (VA.isRegLoc()) {
2589       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2590       continue;
2591     }
2592
2593     // Register can't get to this point...
2594     assert(VA.isMemLoc());
2595
2596     // emit ISD::STORE whichs stores the
2597     // parameter value to a stack Location
2598     MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2599                                          Chain, Arg, DL, IsTailCall, DAG));
2600   }
2601
2602   // Transform all store nodes into one single node because all store
2603   // nodes are independent of each other.
2604   if (!MemOpChains.empty())
2605     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2606
2607   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2608   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2609   // node so that legalize doesn't hack it.
2610   bool IsPICCall =
2611       (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
2612                                          // jalr $25
2613   bool GlobalOrExternal = false, InternalLinkage = false;
2614   SDValue CalleeLo;
2615   EVT Ty = Callee.getValueType();
2616
2617   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2618     if (IsPICCall) {
2619       const GlobalValue *Val = G->getGlobal();
2620       InternalLinkage = Val->hasInternalLinkage();
2621
2622       if (InternalLinkage)
2623         Callee = getAddrLocal(G, Ty, DAG,
2624                               Subtarget.isABI_N32() || Subtarget.isABI_N64());
2625       else if (LargeGOT)
2626         Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2627                                        MipsII::MO_CALL_LO16, Chain,
2628                                        FuncInfo->callPtrInfo(Val));
2629       else
2630         Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2631                                FuncInfo->callPtrInfo(Val));
2632     } else
2633       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2634                                           MipsII::MO_NO_FLAG);
2635     GlobalOrExternal = true;
2636   }
2637   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2638     const char *Sym = S->getSymbol();
2639
2640     if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
2641       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2642                                             MipsII::MO_NO_FLAG);
2643     else if (LargeGOT)
2644       Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2645                                      MipsII::MO_CALL_LO16, Chain,
2646                                      FuncInfo->callPtrInfo(Sym));
2647     else // N64 || PIC
2648       Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2649                              FuncInfo->callPtrInfo(Sym));
2650
2651     GlobalOrExternal = true;
2652   }
2653
2654   SmallVector<SDValue, 8> Ops(1, Chain);
2655   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2656
2657   getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2658               CLI, Callee, Chain);
2659
2660   if (IsTailCall)
2661     return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2662
2663   Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2664   SDValue InFlag = Chain.getValue(1);
2665
2666   // Create the CALLSEQ_END node.
2667   Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2668                              DAG.getIntPtrConstant(0, true), InFlag, DL);
2669   InFlag = Chain.getValue(1);
2670
2671   // Handle result values, copying them out of physregs into vregs that we
2672   // return.
2673   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2674                          Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2675 }
2676
2677 /// LowerCallResult - Lower the result values of a call into the
2678 /// appropriate copies out of appropriate physical registers.
2679 SDValue
2680 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2681                                     CallingConv::ID CallConv, bool IsVarArg,
2682                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2683                                     SDLoc DL, SelectionDAG &DAG,
2684                                     SmallVectorImpl<SDValue> &InVals,
2685                                     const SDNode *CallNode,
2686                                     const Type *RetTy) const {
2687   // Assign locations to each value returned by this call.
2688   SmallVector<CCValAssign, 16> RVLocs;
2689   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2690                  *DAG.getContext());
2691
2692   if (originalTypeIsF128(RetTy, CallNode))
2693     CCInfo.AnalyzeCallResult(Ins, RetCC_F128);
2694   else
2695     CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2696
2697   // Copy all of the result registers out of their specified physreg.
2698   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2699     CCValAssign &VA = RVLocs[i];
2700     assert(VA.isRegLoc() && "Can only return in registers!");
2701
2702     SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2703                                      RVLocs[i].getLocVT(), InFlag);
2704     Chain = Val.getValue(1);
2705     InFlag = Val.getValue(2);
2706
2707     if (VA.isUpperBitsInLoc()) {
2708       unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2709       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2710       unsigned Shift =
2711           VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2712       Val = DAG.getNode(
2713           Shift, DL, VA.getLocVT(), Val,
2714           DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2715     }
2716
2717     switch (VA.getLocInfo()) {
2718     default:
2719       llvm_unreachable("Unknown loc info!");
2720     case CCValAssign::Full:
2721       break;
2722     case CCValAssign::BCvt:
2723       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2724       break;
2725     case CCValAssign::AExt:
2726     case CCValAssign::AExtUpper:
2727       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2728       break;
2729     case CCValAssign::ZExt:
2730     case CCValAssign::ZExtUpper:
2731       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2732                         DAG.getValueType(VA.getValVT()));
2733       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2734       break;
2735     case CCValAssign::SExt:
2736     case CCValAssign::SExtUpper:
2737       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2738                         DAG.getValueType(VA.getValVT()));
2739       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2740       break;
2741     }
2742
2743     InVals.push_back(Val);
2744   }
2745
2746   return Chain;
2747 }
2748
2749 //===----------------------------------------------------------------------===//
2750 //             Formal Arguments Calling Convention Implementation
2751 //===----------------------------------------------------------------------===//
2752 /// LowerFormalArguments - transform physical registers into virtual registers
2753 /// and generate load operations for arguments places on the stack.
2754 SDValue
2755 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2756                                          CallingConv::ID CallConv,
2757                                          bool IsVarArg,
2758                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2759                                          SDLoc DL, SelectionDAG &DAG,
2760                                          SmallVectorImpl<SDValue> &InVals)
2761                                           const {
2762   MachineFunction &MF = DAG.getMachineFunction();
2763   MachineFrameInfo *MFI = MF.getFrameInfo();
2764   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2765
2766   MipsFI->setVarArgsFrameIndex(0);
2767
2768   // Used with vargs to acumulate store chains.
2769   std::vector<SDValue> OutChains;
2770
2771   // Assign locations to all of the incoming arguments.
2772   SmallVector<CCValAssign, 16> ArgLocs;
2773   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2774                  *DAG.getContext());
2775   MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
2776   Function::const_arg_iterator FuncArg =
2777     DAG.getMachineFunction().getFunction()->arg_begin();
2778   bool UseSoftFloat = Subtarget.abiUsesSoftFloat();
2779
2780   MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2781   MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2782                            MipsCCInfo.hasByValArg());
2783
2784   unsigned CurArgIdx = 0;
2785   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2786
2787   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2788     CCValAssign &VA = ArgLocs[i];
2789     std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2790     CurArgIdx = Ins[i].OrigArgIndex;
2791     EVT ValVT = VA.getValVT();
2792     ISD::ArgFlagsTy Flags = Ins[i].Flags;
2793     bool IsRegLoc = VA.isRegLoc();
2794
2795     if (Flags.isByVal()) {
2796       assert(Flags.getByValSize() &&
2797              "ByVal args of size 0 should have been ignored by front-end.");
2798       assert(ByValArg != MipsCCInfo.byval_end());
2799       copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2800                     MipsCCInfo, *ByValArg);
2801       ++ByValArg;
2802       continue;
2803     }
2804
2805     // Arguments stored on registers
2806     if (IsRegLoc) {
2807       MVT RegVT = VA.getLocVT();
2808       unsigned ArgReg = VA.getLocReg();
2809       const TargetRegisterClass *RC = getRegClassFor(RegVT);
2810
2811       // Transform the arguments stored on
2812       // physical registers into virtual ones
2813       unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2814       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2815
2816       // If this is an 8 or 16-bit value, it has been passed promoted
2817       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2818       // truncate to the right size.
2819       if (VA.getLocInfo() != CCValAssign::Full) {
2820         unsigned Opcode = 0;
2821         if (VA.getLocInfo() == CCValAssign::SExt)
2822           Opcode = ISD::AssertSext;
2823         else if (VA.getLocInfo() == CCValAssign::ZExt)
2824           Opcode = ISD::AssertZext;
2825         if (Opcode)
2826           ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2827                                  DAG.getValueType(ValVT));
2828         ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2829       }
2830
2831       // Handle floating point arguments passed in integer registers and
2832       // long double arguments passed in floating point registers.
2833       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2834           (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2835           (RegVT == MVT::f64 && ValVT == MVT::i64))
2836         ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2837       else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
2838                ValVT == MVT::f64) {
2839         unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2840                                   getNextIntArgReg(ArgReg), RC);
2841         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2842         if (!Subtarget.isLittle())
2843           std::swap(ArgValue, ArgValue2);
2844         ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2845                                ArgValue, ArgValue2);
2846       }
2847
2848       InVals.push_back(ArgValue);
2849     } else { // VA.isRegLoc()
2850
2851       // sanity check
2852       assert(VA.isMemLoc());
2853
2854       // The stack pointer offset is relative to the caller stack frame.
2855       int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2856                                       VA.getLocMemOffset(), true);
2857
2858       // Create load nodes to retrieve arguments from the stack
2859       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2860       SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2861                                  MachinePointerInfo::getFixedStack(FI),
2862                                  false, false, false, 0);
2863       InVals.push_back(Load);
2864       OutChains.push_back(Load.getValue(1));
2865     }
2866   }
2867
2868   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2869     // The mips ABIs for returning structs by value requires that we copy
2870     // the sret argument into $v0 for the return. Save the argument into
2871     // a virtual register so that we can access it from the return points.
2872     if (Ins[i].Flags.isSRet()) {
2873       unsigned Reg = MipsFI->getSRetReturnReg();
2874       if (!Reg) {
2875         Reg = MF.getRegInfo().createVirtualRegister(
2876             getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
2877         MipsFI->setSRetReturnReg(Reg);
2878       }
2879       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
2880       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2881       break;
2882     }
2883   }
2884
2885   if (IsVarArg)
2886     writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2887
2888   // All stores are grouped in one node to allow the matching between
2889   // the size of Ins and InVals. This only happens when on varg functions
2890   if (!OutChains.empty()) {
2891     OutChains.push_back(Chain);
2892     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2893   }
2894
2895   return Chain;
2896 }
2897
2898 //===----------------------------------------------------------------------===//
2899 //               Return Value Calling Convention Implementation
2900 //===----------------------------------------------------------------------===//
2901
2902 bool
2903 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2904                                    MachineFunction &MF, bool IsVarArg,
2905                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2906                                    LLVMContext &Context) const {
2907   SmallVector<CCValAssign, 16> RVLocs;
2908   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2909   return CCInfo.CheckReturn(Outs, RetCC_Mips);
2910 }
2911
2912 SDValue
2913 MipsTargetLowering::LowerReturn(SDValue Chain,
2914                                 CallingConv::ID CallConv, bool IsVarArg,
2915                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
2916                                 const SmallVectorImpl<SDValue> &OutVals,
2917                                 SDLoc DL, SelectionDAG &DAG) const {
2918   // CCValAssign - represent the assignment of
2919   // the return value to a location
2920   SmallVector<CCValAssign, 16> RVLocs;
2921   MachineFunction &MF = DAG.getMachineFunction();
2922
2923   // CCState - Info about the registers and stack slot.
2924   CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
2925   MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
2926
2927   // Analyze return values.
2928   if (originalTypeIsF128(MF.getFunction()->getReturnType(), nullptr))
2929     CCInfo.AnalyzeReturn(Outs, RetCC_F128);
2930   else
2931     CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
2932
2933   SDValue Flag;
2934   SmallVector<SDValue, 4> RetOps(1, Chain);
2935
2936   // Copy the result values into the output registers.
2937   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2938     SDValue Val = OutVals[i];
2939     CCValAssign &VA = RVLocs[i];
2940     assert(VA.isRegLoc() && "Can only return in registers!");
2941     bool UseUpperBits = false;
2942
2943     switch (VA.getLocInfo()) {
2944     default:
2945       llvm_unreachable("Unknown loc info!");
2946     case CCValAssign::Full:
2947       break;
2948     case CCValAssign::BCvt:
2949       Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
2950       break;
2951     case CCValAssign::AExtUpper:
2952       UseUpperBits = true;
2953       // Fallthrough
2954     case CCValAssign::AExt:
2955       Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
2956       break;
2957     case CCValAssign::ZExtUpper:
2958       UseUpperBits = true;
2959       // Fallthrough
2960     case CCValAssign::ZExt:
2961       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
2962       break;
2963     case CCValAssign::SExtUpper:
2964       UseUpperBits = true;
2965       // Fallthrough
2966     case CCValAssign::SExt:
2967       Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
2968       break;
2969     }
2970
2971     if (UseUpperBits) {
2972       unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2973       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2974       Val = DAG.getNode(
2975           ISD::SHL, DL, VA.getLocVT(), Val,
2976           DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2977     }
2978
2979     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2980
2981     // Guarantee that all emitted copies are stuck together with flags.
2982     Flag = Chain.getValue(1);
2983     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2984   }
2985
2986   // The mips ABIs for returning structs by value requires that we copy
2987   // the sret argument into $v0 for the return. We saved the argument into
2988   // a virtual register in the entry block, so now we copy the value out
2989   // and into $v0.
2990   if (MF.getFunction()->hasStructRetAttr()) {
2991     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2992     unsigned Reg = MipsFI->getSRetReturnReg();
2993
2994     if (!Reg)
2995       llvm_unreachable("sret virtual register not created in the entry block");
2996     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2997     unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
2998
2999     Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3000     Flag = Chain.getValue(1);
3001     RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3002   }
3003
3004   RetOps[0] = Chain;  // Update chain.
3005
3006   // Add the flag if we have it.
3007   if (Flag.getNode())
3008     RetOps.push_back(Flag);
3009
3010   // Return on Mips is always a "jr $ra"
3011   return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3012 }
3013
3014 //===----------------------------------------------------------------------===//
3015 //                           Mips Inline Assembly Support
3016 //===----------------------------------------------------------------------===//
3017
3018 /// getConstraintType - Given a constraint letter, return the type of
3019 /// constraint it is for this target.
3020 MipsTargetLowering::ConstraintType MipsTargetLowering::
3021 getConstraintType(const std::string &Constraint) const
3022 {
3023   // Mips specific constraints
3024   // GCC config/mips/constraints.md
3025   //
3026   // 'd' : An address register. Equivalent to r
3027   //       unless generating MIPS16 code.
3028   // 'y' : Equivalent to r; retained for
3029   //       backwards compatibility.
3030   // 'c' : A register suitable for use in an indirect
3031   //       jump. This will always be $25 for -mabicalls.
3032   // 'l' : The lo register. 1 word storage.
3033   // 'x' : The hilo register pair. Double word storage.
3034   if (Constraint.size() == 1) {
3035     switch (Constraint[0]) {
3036       default : break;
3037       case 'd':
3038       case 'y':
3039       case 'f':
3040       case 'c':
3041       case 'l':
3042       case 'x':
3043         return C_RegisterClass;
3044       case 'R':
3045         return C_Memory;
3046     }
3047   }
3048   return TargetLowering::getConstraintType(Constraint);
3049 }
3050
3051 /// Examine constraint type and operand type and determine a weight value.
3052 /// This object must already have been set up with the operand type
3053 /// and the current alternative constraint selected.
3054 TargetLowering::ConstraintWeight
3055 MipsTargetLowering::getSingleConstraintMatchWeight(
3056     AsmOperandInfo &info, const char *constraint) const {
3057   ConstraintWeight weight = CW_Invalid;
3058   Value *CallOperandVal = info.CallOperandVal;
3059     // If we don't have a value, we can't do a match,
3060     // but allow it at the lowest weight.
3061   if (!CallOperandVal)
3062     return CW_Default;
3063   Type *type = CallOperandVal->getType();
3064   // Look at the constraint type.
3065   switch (*constraint) {
3066   default:
3067     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3068     break;
3069   case 'd':
3070   case 'y':
3071     if (type->isIntegerTy())
3072       weight = CW_Register;
3073     break;
3074   case 'f': // FPU or MSA register
3075     if (Subtarget.hasMSA() && type->isVectorTy() &&
3076         cast<VectorType>(type)->getBitWidth() == 128)
3077       weight = CW_Register;
3078     else if (type->isFloatTy())
3079       weight = CW_Register;
3080     break;
3081   case 'c': // $25 for indirect jumps
3082   case 'l': // lo register
3083   case 'x': // hilo register pair
3084     if (type->isIntegerTy())
3085       weight = CW_SpecificReg;
3086     break;
3087   case 'I': // signed 16 bit immediate
3088   case 'J': // integer zero
3089   case 'K': // unsigned 16 bit immediate
3090   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3091   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3092   case 'O': // signed 15 bit immediate (+- 16383)
3093   case 'P': // immediate in the range of 65535 to 1 (inclusive)
3094     if (isa<ConstantInt>(CallOperandVal))
3095       weight = CW_Constant;
3096     break;
3097   case 'R':
3098     weight = CW_Memory;
3099     break;
3100   }
3101   return weight;
3102 }
3103
3104 /// This is a helper function to parse a physical register string and split it
3105 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3106 /// that is returned indicates whether parsing was successful. The second flag
3107 /// is true if the numeric part exists.
3108 static std::pair<bool, bool>
3109 parsePhysicalReg(StringRef C, std::string &Prefix,
3110                  unsigned long long &Reg) {
3111   if (C.front() != '{' || C.back() != '}')
3112     return std::make_pair(false, false);
3113
3114   // Search for the first numeric character.
3115   StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3116   I = std::find_if(B, E, std::ptr_fun(isdigit));
3117
3118   Prefix.assign(B, I - B);
3119
3120   // The second flag is set to false if no numeric characters were found.
3121   if (I == E)
3122     return std::make_pair(true, false);
3123
3124   // Parse the numeric characters.
3125   return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3126                         true);
3127 }
3128
3129 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3130 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3131   const TargetRegisterInfo *TRI =
3132       getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3133   const TargetRegisterClass *RC;
3134   std::string Prefix;
3135   unsigned long long Reg;
3136
3137   std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3138
3139   if (!R.first)
3140     return std::make_pair(0U, nullptr);
3141
3142   if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3143     // No numeric characters follow "hi" or "lo".
3144     if (R.second)
3145       return std::make_pair(0U, nullptr);
3146
3147     RC = TRI->getRegClass(Prefix == "hi" ?
3148                           Mips::HI32RegClassID : Mips::LO32RegClassID);
3149     return std::make_pair(*(RC->begin()), RC);
3150   } else if (Prefix.compare(0, 4, "$msa") == 0) {
3151     // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3152
3153     // No numeric characters follow the name.
3154     if (R.second)
3155       return std::make_pair(0U, nullptr);
3156
3157     Reg = StringSwitch<unsigned long long>(Prefix)
3158               .Case("$msair", Mips::MSAIR)
3159               .Case("$msacsr", Mips::MSACSR)
3160               .Case("$msaaccess", Mips::MSAAccess)
3161               .Case("$msasave", Mips::MSASave)
3162               .Case("$msamodify", Mips::MSAModify)
3163               .Case("$msarequest", Mips::MSARequest)
3164               .Case("$msamap", Mips::MSAMap)
3165               .Case("$msaunmap", Mips::MSAUnmap)
3166               .Default(0);
3167
3168     if (!Reg)
3169       return std::make_pair(0U, nullptr);
3170
3171     RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3172     return std::make_pair(Reg, RC);
3173   }
3174
3175   if (!R.second)
3176     return std::make_pair(0U, nullptr);
3177
3178   if (Prefix == "$f") { // Parse $f0-$f31.
3179     // If the size of FP registers is 64-bit or Reg is an even number, select
3180     // the 64-bit register class. Otherwise, select the 32-bit register class.
3181     if (VT == MVT::Other)
3182       VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3183
3184     RC = getRegClassFor(VT);
3185
3186     if (RC == &Mips::AFGR64RegClass) {
3187       assert(Reg % 2 == 0);
3188       Reg >>= 1;
3189     }
3190   } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3191     RC = TRI->getRegClass(Mips::FCCRegClassID);
3192   else if (Prefix == "$w") { // Parse $w0-$w31.
3193     RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3194   } else { // Parse $0-$31.
3195     assert(Prefix == "$");
3196     RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3197   }
3198
3199   assert(Reg < RC->getNumRegs());
3200   return std::make_pair(*(RC->begin() + Reg), RC);
3201 }
3202
3203 /// Given a register class constraint, like 'r', if this corresponds directly
3204 /// to an LLVM register class, return a register of 0 and the register class
3205 /// pointer.
3206 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3207 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3208 {
3209   if (Constraint.size() == 1) {
3210     switch (Constraint[0]) {
3211     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3212     case 'y': // Same as 'r'. Exists for compatibility.
3213     case 'r':
3214       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3215         if (Subtarget.inMips16Mode())
3216           return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3217         return std::make_pair(0U, &Mips::GPR32RegClass);
3218       }
3219       if (VT == MVT::i64 && !Subtarget.isGP64bit())
3220         return std::make_pair(0U, &Mips::GPR32RegClass);
3221       if (VT == MVT::i64 && Subtarget.isGP64bit())
3222         return std::make_pair(0U, &Mips::GPR64RegClass);
3223       // This will generate an error message
3224       return std::make_pair(0U, nullptr);
3225     case 'f': // FPU or MSA register
3226       if (VT == MVT::v16i8)
3227         return std::make_pair(0U, &Mips::MSA128BRegClass);
3228       else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3229         return std::make_pair(0U, &Mips::MSA128HRegClass);
3230       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3231         return std::make_pair(0U, &Mips::MSA128WRegClass);
3232       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3233         return std::make_pair(0U, &Mips::MSA128DRegClass);
3234       else if (VT == MVT::f32)
3235         return std::make_pair(0U, &Mips::FGR32RegClass);
3236       else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3237         if (Subtarget.isFP64bit())
3238           return std::make_pair(0U, &Mips::FGR64RegClass);
3239         return std::make_pair(0U, &Mips::AFGR64RegClass);
3240       }
3241       break;
3242     case 'c': // register suitable for indirect jump
3243       if (VT == MVT::i32)
3244         return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3245       assert(VT == MVT::i64 && "Unexpected type.");
3246       return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3247     case 'l': // register suitable for indirect jump
3248       if (VT == MVT::i32)
3249         return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3250       return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3251     case 'x': // register suitable for indirect jump
3252       // Fixme: Not triggering the use of both hi and low
3253       // This will generate an error message
3254       return std::make_pair(0U, nullptr);
3255     }
3256   }
3257
3258   std::pair<unsigned, const TargetRegisterClass *> R;
3259   R = parseRegForInlineAsmConstraint(Constraint, VT);
3260
3261   if (R.second)
3262     return R;
3263
3264   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3265 }
3266
3267 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3268 /// vector.  If it is invalid, don't add anything to Ops.
3269 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3270                                                      std::string &Constraint,
3271                                                      std::vector<SDValue>&Ops,
3272                                                      SelectionDAG &DAG) const {
3273   SDValue Result;
3274
3275   // Only support length 1 constraints for now.
3276   if (Constraint.length() > 1) return;
3277
3278   char ConstraintLetter = Constraint[0];
3279   switch (ConstraintLetter) {
3280   default: break; // This will fall through to the generic implementation
3281   case 'I': // Signed 16 bit constant
3282     // If this fails, the parent routine will give an error
3283     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3284       EVT Type = Op.getValueType();
3285       int64_t Val = C->getSExtValue();
3286       if (isInt<16>(Val)) {
3287         Result = DAG.getTargetConstant(Val, Type);
3288         break;
3289       }
3290     }
3291     return;
3292   case 'J': // integer zero
3293     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3294       EVT Type = Op.getValueType();
3295       int64_t Val = C->getZExtValue();
3296       if (Val == 0) {
3297         Result = DAG.getTargetConstant(0, Type);
3298         break;
3299       }
3300     }
3301     return;
3302   case 'K': // unsigned 16 bit immediate
3303     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3304       EVT Type = Op.getValueType();
3305       uint64_t Val = (uint64_t)C->getZExtValue();
3306       if (isUInt<16>(Val)) {
3307         Result = DAG.getTargetConstant(Val, Type);
3308         break;
3309       }
3310     }
3311     return;
3312   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3313     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3314       EVT Type = Op.getValueType();
3315       int64_t Val = C->getSExtValue();
3316       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3317         Result = DAG.getTargetConstant(Val, Type);
3318         break;
3319       }
3320     }
3321     return;
3322   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3323     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3324       EVT Type = Op.getValueType();
3325       int64_t Val = C->getSExtValue();
3326       if ((Val >= -65535) && (Val <= -1)) {
3327         Result = DAG.getTargetConstant(Val, Type);
3328         break;
3329       }
3330     }
3331     return;
3332   case 'O': // signed 15 bit immediate
3333     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3334       EVT Type = Op.getValueType();
3335       int64_t Val = C->getSExtValue();
3336       if ((isInt<15>(Val))) {
3337         Result = DAG.getTargetConstant(Val, Type);
3338         break;
3339       }
3340     }
3341     return;
3342   case 'P': // immediate in the range of 1 to 65535 (inclusive)
3343     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3344       EVT Type = Op.getValueType();
3345       int64_t Val = C->getSExtValue();
3346       if ((Val <= 65535) && (Val >= 1)) {
3347         Result = DAG.getTargetConstant(Val, Type);
3348         break;
3349       }
3350     }
3351     return;
3352   }
3353
3354   if (Result.getNode()) {
3355     Ops.push_back(Result);
3356     return;
3357   }
3358
3359   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3360 }
3361
3362 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3363                                                Type *Ty) const {
3364   // No global is ever allowed as a base.
3365   if (AM.BaseGV)
3366     return false;
3367
3368   switch (AM.Scale) {
3369   case 0: // "r+i" or just "i", depending on HasBaseReg.
3370     break;
3371   case 1:
3372     if (!AM.HasBaseReg) // allow "r+i".
3373       break;
3374     return false; // disallow "r+r" or "r+r+i".
3375   default:
3376     return false;
3377   }
3378
3379   return true;
3380 }
3381
3382 bool
3383 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3384   // The Mips target isn't yet aware of offsets.
3385   return false;
3386 }
3387
3388 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3389                                             unsigned SrcAlign,
3390                                             bool IsMemset, bool ZeroMemset,
3391                                             bool MemcpyStrSrc,
3392                                             MachineFunction &MF) const {
3393   if (Subtarget.hasMips64())
3394     return MVT::i64;
3395
3396   return MVT::i32;
3397 }
3398
3399 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3400   if (VT != MVT::f32 && VT != MVT::f64)
3401     return false;
3402   if (Imm.isNegZero())
3403     return false;
3404   return Imm.isZero();
3405 }
3406
3407 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3408   if (Subtarget.isABI_N64())
3409     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3410
3411   return TargetLowering::getJumpTableEncoding();
3412 }
3413
3414 /// This function returns true if CallSym is a long double emulation routine.
3415 static bool isF128SoftLibCall(const char *CallSym) {
3416   const char *const LibCalls[] =
3417     {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3418      "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3419      "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3420      "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3421      "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3422      "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3423      "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3424      "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3425      "truncl"};
3426
3427   const char *const *End = LibCalls + array_lengthof(LibCalls);
3428
3429   // Check that LibCalls is sorted alphabetically.
3430   MipsTargetLowering::LTStr Comp;
3431
3432 #ifndef NDEBUG
3433   for (const char *const *I = LibCalls; I < End - 1; ++I)
3434     assert(Comp(*I, *(I + 1)));
3435 #endif
3436
3437   return std::binary_search(LibCalls, End, CallSym, Comp);
3438 }
3439
3440 /// This function returns true if Ty is fp128 or i128 which was originally a
3441 /// fp128.
3442 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3443   if (Ty->isFP128Ty())
3444     return true;
3445
3446   const ExternalSymbolSDNode *ES =
3447     dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3448
3449   // If the Ty is i128 and the function being called is a long double emulation
3450   // routine, then the original type is f128.
3451   return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3452 }
3453
3454 MipsTargetLowering::MipsCC::SpecialCallingConvType
3455   MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3456   MipsCC::SpecialCallingConvType SpecialCallingConv =
3457     MipsCC::NoSpecialCallingConv;
3458   if (Subtarget.inMips16HardFloat()) {
3459     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3460       llvm::StringRef Sym = G->getGlobal()->getName();
3461       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3462       if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3463         SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3464       }
3465     }
3466   }
3467   return SpecialCallingConv;
3468 }
3469
3470 MipsTargetLowering::MipsCC::MipsCC(
3471     CallingConv::ID CC, const MipsSubtarget &Subtarget_, CCState &Info,
3472     MipsCC::SpecialCallingConvType SpecialCallingConv_)
3473     : CCInfo(Info), CallConv(CC), Subtarget(Subtarget_),
3474       SpecialCallingConv(SpecialCallingConv_) {
3475   // Pre-allocate reserved argument area.
3476   CCInfo.AllocateStack(reservedArgArea(), 1);
3477 }
3478
3479
3480 void MipsTargetLowering::MipsCC::
3481 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3482                     bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3483                     std::vector<ArgListEntry> &FuncArgs) {
3484   assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3485          "CallingConv::Fast shouldn't be used for vararg functions.");
3486
3487   unsigned NumOpnds = Args.size();
3488   llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3489
3490   for (unsigned I = 0; I != NumOpnds; ++I) {
3491     MVT ArgVT = Args[I].VT;
3492     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3493     bool R;
3494
3495     if (ArgFlags.isByVal()) {
3496       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3497       continue;
3498     }
3499
3500     if (IsVarArg && !Args[I].IsFixed)
3501       R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3502     else {
3503       MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3504                            IsSoftFloat);
3505       R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3506     }
3507
3508     if (R) {
3509 #ifndef NDEBUG
3510       dbgs() << "Call operand #" << I << " has unhandled type "
3511              << EVT(ArgVT).getEVTString();
3512 #endif
3513       llvm_unreachable(nullptr);
3514     }
3515   }
3516 }
3517
3518 void MipsTargetLowering::MipsCC::
3519 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3520                        bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3521   unsigned NumArgs = Args.size();
3522   llvm::CCAssignFn *FixedFn = fixedArgFn();
3523   unsigned CurArgIdx = 0;
3524
3525   for (unsigned I = 0; I != NumArgs; ++I) {
3526     MVT ArgVT = Args[I].VT;
3527     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3528     std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3529     CurArgIdx = Args[I].OrigArgIndex;
3530
3531     if (ArgFlags.isByVal()) {
3532       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3533       continue;
3534     }
3535
3536     MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), nullptr, IsSoftFloat);
3537
3538     if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3539       continue;
3540
3541 #ifndef NDEBUG
3542     dbgs() << "Formal Arg #" << I << " has unhandled type "
3543            << EVT(ArgVT).getEVTString();
3544 #endif
3545     llvm_unreachable(nullptr);
3546   }
3547 }
3548
3549 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3550                                                 MVT LocVT,
3551                                                 CCValAssign::LocInfo LocInfo,
3552                                                 ISD::ArgFlagsTy ArgFlags) {
3553   assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3554
3555   struct ByValArgInfo ByVal;
3556   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3557   unsigned ByValSize =
3558       RoundUpToAlignment(ArgFlags.getByValSize(), RegSizeInBytes);
3559   unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSizeInBytes),
3560                             RegSizeInBytes * 2);
3561
3562   if (useRegsForByval())
3563     allocateRegs(ByVal, ByValSize, Align);
3564
3565   // Allocate space on caller's stack.
3566   ByVal.Address =
3567       CCInfo.AllocateStack(ByValSize - RegSizeInBytes * ByVal.NumRegs, Align);
3568   CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3569                                     LocInfo));
3570   ByValArgs.push_back(ByVal);
3571 }
3572
3573 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3574   return (Subtarget.isABI_O32() && (CallConv != CallingConv::Fast)) ? 16 : 0;
3575 }
3576
3577 const ArrayRef<MCPhysReg> MipsTargetLowering::MipsCC::intArgRegs() const {
3578   if (Subtarget.isABI_O32())
3579     return makeArrayRef(O32IntRegs);
3580   return makeArrayRef(Mips64IntRegs);
3581 }
3582
3583 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3584   if (CallConv == CallingConv::Fast)
3585     return CC_Mips_FastCC;
3586
3587   if (SpecialCallingConv == Mips16RetHelperConv)
3588     return CC_Mips16RetHelper;
3589   return Subtarget.isABI_O32()
3590              ? (Subtarget.isFP64bit() ? CC_MipsO32_FP64 : CC_MipsO32_FP32)
3591              : CC_MipsN;
3592 }
3593
3594 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3595   return Subtarget.isABI_O32()
3596              ? (Subtarget.isFP64bit() ? CC_MipsO32_FP64 : CC_MipsO32_FP32)
3597              : CC_MipsN_VarArg;
3598 }
3599
3600 const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
3601   return Subtarget.isABI_O32() ? O32IntRegs : Mips64DPRegs;
3602 }
3603
3604 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3605                                               unsigned ByValSize,
3606                                               unsigned Align) {
3607   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3608   const ArrayRef<MCPhysReg> IntArgRegs = intArgRegs();
3609   const MCPhysReg *ShadowRegs = shadowRegs();
3610   assert(!(ByValSize % RegSizeInBytes) && !(Align % RegSizeInBytes) &&
3611          "Byval argument's size and alignment should be a multiple of"
3612          "RegSizeInBytes.");
3613
3614   ByVal.FirstIdx =
3615       CCInfo.getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3616
3617   // If Align > RegSizeInBytes, the first arg register must be even.
3618   if ((Align > RegSizeInBytes) && (ByVal.FirstIdx % 2)) {
3619     CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3620     ++ByVal.FirstIdx;
3621   }
3622
3623   // Mark the registers allocated.
3624   for (unsigned I = ByVal.FirstIdx; ByValSize && (I < IntArgRegs.size());
3625        ByValSize -= RegSizeInBytes, ++I, ++ByVal.NumRegs)
3626     CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3627 }
3628
3629 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3630                                          const SDNode *CallNode,
3631                                          bool IsSoftFloat) const {
3632   if (IsSoftFloat || Subtarget.isABI_O32())
3633     return VT;
3634
3635   // Check if the original type was fp128.
3636   if (originalTypeIsF128(OrigTy, CallNode)) {
3637     assert(VT == MVT::i64);
3638     return MVT::f64;
3639   }
3640
3641   return VT;
3642 }
3643
3644 void MipsTargetLowering::
3645 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3646               SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3647               SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3648               const MipsCC &CC, const ByValArgInfo &ByVal) const {
3649   MachineFunction &MF = DAG.getMachineFunction();
3650   MachineFrameInfo *MFI = MF.getFrameInfo();
3651   unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3652   unsigned RegAreaSize = ByVal.NumRegs * GPRSizeInBytes;
3653   unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3654   int FrameObjOffset;
3655
3656   if (RegAreaSize)
3657     FrameObjOffset =
3658         (int)CC.reservedArgArea() -
3659         (int)((CC.intArgRegs().size() - ByVal.FirstIdx) * GPRSizeInBytes);
3660   else
3661     FrameObjOffset = ByVal.Address;
3662
3663   // Create frame object.
3664   EVT PtrTy = getPointerTy();
3665   int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3666   SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3667   InVals.push_back(FIN);
3668
3669   if (!ByVal.NumRegs)
3670     return;
3671
3672   // Copy arg registers.
3673   MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3674   const TargetRegisterClass *RC = getRegClassFor(RegTy);
3675
3676   for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3677     unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3678     unsigned VReg = addLiveIn(MF, ArgReg, RC);
3679     unsigned Offset = I * GPRSizeInBytes;
3680     SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3681                                    DAG.getConstant(Offset, PtrTy));
3682     SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3683                                  StorePtr, MachinePointerInfo(FuncArg, Offset),
3684                                  false, false, 0);
3685     OutChains.push_back(Store);
3686   }
3687 }
3688
3689 // Copy byVal arg to registers and stack.
3690 void MipsTargetLowering::
3691 passByValArg(SDValue Chain, SDLoc DL,
3692              std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3693              SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3694              MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3695              const MipsCC &CC, const ByValArgInfo &ByVal,
3696              const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3697   unsigned ByValSizeInBytes = Flags.getByValSize();
3698   unsigned OffsetInBytes = 0; // From beginning of struct
3699   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3700   unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3701   EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3702
3703   if (ByVal.NumRegs) {
3704     const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3705     bool LeftoverBytes = (ByVal.NumRegs * RegSizeInBytes > ByValSizeInBytes);
3706     unsigned I = 0;
3707
3708     // Copy words to registers.
3709     for (; I < ByVal.NumRegs - LeftoverBytes;
3710          ++I, OffsetInBytes += RegSizeInBytes) {
3711       SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3712                                     DAG.getConstant(OffsetInBytes, PtrTy));
3713       SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3714                                     MachinePointerInfo(), false, false, false,
3715                                     Alignment);
3716       MemOpChains.push_back(LoadVal.getValue(1));
3717       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3718       RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3719     }
3720
3721     // Return if the struct has been fully copied.
3722     if (ByValSizeInBytes == OffsetInBytes)
3723       return;
3724
3725     // Copy the remainder of the byval argument with sub-word loads and shifts.
3726     if (LeftoverBytes) {
3727       assert((ByValSizeInBytes > OffsetInBytes) &&
3728              (ByValSizeInBytes < OffsetInBytes + RegSizeInBytes) &&
3729              "Size of the remainder should be smaller than RegSizeInBytes.");
3730       SDValue Val;
3731
3732       for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3733            OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3734         unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3735
3736         if (RemainingSizeInBytes < LoadSizeInBytes)
3737           continue;
3738
3739         // Load subword.
3740         SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3741                                       DAG.getConstant(OffsetInBytes, PtrTy));
3742         SDValue LoadVal = DAG.getExtLoad(
3743             ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3744             MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3745             Alignment);
3746         MemOpChains.push_back(LoadVal.getValue(1));
3747
3748         // Shift the loaded value.
3749         unsigned Shamt;
3750
3751         if (isLittle)
3752           Shamt = TotalBytesLoaded * 8;
3753         else
3754           Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3755
3756         SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3757                                     DAG.getConstant(Shamt, MVT::i32));
3758
3759         if (Val.getNode())
3760           Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3761         else
3762           Val = Shift;
3763
3764         OffsetInBytes += LoadSizeInBytes;
3765         TotalBytesLoaded += LoadSizeInBytes;
3766         Alignment = std::min(Alignment, LoadSizeInBytes);
3767       }
3768
3769       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3770       RegsToPass.push_back(std::make_pair(ArgReg, Val));
3771       return;
3772     }
3773   }
3774
3775   // Copy remainder of byval arg to it with memcpy.
3776   unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3777   SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3778                             DAG.getConstant(OffsetInBytes, PtrTy));
3779   SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3780                             DAG.getIntPtrConstant(ByVal.Address));
3781   Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3782                         Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3783                         MachinePointerInfo(), MachinePointerInfo());
3784   MemOpChains.push_back(Chain);
3785 }
3786
3787 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3788                                          const MipsCC &CC, SDValue Chain,
3789                                          SDLoc DL, SelectionDAG &DAG) const {
3790   const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3791   const CCState &CCInfo = CC.getCCInfo();
3792   unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3793   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3794   MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3795   const TargetRegisterClass *RC = getRegClassFor(RegTy);
3796   MachineFunction &MF = DAG.getMachineFunction();
3797   MachineFrameInfo *MFI = MF.getFrameInfo();
3798   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3799
3800   // Offset of the first variable argument from stack pointer.
3801   int VaArgOffset;
3802
3803   if (ArgRegs.size() == Idx)
3804     VaArgOffset =
3805         RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSizeInBytes);
3806   else
3807     VaArgOffset = (int)CC.reservedArgArea() -
3808                   (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3809
3810   // Record the frame index of the first variable argument
3811   // which is a value necessary to VASTART.
3812   int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3813   MipsFI->setVarArgsFrameIndex(FI);
3814
3815   // Copy the integer registers that have not been used for argument passing
3816   // to the argument register save area. For O32, the save area is allocated
3817   // in the caller's stack frame, while for N32/64, it is allocated in the
3818   // callee's stack frame.
3819   for (unsigned I = Idx; I < ArgRegs.size();
3820        ++I, VaArgOffset += RegSizeInBytes) {
3821     unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3822     SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3823     FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3824     SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3825     SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3826                                  MachinePointerInfo(), false, false, 0);
3827     cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3828         (Value *)nullptr);
3829     OutChains.push_back(Store);
3830   }
3831 }