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