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