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