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