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