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