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