[mips][mips64r6] Add b[on]vc
[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);
1581     CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1582       .setCallee(CallingConv::C, PtrTy, TlsGetAddr, &Args, 0);
1583     std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1584
1585     SDValue Ret = CallResult.first;
1586
1587     if (model != TLSModel::LocalDynamic)
1588       return Ret;
1589
1590     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1591                                                MipsII::MO_DTPREL_HI);
1592     SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1593     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1594                                                MipsII::MO_DTPREL_LO);
1595     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1596     SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1597     return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1598   }
1599
1600   SDValue Offset;
1601   if (model == TLSModel::InitialExec) {
1602     // Initial Exec TLS Model
1603     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1604                                              MipsII::MO_GOTTPREL);
1605     TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1606                       TGA);
1607     Offset = DAG.getLoad(PtrVT, DL,
1608                          DAG.getEntryNode(), TGA, MachinePointerInfo(),
1609                          false, false, false, 0);
1610   } else {
1611     // Local Exec TLS Model
1612     assert(model == TLSModel::LocalExec);
1613     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1614                                                MipsII::MO_TPREL_HI);
1615     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1616                                                MipsII::MO_TPREL_LO);
1617     SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1618     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1619     Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1620   }
1621
1622   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1623   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1624 }
1625
1626 SDValue MipsTargetLowering::
1627 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1628 {
1629   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1630   EVT Ty = Op.getValueType();
1631
1632   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1633     return getAddrNonPIC(N, Ty, DAG);
1634
1635   return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1636 }
1637
1638 SDValue MipsTargetLowering::
1639 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1640 {
1641   // gp_rel relocation
1642   // FIXME: we should reference the constant pool using small data sections,
1643   // but the asm printer currently doesn't support this feature without
1644   // hacking it. This feature should come soon so we can uncomment the
1645   // stuff below.
1646   //if (IsInSmallSection(C->getType())) {
1647   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1648   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1649   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1650   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1651   EVT Ty = Op.getValueType();
1652
1653   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1654     return getAddrNonPIC(N, Ty, DAG);
1655
1656   return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1657 }
1658
1659 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1660   MachineFunction &MF = DAG.getMachineFunction();
1661   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1662
1663   SDLoc DL(Op);
1664   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1665                                  getPointerTy());
1666
1667   // vastart just stores the address of the VarArgsFrameIndex slot into the
1668   // memory location argument.
1669   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1670   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1671                       MachinePointerInfo(SV), false, false, 0);
1672 }
1673
1674 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1675                                 bool HasExtractInsert) {
1676   EVT TyX = Op.getOperand(0).getValueType();
1677   EVT TyY = Op.getOperand(1).getValueType();
1678   SDValue Const1 = DAG.getConstant(1, MVT::i32);
1679   SDValue Const31 = DAG.getConstant(31, MVT::i32);
1680   SDLoc DL(Op);
1681   SDValue Res;
1682
1683   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1684   // to i32.
1685   SDValue X = (TyX == MVT::f32) ?
1686     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1687     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1688                 Const1);
1689   SDValue Y = (TyY == MVT::f32) ?
1690     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1691     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1692                 Const1);
1693
1694   if (HasExtractInsert) {
1695     // ext  E, Y, 31, 1  ; extract bit31 of Y
1696     // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
1697     SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1698     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1699   } else {
1700     // sll SllX, X, 1
1701     // srl SrlX, SllX, 1
1702     // srl SrlY, Y, 31
1703     // sll SllY, SrlX, 31
1704     // or  Or, SrlX, SllY
1705     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1706     SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1707     SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1708     SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1709     Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1710   }
1711
1712   if (TyX == MVT::f32)
1713     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1714
1715   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1716                              Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1717   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1718 }
1719
1720 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1721                                 bool HasExtractInsert) {
1722   unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1723   unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1724   EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1725   SDValue Const1 = DAG.getConstant(1, MVT::i32);
1726   SDLoc DL(Op);
1727
1728   // Bitcast to integer nodes.
1729   SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1730   SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1731
1732   if (HasExtractInsert) {
1733     // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
1734     // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
1735     SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1736                             DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1737
1738     if (WidthX > WidthY)
1739       E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1740     else if (WidthY > WidthX)
1741       E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1742
1743     SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1744                             DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1745     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1746   }
1747
1748   // (d)sll SllX, X, 1
1749   // (d)srl SrlX, SllX, 1
1750   // (d)srl SrlY, Y, width(Y)-1
1751   // (d)sll SllY, SrlX, width(Y)-1
1752   // or     Or, SrlX, SllY
1753   SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1754   SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1755   SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1756                              DAG.getConstant(WidthY - 1, MVT::i32));
1757
1758   if (WidthX > WidthY)
1759     SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1760   else if (WidthY > WidthX)
1761     SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1762
1763   SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1764                              DAG.getConstant(WidthX - 1, MVT::i32));
1765   SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1766   return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1767 }
1768
1769 SDValue
1770 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1771   if (Subtarget->isGP64bit())
1772     return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasExtractInsert());
1773
1774   return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasExtractInsert());
1775 }
1776
1777 SDValue MipsTargetLowering::
1778 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1779   // check the depth
1780   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1781          "Frame address can only be determined for current frame.");
1782
1783   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1784   MFI->setFrameAddressIsTaken(true);
1785   EVT VT = Op.getValueType();
1786   SDLoc DL(Op);
1787   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1788                                          isN64() ? Mips::FP_64 : Mips::FP, VT);
1789   return FrameAddr;
1790 }
1791
1792 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1793                                             SelectionDAG &DAG) const {
1794   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1795     return SDValue();
1796
1797   // check the depth
1798   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1799          "Return address can be determined only for current frame.");
1800
1801   MachineFunction &MF = DAG.getMachineFunction();
1802   MachineFrameInfo *MFI = MF.getFrameInfo();
1803   MVT VT = Op.getSimpleValueType();
1804   unsigned RA = isN64() ? Mips::RA_64 : Mips::RA;
1805   MFI->setReturnAddressIsTaken(true);
1806
1807   // Return RA, which contains the return address. Mark it an implicit live-in.
1808   unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1809   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1810 }
1811
1812 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1813 // generated from __builtin_eh_return (offset, handler)
1814 // The effect of this is to adjust the stack pointer by "offset"
1815 // and then branch to "handler".
1816 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1817                                                                      const {
1818   MachineFunction &MF = DAG.getMachineFunction();
1819   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1820
1821   MipsFI->setCallsEhReturn();
1822   SDValue Chain     = Op.getOperand(0);
1823   SDValue Offset    = Op.getOperand(1);
1824   SDValue Handler   = Op.getOperand(2);
1825   SDLoc DL(Op);
1826   EVT Ty = isN64() ? MVT::i64 : MVT::i32;
1827
1828   // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1829   // EH_RETURN nodes, so that instructions are emitted back-to-back.
1830   unsigned OffsetReg = isN64() ? Mips::V1_64 : Mips::V1;
1831   unsigned AddrReg = isN64() ? Mips::V0_64 : Mips::V0;
1832   Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1833   Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1834   return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1835                      DAG.getRegister(OffsetReg, Ty),
1836                      DAG.getRegister(AddrReg, getPointerTy()),
1837                      Chain.getValue(1));
1838 }
1839
1840 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1841                                               SelectionDAG &DAG) const {
1842   // FIXME: Need pseudo-fence for 'singlethread' fences
1843   // FIXME: Set SType for weaker fences where supported/appropriate.
1844   unsigned SType = 0;
1845   SDLoc DL(Op);
1846   return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1847                      DAG.getConstant(SType, MVT::i32));
1848 }
1849
1850 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1851                                                 SelectionDAG &DAG) const {
1852   SDLoc DL(Op);
1853   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1854   SDValue Shamt = Op.getOperand(2);
1855
1856   // if shamt < 32:
1857   //  lo = (shl lo, shamt)
1858   //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1859   // else:
1860   //  lo = 0
1861   //  hi = (shl lo, shamt[4:0])
1862   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1863                             DAG.getConstant(-1, MVT::i32));
1864   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1865                                       DAG.getConstant(1, MVT::i32));
1866   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1867                                      Not);
1868   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1869   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1870   SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1871   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1872                              DAG.getConstant(0x20, MVT::i32));
1873   Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1874                    DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1875   Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1876
1877   SDValue Ops[2] = {Lo, Hi};
1878   return DAG.getMergeValues(Ops, DL);
1879 }
1880
1881 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1882                                                  bool IsSRA) const {
1883   SDLoc DL(Op);
1884   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1885   SDValue Shamt = Op.getOperand(2);
1886
1887   // if shamt < 32:
1888   //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1889   //  if isSRA:
1890   //    hi = (sra hi, shamt)
1891   //  else:
1892   //    hi = (srl hi, shamt)
1893   // else:
1894   //  if isSRA:
1895   //   lo = (sra hi, shamt[4:0])
1896   //   hi = (sra hi, 31)
1897   //  else:
1898   //   lo = (srl hi, shamt[4:0])
1899   //   hi = 0
1900   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1901                             DAG.getConstant(-1, MVT::i32));
1902   SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1903                                      DAG.getConstant(1, MVT::i32));
1904   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1905   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1906   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1907   SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1908                                      Hi, Shamt);
1909   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1910                              DAG.getConstant(0x20, MVT::i32));
1911   SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1912                                 DAG.getConstant(31, MVT::i32));
1913   Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1914   Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1915                    IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1916                    ShiftRightHi);
1917
1918   SDValue Ops[2] = {Lo, Hi};
1919   return DAG.getMergeValues(Ops, DL);
1920 }
1921
1922 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1923                             SDValue Chain, SDValue Src, unsigned Offset) {
1924   SDValue Ptr = LD->getBasePtr();
1925   EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1926   EVT BasePtrVT = Ptr.getValueType();
1927   SDLoc DL(LD);
1928   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1929
1930   if (Offset)
1931     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1932                       DAG.getConstant(Offset, BasePtrVT));
1933
1934   SDValue Ops[] = { Chain, Ptr, Src };
1935   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
1936                                  LD->getMemOperand());
1937 }
1938
1939 // Expand an unaligned 32 or 64-bit integer load node.
1940 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1941   LoadSDNode *LD = cast<LoadSDNode>(Op);
1942   EVT MemVT = LD->getMemoryVT();
1943
1944   // Return if load is aligned or if MemVT is neither i32 nor i64.
1945   if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1946       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1947     return SDValue();
1948
1949   bool IsLittle = Subtarget->isLittle();
1950   EVT VT = Op.getValueType();
1951   ISD::LoadExtType ExtType = LD->getExtensionType();
1952   SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1953
1954   assert((VT == MVT::i32) || (VT == MVT::i64));
1955
1956   // Expand
1957   //  (set dst, (i64 (load baseptr)))
1958   // to
1959   //  (set tmp, (ldl (add baseptr, 7), undef))
1960   //  (set dst, (ldr baseptr, tmp))
1961   if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1962     SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1963                                IsLittle ? 7 : 0);
1964     return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1965                         IsLittle ? 0 : 7);
1966   }
1967
1968   SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1969                              IsLittle ? 3 : 0);
1970   SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1971                              IsLittle ? 0 : 3);
1972
1973   // Expand
1974   //  (set dst, (i32 (load baseptr))) or
1975   //  (set dst, (i64 (sextload baseptr))) or
1976   //  (set dst, (i64 (extload baseptr)))
1977   // to
1978   //  (set tmp, (lwl (add baseptr, 3), undef))
1979   //  (set dst, (lwr baseptr, tmp))
1980   if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1981       (ExtType == ISD::EXTLOAD))
1982     return LWR;
1983
1984   assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1985
1986   // Expand
1987   //  (set dst, (i64 (zextload baseptr)))
1988   // to
1989   //  (set tmp0, (lwl (add baseptr, 3), undef))
1990   //  (set tmp1, (lwr baseptr, tmp0))
1991   //  (set tmp2, (shl tmp1, 32))
1992   //  (set dst, (srl tmp2, 32))
1993   SDLoc DL(LD);
1994   SDValue Const32 = DAG.getConstant(32, MVT::i32);
1995   SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1996   SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
1997   SDValue Ops[] = { SRL, LWR.getValue(1) };
1998   return DAG.getMergeValues(Ops, DL);
1999 }
2000
2001 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2002                              SDValue Chain, unsigned Offset) {
2003   SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2004   EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2005   SDLoc DL(SD);
2006   SDVTList VTList = DAG.getVTList(MVT::Other);
2007
2008   if (Offset)
2009     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2010                       DAG.getConstant(Offset, BasePtrVT));
2011
2012   SDValue Ops[] = { Chain, Value, Ptr };
2013   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2014                                  SD->getMemOperand());
2015 }
2016
2017 // Expand an unaligned 32 or 64-bit integer store node.
2018 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2019                                       bool IsLittle) {
2020   SDValue Value = SD->getValue(), Chain = SD->getChain();
2021   EVT VT = Value.getValueType();
2022
2023   // Expand
2024   //  (store val, baseptr) or
2025   //  (truncstore val, baseptr)
2026   // to
2027   //  (swl val, (add baseptr, 3))
2028   //  (swr val, baseptr)
2029   if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2030     SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2031                                 IsLittle ? 3 : 0);
2032     return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2033   }
2034
2035   assert(VT == MVT::i64);
2036
2037   // Expand
2038   //  (store val, baseptr)
2039   // to
2040   //  (sdl val, (add baseptr, 7))
2041   //  (sdr val, baseptr)
2042   SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2043   return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2044 }
2045
2046 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2047 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2048   SDValue Val = SD->getValue();
2049
2050   if (Val.getOpcode() != ISD::FP_TO_SINT)
2051     return SDValue();
2052
2053   EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2054   SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2055                            Val.getOperand(0));
2056
2057   return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2058                       SD->getPointerInfo(), SD->isVolatile(),
2059                       SD->isNonTemporal(), SD->getAlignment());
2060 }
2061
2062 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2063   StoreSDNode *SD = cast<StoreSDNode>(Op);
2064   EVT MemVT = SD->getMemoryVT();
2065
2066   // Lower unaligned integer stores.
2067   if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2068       ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2069     return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2070
2071   return lowerFP_TO_SINT_STORE(SD, DAG);
2072 }
2073
2074 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2075   if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2076       || cast<ConstantSDNode>
2077         (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2078       || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2079     return SDValue();
2080
2081   // The pattern
2082   //   (add (frameaddr 0), (frame_to_args_offset))
2083   // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2084   //   (add FrameObject, 0)
2085   // where FrameObject is a fixed StackObject with offset 0 which points to
2086   // the old stack pointer.
2087   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2088   EVT ValTy = Op->getValueType(0);
2089   int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2090   SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2091   return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2092                      DAG.getConstant(0, ValTy));
2093 }
2094
2095 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2096                                             SelectionDAG &DAG) const {
2097   EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2098   SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2099                               Op.getOperand(0));
2100   return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2101 }
2102
2103 //===----------------------------------------------------------------------===//
2104 //                      Calling Convention Implementation
2105 //===----------------------------------------------------------------------===//
2106
2107 //===----------------------------------------------------------------------===//
2108 // TODO: Implement a generic logic using tblgen that can support this.
2109 // Mips O32 ABI rules:
2110 // ---
2111 // i32 - Passed in A0, A1, A2, A3 and stack
2112 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2113 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
2114 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2115 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2116 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
2117 //       go to stack.
2118 //
2119 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2120 //===----------------------------------------------------------------------===//
2121
2122 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2123                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2124                        CCState &State, const MCPhysReg *F64Regs) {
2125
2126   static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2127
2128   static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2129   static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2130
2131   // Do not process byval args here.
2132   if (ArgFlags.isByVal())
2133     return true;
2134
2135   // Promote i8 and i16
2136   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2137     LocVT = MVT::i32;
2138     if (ArgFlags.isSExt())
2139       LocInfo = CCValAssign::SExt;
2140     else if (ArgFlags.isZExt())
2141       LocInfo = CCValAssign::ZExt;
2142     else
2143       LocInfo = CCValAssign::AExt;
2144   }
2145
2146   unsigned Reg;
2147
2148   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2149   // is true: function is vararg, argument is 3rd or higher, there is previous
2150   // argument which is not f32 or f64.
2151   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2152       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2153   unsigned OrigAlign = ArgFlags.getOrigAlign();
2154   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2155
2156   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2157     Reg = State.AllocateReg(IntRegs, IntRegsSize);
2158     // If this is the first part of an i64 arg,
2159     // the allocated register must be either A0 or A2.
2160     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2161       Reg = State.AllocateReg(IntRegs, IntRegsSize);
2162     LocVT = MVT::i32;
2163   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2164     // Allocate int register and shadow next int register. If first
2165     // available register is Mips::A1 or Mips::A3, shadow it too.
2166     Reg = State.AllocateReg(IntRegs, IntRegsSize);
2167     if (Reg == Mips::A1 || Reg == Mips::A3)
2168       Reg = State.AllocateReg(IntRegs, IntRegsSize);
2169     State.AllocateReg(IntRegs, IntRegsSize);
2170     LocVT = MVT::i32;
2171   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2172     // we are guaranteed to find an available float register
2173     if (ValVT == MVT::f32) {
2174       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2175       // Shadow int register
2176       State.AllocateReg(IntRegs, IntRegsSize);
2177     } else {
2178       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2179       // Shadow int registers
2180       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2181       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2182         State.AllocateReg(IntRegs, IntRegsSize);
2183       State.AllocateReg(IntRegs, IntRegsSize);
2184     }
2185   } else
2186     llvm_unreachable("Cannot handle this ValVT.");
2187
2188   if (!Reg) {
2189     unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2190                                           OrigAlign);
2191     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2192   } else
2193     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2194
2195   return false;
2196 }
2197
2198 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2199                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2200                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2201   static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2202
2203   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2204 }
2205
2206 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2207                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2208                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2209   static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2210
2211   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2212 }
2213
2214 #include "MipsGenCallingConv.inc"
2215
2216 //===----------------------------------------------------------------------===//
2217 //                  Call Calling Convention Implementation
2218 //===----------------------------------------------------------------------===//
2219
2220 // Return next O32 integer argument register.
2221 static unsigned getNextIntArgReg(unsigned Reg) {
2222   assert((Reg == Mips::A0) || (Reg == Mips::A2));
2223   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2224 }
2225
2226 SDValue
2227 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2228                                    SDValue Chain, SDValue Arg, SDLoc DL,
2229                                    bool IsTailCall, SelectionDAG &DAG) const {
2230   if (!IsTailCall) {
2231     SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2232                                  DAG.getIntPtrConstant(Offset));
2233     return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2234                         false, 0);
2235   }
2236
2237   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2238   int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2239   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2240   return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2241                       /*isVolatile=*/ true, false, 0);
2242 }
2243
2244 void MipsTargetLowering::
2245 getOpndList(SmallVectorImpl<SDValue> &Ops,
2246             std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2247             bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2248             CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2249   // Insert node "GP copy globalreg" before call to function.
2250   //
2251   // R_MIPS_CALL* operators (emitted when non-internal functions are called
2252   // in PIC mode) allow symbols to be resolved via lazy binding.
2253   // The lazy binding stub requires GP to point to the GOT.
2254   if (IsPICCall && !InternalLinkage) {
2255     unsigned GPReg = isN64() ? Mips::GP_64 : Mips::GP;
2256     EVT Ty = isN64() ? MVT::i64 : MVT::i32;
2257     RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2258   }
2259
2260   // Build a sequence of copy-to-reg nodes chained together with token
2261   // chain and flag operands which copy the outgoing args into registers.
2262   // The InFlag in necessary since all emitted instructions must be
2263   // stuck together.
2264   SDValue InFlag;
2265
2266   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2267     Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2268                                  RegsToPass[i].second, InFlag);
2269     InFlag = Chain.getValue(1);
2270   }
2271
2272   // Add argument registers to the end of the list so that they are
2273   // known live into the call.
2274   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2275     Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2276                                       RegsToPass[i].second.getValueType()));
2277
2278   // Add a register mask operand representing the call-preserved registers.
2279   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2280   const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2281   assert(Mask && "Missing call preserved mask for calling convention");
2282   if (Subtarget->inMips16HardFloat()) {
2283     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2284       llvm::StringRef Sym = G->getGlobal()->getName();
2285       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2286       if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2287         Mask = MipsRegisterInfo::getMips16RetHelperMask();
2288       }
2289     }
2290   }
2291   Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2292
2293   if (InFlag.getNode())
2294     Ops.push_back(InFlag);
2295 }
2296
2297 /// LowerCall - functions arguments are copied from virtual regs to
2298 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2299 SDValue
2300 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2301                               SmallVectorImpl<SDValue> &InVals) const {
2302   SelectionDAG &DAG                     = CLI.DAG;
2303   SDLoc DL                              = CLI.DL;
2304   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2305   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2306   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2307   SDValue Chain                         = CLI.Chain;
2308   SDValue Callee                        = CLI.Callee;
2309   bool &IsTailCall                      = CLI.IsTailCall;
2310   CallingConv::ID CallConv              = CLI.CallConv;
2311   bool IsVarArg                         = CLI.IsVarArg;
2312
2313   MachineFunction &MF = DAG.getMachineFunction();
2314   MachineFrameInfo *MFI = MF.getFrameInfo();
2315   const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2316   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2317   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2318
2319   // Analyze operands of the call, assigning locations to each operand.
2320   SmallVector<CCValAssign, 16> ArgLocs;
2321   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2322                  getTargetMachine(), ArgLocs, *DAG.getContext());
2323   MipsCC::SpecialCallingConvType SpecialCallingConv =
2324     getSpecialCallingConv(Callee);
2325   MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo,
2326                     SpecialCallingConv);
2327
2328   MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2329                                  Subtarget->mipsSEUsesSoftFloat(),
2330                                  Callee.getNode(), CLI.getArgs());
2331
2332   // Get a count of how many bytes are to be pushed on the stack.
2333   unsigned NextStackOffset = CCInfo.getNextStackOffset();
2334
2335   // Check if it's really possible to do a tail call.
2336   if (IsTailCall)
2337     IsTailCall =
2338       isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2339                                         *MF.getInfo<MipsFunctionInfo>());
2340
2341   if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2342     report_fatal_error("failed to perform tail call elimination on a call "
2343                        "site marked musttail");
2344
2345   if (IsTailCall)
2346     ++NumTailCalls;
2347
2348   // Chain is the output chain of the last Load/Store or CopyToReg node.
2349   // ByValChain is the output chain of the last Memcpy node created for copying
2350   // byval arguments to the stack.
2351   unsigned StackAlignment = TFL->getStackAlignment();
2352   NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2353   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2354
2355   if (!IsTailCall)
2356     Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2357
2358   SDValue StackPtr = DAG.getCopyFromReg(
2359       Chain, DL, isN64() ? Mips::SP_64 : Mips::SP, getPointerTy());
2360
2361   // With EABI is it possible to have 16 args on registers.
2362   std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2363   SmallVector<SDValue, 8> MemOpChains;
2364   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2365
2366   // Walk the register/memloc assignments, inserting copies/loads.
2367   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2368     SDValue Arg = OutVals[i];
2369     CCValAssign &VA = ArgLocs[i];
2370     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2371     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2372
2373     // ByVal Arg.
2374     if (Flags.isByVal()) {
2375       assert(Flags.getByValSize() &&
2376              "ByVal args of size 0 should have been ignored by front-end.");
2377       assert(ByValArg != MipsCCInfo.byval_end());
2378       assert(!IsTailCall &&
2379              "Do not tail-call optimize if there is a byval argument.");
2380       passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2381                    MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2382       ++ByValArg;
2383       continue;
2384     }
2385
2386     // Promote the value if needed.
2387     switch (VA.getLocInfo()) {
2388     default: llvm_unreachable("Unknown loc info!");
2389     case CCValAssign::Full:
2390       if (VA.isRegLoc()) {
2391         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2392             (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2393             (ValVT == MVT::i64 && LocVT == MVT::f64))
2394           Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2395         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2396           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2397                                    Arg, DAG.getConstant(0, MVT::i32));
2398           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2399                                    Arg, DAG.getConstant(1, MVT::i32));
2400           if (!Subtarget->isLittle())
2401             std::swap(Lo, Hi);
2402           unsigned LocRegLo = VA.getLocReg();
2403           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2404           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2405           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2406           continue;
2407         }
2408       }
2409       break;
2410     case CCValAssign::SExt:
2411       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2412       break;
2413     case CCValAssign::ZExt:
2414       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2415       break;
2416     case CCValAssign::AExt:
2417       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2418       break;
2419     }
2420
2421     // Arguments that can be passed on register must be kept at
2422     // RegsToPass vector
2423     if (VA.isRegLoc()) {
2424       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2425       continue;
2426     }
2427
2428     // Register can't get to this point...
2429     assert(VA.isMemLoc());
2430
2431     // emit ISD::STORE whichs stores the
2432     // parameter value to a stack Location
2433     MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2434                                          Chain, Arg, DL, IsTailCall, DAG));
2435   }
2436
2437   // Transform all store nodes into one single node because all store
2438   // nodes are independent of each other.
2439   if (!MemOpChains.empty())
2440     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2441
2442   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2443   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2444   // node so that legalize doesn't hack it.
2445   bool IsPICCall = (isN64() || IsPIC); // true if calls are translated to
2446                                        // jalr $25
2447   bool GlobalOrExternal = false, InternalLinkage = false;
2448   SDValue CalleeLo;
2449   EVT Ty = Callee.getValueType();
2450
2451   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2452     if (IsPICCall) {
2453       const GlobalValue *Val = G->getGlobal();
2454       InternalLinkage = Val->hasInternalLinkage();
2455
2456       if (InternalLinkage)
2457         Callee = getAddrLocal(G, Ty, DAG, isN32() || isN64());
2458       else if (LargeGOT)
2459         Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2460                                        MipsII::MO_CALL_LO16, Chain,
2461                                        FuncInfo->callPtrInfo(Val));
2462       else
2463         Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2464                                FuncInfo->callPtrInfo(Val));
2465     } else
2466       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2467                                           MipsII::MO_NO_FLAG);
2468     GlobalOrExternal = true;
2469   }
2470   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2471     const char *Sym = S->getSymbol();
2472
2473     if (!isN64() && !IsPIC) // !N64 && static
2474       Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2475                                             MipsII::MO_NO_FLAG);
2476     else if (LargeGOT)
2477       Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2478                                      MipsII::MO_CALL_LO16, Chain,
2479                                      FuncInfo->callPtrInfo(Sym));
2480     else // N64 || PIC
2481       Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2482                              FuncInfo->callPtrInfo(Sym));
2483
2484     GlobalOrExternal = true;
2485   }
2486
2487   SmallVector<SDValue, 8> Ops(1, Chain);
2488   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2489
2490   getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2491               CLI, Callee, Chain);
2492
2493   if (IsTailCall)
2494     return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2495
2496   Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2497   SDValue InFlag = Chain.getValue(1);
2498
2499   // Create the CALLSEQ_END node.
2500   Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2501                              DAG.getIntPtrConstant(0, true), InFlag, DL);
2502   InFlag = Chain.getValue(1);
2503
2504   // Handle result values, copying them out of physregs into vregs that we
2505   // return.
2506   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2507                          Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2508 }
2509
2510 /// LowerCallResult - Lower the result values of a call into the
2511 /// appropriate copies out of appropriate physical registers.
2512 SDValue
2513 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2514                                     CallingConv::ID CallConv, bool IsVarArg,
2515                                     const SmallVectorImpl<ISD::InputArg> &Ins,
2516                                     SDLoc DL, SelectionDAG &DAG,
2517                                     SmallVectorImpl<SDValue> &InVals,
2518                                     const SDNode *CallNode,
2519                                     const Type *RetTy) const {
2520   // Assign locations to each value returned by this call.
2521   SmallVector<CCValAssign, 16> RVLocs;
2522   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2523                  getTargetMachine(), RVLocs, *DAG.getContext());
2524   MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2525
2526   MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2527                                CallNode, RetTy);
2528
2529   // Copy all of the result registers out of their specified physreg.
2530   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2531     SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2532                                      RVLocs[i].getLocVT(), InFlag);
2533     Chain = Val.getValue(1);
2534     InFlag = Val.getValue(2);
2535
2536     if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2537       Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2538
2539     InVals.push_back(Val);
2540   }
2541
2542   return Chain;
2543 }
2544
2545 //===----------------------------------------------------------------------===//
2546 //             Formal Arguments Calling Convention Implementation
2547 //===----------------------------------------------------------------------===//
2548 /// LowerFormalArguments - transform physical registers into virtual registers
2549 /// and generate load operations for arguments places on the stack.
2550 SDValue
2551 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2552                                          CallingConv::ID CallConv,
2553                                          bool IsVarArg,
2554                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2555                                          SDLoc DL, SelectionDAG &DAG,
2556                                          SmallVectorImpl<SDValue> &InVals)
2557                                           const {
2558   MachineFunction &MF = DAG.getMachineFunction();
2559   MachineFrameInfo *MFI = MF.getFrameInfo();
2560   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2561
2562   MipsFI->setVarArgsFrameIndex(0);
2563
2564   // Used with vargs to acumulate store chains.
2565   std::vector<SDValue> OutChains;
2566
2567   // Assign locations to all of the incoming arguments.
2568   SmallVector<CCValAssign, 16> ArgLocs;
2569   CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2570                  getTargetMachine(), ArgLocs, *DAG.getContext());
2571   MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2572   Function::const_arg_iterator FuncArg =
2573     DAG.getMachineFunction().getFunction()->arg_begin();
2574   bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2575
2576   MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2577   MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2578                            MipsCCInfo.hasByValArg());
2579
2580   unsigned CurArgIdx = 0;
2581   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2582
2583   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2584     CCValAssign &VA = ArgLocs[i];
2585     std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2586     CurArgIdx = Ins[i].OrigArgIndex;
2587     EVT ValVT = VA.getValVT();
2588     ISD::ArgFlagsTy Flags = Ins[i].Flags;
2589     bool IsRegLoc = VA.isRegLoc();
2590
2591     if (Flags.isByVal()) {
2592       assert(Flags.getByValSize() &&
2593              "ByVal args of size 0 should have been ignored by front-end.");
2594       assert(ByValArg != MipsCCInfo.byval_end());
2595       copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2596                     MipsCCInfo, *ByValArg);
2597       ++ByValArg;
2598       continue;
2599     }
2600
2601     // Arguments stored on registers
2602     if (IsRegLoc) {
2603       MVT RegVT = VA.getLocVT();
2604       unsigned ArgReg = VA.getLocReg();
2605       const TargetRegisterClass *RC = getRegClassFor(RegVT);
2606
2607       // Transform the arguments stored on
2608       // physical registers into virtual ones
2609       unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2610       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2611
2612       // If this is an 8 or 16-bit value, it has been passed promoted
2613       // to 32 bits.  Insert an assert[sz]ext to capture this, then
2614       // truncate to the right size.
2615       if (VA.getLocInfo() != CCValAssign::Full) {
2616         unsigned Opcode = 0;
2617         if (VA.getLocInfo() == CCValAssign::SExt)
2618           Opcode = ISD::AssertSext;
2619         else if (VA.getLocInfo() == CCValAssign::ZExt)
2620           Opcode = ISD::AssertZext;
2621         if (Opcode)
2622           ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2623                                  DAG.getValueType(ValVT));
2624         ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2625       }
2626
2627       // Handle floating point arguments passed in integer registers and
2628       // long double arguments passed in floating point registers.
2629       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2630           (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2631           (RegVT == MVT::f64 && ValVT == MVT::i64))
2632         ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2633       else if (isO32() && RegVT == MVT::i32 && ValVT == MVT::f64) {
2634         unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2635                                   getNextIntArgReg(ArgReg), RC);
2636         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2637         if (!Subtarget->isLittle())
2638           std::swap(ArgValue, ArgValue2);
2639         ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2640                                ArgValue, ArgValue2);
2641       }
2642
2643       InVals.push_back(ArgValue);
2644     } else { // VA.isRegLoc()
2645
2646       // sanity check
2647       assert(VA.isMemLoc());
2648
2649       // The stack pointer offset is relative to the caller stack frame.
2650       int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2651                                       VA.getLocMemOffset(), true);
2652
2653       // Create load nodes to retrieve arguments from the stack
2654       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2655       SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2656                                  MachinePointerInfo::getFixedStack(FI),
2657                                  false, false, false, 0);
2658       InVals.push_back(Load);
2659       OutChains.push_back(Load.getValue(1));
2660     }
2661   }
2662
2663   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2664     // The mips ABIs for returning structs by value requires that we copy
2665     // the sret argument into $v0 for the return. Save the argument into
2666     // a virtual register so that we can access it from the return points.
2667     if (Ins[i].Flags.isSRet()) {
2668       unsigned Reg = MipsFI->getSRetReturnReg();
2669       if (!Reg) {
2670         Reg = MF.getRegInfo().createVirtualRegister(
2671             getRegClassFor(isN64() ? MVT::i64 : MVT::i32));
2672         MipsFI->setSRetReturnReg(Reg);
2673       }
2674       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
2675       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2676       break;
2677     }
2678   }
2679
2680   if (IsVarArg)
2681     writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2682
2683   // All stores are grouped in one node to allow the matching between
2684   // the size of Ins and InVals. This only happens when on varg functions
2685   if (!OutChains.empty()) {
2686     OutChains.push_back(Chain);
2687     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2688   }
2689
2690   return Chain;
2691 }
2692
2693 //===----------------------------------------------------------------------===//
2694 //               Return Value Calling Convention Implementation
2695 //===----------------------------------------------------------------------===//
2696
2697 bool
2698 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2699                                    MachineFunction &MF, bool IsVarArg,
2700                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2701                                    LLVMContext &Context) const {
2702   SmallVector<CCValAssign, 16> RVLocs;
2703   CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2704                  RVLocs, Context);
2705   return CCInfo.CheckReturn(Outs, RetCC_Mips);
2706 }
2707
2708 SDValue
2709 MipsTargetLowering::LowerReturn(SDValue Chain,
2710                                 CallingConv::ID CallConv, bool IsVarArg,
2711                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
2712                                 const SmallVectorImpl<SDValue> &OutVals,
2713                                 SDLoc DL, SelectionDAG &DAG) const {
2714   // CCValAssign - represent the assignment of
2715   // the return value to a location
2716   SmallVector<CCValAssign, 16> RVLocs;
2717   MachineFunction &MF = DAG.getMachineFunction();
2718
2719   // CCState - Info about the registers and stack slot.
2720   CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2721                  *DAG.getContext());
2722   MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2723
2724   // Analyze return values.
2725   MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2726                            MF.getFunction()->getReturnType());
2727
2728   SDValue Flag;
2729   SmallVector<SDValue, 4> RetOps(1, Chain);
2730
2731   // Copy the result values into the output registers.
2732   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2733     SDValue Val = OutVals[i];
2734     CCValAssign &VA = RVLocs[i];
2735     assert(VA.isRegLoc() && "Can only return in registers!");
2736
2737     if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2738       Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2739
2740     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2741
2742     // Guarantee that all emitted copies are stuck together with flags.
2743     Flag = Chain.getValue(1);
2744     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2745   }
2746
2747   // The mips ABIs for returning structs by value requires that we copy
2748   // the sret argument into $v0 for the return. We saved the argument into
2749   // a virtual register in the entry block, so now we copy the value out
2750   // and into $v0.
2751   if (MF.getFunction()->hasStructRetAttr()) {
2752     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2753     unsigned Reg = MipsFI->getSRetReturnReg();
2754
2755     if (!Reg)
2756       llvm_unreachable("sret virtual register not created in the entry block");
2757     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2758     unsigned V0 = isN64() ? Mips::V0_64 : Mips::V0;
2759
2760     Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2761     Flag = Chain.getValue(1);
2762     RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2763   }
2764
2765   RetOps[0] = Chain;  // Update chain.
2766
2767   // Add the flag if we have it.
2768   if (Flag.getNode())
2769     RetOps.push_back(Flag);
2770
2771   // Return on Mips is always a "jr $ra"
2772   return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
2773 }
2774
2775 //===----------------------------------------------------------------------===//
2776 //                           Mips Inline Assembly Support
2777 //===----------------------------------------------------------------------===//
2778
2779 /// getConstraintType - Given a constraint letter, return the type of
2780 /// constraint it is for this target.
2781 MipsTargetLowering::ConstraintType MipsTargetLowering::
2782 getConstraintType(const std::string &Constraint) const
2783 {
2784   // Mips specific constraints
2785   // GCC config/mips/constraints.md
2786   //
2787   // 'd' : An address register. Equivalent to r
2788   //       unless generating MIPS16 code.
2789   // 'y' : Equivalent to r; retained for
2790   //       backwards compatibility.
2791   // 'c' : A register suitable for use in an indirect
2792   //       jump. This will always be $25 for -mabicalls.
2793   // 'l' : The lo register. 1 word storage.
2794   // 'x' : The hilo register pair. Double word storage.
2795   if (Constraint.size() == 1) {
2796     switch (Constraint[0]) {
2797       default : break;
2798       case 'd':
2799       case 'y':
2800       case 'f':
2801       case 'c':
2802       case 'l':
2803       case 'x':
2804         return C_RegisterClass;
2805       case 'R':
2806         return C_Memory;
2807     }
2808   }
2809   return TargetLowering::getConstraintType(Constraint);
2810 }
2811
2812 /// Examine constraint type and operand type and determine a weight value.
2813 /// This object must already have been set up with the operand type
2814 /// and the current alternative constraint selected.
2815 TargetLowering::ConstraintWeight
2816 MipsTargetLowering::getSingleConstraintMatchWeight(
2817     AsmOperandInfo &info, const char *constraint) const {
2818   ConstraintWeight weight = CW_Invalid;
2819   Value *CallOperandVal = info.CallOperandVal;
2820     // If we don't have a value, we can't do a match,
2821     // but allow it at the lowest weight.
2822   if (!CallOperandVal)
2823     return CW_Default;
2824   Type *type = CallOperandVal->getType();
2825   // Look at the constraint type.
2826   switch (*constraint) {
2827   default:
2828     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2829     break;
2830   case 'd':
2831   case 'y':
2832     if (type->isIntegerTy())
2833       weight = CW_Register;
2834     break;
2835   case 'f': // FPU or MSA register
2836     if (Subtarget->hasMSA() && type->isVectorTy() &&
2837         cast<VectorType>(type)->getBitWidth() == 128)
2838       weight = CW_Register;
2839     else if (type->isFloatTy())
2840       weight = CW_Register;
2841     break;
2842   case 'c': // $25 for indirect jumps
2843   case 'l': // lo register
2844   case 'x': // hilo register pair
2845     if (type->isIntegerTy())
2846       weight = CW_SpecificReg;
2847     break;
2848   case 'I': // signed 16 bit immediate
2849   case 'J': // integer zero
2850   case 'K': // unsigned 16 bit immediate
2851   case 'L': // signed 32 bit immediate where lower 16 bits are 0
2852   case 'N': // immediate in the range of -65535 to -1 (inclusive)
2853   case 'O': // signed 15 bit immediate (+- 16383)
2854   case 'P': // immediate in the range of 65535 to 1 (inclusive)
2855     if (isa<ConstantInt>(CallOperandVal))
2856       weight = CW_Constant;
2857     break;
2858   case 'R':
2859     weight = CW_Memory;
2860     break;
2861   }
2862   return weight;
2863 }
2864
2865 /// This is a helper function to parse a physical register string and split it
2866 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2867 /// that is returned indicates whether parsing was successful. The second flag
2868 /// is true if the numeric part exists.
2869 static std::pair<bool, bool>
2870 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2871                  unsigned long long &Reg) {
2872   if (C.front() != '{' || C.back() != '}')
2873     return std::make_pair(false, false);
2874
2875   // Search for the first numeric character.
2876   StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2877   I = std::find_if(B, E, std::ptr_fun(isdigit));
2878
2879   Prefix.assign(B, I - B);
2880
2881   // The second flag is set to false if no numeric characters were found.
2882   if (I == E)
2883     return std::make_pair(true, false);
2884
2885   // Parse the numeric characters.
2886   return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2887                         true);
2888 }
2889
2890 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2891 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2892   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2893   const TargetRegisterClass *RC;
2894   std::string Prefix;
2895   unsigned long long Reg;
2896
2897   std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2898
2899   if (!R.first)
2900     return std::make_pair(0U, nullptr);
2901
2902   if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2903     // No numeric characters follow "hi" or "lo".
2904     if (R.second)
2905       return std::make_pair(0U, nullptr);
2906
2907     RC = TRI->getRegClass(Prefix == "hi" ?
2908                           Mips::HI32RegClassID : Mips::LO32RegClassID);
2909     return std::make_pair(*(RC->begin()), RC);
2910   } else if (Prefix.compare(0, 4, "$msa") == 0) {
2911     // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
2912
2913     // No numeric characters follow the name.
2914     if (R.second)
2915       return std::make_pair(0U, nullptr);
2916
2917     Reg = StringSwitch<unsigned long long>(Prefix)
2918               .Case("$msair", Mips::MSAIR)
2919               .Case("$msacsr", Mips::MSACSR)
2920               .Case("$msaaccess", Mips::MSAAccess)
2921               .Case("$msasave", Mips::MSASave)
2922               .Case("$msamodify", Mips::MSAModify)
2923               .Case("$msarequest", Mips::MSARequest)
2924               .Case("$msamap", Mips::MSAMap)
2925               .Case("$msaunmap", Mips::MSAUnmap)
2926               .Default(0);
2927
2928     if (!Reg)
2929       return std::make_pair(0U, nullptr);
2930
2931     RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
2932     return std::make_pair(Reg, RC);
2933   }
2934
2935   if (!R.second)
2936     return std::make_pair(0U, nullptr);
2937
2938   if (Prefix == "$f") { // Parse $f0-$f31.
2939     // If the size of FP registers is 64-bit or Reg is an even number, select
2940     // the 64-bit register class. Otherwise, select the 32-bit register class.
2941     if (VT == MVT::Other)
2942       VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2943
2944     RC = getRegClassFor(VT);
2945
2946     if (RC == &Mips::AFGR64RegClass) {
2947       assert(Reg % 2 == 0);
2948       Reg >>= 1;
2949     }
2950   } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
2951     RC = TRI->getRegClass(Mips::FCCRegClassID);
2952   else if (Prefix == "$w") { // Parse $w0-$w31.
2953     RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
2954   } else { // Parse $0-$31.
2955     assert(Prefix == "$");
2956     RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2957   }
2958
2959   assert(Reg < RC->getNumRegs());
2960   return std::make_pair(*(RC->begin() + Reg), RC);
2961 }
2962
2963 /// Given a register class constraint, like 'r', if this corresponds directly
2964 /// to an LLVM register class, return a register of 0 and the register class
2965 /// pointer.
2966 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2967 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2968 {
2969   if (Constraint.size() == 1) {
2970     switch (Constraint[0]) {
2971     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2972     case 'y': // Same as 'r'. Exists for compatibility.
2973     case 'r':
2974       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2975         if (Subtarget->inMips16Mode())
2976           return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2977         return std::make_pair(0U, &Mips::GPR32RegClass);
2978       }
2979       if (VT == MVT::i64 && !isGP64bit())
2980         return std::make_pair(0U, &Mips::GPR32RegClass);
2981       if (VT == MVT::i64 && isGP64bit())
2982         return std::make_pair(0U, &Mips::GPR64RegClass);
2983       // This will generate an error message
2984       return std::make_pair(0U, nullptr);
2985     case 'f': // FPU or MSA register
2986       if (VT == MVT::v16i8)
2987         return std::make_pair(0U, &Mips::MSA128BRegClass);
2988       else if (VT == MVT::v8i16 || VT == MVT::v8f16)
2989         return std::make_pair(0U, &Mips::MSA128HRegClass);
2990       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2991         return std::make_pair(0U, &Mips::MSA128WRegClass);
2992       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2993         return std::make_pair(0U, &Mips::MSA128DRegClass);
2994       else if (VT == MVT::f32)
2995         return std::make_pair(0U, &Mips::FGR32RegClass);
2996       else if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2997         if (Subtarget->isFP64bit())
2998           return std::make_pair(0U, &Mips::FGR64RegClass);
2999         return std::make_pair(0U, &Mips::AFGR64RegClass);
3000       }
3001       break;
3002     case 'c': // register suitable for indirect jump
3003       if (VT == MVT::i32)
3004         return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3005       assert(VT == MVT::i64 && "Unexpected type.");
3006       return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3007     case 'l': // register suitable for indirect jump
3008       if (VT == MVT::i32)
3009         return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3010       return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3011     case 'x': // register suitable for indirect jump
3012       // Fixme: Not triggering the use of both hi and low
3013       // This will generate an error message
3014       return std::make_pair(0U, nullptr);
3015     }
3016   }
3017
3018   std::pair<unsigned, const TargetRegisterClass *> R;
3019   R = parseRegForInlineAsmConstraint(Constraint, VT);
3020
3021   if (R.second)
3022     return R;
3023
3024   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3025 }
3026
3027 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3028 /// vector.  If it is invalid, don't add anything to Ops.
3029 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3030                                                      std::string &Constraint,
3031                                                      std::vector<SDValue>&Ops,
3032                                                      SelectionDAG &DAG) const {
3033   SDValue Result;
3034
3035   // Only support length 1 constraints for now.
3036   if (Constraint.length() > 1) return;
3037
3038   char ConstraintLetter = Constraint[0];
3039   switch (ConstraintLetter) {
3040   default: break; // This will fall through to the generic implementation
3041   case 'I': // Signed 16 bit constant
3042     // If this fails, the parent routine will give an error
3043     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3044       EVT Type = Op.getValueType();
3045       int64_t Val = C->getSExtValue();
3046       if (isInt<16>(Val)) {
3047         Result = DAG.getTargetConstant(Val, Type);
3048         break;
3049       }
3050     }
3051     return;
3052   case 'J': // integer zero
3053     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3054       EVT Type = Op.getValueType();
3055       int64_t Val = C->getZExtValue();
3056       if (Val == 0) {
3057         Result = DAG.getTargetConstant(0, Type);
3058         break;
3059       }
3060     }
3061     return;
3062   case 'K': // unsigned 16 bit immediate
3063     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3064       EVT Type = Op.getValueType();
3065       uint64_t Val = (uint64_t)C->getZExtValue();
3066       if (isUInt<16>(Val)) {
3067         Result = DAG.getTargetConstant(Val, Type);
3068         break;
3069       }
3070     }
3071     return;
3072   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3073     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3074       EVT Type = Op.getValueType();
3075       int64_t Val = C->getSExtValue();
3076       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3077         Result = DAG.getTargetConstant(Val, Type);
3078         break;
3079       }
3080     }
3081     return;
3082   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3083     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3084       EVT Type = Op.getValueType();
3085       int64_t Val = C->getSExtValue();
3086       if ((Val >= -65535) && (Val <= -1)) {
3087         Result = DAG.getTargetConstant(Val, Type);
3088         break;
3089       }
3090     }
3091     return;
3092   case 'O': // signed 15 bit immediate
3093     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3094       EVT Type = Op.getValueType();
3095       int64_t Val = C->getSExtValue();
3096       if ((isInt<15>(Val))) {
3097         Result = DAG.getTargetConstant(Val, Type);
3098         break;
3099       }
3100     }
3101     return;
3102   case 'P': // immediate in the range of 1 to 65535 (inclusive)
3103     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3104       EVT Type = Op.getValueType();
3105       int64_t Val = C->getSExtValue();
3106       if ((Val <= 65535) && (Val >= 1)) {
3107         Result = DAG.getTargetConstant(Val, Type);
3108         break;
3109       }
3110     }
3111     return;
3112   }
3113
3114   if (Result.getNode()) {
3115     Ops.push_back(Result);
3116     return;
3117   }
3118
3119   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3120 }
3121
3122 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3123                                                Type *Ty) const {
3124   // No global is ever allowed as a base.
3125   if (AM.BaseGV)
3126     return false;
3127
3128   switch (AM.Scale) {
3129   case 0: // "r+i" or just "i", depending on HasBaseReg.
3130     break;
3131   case 1:
3132     if (!AM.HasBaseReg) // allow "r+i".
3133       break;
3134     return false; // disallow "r+r" or "r+r+i".
3135   default:
3136     return false;
3137   }
3138
3139   return true;
3140 }
3141
3142 bool
3143 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3144   // The Mips target isn't yet aware of offsets.
3145   return false;
3146 }
3147
3148 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3149                                             unsigned SrcAlign,
3150                                             bool IsMemset, bool ZeroMemset,
3151                                             bool MemcpyStrSrc,
3152                                             MachineFunction &MF) const {
3153   if (Subtarget->hasMips64())
3154     return MVT::i64;
3155
3156   return MVT::i32;
3157 }
3158
3159 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3160   if (VT != MVT::f32 && VT != MVT::f64)
3161     return false;
3162   if (Imm.isNegZero())
3163     return false;
3164   return Imm.isZero();
3165 }
3166
3167 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3168   if (isN64())
3169     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3170
3171   return TargetLowering::getJumpTableEncoding();
3172 }
3173
3174 /// This function returns true if CallSym is a long double emulation routine.
3175 static bool isF128SoftLibCall(const char *CallSym) {
3176   const char *const LibCalls[] =
3177     {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3178      "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3179      "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3180      "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3181      "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3182      "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3183      "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3184      "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3185      "truncl"};
3186
3187   const char *const *End = LibCalls + array_lengthof(LibCalls);
3188
3189   // Check that LibCalls is sorted alphabetically.
3190   MipsTargetLowering::LTStr Comp;
3191
3192 #ifndef NDEBUG
3193   for (const char *const *I = LibCalls; I < End - 1; ++I)
3194     assert(Comp(*I, *(I + 1)));
3195 #endif
3196
3197   return std::binary_search(LibCalls, End, CallSym, Comp);
3198 }
3199
3200 /// This function returns true if Ty is fp128 or i128 which was originally a
3201 /// fp128.
3202 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3203   if (Ty->isFP128Ty())
3204     return true;
3205
3206   const ExternalSymbolSDNode *ES =
3207     dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3208
3209   // If the Ty is i128 and the function being called is a long double emulation
3210   // routine, then the original type is f128.
3211   return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3212 }
3213
3214 MipsTargetLowering::MipsCC::SpecialCallingConvType
3215   MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3216   MipsCC::SpecialCallingConvType SpecialCallingConv =
3217     MipsCC::NoSpecialCallingConv;
3218   if (Subtarget->inMips16HardFloat()) {
3219     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3220       llvm::StringRef Sym = G->getGlobal()->getName();
3221       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3222       if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3223         SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3224       }
3225     }
3226   }
3227   return SpecialCallingConv;
3228 }
3229
3230 MipsTargetLowering::MipsCC::MipsCC(
3231   CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3232   MipsCC::SpecialCallingConvType SpecialCallingConv_)
3233   : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3234     SpecialCallingConv(SpecialCallingConv_){
3235   // Pre-allocate reserved argument area.
3236   CCInfo.AllocateStack(reservedArgArea(), 1);
3237 }
3238
3239
3240 void MipsTargetLowering::MipsCC::
3241 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3242                     bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3243                     std::vector<ArgListEntry> &FuncArgs) {
3244   assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3245          "CallingConv::Fast shouldn't be used for vararg functions.");
3246
3247   unsigned NumOpnds = Args.size();
3248   llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3249
3250   for (unsigned I = 0; I != NumOpnds; ++I) {
3251     MVT ArgVT = Args[I].VT;
3252     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3253     bool R;
3254
3255     if (ArgFlags.isByVal()) {
3256       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3257       continue;
3258     }
3259
3260     if (IsVarArg && !Args[I].IsFixed)
3261       R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3262     else {
3263       MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3264                            IsSoftFloat);
3265       R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3266     }
3267
3268     if (R) {
3269 #ifndef NDEBUG
3270       dbgs() << "Call operand #" << I << " has unhandled type "
3271              << EVT(ArgVT).getEVTString();
3272 #endif
3273       llvm_unreachable(nullptr);
3274     }
3275   }
3276 }
3277
3278 void MipsTargetLowering::MipsCC::
3279 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3280                        bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3281   unsigned NumArgs = Args.size();
3282   llvm::CCAssignFn *FixedFn = fixedArgFn();
3283   unsigned CurArgIdx = 0;
3284
3285   for (unsigned I = 0; I != NumArgs; ++I) {
3286     MVT ArgVT = Args[I].VT;
3287     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3288     std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3289     CurArgIdx = Args[I].OrigArgIndex;
3290
3291     if (ArgFlags.isByVal()) {
3292       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3293       continue;
3294     }
3295
3296     MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), nullptr, IsSoftFloat);
3297
3298     if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3299       continue;
3300
3301 #ifndef NDEBUG
3302     dbgs() << "Formal Arg #" << I << " has unhandled type "
3303            << EVT(ArgVT).getEVTString();
3304 #endif
3305     llvm_unreachable(nullptr);
3306   }
3307 }
3308
3309 template<typename Ty>
3310 void MipsTargetLowering::MipsCC::
3311 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3312               const SDNode *CallNode, const Type *RetTy) const {
3313   CCAssignFn *Fn;
3314
3315   if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3316     Fn = RetCC_F128Soft;
3317   else
3318     Fn = RetCC_Mips;
3319
3320   for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3321     MVT VT = RetVals[I].VT;
3322     ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3323     MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3324
3325     if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3326 #ifndef NDEBUG
3327       dbgs() << "Call result #" << I << " has unhandled type "
3328              << EVT(VT).getEVTString() << '\n';
3329 #endif
3330       llvm_unreachable(nullptr);
3331     }
3332   }
3333 }
3334
3335 void MipsTargetLowering::MipsCC::
3336 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3337                   const SDNode *CallNode, const Type *RetTy) const {
3338   analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3339 }
3340
3341 void MipsTargetLowering::MipsCC::
3342 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3343               const Type *RetTy) const {
3344   analyzeReturn(Outs, IsSoftFloat, nullptr, RetTy);
3345 }
3346
3347 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3348                                                 MVT LocVT,
3349                                                 CCValAssign::LocInfo LocInfo,
3350                                                 ISD::ArgFlagsTy ArgFlags) {
3351   assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3352
3353   struct ByValArgInfo ByVal;
3354   unsigned RegSize = regSize();
3355   unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3356   unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3357                             RegSize * 2);
3358
3359   if (useRegsForByval())
3360     allocateRegs(ByVal, ByValSize, Align);
3361
3362   // Allocate space on caller's stack.
3363   ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3364                                        Align);
3365   CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3366                                     LocInfo));
3367   ByValArgs.push_back(ByVal);
3368 }
3369
3370 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3371   return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3372 }
3373
3374 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3375   return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3376 }
3377
3378 const MCPhysReg *MipsTargetLowering::MipsCC::intArgRegs() const {
3379   return IsO32 ? O32IntRegs : Mips64IntRegs;
3380 }
3381
3382 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3383   if (CallConv == CallingConv::Fast)
3384     return CC_Mips_FastCC;
3385
3386   if (SpecialCallingConv == Mips16RetHelperConv)
3387     return CC_Mips16RetHelper;
3388   return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3389 }
3390
3391 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3392   return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3393 }
3394
3395 const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
3396   return IsO32 ? O32IntRegs : Mips64DPRegs;
3397 }
3398
3399 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3400                                               unsigned ByValSize,
3401                                               unsigned Align) {
3402   unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3403   const MCPhysReg *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3404   assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3405          "Byval argument's size and alignment should be a multiple of"
3406          "RegSize.");
3407
3408   ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3409
3410   // If Align > RegSize, the first arg register must be even.
3411   if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3412     CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3413     ++ByVal.FirstIdx;
3414   }
3415
3416   // Mark the registers allocated.
3417   for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3418        ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3419     CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3420 }
3421
3422 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3423                                          const SDNode *CallNode,
3424                                          bool IsSoftFloat) const {
3425   if (IsSoftFloat || IsO32)
3426     return VT;
3427
3428   // Check if the original type was fp128.
3429   if (originalTypeIsF128(OrigTy, CallNode)) {
3430     assert(VT == MVT::i64);
3431     return MVT::f64;
3432   }
3433
3434   return VT;
3435 }
3436
3437 void MipsTargetLowering::
3438 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3439               SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3440               SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3441               const MipsCC &CC, const ByValArgInfo &ByVal) const {
3442   MachineFunction &MF = DAG.getMachineFunction();
3443   MachineFrameInfo *MFI = MF.getFrameInfo();
3444   unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3445   unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3446   int FrameObjOffset;
3447
3448   if (RegAreaSize)
3449     FrameObjOffset = (int)CC.reservedArgArea() -
3450       (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3451   else
3452     FrameObjOffset = ByVal.Address;
3453
3454   // Create frame object.
3455   EVT PtrTy = getPointerTy();
3456   int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3457   SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3458   InVals.push_back(FIN);
3459
3460   if (!ByVal.NumRegs)
3461     return;
3462
3463   // Copy arg registers.
3464   MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3465   const TargetRegisterClass *RC = getRegClassFor(RegTy);
3466
3467   for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3468     unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3469     unsigned VReg = addLiveIn(MF, ArgReg, RC);
3470     unsigned Offset = I * CC.regSize();
3471     SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3472                                    DAG.getConstant(Offset, PtrTy));
3473     SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3474                                  StorePtr, MachinePointerInfo(FuncArg, Offset),
3475                                  false, false, 0);
3476     OutChains.push_back(Store);
3477   }
3478 }
3479
3480 // Copy byVal arg to registers and stack.
3481 void MipsTargetLowering::
3482 passByValArg(SDValue Chain, SDLoc DL,
3483              std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3484              SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3485              MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3486              const MipsCC &CC, const ByValArgInfo &ByVal,
3487              const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3488   unsigned ByValSize = Flags.getByValSize();
3489   unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3490   unsigned RegSize = CC.regSize();
3491   unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3492   EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3493
3494   if (ByVal.NumRegs) {
3495     const MCPhysReg *ArgRegs = CC.intArgRegs();
3496     bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3497     unsigned I = 0;
3498
3499     // Copy words to registers.
3500     for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3501       SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3502                                     DAG.getConstant(Offset, PtrTy));
3503       SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3504                                     MachinePointerInfo(), false, false, false,
3505                                     Alignment);
3506       MemOpChains.push_back(LoadVal.getValue(1));
3507       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3508       RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3509     }
3510
3511     // Return if the struct has been fully copied.
3512     if (ByValSize == Offset)
3513       return;
3514
3515     // Copy the remainder of the byval argument with sub-word loads and shifts.
3516     if (LeftoverBytes) {
3517       assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3518              "Size of the remainder should be smaller than RegSize.");
3519       SDValue Val;
3520
3521       for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3522            Offset < ByValSize; LoadSize /= 2) {
3523         unsigned RemSize = ByValSize - Offset;
3524
3525         if (RemSize < LoadSize)
3526           continue;
3527
3528         // Load subword.
3529         SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3530                                       DAG.getConstant(Offset, PtrTy));
3531         SDValue LoadVal =
3532           DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3533                          MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3534                          false, false, Alignment);
3535         MemOpChains.push_back(LoadVal.getValue(1));
3536
3537         // Shift the loaded value.
3538         unsigned Shamt;
3539
3540         if (isLittle)
3541           Shamt = TotalSizeLoaded;
3542         else
3543           Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3544
3545         SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3546                                     DAG.getConstant(Shamt, MVT::i32));
3547
3548         if (Val.getNode())
3549           Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3550         else
3551           Val = Shift;
3552
3553         Offset += LoadSize;
3554         TotalSizeLoaded += LoadSize;
3555         Alignment = std::min(Alignment, LoadSize);
3556       }
3557
3558       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3559       RegsToPass.push_back(std::make_pair(ArgReg, Val));
3560       return;
3561     }
3562   }
3563
3564   // Copy remainder of byval arg to it with memcpy.
3565   unsigned MemCpySize = ByValSize - Offset;
3566   SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3567                             DAG.getConstant(Offset, PtrTy));
3568   SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3569                             DAG.getIntPtrConstant(ByVal.Address));
3570   Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3571                         Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3572                         MachinePointerInfo(), MachinePointerInfo());
3573   MemOpChains.push_back(Chain);
3574 }
3575
3576 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3577                                          const MipsCC &CC, SDValue Chain,
3578                                          SDLoc DL, SelectionDAG &DAG) const {
3579   unsigned NumRegs = CC.numIntArgRegs();
3580   const MCPhysReg *ArgRegs = CC.intArgRegs();
3581   const CCState &CCInfo = CC.getCCInfo();
3582   unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3583   unsigned RegSize = CC.regSize();
3584   MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3585   const TargetRegisterClass *RC = getRegClassFor(RegTy);
3586   MachineFunction &MF = DAG.getMachineFunction();
3587   MachineFrameInfo *MFI = MF.getFrameInfo();
3588   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3589
3590   // Offset of the first variable argument from stack pointer.
3591   int VaArgOffset;
3592
3593   if (NumRegs == Idx)
3594     VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3595   else
3596     VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3597
3598   // Record the frame index of the first variable argument
3599   // which is a value necessary to VASTART.
3600   int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3601   MipsFI->setVarArgsFrameIndex(FI);
3602
3603   // Copy the integer registers that have not been used for argument passing
3604   // to the argument register save area. For O32, the save area is allocated
3605   // in the caller's stack frame, while for N32/64, it is allocated in the
3606   // callee's stack frame.
3607   for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3608     unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3609     SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3610     FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3611     SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3612     SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3613                                  MachinePointerInfo(), false, false, 0);
3614     cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue((Value*)nullptr);
3615     OutChains.push_back(Store);
3616   }
3617 }