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