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