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