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