Expand pseudos/macros for Selt. This is the last of the complex
[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 <set>
16 #include "MipsISelLowering.h"
17 #include "InstPrinter/MipsInstPrinter.h"
18 #include "MCTargetDesc/MipsBaseInfo.h"
19 #include "MipsMachineFunction.h"
20 #include "MipsSubtarget.h"
21 #include "MipsTargetMachine.h"
22 #include "MipsTargetObjectFile.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
40
41 using namespace llvm;
42
43 STATISTIC(NumTailCalls, "Number of tail calls");
44
45 static cl::opt<bool>
46 EnableMipsTailCalls("enable-mips-tail-calls", cl::Hidden,
47                     cl::desc("MIPS: Enable tail calls."), cl::init(false));
48
49 static cl::opt<bool>
50 LargeGOT("mxgot", cl::Hidden,
51          cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
52
53 static cl::opt<bool>
54 Mips16HardFloat("mips16-hard-float", cl::NotHidden,
55                 cl::desc("MIPS: mips16 hard float enable."),
56                 cl::init(false));
57
58 static cl::opt<bool> DontExpandCondPseudos16(
59   "mips16-dont-expand-cond-pseudo",
60   cl::init(false),
61   cl::desc("Dont expand conditional move related "
62            "pseudos for Mips 16"),
63   cl::Hidden);
64
65
66 static const uint16_t O32IntRegs[4] = {
67   Mips::A0, Mips::A1, Mips::A2, Mips::A3
68 };
69
70 static const uint16_t Mips64IntRegs[8] = {
71   Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
72   Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
73 };
74
75 static const uint16_t Mips64DPRegs[8] = {
76   Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
77   Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
78 };
79
80 // If I is a shifted mask, set the size (Size) and the first bit of the
81 // mask (Pos), and return true.
82 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
83 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
84   if (!isShiftedMask_64(I))
85      return false;
86
87   Size = CountPopulation_64(I);
88   Pos = CountTrailingZeros_64(I);
89   return true;
90 }
91
92 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
93   MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
94   return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
95 }
96
97 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
98   EVT Ty = Op.getValueType();
99
100   if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
101     return DAG.getTargetGlobalAddress(N->getGlobal(), Op.getDebugLoc(), Ty, 0,
102                                       Flag);
103   if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
104     return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
105   if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
106     return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
107   if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
108     return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
109   if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
110     return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
111                                      N->getOffset(), Flag);
112
113   llvm_unreachable("Unexpected node type.");
114   return SDValue();
115 }
116
117 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
118   DebugLoc DL = Op.getDebugLoc();
119   EVT Ty = Op.getValueType();
120   SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
121   SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
122   return DAG.getNode(ISD::ADD, DL, Ty,
123                      DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
124                      DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
125 }
126
127 static SDValue getAddrLocal(SDValue Op, SelectionDAG &DAG, bool HasMips64) {
128   DebugLoc DL = Op.getDebugLoc();
129   EVT Ty = Op.getValueType();
130   unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
131   SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
132                             getTargetNode(Op, DAG, GOTFlag));
133   SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
134                              MachinePointerInfo::getGOT(), false, false, false,
135                              0);
136   unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
137   SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
138   return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
139 }
140
141 static SDValue getAddrGlobal(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
142   DebugLoc DL = Op.getDebugLoc();
143   EVT Ty = Op.getValueType();
144   SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
145                             getTargetNode(Op, DAG, Flag));
146   return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
147                      MachinePointerInfo::getGOT(), false, false, false, 0);
148 }
149
150 static SDValue getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
151                                      unsigned HiFlag, unsigned LoFlag) {
152   DebugLoc DL = Op.getDebugLoc();
153   EVT Ty = Op.getValueType();
154   SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
155   Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, GetGlobalReg(DAG, Ty));
156   SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
157                                 getTargetNode(Op, DAG, LoFlag));
158   return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
159                      MachinePointerInfo::getGOT(), false, false, false, 0);
160 }
161
162 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
163   switch (Opcode) {
164   case MipsISD::JmpLink:           return "MipsISD::JmpLink";
165   case MipsISD::TailCall:          return "MipsISD::TailCall";
166   case MipsISD::Hi:                return "MipsISD::Hi";
167   case MipsISD::Lo:                return "MipsISD::Lo";
168   case MipsISD::GPRel:             return "MipsISD::GPRel";
169   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
170   case MipsISD::Ret:               return "MipsISD::Ret";
171   case MipsISD::EH_RETURN:         return "MipsISD::EH_RETURN";
172   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
173   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
174   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
175   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
176   case MipsISD::FPRound:           return "MipsISD::FPRound";
177   case MipsISD::MAdd:              return "MipsISD::MAdd";
178   case MipsISD::MAddu:             return "MipsISD::MAddu";
179   case MipsISD::MSub:              return "MipsISD::MSub";
180   case MipsISD::MSubu:             return "MipsISD::MSubu";
181   case MipsISD::DivRem:            return "MipsISD::DivRem";
182   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
183   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
184   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
185   case MipsISD::Wrapper:           return "MipsISD::Wrapper";
186   case MipsISD::Sync:              return "MipsISD::Sync";
187   case MipsISD::Ext:               return "MipsISD::Ext";
188   case MipsISD::Ins:               return "MipsISD::Ins";
189   case MipsISD::LWL:               return "MipsISD::LWL";
190   case MipsISD::LWR:               return "MipsISD::LWR";
191   case MipsISD::SWL:               return "MipsISD::SWL";
192   case MipsISD::SWR:               return "MipsISD::SWR";
193   case MipsISD::LDL:               return "MipsISD::LDL";
194   case MipsISD::LDR:               return "MipsISD::LDR";
195   case MipsISD::SDL:               return "MipsISD::SDL";
196   case MipsISD::SDR:               return "MipsISD::SDR";
197   case MipsISD::EXTP:              return "MipsISD::EXTP";
198   case MipsISD::EXTPDP:            return "MipsISD::EXTPDP";
199   case MipsISD::EXTR_S_H:          return "MipsISD::EXTR_S_H";
200   case MipsISD::EXTR_W:            return "MipsISD::EXTR_W";
201   case MipsISD::EXTR_R_W:          return "MipsISD::EXTR_R_W";
202   case MipsISD::EXTR_RS_W:         return "MipsISD::EXTR_RS_W";
203   case MipsISD::SHILO:             return "MipsISD::SHILO";
204   case MipsISD::MTHLIP:            return "MipsISD::MTHLIP";
205   case MipsISD::MULT:              return "MipsISD::MULT";
206   case MipsISD::MULTU:             return "MipsISD::MULTU";
207   case MipsISD::MADD_DSP:          return "MipsISD::MADD_DSPDSP";
208   case MipsISD::MADDU_DSP:         return "MipsISD::MADDU_DSP";
209   case MipsISD::MSUB_DSP:          return "MipsISD::MSUB_DSP";
210   case MipsISD::MSUBU_DSP:         return "MipsISD::MSUBU_DSP";
211   default:                         return NULL;
212   }
213 }
214
215 namespace {
216   struct ltstr {
217     bool operator()(const char *s1, const char *s2) const
218     {
219       return strcmp(s1, s2) < 0;
220     }
221   };
222
223   std::set<const char*, ltstr> noHelperNeeded;
224 }
225
226 void MipsTargetLowering::SetMips16LibcallName
227   (RTLIB::Libcall l, const char *Name) {
228   setLibcallName(l, Name);
229   noHelperNeeded.insert(Name);
230 }
231
232 void MipsTargetLowering::setMips16HardFloatLibCalls() {
233   SetMips16LibcallName(RTLIB::ADD_F32, "__mips16_addsf3");
234   SetMips16LibcallName(RTLIB::ADD_F64, "__mips16_adddf3");
235   SetMips16LibcallName(RTLIB::SUB_F32, "__mips16_subsf3");
236   SetMips16LibcallName(RTLIB::SUB_F64, "__mips16_subdf3");
237   SetMips16LibcallName(RTLIB::MUL_F32, "__mips16_mulsf3");
238   SetMips16LibcallName(RTLIB::MUL_F64, "__mips16_muldf3");
239   SetMips16LibcallName(RTLIB::DIV_F32, "__mips16_divsf3");
240   SetMips16LibcallName(RTLIB::DIV_F64, "__mips16_divdf3");
241   SetMips16LibcallName(RTLIB::FPEXT_F32_F64, "__mips16_extendsfdf2");
242   SetMips16LibcallName(RTLIB::FPROUND_F64_F32, "__mips16_truncdfsf2");
243   SetMips16LibcallName(RTLIB::FPTOSINT_F32_I32, "__mips16_fix_truncsfsi");
244   SetMips16LibcallName(RTLIB::FPTOSINT_F64_I32, "__mips16_fix_truncdfsi");
245   SetMips16LibcallName(RTLIB::SINTTOFP_I32_F32, "__mips16_floatsisf");
246   SetMips16LibcallName(RTLIB::SINTTOFP_I32_F64, "__mips16_floatsidf");
247   SetMips16LibcallName(RTLIB::UINTTOFP_I32_F32, "__mips16_floatunsisf");
248   SetMips16LibcallName(RTLIB::UINTTOFP_I32_F64, "__mips16_floatunsidf");
249   SetMips16LibcallName(RTLIB::OEQ_F32, "__mips16_eqsf2");
250   SetMips16LibcallName(RTLIB::OEQ_F64, "__mips16_eqdf2");
251   SetMips16LibcallName(RTLIB::UNE_F32, "__mips16_nesf2");
252   SetMips16LibcallName(RTLIB::UNE_F64, "__mips16_nedf2");
253   SetMips16LibcallName(RTLIB::OGE_F32, "__mips16_gesf2");
254   SetMips16LibcallName(RTLIB::OGE_F64, "__mips16_gedf2");
255   SetMips16LibcallName(RTLIB::OLT_F32, "__mips16_ltsf2");
256   SetMips16LibcallName(RTLIB::OLT_F64, "__mips16_ltdf2");
257   SetMips16LibcallName(RTLIB::OLE_F32, "__mips16_lesf2");
258   SetMips16LibcallName(RTLIB::OLE_F64, "__mips16_ledf2");
259   SetMips16LibcallName(RTLIB::OGT_F32, "__mips16_gtsf2");
260   SetMips16LibcallName(RTLIB::OGT_F64, "__mips16_gtdf2");
261   SetMips16LibcallName(RTLIB::UO_F32, "__mips16_unordsf2");
262   SetMips16LibcallName(RTLIB::UO_F64, "__mips16_unorddf2");
263   SetMips16LibcallName(RTLIB::O_F32, "__mips16_unordsf2");
264   SetMips16LibcallName(RTLIB::O_F64, "__mips16_unorddf2");
265 }
266
267 MipsTargetLowering::
268 MipsTargetLowering(MipsTargetMachine &TM)
269   : TargetLowering(TM, new MipsTargetObjectFile()),
270     Subtarget(&TM.getSubtarget<MipsSubtarget>()),
271     HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
272     IsO32(Subtarget->isABI_O32()) {
273
274   // Mips does not have i1 type, so use i32 for
275   // setcc operations results (slt, sgt, ...).
276   setBooleanContents(ZeroOrOneBooleanContent);
277   setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
278
279   // Set up the register classes
280   addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
281
282   if (HasMips64)
283     addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
284
285   if (Subtarget->inMips16Mode()) {
286     addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
287     if (Mips16HardFloat)
288       setMips16HardFloatLibCalls();
289   }
290
291   if (Subtarget->hasDSP()) {
292     MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
293
294     for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
295       addRegisterClass(VecTys[i], &Mips::DSPRegsRegClass);
296
297       // Expand all builtin opcodes.
298       for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
299         setOperationAction(Opc, VecTys[i], Expand);
300
301       setOperationAction(ISD::LOAD, VecTys[i], Legal);
302       setOperationAction(ISD::STORE, VecTys[i], Legal);
303       setOperationAction(ISD::BITCAST, VecTys[i], Legal);
304     }
305   }
306
307   if (!TM.Options.UseSoftFloat) {
308     addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
309
310     // When dealing with single precision only, use libcalls
311     if (!Subtarget->isSingleFloat()) {
312       if (HasMips64)
313         addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
314       else
315         addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
316     }
317   }
318
319   // Load extented operations for i1 types must be promoted
320   setLoadExtAction(ISD::EXTLOAD,  MVT::i1,  Promote);
321   setLoadExtAction(ISD::ZEXTLOAD, MVT::i1,  Promote);
322   setLoadExtAction(ISD::SEXTLOAD, MVT::i1,  Promote);
323
324   // MIPS doesn't have extending float->double load/store
325   setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
326   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
327
328   // Used by legalize types to correctly generate the setcc result.
329   // Without this, every float setcc comes with a AND/OR with the result,
330   // we don't want this, since the fpcmp result goes to a flag register,
331   // which is used implicitly by brcond and select operations.
332   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
333
334   // Mips Custom Operations
335   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
336   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
337   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
338   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
339   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
340   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
341   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
342   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
343   setOperationAction(ISD::SELECT_CC,          MVT::f32,   Custom);
344   setOperationAction(ISD::SELECT_CC,          MVT::f64,   Custom);
345   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
346   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
347   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
348   setOperationAction(ISD::VASTART,            MVT::Other, Custom);
349   setOperationAction(ISD::FCOPYSIGN,          MVT::f32,   Custom);
350   setOperationAction(ISD::FCOPYSIGN,          MVT::f64,   Custom);
351   if (Subtarget->inMips16Mode()) {
352     setOperationAction(ISD::MEMBARRIER,         MVT::Other, Expand);
353     setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Expand);
354   }
355   else {
356     setOperationAction(ISD::MEMBARRIER,         MVT::Other, Custom);
357     setOperationAction(ISD::ATOMIC_FENCE,       MVT::Other, Custom);
358   }
359   if (!Subtarget->inMips16Mode()) {
360     setOperationAction(ISD::LOAD,               MVT::i32, Custom);
361     setOperationAction(ISD::STORE,              MVT::i32, Custom);
362   }
363
364   if (!TM.Options.NoNaNsFPMath) {
365     setOperationAction(ISD::FABS,             MVT::f32,   Custom);
366     setOperationAction(ISD::FABS,             MVT::f64,   Custom);
367   }
368
369   if (HasMips64) {
370     setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
371     setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
372     setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
373     setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
374     setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
375     setOperationAction(ISD::SELECT,             MVT::i64,   Custom);
376     setOperationAction(ISD::LOAD,               MVT::i64,   Custom);
377     setOperationAction(ISD::STORE,              MVT::i64,   Custom);
378   }
379
380   if (!HasMips64) {
381     setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Custom);
382     setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Custom);
383     setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Custom);
384   }
385
386   setOperationAction(ISD::ADD,                MVT::i32,   Custom);
387   if (HasMips64)
388     setOperationAction(ISD::ADD,                MVT::i64,   Custom);
389
390   setOperationAction(ISD::SDIV, MVT::i32, Expand);
391   setOperationAction(ISD::SREM, MVT::i32, Expand);
392   setOperationAction(ISD::UDIV, MVT::i32, Expand);
393   setOperationAction(ISD::UREM, MVT::i32, Expand);
394   setOperationAction(ISD::SDIV, MVT::i64, Expand);
395   setOperationAction(ISD::SREM, MVT::i64, Expand);
396   setOperationAction(ISD::UDIV, MVT::i64, Expand);
397   setOperationAction(ISD::UREM, MVT::i64, Expand);
398
399   // Operations not directly supported by Mips.
400   setOperationAction(ISD::BR_JT,             MVT::Other, Expand);
401   setOperationAction(ISD::BR_CC,             MVT::Other, Expand);
402   setOperationAction(ISD::SELECT_CC,         MVT::Other, Expand);
403   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
404   setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
405   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
406   setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
407   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
408   setOperationAction(ISD::CTPOP,             MVT::i32,   Expand);
409   setOperationAction(ISD::CTPOP,             MVT::i64,   Expand);
410   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
411   setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
412   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i32,   Expand);
413   setOperationAction(ISD::CTTZ_ZERO_UNDEF,   MVT::i64,   Expand);
414   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i32,   Expand);
415   setOperationAction(ISD::CTLZ_ZERO_UNDEF,   MVT::i64,   Expand);
416   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
417   setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
418   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,  Expand);
419   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,  Expand);
420
421   if (!Subtarget->hasMips32r2())
422     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
423
424   if (!Subtarget->hasMips64r2())
425     setOperationAction(ISD::ROTR, MVT::i64,   Expand);
426
427   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
428   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
429   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
430   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
431   setOperationAction(ISD::FSINCOS,           MVT::f32,   Expand);
432   setOperationAction(ISD::FSINCOS,           MVT::f64,   Expand);
433   setOperationAction(ISD::FPOWI,             MVT::f32,   Expand);
434   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
435   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
436   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
437   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
438   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
439   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
440   setOperationAction(ISD::FMA,               MVT::f32,   Expand);
441   setOperationAction(ISD::FMA,               MVT::f64,   Expand);
442   setOperationAction(ISD::FREM,              MVT::f32,   Expand);
443   setOperationAction(ISD::FREM,              MVT::f64,   Expand);
444
445   if (!TM.Options.NoNaNsFPMath) {
446     setOperationAction(ISD::FNEG,             MVT::f32,   Expand);
447     setOperationAction(ISD::FNEG,             MVT::f64,   Expand);
448   }
449
450   setOperationAction(ISD::EXCEPTIONADDR,     MVT::i32, Expand);
451   setOperationAction(ISD::EXCEPTIONADDR,     MVT::i64, Expand);
452   setOperationAction(ISD::EHSELECTION,       MVT::i32, Expand);
453   setOperationAction(ISD::EHSELECTION,       MVT::i64, Expand);
454
455   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
456
457   setOperationAction(ISD::VAARG,             MVT::Other, Expand);
458   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
459   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
460
461   setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
462   setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
463
464   // Use the default for now
465   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
466   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
467
468   setOperationAction(ISD::ATOMIC_LOAD,       MVT::i32,    Expand);
469   setOperationAction(ISD::ATOMIC_LOAD,       MVT::i64,    Expand);
470   setOperationAction(ISD::ATOMIC_STORE,      MVT::i32,    Expand);
471   setOperationAction(ISD::ATOMIC_STORE,      MVT::i64,    Expand);
472
473   if (Subtarget->inMips16Mode()) {
474     setOperationAction(ISD::ATOMIC_CMP_SWAP,       MVT::i32,    Expand);
475     setOperationAction(ISD::ATOMIC_SWAP,           MVT::i32,    Expand);
476     setOperationAction(ISD::ATOMIC_LOAD_ADD,       MVT::i32,    Expand);
477     setOperationAction(ISD::ATOMIC_LOAD_SUB,       MVT::i32,    Expand);
478     setOperationAction(ISD::ATOMIC_LOAD_AND,       MVT::i32,    Expand);
479     setOperationAction(ISD::ATOMIC_LOAD_OR,        MVT::i32,    Expand);
480     setOperationAction(ISD::ATOMIC_LOAD_XOR,       MVT::i32,    Expand);
481     setOperationAction(ISD::ATOMIC_LOAD_NAND,      MVT::i32,    Expand);
482     setOperationAction(ISD::ATOMIC_LOAD_MIN,       MVT::i32,    Expand);
483     setOperationAction(ISD::ATOMIC_LOAD_MAX,       MVT::i32,    Expand);
484     setOperationAction(ISD::ATOMIC_LOAD_UMIN,      MVT::i32,    Expand);
485     setOperationAction(ISD::ATOMIC_LOAD_UMAX,      MVT::i32,    Expand);
486   }
487
488   setInsertFencesForAtomic(true);
489
490   if (!Subtarget->hasSEInReg()) {
491     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
492     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
493   }
494
495   if (!Subtarget->hasBitCount()) {
496     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
497     setOperationAction(ISD::CTLZ, MVT::i64, Expand);
498   }
499
500   if (!Subtarget->hasSwap()) {
501     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
502     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
503   }
504
505   if (HasMips64) {
506     setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
507     setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
508     setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
509     setTruncStoreAction(MVT::i64, MVT::i32, Custom);
510   }
511
512   setTargetDAGCombine(ISD::ADDE);
513   setTargetDAGCombine(ISD::SUBE);
514   setTargetDAGCombine(ISD::SDIVREM);
515   setTargetDAGCombine(ISD::UDIVREM);
516   setTargetDAGCombine(ISD::SELECT);
517   setTargetDAGCombine(ISD::AND);
518   setTargetDAGCombine(ISD::OR);
519   setTargetDAGCombine(ISD::ADD);
520
521   setMinFunctionAlignment(HasMips64 ? 3 : 2);
522
523   setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
524   computeRegisterProperties();
525
526   setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
527   setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
528
529   MaxStoresPerMemcpy = 16;
530 }
531
532 bool
533 MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
534   MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
535
536   if (Subtarget->inMips16Mode())
537     return false;
538
539   switch (SVT) {
540   case MVT::i64:
541   case MVT::i32:
542     if (Fast)
543       *Fast = true;
544     return true;
545   default:
546     return false;
547   }
548 }
549
550 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
551   if (!VT.isVector())
552     return MVT::i32;
553   return VT.changeVectorElementTypeToInteger();
554 }
555
556 // SelectMadd -
557 // Transforms a subgraph in CurDAG if the following pattern is found:
558 //  (addc multLo, Lo0), (adde multHi, Hi0),
559 // where,
560 //  multHi/Lo: product of multiplication
561 //  Lo0: initial value of Lo register
562 //  Hi0: initial value of Hi register
563 // Return true if pattern matching was successful.
564 static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
565   // ADDENode's second operand must be a flag output of an ADDC node in order
566   // for the matching to be successful.
567   SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
568
569   if (ADDCNode->getOpcode() != ISD::ADDC)
570     return false;
571
572   SDValue MultHi = ADDENode->getOperand(0);
573   SDValue MultLo = ADDCNode->getOperand(0);
574   SDNode *MultNode = MultHi.getNode();
575   unsigned MultOpc = MultHi.getOpcode();
576
577   // MultHi and MultLo must be generated by the same node,
578   if (MultLo.getNode() != MultNode)
579     return false;
580
581   // and it must be a multiplication.
582   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
583     return false;
584
585   // MultLo amd MultHi must be the first and second output of MultNode
586   // respectively.
587   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
588     return false;
589
590   // Transform this to a MADD only if ADDENode and ADDCNode are the only users
591   // of the values of MultNode, in which case MultNode will be removed in later
592   // phases.
593   // If there exist users other than ADDENode or ADDCNode, this function returns
594   // here, which will result in MultNode being mapped to a single MULT
595   // instruction node rather than a pair of MULT and MADD instructions being
596   // produced.
597   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
598     return false;
599
600   SDValue Chain = CurDAG->getEntryNode();
601   DebugLoc dl = ADDENode->getDebugLoc();
602
603   // create MipsMAdd(u) node
604   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
605
606   SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
607                                  MultNode->getOperand(0),// Factor 0
608                                  MultNode->getOperand(1),// Factor 1
609                                  ADDCNode->getOperand(1),// Lo0
610                                  ADDENode->getOperand(1));// Hi0
611
612   // create CopyFromReg nodes
613   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
614                                               MAdd);
615   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
616                                               Mips::HI, MVT::i32,
617                                               CopyFromLo.getValue(2));
618
619   // replace uses of adde and addc here
620   if (!SDValue(ADDCNode, 0).use_empty())
621     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
622
623   if (!SDValue(ADDENode, 0).use_empty())
624     CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
625
626   return true;
627 }
628
629 // SelectMsub -
630 // Transforms a subgraph in CurDAG if the following pattern is found:
631 //  (addc Lo0, multLo), (sube Hi0, multHi),
632 // where,
633 //  multHi/Lo: product of multiplication
634 //  Lo0: initial value of Lo register
635 //  Hi0: initial value of Hi register
636 // Return true if pattern matching was successful.
637 static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
638   // SUBENode's second operand must be a flag output of an SUBC node in order
639   // for the matching to be successful.
640   SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
641
642   if (SUBCNode->getOpcode() != ISD::SUBC)
643     return false;
644
645   SDValue MultHi = SUBENode->getOperand(1);
646   SDValue MultLo = SUBCNode->getOperand(1);
647   SDNode *MultNode = MultHi.getNode();
648   unsigned MultOpc = MultHi.getOpcode();
649
650   // MultHi and MultLo must be generated by the same node,
651   if (MultLo.getNode() != MultNode)
652     return false;
653
654   // and it must be a multiplication.
655   if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
656     return false;
657
658   // MultLo amd MultHi must be the first and second output of MultNode
659   // respectively.
660   if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
661     return false;
662
663   // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
664   // of the values of MultNode, in which case MultNode will be removed in later
665   // phases.
666   // If there exist users other than SUBENode or SUBCNode, this function returns
667   // here, which will result in MultNode being mapped to a single MULT
668   // instruction node rather than a pair of MULT and MSUB instructions being
669   // produced.
670   if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
671     return false;
672
673   SDValue Chain = CurDAG->getEntryNode();
674   DebugLoc dl = SUBENode->getDebugLoc();
675
676   // create MipsSub(u) node
677   MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
678
679   SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
680                                  MultNode->getOperand(0),// Factor 0
681                                  MultNode->getOperand(1),// Factor 1
682                                  SUBCNode->getOperand(0),// Lo0
683                                  SUBENode->getOperand(0));// Hi0
684
685   // create CopyFromReg nodes
686   SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
687                                               MSub);
688   SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
689                                               Mips::HI, MVT::i32,
690                                               CopyFromLo.getValue(2));
691
692   // replace uses of sube and subc here
693   if (!SDValue(SUBCNode, 0).use_empty())
694     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
695
696   if (!SDValue(SUBENode, 0).use_empty())
697     CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
698
699   return true;
700 }
701
702 static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
703                                   TargetLowering::DAGCombinerInfo &DCI,
704                                   const MipsSubtarget *Subtarget) {
705   if (DCI.isBeforeLegalize())
706     return SDValue();
707
708   if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
709       SelectMadd(N, &DAG))
710     return SDValue(N, 0);
711
712   return SDValue();
713 }
714
715 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
716                                   TargetLowering::DAGCombinerInfo &DCI,
717                                   const MipsSubtarget *Subtarget) {
718   if (DCI.isBeforeLegalize())
719     return SDValue();
720
721   if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
722       SelectMsub(N, &DAG))
723     return SDValue(N, 0);
724
725   return SDValue();
726 }
727
728 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
729                                     TargetLowering::DAGCombinerInfo &DCI,
730                                     const MipsSubtarget *Subtarget) {
731   if (DCI.isBeforeLegalizeOps())
732     return SDValue();
733
734   EVT Ty = N->getValueType(0);
735   unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
736   unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
737   unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
738                                                   MipsISD::DivRemU;
739   DebugLoc dl = N->getDebugLoc();
740
741   SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
742                                N->getOperand(0), N->getOperand(1));
743   SDValue InChain = DAG.getEntryNode();
744   SDValue InGlue = DivRem;
745
746   // insert MFLO
747   if (N->hasAnyUseOfValue(0)) {
748     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
749                                             InGlue);
750     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
751     InChain = CopyFromLo.getValue(1);
752     InGlue = CopyFromLo.getValue(2);
753   }
754
755   // insert MFHI
756   if (N->hasAnyUseOfValue(1)) {
757     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
758                                             HI, Ty, InGlue);
759     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
760   }
761
762   return SDValue();
763 }
764
765 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
766   switch (CC) {
767   default: llvm_unreachable("Unknown fp condition code!");
768   case ISD::SETEQ:
769   case ISD::SETOEQ: return Mips::FCOND_OEQ;
770   case ISD::SETUNE: return Mips::FCOND_UNE;
771   case ISD::SETLT:
772   case ISD::SETOLT: return Mips::FCOND_OLT;
773   case ISD::SETGT:
774   case ISD::SETOGT: return Mips::FCOND_OGT;
775   case ISD::SETLE:
776   case ISD::SETOLE: return Mips::FCOND_OLE;
777   case ISD::SETGE:
778   case ISD::SETOGE: return Mips::FCOND_OGE;
779   case ISD::SETULT: return Mips::FCOND_ULT;
780   case ISD::SETULE: return Mips::FCOND_ULE;
781   case ISD::SETUGT: return Mips::FCOND_UGT;
782   case ISD::SETUGE: return Mips::FCOND_UGE;
783   case ISD::SETUO:  return Mips::FCOND_UN;
784   case ISD::SETO:   return Mips::FCOND_OR;
785   case ISD::SETNE:
786   case ISD::SETONE: return Mips::FCOND_ONE;
787   case ISD::SETUEQ: return Mips::FCOND_UEQ;
788   }
789 }
790
791
792 // Returns true if condition code has to be inverted.
793 static bool InvertFPCondCode(Mips::CondCode CC) {
794   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
795     return false;
796
797   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
798          "Illegal Condition Code");
799
800   return true;
801 }
802
803 // Creates and returns an FPCmp node from a setcc node.
804 // Returns Op if setcc is not a floating point comparison.
805 static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
806   // must be a SETCC node
807   if (Op.getOpcode() != ISD::SETCC)
808     return Op;
809
810   SDValue LHS = Op.getOperand(0);
811
812   if (!LHS.getValueType().isFloatingPoint())
813     return Op;
814
815   SDValue RHS = Op.getOperand(1);
816   DebugLoc dl = Op.getDebugLoc();
817
818   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
819   // node if necessary.
820   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
821
822   return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
823                      DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
824 }
825
826 // Creates and returns a CMovFPT/F node.
827 static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
828                             SDValue False, DebugLoc DL) {
829   bool invert = InvertFPCondCode((Mips::CondCode)
830                                  cast<ConstantSDNode>(Cond.getOperand(2))
831                                  ->getSExtValue());
832
833   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
834                      True.getValueType(), True, False, Cond);
835 }
836
837 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
838                                     TargetLowering::DAGCombinerInfo &DCI,
839                                     const MipsSubtarget *Subtarget) {
840   if (DCI.isBeforeLegalizeOps())
841     return SDValue();
842
843   SDValue SetCC = N->getOperand(0);
844
845   if ((SetCC.getOpcode() != ISD::SETCC) ||
846       !SetCC.getOperand(0).getValueType().isInteger())
847     return SDValue();
848
849   SDValue False = N->getOperand(2);
850   EVT FalseTy = False.getValueType();
851
852   if (!FalseTy.isInteger())
853     return SDValue();
854
855   ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
856
857   if (!CN || CN->getZExtValue())
858     return SDValue();
859
860   const DebugLoc DL = N->getDebugLoc();
861   ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
862   SDValue True = N->getOperand(1);
863
864   SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
865                        SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
866
867   return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
868 }
869
870 static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
871                                  TargetLowering::DAGCombinerInfo &DCI,
872                                  const MipsSubtarget *Subtarget) {
873   // Pattern match EXT.
874   //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
875   //  => ext $dst, $src, size, pos
876   if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
877     return SDValue();
878
879   SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
880   unsigned ShiftRightOpc = ShiftRight.getOpcode();
881
882   // Op's first operand must be a shift right.
883   if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
884     return SDValue();
885
886   // The second operand of the shift must be an immediate.
887   ConstantSDNode *CN;
888   if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
889     return SDValue();
890
891   uint64_t Pos = CN->getZExtValue();
892   uint64_t SMPos, SMSize;
893
894   // Op's second operand must be a shifted mask.
895   if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
896       !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
897     return SDValue();
898
899   // Return if the shifted mask does not start at bit 0 or the sum of its size
900   // and Pos exceeds the word's size.
901   EVT ValTy = N->getValueType(0);
902   if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
903     return SDValue();
904
905   return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
906                      ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
907                      DAG.getConstant(SMSize, MVT::i32));
908 }
909
910 static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
911                                 TargetLowering::DAGCombinerInfo &DCI,
912                                 const MipsSubtarget *Subtarget) {
913   // Pattern match INS.
914   //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
915   //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1
916   //  => ins $dst, $src, size, pos, $src1
917   if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
918     return SDValue();
919
920   SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
921   uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
922   ConstantSDNode *CN;
923
924   // See if Op's first operand matches (and $src1 , mask0).
925   if (And0.getOpcode() != ISD::AND)
926     return SDValue();
927
928   if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
929       !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
930     return SDValue();
931
932   // See if Op's second operand matches (and (shl $src, pos), mask1).
933   if (And1.getOpcode() != ISD::AND)
934     return SDValue();
935
936   if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
937       !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
938     return SDValue();
939
940   // The shift masks must have the same position and size.
941   if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
942     return SDValue();
943
944   SDValue Shl = And1.getOperand(0);
945   if (Shl.getOpcode() != ISD::SHL)
946     return SDValue();
947
948   if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
949     return SDValue();
950
951   unsigned Shamt = CN->getZExtValue();
952
953   // Return if the shift amount and the first bit position of mask are not the
954   // same.
955   EVT ValTy = N->getValueType(0);
956   if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
957     return SDValue();
958
959   return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
960                      DAG.getConstant(SMPos0, MVT::i32),
961                      DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
962 }
963
964 static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
965                                  TargetLowering::DAGCombinerInfo &DCI,
966                                  const MipsSubtarget *Subtarget) {
967   // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
968
969   if (DCI.isBeforeLegalizeOps())
970     return SDValue();
971
972   SDValue Add = N->getOperand(1);
973
974   if (Add.getOpcode() != ISD::ADD)
975     return SDValue();
976
977   SDValue Lo = Add.getOperand(1);
978
979   if ((Lo.getOpcode() != MipsISD::Lo) ||
980       (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
981     return SDValue();
982
983   EVT ValTy = N->getValueType(0);
984   DebugLoc DL = N->getDebugLoc();
985
986   SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
987                              Add.getOperand(0));
988   return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
989 }
990
991 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
992   const {
993   SelectionDAG &DAG = DCI.DAG;
994   unsigned opc = N->getOpcode();
995
996   switch (opc) {
997   default: break;
998   case ISD::ADDE:
999     return PerformADDECombine(N, DAG, DCI, Subtarget);
1000   case ISD::SUBE:
1001     return PerformSUBECombine(N, DAG, DCI, Subtarget);
1002   case ISD::SDIVREM:
1003   case ISD::UDIVREM:
1004     return PerformDivRemCombine(N, DAG, DCI, Subtarget);
1005   case ISD::SELECT:
1006     return PerformSELECTCombine(N, DAG, DCI, Subtarget);
1007   case ISD::AND:
1008     return PerformANDCombine(N, DAG, DCI, Subtarget);
1009   case ISD::OR:
1010     return PerformORCombine(N, DAG, DCI, Subtarget);
1011   case ISD::ADD:
1012     return PerformADDCombine(N, DAG, DCI, Subtarget);
1013   }
1014
1015   return SDValue();
1016 }
1017
1018 void
1019 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1020                                           SmallVectorImpl<SDValue> &Results,
1021                                           SelectionDAG &DAG) const {
1022   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1023
1024   for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1025     Results.push_back(Res.getValue(I));
1026 }
1027
1028 void
1029 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1030                                        SmallVectorImpl<SDValue> &Results,
1031                                        SelectionDAG &DAG) const {
1032   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1033
1034   for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1035     Results.push_back(Res.getValue(I));
1036 }
1037
1038 SDValue MipsTargetLowering::
1039 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1040 {
1041   switch (Op.getOpcode())
1042   {
1043     case ISD::BRCOND:             return LowerBRCOND(Op, DAG);
1044     case ISD::ConstantPool:       return LowerConstantPool(Op, DAG);
1045     case ISD::GlobalAddress:      return LowerGlobalAddress(Op, DAG);
1046     case ISD::BlockAddress:       return LowerBlockAddress(Op, DAG);
1047     case ISD::GlobalTLSAddress:   return LowerGlobalTLSAddress(Op, DAG);
1048     case ISD::JumpTable:          return LowerJumpTable(Op, DAG);
1049     case ISD::SELECT:             return LowerSELECT(Op, DAG);
1050     case ISD::SELECT_CC:          return LowerSELECT_CC(Op, DAG);
1051     case ISD::SETCC:              return LowerSETCC(Op, DAG);
1052     case ISD::VASTART:            return LowerVASTART(Op, DAG);
1053     case ISD::FCOPYSIGN:          return LowerFCOPYSIGN(Op, DAG);
1054     case ISD::FABS:               return LowerFABS(Op, DAG);
1055     case ISD::FRAMEADDR:          return LowerFRAMEADDR(Op, DAG);
1056     case ISD::RETURNADDR:         return LowerRETURNADDR(Op, DAG);
1057     case ISD::EH_RETURN:          return LowerEH_RETURN(Op, DAG);
1058     case ISD::MEMBARRIER:         return LowerMEMBARRIER(Op, DAG);
1059     case ISD::ATOMIC_FENCE:       return LowerATOMIC_FENCE(Op, DAG);
1060     case ISD::SHL_PARTS:          return LowerShiftLeftParts(Op, DAG);
1061     case ISD::SRA_PARTS:          return LowerShiftRightParts(Op, DAG, true);
1062     case ISD::SRL_PARTS:          return LowerShiftRightParts(Op, DAG, false);
1063     case ISD::LOAD:               return LowerLOAD(Op, DAG);
1064     case ISD::STORE:              return LowerSTORE(Op, DAG);
1065     case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1066     case ISD::INTRINSIC_W_CHAIN:  return LowerINTRINSIC_W_CHAIN(Op, DAG);
1067     case ISD::ADD:                return LowerADD(Op, DAG);
1068   }
1069   return SDValue();
1070 }
1071
1072 //===----------------------------------------------------------------------===//
1073 //  Lower helper functions
1074 //===----------------------------------------------------------------------===//
1075
1076 // AddLiveIn - This helper function adds the specified physical register to the
1077 // MachineFunction as a live in value.  It also creates a corresponding
1078 // virtual register for it.
1079 static unsigned
1080 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1081 {
1082   unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1083   MF.getRegInfo().addLiveIn(PReg, VReg);
1084   return VReg;
1085 }
1086
1087 // Get fp branch code (not opcode) from condition code.
1088 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
1089   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
1090     return Mips::BRANCH_T;
1091
1092   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
1093          "Invalid CondCode.");
1094
1095   return Mips::BRANCH_F;
1096 }
1097
1098 /*
1099 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
1100                                         DebugLoc dl,
1101                                         const MipsSubtarget *Subtarget,
1102                                         const TargetInstrInfo *TII,
1103                                         bool isFPCmp, unsigned Opc) {
1104   // There is no need to expand CMov instructions if target has
1105   // conditional moves.
1106   if (Subtarget->hasCondMov())
1107     return BB;
1108
1109   // To "insert" a SELECT_CC instruction, we actually have to insert the
1110   // diamond control-flow pattern.  The incoming instruction knows the
1111   // destination vreg to set, the condition code register to branch on, the
1112   // true/false values to select between, and a branch opcode to use.
1113   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1114   MachineFunction::iterator It = BB;
1115   ++It;
1116
1117   //  thisMBB:
1118   //  ...
1119   //   TrueVal = ...
1120   //   setcc r1, r2, r3
1121   //   bNE   r1, r0, copy1MBB
1122   //   fallthrough --> copy0MBB
1123   MachineBasicBlock *thisMBB  = BB;
1124   MachineFunction *F = BB->getParent();
1125   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1126   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
1127   F->insert(It, copy0MBB);
1128   F->insert(It, sinkMBB);
1129
1130   // Transfer the remainder of BB and its successor edges to sinkMBB.
1131   sinkMBB->splice(sinkMBB->begin(), BB,
1132                   llvm::next(MachineBasicBlock::iterator(MI)),
1133                   BB->end());
1134   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1135
1136   // Next, add the true and fallthrough blocks as its successors.
1137   BB->addSuccessor(copy0MBB);
1138   BB->addSuccessor(sinkMBB);
1139
1140   // Emit the right instruction according to the type of the operands compared
1141   if (isFPCmp)
1142     BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
1143   else
1144     BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
1145       .addReg(Mips::ZERO).addMBB(sinkMBB);
1146
1147   //  copy0MBB:
1148   //   %FalseValue = ...
1149   //   # fallthrough to sinkMBB
1150   BB = copy0MBB;
1151
1152   // Update machine-CFG edges
1153   BB->addSuccessor(sinkMBB);
1154
1155   //  sinkMBB:
1156   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1157   //  ...
1158   BB = sinkMBB;
1159
1160   if (isFPCmp)
1161     BuildMI(*BB, BB->begin(), dl,
1162             TII->get(Mips::PHI), MI->getOperand(0).getReg())
1163       .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
1164       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1165   else
1166     BuildMI(*BB, BB->begin(), dl,
1167             TII->get(Mips::PHI), MI->getOperand(0).getReg())
1168       .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
1169       .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1170
1171   MI->eraseFromParent();   // The pseudo instruction is gone now.
1172   return BB;
1173 }
1174 */
1175
1176 MachineBasicBlock *
1177 MipsTargetLowering::EmitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
1178   // $bb:
1179   //  bposge32_pseudo $vr0
1180   //  =>
1181   // $bb:
1182   //  bposge32 $tbb
1183   // $fbb:
1184   //  li $vr2, 0
1185   //  b $sink
1186   // $tbb:
1187   //  li $vr1, 1
1188   // $sink:
1189   //  $vr0 = phi($vr2, $fbb, $vr1, $tbb)
1190
1191   MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
1192   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1193   const TargetRegisterClass *RC = &Mips::CPURegsRegClass;
1194   DebugLoc DL = MI->getDebugLoc();
1195   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1196   MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
1197   MachineFunction *F = BB->getParent();
1198   MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
1199   MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
1200   MachineBasicBlock *Sink  = F->CreateMachineBasicBlock(LLVM_BB);
1201   F->insert(It, FBB);
1202   F->insert(It, TBB);
1203   F->insert(It, Sink);
1204
1205   // Transfer the remainder of BB and its successor edges to Sink.
1206   Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
1207                BB->end());
1208   Sink->transferSuccessorsAndUpdatePHIs(BB);
1209
1210   // Add successors.
1211   BB->addSuccessor(FBB);
1212   BB->addSuccessor(TBB);
1213   FBB->addSuccessor(Sink);
1214   TBB->addSuccessor(Sink);
1215
1216   // Insert the real bposge32 instruction to $BB.
1217   BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
1218
1219   // Fill $FBB.
1220   unsigned VR2 = RegInfo.createVirtualRegister(RC);
1221   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
1222     .addReg(Mips::ZERO).addImm(0);
1223   BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
1224
1225   // Fill $TBB.
1226   unsigned VR1 = RegInfo.createVirtualRegister(RC);
1227   BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
1228     .addReg(Mips::ZERO).addImm(1);
1229
1230   // Insert phi function to $Sink.
1231   BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
1232           MI->getOperand(0).getReg())
1233     .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
1234
1235   MI->eraseFromParent();   // The pseudo instruction is gone now.
1236   return Sink;
1237 }
1238
1239 MachineBasicBlock *MipsTargetLowering::EmitSel16(unsigned Opc, MachineInstr *MI,
1240                              MachineBasicBlock *BB) const {
1241   if (DontExpandCondPseudos16)
1242     return BB;
1243   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1244   DebugLoc dl = MI->getDebugLoc();
1245   // To "insert" a SELECT_CC instruction, we actually have to insert the
1246   // diamond control-flow pattern.  The incoming instruction knows the
1247   // destination vreg to set, the condition code register to branch on, the
1248   // true/false values to select between, and a branch opcode to use.
1249   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1250   MachineFunction::iterator It = BB;
1251   ++It;
1252
1253   //  thisMBB:
1254   //  ...
1255   //   TrueVal = ...
1256   //   setcc r1, r2, r3
1257   //   bNE   r1, r0, copy1MBB
1258   //   fallthrough --> copy0MBB
1259   MachineBasicBlock *thisMBB  = BB;
1260   MachineFunction *F = BB->getParent();
1261   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1262   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
1263   F->insert(It, copy0MBB);
1264   F->insert(It, sinkMBB);
1265
1266   // Transfer the remainder of BB and its successor edges to sinkMBB.
1267   sinkMBB->splice(sinkMBB->begin(), BB,
1268                   llvm::next(MachineBasicBlock::iterator(MI)),
1269                   BB->end());
1270   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1271
1272   // Next, add the true and fallthrough blocks as its successors.
1273   BB->addSuccessor(copy0MBB);
1274   BB->addSuccessor(sinkMBB);
1275
1276   BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(3).getReg())
1277     .addMBB(sinkMBB);
1278
1279   //  copy0MBB:
1280   //   %FalseValue = ...
1281   //   # fallthrough to sinkMBB
1282   BB = copy0MBB;
1283
1284   // Update machine-CFG edges
1285   BB->addSuccessor(sinkMBB);
1286
1287   //  sinkMBB:
1288   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1289   //  ...
1290   BB = sinkMBB;
1291
1292   BuildMI(*BB, BB->begin(), dl,
1293           TII->get(Mips::PHI), MI->getOperand(0).getReg())
1294     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
1295     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
1296
1297   MI->eraseFromParent();   // The pseudo instruction is gone now.
1298   return BB;
1299 }
1300
1301 MachineBasicBlock *MipsTargetLowering::EmitSelT16
1302   (unsigned Opc1, unsigned Opc2,
1303    MachineInstr *MI, MachineBasicBlock *BB) const {
1304   if (DontExpandCondPseudos16)
1305     return BB;
1306   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1307   DebugLoc dl = MI->getDebugLoc();
1308   // To "insert" a SELECT_CC instruction, we actually have to insert the
1309   // diamond control-flow pattern.  The incoming instruction knows the
1310   // destination vreg to set, the condition code register to branch on, the
1311   // true/false values to select between, and a branch opcode to use.
1312   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1313   MachineFunction::iterator It = BB;
1314   ++It;
1315
1316   //  thisMBB:
1317   //  ...
1318   //   TrueVal = ...
1319   //   setcc r1, r2, r3
1320   //   bNE   r1, r0, copy1MBB
1321   //   fallthrough --> copy0MBB
1322   MachineBasicBlock *thisMBB  = BB;
1323   MachineFunction *F = BB->getParent();
1324   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1325   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
1326   F->insert(It, copy0MBB);
1327   F->insert(It, sinkMBB);
1328
1329   // Transfer the remainder of BB and its successor edges to sinkMBB.
1330   sinkMBB->splice(sinkMBB->begin(), BB,
1331                   llvm::next(MachineBasicBlock::iterator(MI)),
1332                   BB->end());
1333   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1334
1335   // Next, add the true and fallthrough blocks as its successors.
1336   BB->addSuccessor(copy0MBB);
1337   BB->addSuccessor(sinkMBB);
1338
1339   BuildMI(BB, dl, TII->get(Opc2)).addReg(MI->getOperand(3).getReg())
1340     .addReg(MI->getOperand(4).getReg());
1341   BuildMI(BB, dl, TII->get(Opc1)).addMBB(sinkMBB);
1342
1343   //  copy0MBB:
1344   //   %FalseValue = ...
1345   //   # fallthrough to sinkMBB
1346   BB = copy0MBB;
1347
1348   // Update machine-CFG edges
1349   BB->addSuccessor(sinkMBB);
1350
1351   //  sinkMBB:
1352   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1353   //  ...
1354   BB = sinkMBB;
1355
1356   BuildMI(*BB, BB->begin(), dl,
1357           TII->get(Mips::PHI), MI->getOperand(0).getReg())
1358     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
1359     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
1360
1361   MI->eraseFromParent();   // The pseudo instruction is gone now.
1362   return BB;
1363
1364 }
1365
1366
1367 MachineBasicBlock *MipsTargetLowering::EmitSeliT16
1368   (unsigned Opc1, unsigned Opc2,
1369    MachineInstr *MI, MachineBasicBlock *BB) const {
1370   if (DontExpandCondPseudos16)
1371     return BB;
1372   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1373   DebugLoc dl = MI->getDebugLoc();
1374   // To "insert" a SELECT_CC instruction, we actually have to insert the
1375   // diamond control-flow pattern.  The incoming instruction knows the
1376   // destination vreg to set, the condition code register to branch on, the
1377   // true/false values to select between, and a branch opcode to use.
1378   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1379   MachineFunction::iterator It = BB;
1380   ++It;
1381
1382   //  thisMBB:
1383   //  ...
1384   //   TrueVal = ...
1385   //   setcc r1, r2, r3
1386   //   bNE   r1, r0, copy1MBB
1387   //   fallthrough --> copy0MBB
1388   MachineBasicBlock *thisMBB  = BB;
1389   MachineFunction *F = BB->getParent();
1390   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1391   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
1392   F->insert(It, copy0MBB);
1393   F->insert(It, sinkMBB);
1394
1395   // Transfer the remainder of BB and its successor edges to sinkMBB.
1396   sinkMBB->splice(sinkMBB->begin(), BB,
1397                   llvm::next(MachineBasicBlock::iterator(MI)),
1398                   BB->end());
1399   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1400
1401   // Next, add the true and fallthrough blocks as its successors.
1402   BB->addSuccessor(copy0MBB);
1403   BB->addSuccessor(sinkMBB);
1404
1405   BuildMI(BB, dl, TII->get(Opc2)).addReg(MI->getOperand(3).getReg())
1406     .addImm(MI->getOperand(4).getImm());
1407   BuildMI(BB, dl, TII->get(Opc1)).addMBB(sinkMBB);
1408
1409   //  copy0MBB:
1410   //   %FalseValue = ...
1411   //   # fallthrough to sinkMBB
1412   BB = copy0MBB;
1413
1414   // Update machine-CFG edges
1415   BB->addSuccessor(sinkMBB);
1416
1417   //  sinkMBB:
1418   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1419   //  ...
1420   BB = sinkMBB;
1421
1422   BuildMI(*BB, BB->begin(), dl,
1423           TII->get(Mips::PHI), MI->getOperand(0).getReg())
1424     .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
1425     .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
1426
1427   MI->eraseFromParent();   // The pseudo instruction is gone now.
1428   return BB;
1429
1430 }
1431
1432 MachineBasicBlock *
1433 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1434                                                 MachineBasicBlock *BB) const {
1435   switch (MI->getOpcode()) {
1436   default:
1437     llvm_unreachable("Unexpected instr type to insert");
1438   case Mips::ATOMIC_LOAD_ADD_I8:
1439   case Mips::ATOMIC_LOAD_ADD_I8_P8:
1440     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1441   case Mips::ATOMIC_LOAD_ADD_I16:
1442   case Mips::ATOMIC_LOAD_ADD_I16_P8:
1443     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1444   case Mips::ATOMIC_LOAD_ADD_I32:
1445   case Mips::ATOMIC_LOAD_ADD_I32_P8:
1446     return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
1447   case Mips::ATOMIC_LOAD_ADD_I64:
1448   case Mips::ATOMIC_LOAD_ADD_I64_P8:
1449     return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
1450
1451   case Mips::ATOMIC_LOAD_AND_I8:
1452   case Mips::ATOMIC_LOAD_AND_I8_P8:
1453     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1454   case Mips::ATOMIC_LOAD_AND_I16:
1455   case Mips::ATOMIC_LOAD_AND_I16_P8:
1456     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1457   case Mips::ATOMIC_LOAD_AND_I32:
1458   case Mips::ATOMIC_LOAD_AND_I32_P8:
1459     return EmitAtomicBinary(MI, BB, 4, Mips::AND);
1460   case Mips::ATOMIC_LOAD_AND_I64:
1461   case Mips::ATOMIC_LOAD_AND_I64_P8:
1462     return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
1463
1464   case Mips::ATOMIC_LOAD_OR_I8:
1465   case Mips::ATOMIC_LOAD_OR_I8_P8:
1466     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1467   case Mips::ATOMIC_LOAD_OR_I16:
1468   case Mips::ATOMIC_LOAD_OR_I16_P8:
1469     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1470   case Mips::ATOMIC_LOAD_OR_I32:
1471   case Mips::ATOMIC_LOAD_OR_I32_P8:
1472     return EmitAtomicBinary(MI, BB, 4, Mips::OR);
1473   case Mips::ATOMIC_LOAD_OR_I64:
1474   case Mips::ATOMIC_LOAD_OR_I64_P8:
1475     return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
1476
1477   case Mips::ATOMIC_LOAD_XOR_I8:
1478   case Mips::ATOMIC_LOAD_XOR_I8_P8:
1479     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1480   case Mips::ATOMIC_LOAD_XOR_I16:
1481   case Mips::ATOMIC_LOAD_XOR_I16_P8:
1482     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1483   case Mips::ATOMIC_LOAD_XOR_I32:
1484   case Mips::ATOMIC_LOAD_XOR_I32_P8:
1485     return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
1486   case Mips::ATOMIC_LOAD_XOR_I64:
1487   case Mips::ATOMIC_LOAD_XOR_I64_P8:
1488     return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
1489
1490   case Mips::ATOMIC_LOAD_NAND_I8:
1491   case Mips::ATOMIC_LOAD_NAND_I8_P8:
1492     return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
1493   case Mips::ATOMIC_LOAD_NAND_I16:
1494   case Mips::ATOMIC_LOAD_NAND_I16_P8:
1495     return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
1496   case Mips::ATOMIC_LOAD_NAND_I32:
1497   case Mips::ATOMIC_LOAD_NAND_I32_P8:
1498     return EmitAtomicBinary(MI, BB, 4, 0, true);
1499   case Mips::ATOMIC_LOAD_NAND_I64:
1500   case Mips::ATOMIC_LOAD_NAND_I64_P8:
1501     return EmitAtomicBinary(MI, BB, 8, 0, true);
1502
1503   case Mips::ATOMIC_LOAD_SUB_I8:
1504   case Mips::ATOMIC_LOAD_SUB_I8_P8:
1505     return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1506   case Mips::ATOMIC_LOAD_SUB_I16:
1507   case Mips::ATOMIC_LOAD_SUB_I16_P8:
1508     return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1509   case Mips::ATOMIC_LOAD_SUB_I32:
1510   case Mips::ATOMIC_LOAD_SUB_I32_P8:
1511     return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1512   case Mips::ATOMIC_LOAD_SUB_I64:
1513   case Mips::ATOMIC_LOAD_SUB_I64_P8:
1514     return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1515
1516   case Mips::ATOMIC_SWAP_I8:
1517   case Mips::ATOMIC_SWAP_I8_P8:
1518     return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1519   case Mips::ATOMIC_SWAP_I16:
1520   case Mips::ATOMIC_SWAP_I16_P8:
1521     return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1522   case Mips::ATOMIC_SWAP_I32:
1523   case Mips::ATOMIC_SWAP_I32_P8:
1524     return EmitAtomicBinary(MI, BB, 4, 0);
1525   case Mips::ATOMIC_SWAP_I64:
1526   case Mips::ATOMIC_SWAP_I64_P8:
1527     return EmitAtomicBinary(MI, BB, 8, 0);
1528
1529   case Mips::ATOMIC_CMP_SWAP_I8:
1530   case Mips::ATOMIC_CMP_SWAP_I8_P8:
1531     return EmitAtomicCmpSwapPartword(MI, BB, 1);
1532   case Mips::ATOMIC_CMP_SWAP_I16:
1533   case Mips::ATOMIC_CMP_SWAP_I16_P8:
1534     return EmitAtomicCmpSwapPartword(MI, BB, 2);
1535   case Mips::ATOMIC_CMP_SWAP_I32:
1536   case Mips::ATOMIC_CMP_SWAP_I32_P8:
1537     return EmitAtomicCmpSwap(MI, BB, 4);
1538   case Mips::ATOMIC_CMP_SWAP_I64:
1539   case Mips::ATOMIC_CMP_SWAP_I64_P8:
1540     return EmitAtomicCmpSwap(MI, BB, 8);
1541   case Mips::BPOSGE32_PSEUDO:
1542     return EmitBPOSGE32(MI, BB);
1543   case Mips::SelBeqZ:
1544     return EmitSel16(Mips::BeqzRxImm16, MI, BB);
1545   case Mips::SelBneZ:
1546     return EmitSel16(Mips::BnezRxImm16, MI, BB);
1547   case Mips::SelTBteqZCmpi:
1548     return EmitSeliT16(Mips::BteqzX16, Mips::CmpiRxImmX16, MI, BB);
1549   case Mips::SelTBteqZSlti:
1550     return EmitSeliT16(Mips::BteqzX16, Mips::SltiRxImmX16, MI, BB);
1551   case Mips::SelTBteqZSltiu:
1552     return EmitSeliT16(Mips::BteqzX16, Mips::SltiuRxImmX16, MI, BB);
1553   case Mips::SelTBtneZCmpi:
1554     return EmitSeliT16(Mips::BtnezX16, Mips::CmpiRxImmX16, MI, BB);
1555   case Mips::SelTBtneZSlti:
1556     return EmitSeliT16(Mips::BtnezX16, Mips::SltiRxImmX16, MI, BB);
1557   case Mips::SelTBtneZSltiu:
1558     return EmitSeliT16(Mips::BtnezX16, Mips::SltiuRxImmX16, MI, BB);
1559   case Mips::SelTBteqZCmp:
1560     return EmitSelT16(Mips::BteqzX16, Mips::CmpRxRy16, MI, BB);
1561   case Mips::SelTBteqZSlt:
1562     return EmitSelT16(Mips::BteqzX16, Mips::SltRxRy16, MI, BB);
1563   case Mips::SelTBteqZSltu:
1564     return EmitSelT16(Mips::BteqzX16, Mips::SltuRxRy16, MI, BB);
1565   case Mips::SelTBtneZCmp:
1566     return EmitSelT16(Mips::BtnezX16, Mips::CmpRxRy16, MI, BB);
1567   case Mips::SelTBtneZSlt:
1568     return EmitSelT16(Mips::BtnezX16, Mips::SltRxRy16, MI, BB);
1569   case Mips::SelTBtneZSltu:
1570     return EmitSelT16(Mips::BtnezX16, Mips::SltuRxRy16, MI, BB);
1571   }
1572 }
1573
1574 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1575 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1576 MachineBasicBlock *
1577 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1578                                      unsigned Size, unsigned BinOpcode,
1579                                      bool Nand) const {
1580   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1581
1582   MachineFunction *MF = BB->getParent();
1583   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1584   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1585   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1586   DebugLoc dl = MI->getDebugLoc();
1587   unsigned LL, SC, AND, NOR, ZERO, BEQ;
1588
1589   if (Size == 4) {
1590     LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1591     SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1592     AND = Mips::AND;
1593     NOR = Mips::NOR;
1594     ZERO = Mips::ZERO;
1595     BEQ = Mips::BEQ;
1596   }
1597   else {
1598     LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1599     SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1600     AND = Mips::AND64;
1601     NOR = Mips::NOR64;
1602     ZERO = Mips::ZERO_64;
1603     BEQ = Mips::BEQ64;
1604   }
1605
1606   unsigned OldVal = MI->getOperand(0).getReg();
1607   unsigned Ptr = MI->getOperand(1).getReg();
1608   unsigned Incr = MI->getOperand(2).getReg();
1609
1610   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1611   unsigned AndRes = RegInfo.createVirtualRegister(RC);
1612   unsigned Success = RegInfo.createVirtualRegister(RC);
1613
1614   // insert new blocks after the current block
1615   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1616   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1617   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1618   MachineFunction::iterator It = BB;
1619   ++It;
1620   MF->insert(It, loopMBB);
1621   MF->insert(It, exitMBB);
1622
1623   // Transfer the remainder of BB and its successor edges to exitMBB.
1624   exitMBB->splice(exitMBB->begin(), BB,
1625                   llvm::next(MachineBasicBlock::iterator(MI)),
1626                   BB->end());
1627   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1628
1629   //  thisMBB:
1630   //    ...
1631   //    fallthrough --> loopMBB
1632   BB->addSuccessor(loopMBB);
1633   loopMBB->addSuccessor(loopMBB);
1634   loopMBB->addSuccessor(exitMBB);
1635
1636   //  loopMBB:
1637   //    ll oldval, 0(ptr)
1638   //    <binop> storeval, oldval, incr
1639   //    sc success, storeval, 0(ptr)
1640   //    beq success, $0, loopMBB
1641   BB = loopMBB;
1642   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1643   if (Nand) {
1644     //  and andres, oldval, incr
1645     //  nor storeval, $0, andres
1646     BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1647     BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1648   } else if (BinOpcode) {
1649     //  <binop> storeval, oldval, incr
1650     BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1651   } else {
1652     StoreVal = Incr;
1653   }
1654   BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1655   BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1656
1657   MI->eraseFromParent();   // The instruction is gone now.
1658
1659   return exitMBB;
1660 }
1661
1662 MachineBasicBlock *
1663 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1664                                              MachineBasicBlock *BB,
1665                                              unsigned Size, unsigned BinOpcode,
1666                                              bool Nand) const {
1667   assert((Size == 1 || Size == 2) &&
1668       "Unsupported size for EmitAtomicBinaryPartial.");
1669
1670   MachineFunction *MF = BB->getParent();
1671   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1672   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1673   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1674   DebugLoc dl = MI->getDebugLoc();
1675   unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1676   unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1677
1678   unsigned Dest = MI->getOperand(0).getReg();
1679   unsigned Ptr = MI->getOperand(1).getReg();
1680   unsigned Incr = MI->getOperand(2).getReg();
1681
1682   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1683   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1684   unsigned Mask = RegInfo.createVirtualRegister(RC);
1685   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1686   unsigned NewVal = RegInfo.createVirtualRegister(RC);
1687   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1688   unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1689   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1690   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1691   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1692   unsigned AndRes = RegInfo.createVirtualRegister(RC);
1693   unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1694   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1695   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1696   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1697   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1698   unsigned SllRes = RegInfo.createVirtualRegister(RC);
1699   unsigned Success = RegInfo.createVirtualRegister(RC);
1700
1701   // insert new blocks after the current block
1702   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1703   MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1704   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1705   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1706   MachineFunction::iterator It = BB;
1707   ++It;
1708   MF->insert(It, loopMBB);
1709   MF->insert(It, sinkMBB);
1710   MF->insert(It, exitMBB);
1711
1712   // Transfer the remainder of BB and its successor edges to exitMBB.
1713   exitMBB->splice(exitMBB->begin(), BB,
1714                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1715   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1716
1717   BB->addSuccessor(loopMBB);
1718   loopMBB->addSuccessor(loopMBB);
1719   loopMBB->addSuccessor(sinkMBB);
1720   sinkMBB->addSuccessor(exitMBB);
1721
1722   //  thisMBB:
1723   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1724   //    and     alignedaddr,ptr,masklsb2
1725   //    andi    ptrlsb2,ptr,3
1726   //    sll     shiftamt,ptrlsb2,3
1727   //    ori     maskupper,$0,255               # 0xff
1728   //    sll     mask,maskupper,shiftamt
1729   //    nor     mask2,$0,mask
1730   //    sll     incr2,incr,shiftamt
1731
1732   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1733   BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1734     .addReg(Mips::ZERO).addImm(-4);
1735   BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1736     .addReg(Ptr).addReg(MaskLSB2);
1737   BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1738   BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1739   BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1740     .addReg(Mips::ZERO).addImm(MaskImm);
1741   BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1742     .addReg(ShiftAmt).addReg(MaskUpper);
1743   BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1744   BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1745
1746   // atomic.load.binop
1747   // loopMBB:
1748   //   ll      oldval,0(alignedaddr)
1749   //   binop   binopres,oldval,incr2
1750   //   and     newval,binopres,mask
1751   //   and     maskedoldval0,oldval,mask2
1752   //   or      storeval,maskedoldval0,newval
1753   //   sc      success,storeval,0(alignedaddr)
1754   //   beq     success,$0,loopMBB
1755
1756   // atomic.swap
1757   // loopMBB:
1758   //   ll      oldval,0(alignedaddr)
1759   //   and     newval,incr2,mask
1760   //   and     maskedoldval0,oldval,mask2
1761   //   or      storeval,maskedoldval0,newval
1762   //   sc      success,storeval,0(alignedaddr)
1763   //   beq     success,$0,loopMBB
1764
1765   BB = loopMBB;
1766   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1767   if (Nand) {
1768     //  and andres, oldval, incr2
1769     //  nor binopres, $0, andres
1770     //  and newval, binopres, mask
1771     BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1772     BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1773       .addReg(Mips::ZERO).addReg(AndRes);
1774     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1775   } else if (BinOpcode) {
1776     //  <binop> binopres, oldval, incr2
1777     //  and newval, binopres, mask
1778     BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1779     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1780   } else {// atomic.swap
1781     //  and newval, incr2, mask
1782     BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1783   }
1784
1785   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1786     .addReg(OldVal).addReg(Mask2);
1787   BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1788     .addReg(MaskedOldVal0).addReg(NewVal);
1789   BuildMI(BB, dl, TII->get(SC), Success)
1790     .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1791   BuildMI(BB, dl, TII->get(Mips::BEQ))
1792     .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1793
1794   //  sinkMBB:
1795   //    and     maskedoldval1,oldval,mask
1796   //    srl     srlres,maskedoldval1,shiftamt
1797   //    sll     sllres,srlres,24
1798   //    sra     dest,sllres,24
1799   BB = sinkMBB;
1800   int64_t ShiftImm = (Size == 1) ? 24 : 16;
1801
1802   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1803     .addReg(OldVal).addReg(Mask);
1804   BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1805       .addReg(ShiftAmt).addReg(MaskedOldVal1);
1806   BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1807       .addReg(SrlRes).addImm(ShiftImm);
1808   BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1809       .addReg(SllRes).addImm(ShiftImm);
1810
1811   MI->eraseFromParent();   // The instruction is gone now.
1812
1813   return exitMBB;
1814 }
1815
1816 MachineBasicBlock *
1817 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1818                                       MachineBasicBlock *BB,
1819                                       unsigned Size) const {
1820   assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1821
1822   MachineFunction *MF = BB->getParent();
1823   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1824   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1825   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1826   DebugLoc dl = MI->getDebugLoc();
1827   unsigned LL, SC, ZERO, BNE, BEQ;
1828
1829   if (Size == 4) {
1830     LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1831     SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1832     ZERO = Mips::ZERO;
1833     BNE = Mips::BNE;
1834     BEQ = Mips::BEQ;
1835   }
1836   else {
1837     LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1838     SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1839     ZERO = Mips::ZERO_64;
1840     BNE = Mips::BNE64;
1841     BEQ = Mips::BEQ64;
1842   }
1843
1844   unsigned Dest    = MI->getOperand(0).getReg();
1845   unsigned Ptr     = MI->getOperand(1).getReg();
1846   unsigned OldVal  = MI->getOperand(2).getReg();
1847   unsigned NewVal  = MI->getOperand(3).getReg();
1848
1849   unsigned Success = RegInfo.createVirtualRegister(RC);
1850
1851   // insert new blocks after the current block
1852   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1853   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1854   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1855   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1856   MachineFunction::iterator It = BB;
1857   ++It;
1858   MF->insert(It, loop1MBB);
1859   MF->insert(It, loop2MBB);
1860   MF->insert(It, exitMBB);
1861
1862   // Transfer the remainder of BB and its successor edges to exitMBB.
1863   exitMBB->splice(exitMBB->begin(), BB,
1864                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1865   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1866
1867   //  thisMBB:
1868   //    ...
1869   //    fallthrough --> loop1MBB
1870   BB->addSuccessor(loop1MBB);
1871   loop1MBB->addSuccessor(exitMBB);
1872   loop1MBB->addSuccessor(loop2MBB);
1873   loop2MBB->addSuccessor(loop1MBB);
1874   loop2MBB->addSuccessor(exitMBB);
1875
1876   // loop1MBB:
1877   //   ll dest, 0(ptr)
1878   //   bne dest, oldval, exitMBB
1879   BB = loop1MBB;
1880   BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1881   BuildMI(BB, dl, TII->get(BNE))
1882     .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1883
1884   // loop2MBB:
1885   //   sc success, newval, 0(ptr)
1886   //   beq success, $0, loop1MBB
1887   BB = loop2MBB;
1888   BuildMI(BB, dl, TII->get(SC), Success)
1889     .addReg(NewVal).addReg(Ptr).addImm(0);
1890   BuildMI(BB, dl, TII->get(BEQ))
1891     .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1892
1893   MI->eraseFromParent();   // The instruction is gone now.
1894
1895   return exitMBB;
1896 }
1897
1898 MachineBasicBlock *
1899 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1900                                               MachineBasicBlock *BB,
1901                                               unsigned Size) const {
1902   assert((Size == 1 || Size == 2) &&
1903       "Unsupported size for EmitAtomicCmpSwapPartial.");
1904
1905   MachineFunction *MF = BB->getParent();
1906   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1907   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1908   const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1909   DebugLoc dl = MI->getDebugLoc();
1910   unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1911   unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1912
1913   unsigned Dest    = MI->getOperand(0).getReg();
1914   unsigned Ptr     = MI->getOperand(1).getReg();
1915   unsigned CmpVal  = MI->getOperand(2).getReg();
1916   unsigned NewVal  = MI->getOperand(3).getReg();
1917
1918   unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1919   unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1920   unsigned Mask = RegInfo.createVirtualRegister(RC);
1921   unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1922   unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1923   unsigned OldVal = RegInfo.createVirtualRegister(RC);
1924   unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1925   unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1926   unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1927   unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1928   unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1929   unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1930   unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1931   unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1932   unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1933   unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1934   unsigned SllRes = RegInfo.createVirtualRegister(RC);
1935   unsigned Success = RegInfo.createVirtualRegister(RC);
1936
1937   // insert new blocks after the current block
1938   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1939   MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1940   MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1941   MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1942   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1943   MachineFunction::iterator It = BB;
1944   ++It;
1945   MF->insert(It, loop1MBB);
1946   MF->insert(It, loop2MBB);
1947   MF->insert(It, sinkMBB);
1948   MF->insert(It, exitMBB);
1949
1950   // Transfer the remainder of BB and its successor edges to exitMBB.
1951   exitMBB->splice(exitMBB->begin(), BB,
1952                   llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1953   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1954
1955   BB->addSuccessor(loop1MBB);
1956   loop1MBB->addSuccessor(sinkMBB);
1957   loop1MBB->addSuccessor(loop2MBB);
1958   loop2MBB->addSuccessor(loop1MBB);
1959   loop2MBB->addSuccessor(sinkMBB);
1960   sinkMBB->addSuccessor(exitMBB);
1961
1962   // FIXME: computation of newval2 can be moved to loop2MBB.
1963   //  thisMBB:
1964   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1965   //    and     alignedaddr,ptr,masklsb2
1966   //    andi    ptrlsb2,ptr,3
1967   //    sll     shiftamt,ptrlsb2,3
1968   //    ori     maskupper,$0,255               # 0xff
1969   //    sll     mask,maskupper,shiftamt
1970   //    nor     mask2,$0,mask
1971   //    andi    maskedcmpval,cmpval,255
1972   //    sll     shiftedcmpval,maskedcmpval,shiftamt
1973   //    andi    maskednewval,newval,255
1974   //    sll     shiftednewval,maskednewval,shiftamt
1975   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1976   BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1977     .addReg(Mips::ZERO).addImm(-4);
1978   BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1979     .addReg(Ptr).addReg(MaskLSB2);
1980   BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1981   BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1982   BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1983     .addReg(Mips::ZERO).addImm(MaskImm);
1984   BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1985     .addReg(ShiftAmt).addReg(MaskUpper);
1986   BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1987   BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1988     .addReg(CmpVal).addImm(MaskImm);
1989   BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1990     .addReg(ShiftAmt).addReg(MaskedCmpVal);
1991   BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1992     .addReg(NewVal).addImm(MaskImm);
1993   BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1994     .addReg(ShiftAmt).addReg(MaskedNewVal);
1995
1996   //  loop1MBB:
1997   //    ll      oldval,0(alginedaddr)
1998   //    and     maskedoldval0,oldval,mask
1999   //    bne     maskedoldval0,shiftedcmpval,sinkMBB
2000   BB = loop1MBB;
2001   BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
2002   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
2003     .addReg(OldVal).addReg(Mask);
2004   BuildMI(BB, dl, TII->get(Mips::BNE))
2005     .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
2006
2007   //  loop2MBB:
2008   //    and     maskedoldval1,oldval,mask2
2009   //    or      storeval,maskedoldval1,shiftednewval
2010   //    sc      success,storeval,0(alignedaddr)
2011   //    beq     success,$0,loop1MBB
2012   BB = loop2MBB;
2013   BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
2014     .addReg(OldVal).addReg(Mask2);
2015   BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
2016     .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
2017   BuildMI(BB, dl, TII->get(SC), Success)
2018       .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
2019   BuildMI(BB, dl, TII->get(Mips::BEQ))
2020       .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
2021
2022   //  sinkMBB:
2023   //    srl     srlres,maskedoldval0,shiftamt
2024   //    sll     sllres,srlres,24
2025   //    sra     dest,sllres,24
2026   BB = sinkMBB;
2027   int64_t ShiftImm = (Size == 1) ? 24 : 16;
2028
2029   BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
2030       .addReg(ShiftAmt).addReg(MaskedOldVal0);
2031   BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
2032       .addReg(SrlRes).addImm(ShiftImm);
2033   BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
2034       .addReg(SllRes).addImm(ShiftImm);
2035
2036   MI->eraseFromParent();   // The instruction is gone now.
2037
2038   return exitMBB;
2039 }
2040
2041 //===----------------------------------------------------------------------===//
2042 //  Misc Lower Operation implementation
2043 //===----------------------------------------------------------------------===//
2044 SDValue MipsTargetLowering::
2045 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
2046 {
2047   // The first operand is the chain, the second is the condition, the third is
2048   // the block to branch to if the condition is true.
2049   SDValue Chain = Op.getOperand(0);
2050   SDValue Dest = Op.getOperand(2);
2051   DebugLoc dl = Op.getDebugLoc();
2052
2053   SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
2054
2055   // Return if flag is not set by a floating point comparison.
2056   if (CondRes.getOpcode() != MipsISD::FPCmp)
2057     return Op;
2058
2059   SDValue CCNode  = CondRes.getOperand(2);
2060   Mips::CondCode CC =
2061     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
2062   SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
2063
2064   return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
2065                      Dest, CondRes);
2066 }
2067
2068 SDValue MipsTargetLowering::
2069 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
2070 {
2071   SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
2072
2073   // Return if flag is not set by a floating point comparison.
2074   if (Cond.getOpcode() != MipsISD::FPCmp)
2075     return Op;
2076
2077   return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2078                       Op.getDebugLoc());
2079 }
2080
2081 SDValue MipsTargetLowering::
2082 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
2083 {
2084   DebugLoc DL = Op.getDebugLoc();
2085   EVT Ty = Op.getOperand(0).getValueType();
2086   SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
2087                              Op.getOperand(0), Op.getOperand(1),
2088                              Op.getOperand(4));
2089
2090   return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
2091                      Op.getOperand(3));
2092 }
2093
2094 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2095   SDValue Cond = CreateFPCmp(DAG, Op);
2096
2097   assert(Cond.getOpcode() == MipsISD::FPCmp &&
2098          "Floating point operand expected.");
2099
2100   SDValue True  = DAG.getConstant(1, MVT::i32);
2101   SDValue False = DAG.getConstant(0, MVT::i32);
2102
2103   return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
2104 }
2105
2106 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
2107                                                SelectionDAG &DAG) const {
2108   // FIXME there isn't actually debug info here
2109   DebugLoc dl = Op.getDebugLoc();
2110   const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2111
2112   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
2113     const MipsTargetObjectFile &TLOF =
2114       (const MipsTargetObjectFile&)getObjFileLowering();
2115
2116     // %gp_rel relocation
2117     if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
2118       SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
2119                                               MipsII::MO_GPREL);
2120       SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl,
2121                                       DAG.getVTList(MVT::i32), &GA, 1);
2122       SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
2123       return DAG.getNode(ISD::ADD, dl, MVT::i32, GPReg, GPRelNode);
2124     }
2125
2126     // %hi/%lo relocation
2127     return getAddrNonPIC(Op, DAG);
2128   }
2129
2130   if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
2131     return getAddrLocal(Op, DAG, HasMips64);
2132
2133   if (LargeGOT)
2134     return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
2135                                  MipsII::MO_GOT_LO16);
2136
2137   return getAddrGlobal(Op, DAG,
2138                        HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
2139 }
2140
2141 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
2142                                               SelectionDAG &DAG) const {
2143   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2144     return getAddrNonPIC(Op, DAG);
2145
2146   return getAddrLocal(Op, DAG, HasMips64);
2147 }
2148
2149 SDValue MipsTargetLowering::
2150 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2151 {
2152   // If the relocation model is PIC, use the General Dynamic TLS Model or
2153   // Local Dynamic TLS model, otherwise use the Initial Exec or
2154   // Local Exec TLS Model.
2155
2156   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2157   DebugLoc dl = GA->getDebugLoc();
2158   const GlobalValue *GV = GA->getGlobal();
2159   EVT PtrVT = getPointerTy();
2160
2161   TLSModel::Model model = getTargetMachine().getTLSModel(GV);
2162
2163   if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2164     // General Dynamic and Local Dynamic TLS Model.
2165     unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2166                                                       : MipsII::MO_TLSGD;
2167
2168     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
2169     SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
2170                                    GetGlobalReg(DAG, PtrVT), TGA);
2171     unsigned PtrSize = PtrVT.getSizeInBits();
2172     IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2173
2174     SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2175
2176     ArgListTy Args;
2177     ArgListEntry Entry;
2178     Entry.Node = Argument;
2179     Entry.Ty = PtrTy;
2180     Args.push_back(Entry);
2181
2182     TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
2183                   false, false, false, false, 0, CallingConv::C,
2184                   /*isTailCall=*/false, /*doesNotRet=*/false,
2185                   /*isReturnValueUsed=*/true,
2186                   TlsGetAddr, Args, DAG, dl);
2187     std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2188
2189     SDValue Ret = CallResult.first;
2190
2191     if (model != TLSModel::LocalDynamic)
2192       return Ret;
2193
2194     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2195                                                MipsII::MO_DTPREL_HI);
2196     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
2197     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2198                                                MipsII::MO_DTPREL_LO);
2199     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
2200     SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
2201     return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
2202   }
2203
2204   SDValue Offset;
2205   if (model == TLSModel::InitialExec) {
2206     // Initial Exec TLS Model
2207     SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2208                                              MipsII::MO_GOTTPREL);
2209     TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
2210                       TGA);
2211     Offset = DAG.getLoad(PtrVT, dl,
2212                          DAG.getEntryNode(), TGA, MachinePointerInfo(),
2213                          false, false, false, 0);
2214   } else {
2215     // Local Exec TLS Model
2216     assert(model == TLSModel::LocalExec);
2217     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2218                                                MipsII::MO_TPREL_HI);
2219     SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
2220                                                MipsII::MO_TPREL_LO);
2221     SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
2222     SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
2223     Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
2224   }
2225
2226   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
2227   return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2228 }
2229
2230 SDValue MipsTargetLowering::
2231 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2232 {
2233   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2234     return getAddrNonPIC(Op, DAG);
2235
2236   return getAddrLocal(Op, DAG, HasMips64);
2237 }
2238
2239 SDValue MipsTargetLowering::
2240 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2241 {
2242   // gp_rel relocation
2243   // FIXME: we should reference the constant pool using small data sections,
2244   // but the asm printer currently doesn't support this feature without
2245   // hacking it. This feature should come soon so we can uncomment the
2246   // stuff below.
2247   //if (IsInSmallSection(C->getType())) {
2248   //  SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
2249   //  SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
2250   //  ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
2251
2252   if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2253     return getAddrNonPIC(Op, DAG);
2254
2255   return getAddrLocal(Op, DAG, HasMips64);
2256 }
2257
2258 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2259   MachineFunction &MF = DAG.getMachineFunction();
2260   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2261
2262   DebugLoc dl = Op.getDebugLoc();
2263   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2264                                  getPointerTy());
2265
2266   // vastart just stores the address of the VarArgsFrameIndex slot into the
2267   // memory location argument.
2268   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2269   return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
2270                       MachinePointerInfo(SV), false, false, 0);
2271 }
2272
2273 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2274   EVT TyX = Op.getOperand(0).getValueType();
2275   EVT TyY = Op.getOperand(1).getValueType();
2276   SDValue Const1 = DAG.getConstant(1, MVT::i32);
2277   SDValue Const31 = DAG.getConstant(31, MVT::i32);
2278   DebugLoc DL = Op.getDebugLoc();
2279   SDValue Res;
2280
2281   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2282   // to i32.
2283   SDValue X = (TyX == MVT::f32) ?
2284     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2285     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2286                 Const1);
2287   SDValue Y = (TyY == MVT::f32) ?
2288     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2289     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2290                 Const1);
2291
2292   if (HasR2) {
2293     // ext  E, Y, 31, 1  ; extract bit31 of Y
2294     // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
2295     SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2296     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2297   } else {
2298     // sll SllX, X, 1
2299     // srl SrlX, SllX, 1
2300     // srl SrlY, Y, 31
2301     // sll SllY, SrlX, 31
2302     // or  Or, SrlX, SllY
2303     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2304     SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2305     SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2306     SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2307     Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2308   }
2309
2310   if (TyX == MVT::f32)
2311     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2312
2313   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2314                              Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2315   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2316 }
2317
2318 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2319   unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2320   unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2321   EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2322   SDValue Const1 = DAG.getConstant(1, MVT::i32);
2323   DebugLoc DL = Op.getDebugLoc();
2324
2325   // Bitcast to integer nodes.
2326   SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2327   SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2328
2329   if (HasR2) {
2330     // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
2331     // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
2332     SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2333                             DAG.getConstant(WidthY - 1, MVT::i32), Const1);
2334
2335     if (WidthX > WidthY)
2336       E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2337     else if (WidthY > WidthX)
2338       E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2339
2340     SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2341                             DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2342     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2343   }
2344
2345   // (d)sll SllX, X, 1
2346   // (d)srl SrlX, SllX, 1
2347   // (d)srl SrlY, Y, width(Y)-1
2348   // (d)sll SllY, SrlX, width(Y)-1
2349   // or     Or, SrlX, SllY
2350   SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2351   SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2352   SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2353                              DAG.getConstant(WidthY - 1, MVT::i32));
2354
2355   if (WidthX > WidthY)
2356     SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2357   else if (WidthY > WidthX)
2358     SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2359
2360   SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2361                              DAG.getConstant(WidthX - 1, MVT::i32));
2362   SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2363   return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2364 }
2365
2366 SDValue
2367 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2368   if (Subtarget->hasMips64())
2369     return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
2370
2371   return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
2372 }
2373
2374 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2375   SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2376   DebugLoc DL = Op.getDebugLoc();
2377
2378   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2379   // to i32.
2380   SDValue X = (Op.getValueType() == MVT::f32) ?
2381     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2382     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2383                 Const1);
2384
2385   // Clear MSB.
2386   if (HasR2)
2387     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2388                       DAG.getRegister(Mips::ZERO, MVT::i32),
2389                       DAG.getConstant(31, MVT::i32), Const1, X);
2390   else {
2391     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2392     Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2393   }
2394
2395   if (Op.getValueType() == MVT::f32)
2396     return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2397
2398   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2399                              Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2400   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2401 }
2402
2403 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2404   SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2405   DebugLoc DL = Op.getDebugLoc();
2406
2407   // Bitcast to integer node.
2408   SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2409
2410   // Clear MSB.
2411   if (HasR2)
2412     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2413                       DAG.getRegister(Mips::ZERO_64, MVT::i64),
2414                       DAG.getConstant(63, MVT::i32), Const1, X);
2415   else {
2416     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2417     Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2418   }
2419
2420   return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2421 }
2422
2423 SDValue
2424 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
2425   if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2426     return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2427
2428   return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2429 }
2430
2431 SDValue MipsTargetLowering::
2432 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2433   // check the depth
2434   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2435          "Frame address can only be determined for current frame.");
2436
2437   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2438   MFI->setFrameAddressIsTaken(true);
2439   EVT VT = Op.getValueType();
2440   DebugLoc dl = Op.getDebugLoc();
2441   SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2442                                          IsN64 ? Mips::FP_64 : Mips::FP, VT);
2443   return FrameAddr;
2444 }
2445
2446 SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2447                                             SelectionDAG &DAG) const {
2448   // check the depth
2449   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2450          "Return address can be determined only for current frame.");
2451
2452   MachineFunction &MF = DAG.getMachineFunction();
2453   MachineFrameInfo *MFI = MF.getFrameInfo();
2454   MVT VT = Op.getSimpleValueType();
2455   unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2456   MFI->setReturnAddressIsTaken(true);
2457
2458   // Return RA, which contains the return address. Mark it an implicit live-in.
2459   unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2460   return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2461 }
2462
2463 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2464 // generated from __builtin_eh_return (offset, handler)
2465 // The effect of this is to adjust the stack pointer by "offset"
2466 // and then branch to "handler".
2467 SDValue MipsTargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2468                                                                      const {
2469   MachineFunction &MF = DAG.getMachineFunction();
2470   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2471
2472   MipsFI->setCallsEhReturn();
2473   SDValue Chain     = Op.getOperand(0);
2474   SDValue Offset    = Op.getOperand(1);
2475   SDValue Handler   = Op.getOperand(2);
2476   DebugLoc DL       = Op.getDebugLoc();
2477   EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2478
2479   // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2480   // EH_RETURN nodes, so that instructions are emitted back-to-back.
2481   unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
2482   unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
2483   Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2484   Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2485   return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2486                      DAG.getRegister(OffsetReg, Ty),
2487                      DAG.getRegister(AddrReg, getPointerTy()),
2488                      Chain.getValue(1));
2489 }
2490
2491 // TODO: set SType according to the desired memory barrier behavior.
2492 SDValue
2493 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2494   unsigned SType = 0;
2495   DebugLoc dl = Op.getDebugLoc();
2496   return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2497                      DAG.getConstant(SType, MVT::i32));
2498 }
2499
2500 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2501                                               SelectionDAG &DAG) const {
2502   // FIXME: Need pseudo-fence for 'singlethread' fences
2503   // FIXME: Set SType for weaker fences where supported/appropriate.
2504   unsigned SType = 0;
2505   DebugLoc dl = Op.getDebugLoc();
2506   return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2507                      DAG.getConstant(SType, MVT::i32));
2508 }
2509
2510 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2511                                                 SelectionDAG &DAG) const {
2512   DebugLoc DL = Op.getDebugLoc();
2513   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2514   SDValue Shamt = Op.getOperand(2);
2515
2516   // if shamt < 32:
2517   //  lo = (shl lo, shamt)
2518   //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2519   // else:
2520   //  lo = 0
2521   //  hi = (shl lo, shamt[4:0])
2522   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2523                             DAG.getConstant(-1, MVT::i32));
2524   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2525                                       DAG.getConstant(1, MVT::i32));
2526   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2527                                      Not);
2528   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2529   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2530   SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2531   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2532                              DAG.getConstant(0x20, MVT::i32));
2533   Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2534                    DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2535   Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2536
2537   SDValue Ops[2] = {Lo, Hi};
2538   return DAG.getMergeValues(Ops, 2, DL);
2539 }
2540
2541 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2542                                                  bool IsSRA) const {
2543   DebugLoc DL = Op.getDebugLoc();
2544   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2545   SDValue Shamt = Op.getOperand(2);
2546
2547   // if shamt < 32:
2548   //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2549   //  if isSRA:
2550   //    hi = (sra hi, shamt)
2551   //  else:
2552   //    hi = (srl hi, shamt)
2553   // else:
2554   //  if isSRA:
2555   //   lo = (sra hi, shamt[4:0])
2556   //   hi = (sra hi, 31)
2557   //  else:
2558   //   lo = (srl hi, shamt[4:0])
2559   //   hi = 0
2560   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2561                             DAG.getConstant(-1, MVT::i32));
2562   SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2563                                      DAG.getConstant(1, MVT::i32));
2564   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2565   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2566   SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2567   SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2568                                      Hi, Shamt);
2569   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2570                              DAG.getConstant(0x20, MVT::i32));
2571   SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2572                                 DAG.getConstant(31, MVT::i32));
2573   Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2574   Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2575                    IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2576                    ShiftRightHi);
2577
2578   SDValue Ops[2] = {Lo, Hi};
2579   return DAG.getMergeValues(Ops, 2, DL);
2580 }
2581
2582 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2583                             SDValue Chain, SDValue Src, unsigned Offset) {
2584   SDValue Ptr = LD->getBasePtr();
2585   EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2586   EVT BasePtrVT = Ptr.getValueType();
2587   DebugLoc DL = LD->getDebugLoc();
2588   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2589
2590   if (Offset)
2591     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2592                       DAG.getConstant(Offset, BasePtrVT));
2593
2594   SDValue Ops[] = { Chain, Ptr, Src };
2595   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2596                                  LD->getMemOperand());
2597 }
2598
2599 // Expand an unaligned 32 or 64-bit integer load node.
2600 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2601   LoadSDNode *LD = cast<LoadSDNode>(Op);
2602   EVT MemVT = LD->getMemoryVT();
2603
2604   // Return if load is aligned or if MemVT is neither i32 nor i64.
2605   if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2606       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2607     return SDValue();
2608
2609   bool IsLittle = Subtarget->isLittle();
2610   EVT VT = Op.getValueType();
2611   ISD::LoadExtType ExtType = LD->getExtensionType();
2612   SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2613
2614   assert((VT == MVT::i32) || (VT == MVT::i64));
2615
2616   // Expand
2617   //  (set dst, (i64 (load baseptr)))
2618   // to
2619   //  (set tmp, (ldl (add baseptr, 7), undef))
2620   //  (set dst, (ldr baseptr, tmp))
2621   if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2622     SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2623                                IsLittle ? 7 : 0);
2624     return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2625                         IsLittle ? 0 : 7);
2626   }
2627
2628   SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2629                              IsLittle ? 3 : 0);
2630   SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2631                              IsLittle ? 0 : 3);
2632
2633   // Expand
2634   //  (set dst, (i32 (load baseptr))) or
2635   //  (set dst, (i64 (sextload baseptr))) or
2636   //  (set dst, (i64 (extload baseptr)))
2637   // to
2638   //  (set tmp, (lwl (add baseptr, 3), undef))
2639   //  (set dst, (lwr baseptr, tmp))
2640   if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2641       (ExtType == ISD::EXTLOAD))
2642     return LWR;
2643
2644   assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2645
2646   // Expand
2647   //  (set dst, (i64 (zextload baseptr)))
2648   // to
2649   //  (set tmp0, (lwl (add baseptr, 3), undef))
2650   //  (set tmp1, (lwr baseptr, tmp0))
2651   //  (set tmp2, (shl tmp1, 32))
2652   //  (set dst, (srl tmp2, 32))
2653   DebugLoc DL = LD->getDebugLoc();
2654   SDValue Const32 = DAG.getConstant(32, MVT::i32);
2655   SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2656   SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2657   SDValue Ops[] = { SRL, LWR.getValue(1) };
2658   return DAG.getMergeValues(Ops, 2, DL);
2659 }
2660
2661 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2662                              SDValue Chain, unsigned Offset) {
2663   SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2664   EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2665   DebugLoc DL = SD->getDebugLoc();
2666   SDVTList VTList = DAG.getVTList(MVT::Other);
2667
2668   if (Offset)
2669     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2670                       DAG.getConstant(Offset, BasePtrVT));
2671
2672   SDValue Ops[] = { Chain, Value, Ptr };
2673   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2674                                  SD->getMemOperand());
2675 }
2676
2677 // Expand an unaligned 32 or 64-bit integer store node.
2678 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2679   StoreSDNode *SD = cast<StoreSDNode>(Op);
2680   EVT MemVT = SD->getMemoryVT();
2681
2682   // Return if store is aligned or if MemVT is neither i32 nor i64.
2683   if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2684       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2685     return SDValue();
2686
2687   bool IsLittle = Subtarget->isLittle();
2688   SDValue Value = SD->getValue(), Chain = SD->getChain();
2689   EVT VT = Value.getValueType();
2690
2691   // Expand
2692   //  (store val, baseptr) or
2693   //  (truncstore val, baseptr)
2694   // to
2695   //  (swl val, (add baseptr, 3))
2696   //  (swr val, baseptr)
2697   if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2698     SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2699                                 IsLittle ? 3 : 0);
2700     return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2701   }
2702
2703   assert(VT == MVT::i64);
2704
2705   // Expand
2706   //  (store val, baseptr)
2707   // to
2708   //  (sdl val, (add baseptr, 7))
2709   //  (sdr val, baseptr)
2710   SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2711   return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2712 }
2713
2714 // This function expands mips intrinsic nodes which have 64-bit input operands
2715 // or output values.
2716 //
2717 // out64 = intrinsic-node in64
2718 // =>
2719 // lo = copy (extract-element (in64, 0))
2720 // hi = copy (extract-element (in64, 1))
2721 // mips-specific-node
2722 // v0 = copy lo
2723 // v1 = copy hi
2724 // out64 = merge-values (v0, v1)
2725 //
2726 static SDValue LowerDSPIntr(SDValue Op, SelectionDAG &DAG,
2727                             unsigned Opc, bool HasI64In, bool HasI64Out) {
2728   DebugLoc DL = Op.getDebugLoc();
2729   bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
2730   SDValue Chain = HasChainIn ? Op->getOperand(0) : DAG.getEntryNode();
2731   SmallVector<SDValue, 3> Ops;
2732
2733   if (HasI64In) {
2734     SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2735                                Op->getOperand(1 + HasChainIn),
2736                                DAG.getConstant(0, MVT::i32));
2737     SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2738                                Op->getOperand(1 + HasChainIn),
2739                                DAG.getConstant(1, MVT::i32));
2740
2741     Chain = DAG.getCopyToReg(Chain, DL, Mips::LO, InLo, SDValue());
2742     Chain = DAG.getCopyToReg(Chain, DL, Mips::HI, InHi, Chain.getValue(1));
2743
2744     Ops.push_back(Chain);
2745     Ops.append(Op->op_begin() + HasChainIn + 2, Op->op_end());
2746     Ops.push_back(Chain.getValue(1));
2747   } else {
2748     Ops.push_back(Chain);
2749     Ops.append(Op->op_begin() + HasChainIn + 1, Op->op_end());
2750   }
2751
2752   if (!HasI64Out)
2753     return DAG.getNode(Opc, DL, Op->value_begin(), Op->getNumValues(),
2754                        Ops.begin(), Ops.size());
2755
2756   SDValue Intr = DAG.getNode(Opc, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2757                              Ops.begin(), Ops.size());
2758   SDValue OutLo = DAG.getCopyFromReg(Intr.getValue(0), DL, Mips::LO, MVT::i32,
2759                                      Intr.getValue(1));
2760   SDValue OutHi = DAG.getCopyFromReg(OutLo.getValue(1), DL, Mips::HI, MVT::i32,
2761                                      OutLo.getValue(2));
2762   SDValue Out = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, OutLo, OutHi);
2763
2764   if (!HasChainIn)
2765     return Out;
2766
2767   SDValue Vals[] = { Out, OutHi.getValue(1) };
2768   return DAG.getMergeValues(Vals, 2, DL);
2769 }
2770
2771 SDValue MipsTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2772                                                     SelectionDAG &DAG) const {
2773   switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
2774   default:
2775     return SDValue();
2776   case Intrinsic::mips_shilo:
2777     return LowerDSPIntr(Op, DAG, MipsISD::SHILO, true, true);
2778   case Intrinsic::mips_dpau_h_qbl:
2779     return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL, true, true);
2780   case Intrinsic::mips_dpau_h_qbr:
2781     return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR, true, true);
2782   case Intrinsic::mips_dpsu_h_qbl:
2783     return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL, true, true);
2784   case Intrinsic::mips_dpsu_h_qbr:
2785     return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR, true, true);
2786   case Intrinsic::mips_dpa_w_ph:
2787     return LowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH, true, true);
2788   case Intrinsic::mips_dps_w_ph:
2789     return LowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH, true, true);
2790   case Intrinsic::mips_dpax_w_ph:
2791     return LowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH, true, true);
2792   case Intrinsic::mips_dpsx_w_ph:
2793     return LowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH, true, true);
2794   case Intrinsic::mips_mulsa_w_ph:
2795     return LowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH, true, true);
2796   case Intrinsic::mips_mult:
2797     return LowerDSPIntr(Op, DAG, MipsISD::MULT, false, true);
2798   case Intrinsic::mips_multu:
2799     return LowerDSPIntr(Op, DAG, MipsISD::MULTU, false, true);
2800   case Intrinsic::mips_madd:
2801     return LowerDSPIntr(Op, DAG, MipsISD::MADD_DSP, true, true);
2802   case Intrinsic::mips_maddu:
2803     return LowerDSPIntr(Op, DAG, MipsISD::MADDU_DSP, true, true);
2804   case Intrinsic::mips_msub:
2805     return LowerDSPIntr(Op, DAG, MipsISD::MSUB_DSP, true, true);
2806   case Intrinsic::mips_msubu:
2807     return LowerDSPIntr(Op, DAG, MipsISD::MSUBU_DSP, true, true);
2808   }
2809 }
2810
2811 SDValue MipsTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2812                                                    SelectionDAG &DAG) const {
2813   switch (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue()) {
2814   default:
2815     return SDValue();
2816   case Intrinsic::mips_extp:
2817     return LowerDSPIntr(Op, DAG, MipsISD::EXTP, true, false);
2818   case Intrinsic::mips_extpdp:
2819     return LowerDSPIntr(Op, DAG, MipsISD::EXTPDP, true, false);
2820   case Intrinsic::mips_extr_w:
2821     return LowerDSPIntr(Op, DAG, MipsISD::EXTR_W, true, false);
2822   case Intrinsic::mips_extr_r_w:
2823     return LowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W, true, false);
2824   case Intrinsic::mips_extr_rs_w:
2825     return LowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W, true, false);
2826   case Intrinsic::mips_extr_s_h:
2827     return LowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H, true, false);
2828   case Intrinsic::mips_mthlip:
2829     return LowerDSPIntr(Op, DAG, MipsISD::MTHLIP, true, true);
2830   case Intrinsic::mips_mulsaq_s_w_ph:
2831     return LowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH, true, true);
2832   case Intrinsic::mips_maq_s_w_phl:
2833     return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL, true, true);
2834   case Intrinsic::mips_maq_s_w_phr:
2835     return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR, true, true);
2836   case Intrinsic::mips_maq_sa_w_phl:
2837     return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL, true, true);
2838   case Intrinsic::mips_maq_sa_w_phr:
2839     return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR, true, true);
2840   case Intrinsic::mips_dpaq_s_w_ph:
2841     return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH, true, true);
2842   case Intrinsic::mips_dpsq_s_w_ph:
2843     return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH, true, true);
2844   case Intrinsic::mips_dpaq_sa_l_w:
2845     return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W, true, true);
2846   case Intrinsic::mips_dpsq_sa_l_w:
2847     return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W, true, true);
2848   case Intrinsic::mips_dpaqx_s_w_ph:
2849     return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH, true, true);
2850   case Intrinsic::mips_dpaqx_sa_w_ph:
2851     return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH, true, true);
2852   case Intrinsic::mips_dpsqx_s_w_ph:
2853     return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH, true, true);
2854   case Intrinsic::mips_dpsqx_sa_w_ph:
2855     return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH, true, true);
2856   }
2857 }
2858
2859 SDValue MipsTargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
2860   if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2861       || cast<ConstantSDNode>
2862         (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2863       || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2864     return SDValue();
2865
2866   // The pattern
2867   //   (add (frameaddr 0), (frame_to_args_offset))
2868   // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2869   //   (add FrameObject, 0)
2870   // where FrameObject is a fixed StackObject with offset 0 which points to
2871   // the old stack pointer.
2872   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2873   EVT ValTy = Op->getValueType(0);
2874   int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2875   SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2876   return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2877                      DAG.getConstant(0, ValTy));
2878 }
2879
2880 //===----------------------------------------------------------------------===//
2881 //                      Calling Convention Implementation
2882 //===----------------------------------------------------------------------===//
2883
2884 //===----------------------------------------------------------------------===//
2885 // TODO: Implement a generic logic using tblgen that can support this.
2886 // Mips O32 ABI rules:
2887 // ---
2888 // i32 - Passed in A0, A1, A2, A3 and stack
2889 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2890 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
2891 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2892 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2893 //       not used, it must be shadowed. If only A3 is avaiable, shadow it and
2894 //       go to stack.
2895 //
2896 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2897 //===----------------------------------------------------------------------===//
2898
2899 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2900                        MVT LocVT, CCValAssign::LocInfo LocInfo,
2901                        ISD::ArgFlagsTy ArgFlags, CCState &State) {
2902
2903   static const unsigned IntRegsSize=4, FloatRegsSize=2;
2904
2905   static const uint16_t IntRegs[] = {
2906       Mips::A0, Mips::A1, Mips::A2, Mips::A3
2907   };
2908   static const uint16_t F32Regs[] = {
2909       Mips::F12, Mips::F14
2910   };
2911   static const uint16_t F64Regs[] = {
2912       Mips::D6, Mips::D7
2913   };
2914
2915   // Do not process byval args here.
2916   if (ArgFlags.isByVal())
2917     return true;
2918
2919   // Promote i8 and i16
2920   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2921     LocVT = MVT::i32;
2922     if (ArgFlags.isSExt())
2923       LocInfo = CCValAssign::SExt;
2924     else if (ArgFlags.isZExt())
2925       LocInfo = CCValAssign::ZExt;
2926     else
2927       LocInfo = CCValAssign::AExt;
2928   }
2929
2930   unsigned Reg;
2931
2932   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2933   // is true: function is vararg, argument is 3rd or higher, there is previous
2934   // argument which is not f32 or f64.
2935   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2936       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2937   unsigned OrigAlign = ArgFlags.getOrigAlign();
2938   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2939
2940   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2941     Reg = State.AllocateReg(IntRegs, IntRegsSize);
2942     // If this is the first part of an i64 arg,
2943     // the allocated register must be either A0 or A2.
2944     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2945       Reg = State.AllocateReg(IntRegs, IntRegsSize);
2946     LocVT = MVT::i32;
2947   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2948     // Allocate int register and shadow next int register. If first
2949     // available register is Mips::A1 or Mips::A3, shadow it too.
2950     Reg = State.AllocateReg(IntRegs, IntRegsSize);
2951     if (Reg == Mips::A1 || Reg == Mips::A3)
2952       Reg = State.AllocateReg(IntRegs, IntRegsSize);
2953     State.AllocateReg(IntRegs, IntRegsSize);
2954     LocVT = MVT::i32;
2955   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2956     // we are guaranteed to find an available float register
2957     if (ValVT == MVT::f32) {
2958       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2959       // Shadow int register
2960       State.AllocateReg(IntRegs, IntRegsSize);
2961     } else {
2962       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2963       // Shadow int registers
2964       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2965       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2966         State.AllocateReg(IntRegs, IntRegsSize);
2967       State.AllocateReg(IntRegs, IntRegsSize);
2968     }
2969   } else
2970     llvm_unreachable("Cannot handle this ValVT.");
2971
2972   if (!Reg) {
2973     unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2974                                           OrigAlign);
2975     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2976   } else
2977     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2978
2979   return false;
2980 }
2981
2982 #include "MipsGenCallingConv.inc"
2983
2984 //===----------------------------------------------------------------------===//
2985 //                  Call Calling Convention Implementation
2986 //===----------------------------------------------------------------------===//
2987
2988 static const unsigned O32IntRegsSize = 4;
2989
2990 // Return next O32 integer argument register.
2991 static unsigned getNextIntArgReg(unsigned Reg) {
2992   assert((Reg == Mips::A0) || (Reg == Mips::A2));
2993   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2994 }
2995
2996 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2997 /// for tail call optimization.
2998 bool MipsTargetLowering::
2999 IsEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
3000                                   unsigned NextStackOffset,
3001                                   const MipsFunctionInfo& FI) const {
3002   if (!EnableMipsTailCalls)
3003     return false;
3004
3005   // No tail call optimization for mips16.
3006   if (Subtarget->inMips16Mode())
3007     return false;
3008
3009   // Return false if either the callee or caller has a byval argument.
3010   if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
3011     return false;
3012
3013   // Return true if the callee's argument area is no larger than the
3014   // caller's.
3015   return NextStackOffset <= FI.getIncomingArgSize();
3016 }
3017
3018 SDValue
3019 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
3020                                    SDValue Chain, SDValue Arg, DebugLoc DL,
3021                                    bool IsTailCall, SelectionDAG &DAG) const {
3022   if (!IsTailCall) {
3023     SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
3024                                  DAG.getIntPtrConstant(Offset));
3025     return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
3026                         false, 0);
3027   }
3028
3029   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3030   int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
3031   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3032   return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
3033                       /*isVolatile=*/ true, false, 0);
3034 }
3035
3036 //
3037 // The Mips16 hard float is a crazy quilt inherited from gcc. I have a much
3038 // cleaner way to do all of this but it will have to wait until the traditional
3039 // gcc mechanism is completed.
3040 //
3041 // For Pic, in order for Mips16 code to call Mips32 code which according the abi
3042 // have either arguments or returned values placed in floating point registers,
3043 // we use a set of helper functions. (This includes functions which return type
3044 //  complex which on Mips are returned in a pair of floating point registers).
3045 //
3046 // This is an encoding that we inherited from gcc.
3047 // In Mips traditional O32, N32 ABI, floating point numbers are passed in
3048 // floating point argument registers 1,2 only when the first and optionally
3049 // the second arguments are float (sf) or double (df).
3050 // For Mips16 we are only concerned with the situations where floating point
3051 // arguments are being passed in floating point registers by the ABI, because
3052 // Mips16 mode code cannot execute floating point instructions to load those
3053 // values and hence helper functions are needed.
3054 // The possibilities are (), (sf), (sf, sf), (sf, df), (df), (df, sf), (df, df)
3055 // the helper function suffixs for these are:
3056 //                        0,  1,    5,        9,         2,   6,        10
3057 // this suffix can then be calculated as follows:
3058 // for a given argument Arg:
3059 //     Arg1x, Arg2x = 1 :  Arg is sf
3060 //                    2 :  Arg is df
3061 //                    0:   Arg is neither sf or df
3062 // So this stub is the string for number Arg1x + Arg2x*4.
3063 // However not all numbers between 0 and 10 are possible, we check anyway and
3064 // assert if the impossible exists.
3065 //
3066
3067 unsigned int MipsTargetLowering::getMips16HelperFunctionStubNumber
3068   (ArgListTy &Args) const {
3069   unsigned int resultNum = 0;
3070   if (Args.size() >= 1) {
3071     Type *t = Args[0].Ty;
3072     if (t->isFloatTy()) {
3073       resultNum = 1;
3074     }
3075     else if (t->isDoubleTy()) {
3076       resultNum = 2;
3077     }
3078   }
3079   if (resultNum) {
3080     if (Args.size() >=2) {
3081       Type *t = Args[1].Ty;
3082       if (t->isFloatTy()) {
3083         resultNum += 4;
3084       }
3085       else if (t->isDoubleTy()) {
3086         resultNum += 8;
3087       }
3088     }
3089   }
3090   return resultNum;
3091 }
3092
3093 //
3094 // prefixs are attached to stub numbers depending on the return type .
3095 // return type: float  sf_
3096 //              double df_
3097 //              single complex sc_
3098 //              double complext dc_
3099 //              others  NO PREFIX
3100 //
3101 //
3102 // The full name of a helper function is__mips16_call_stub +
3103 //    return type dependent prefix + stub number
3104 //
3105 //
3106 // This is something that probably should be in a different source file and
3107 // perhaps done differently but my main purpose is to not waste runtime
3108 // on something that we can enumerate in the source. Another possibility is
3109 // to have a python script to generate these mapping tables. This will do
3110 // for now. There are a whole series of helper function mapping arrays, one
3111 // for each return type class as outlined above. There there are 11 possible
3112 //  entries. Ones with 0 are ones which should never be selected
3113 //
3114 // All the arrays are similar except for ones which return neither
3115 // sf, df, sc, dc, in which only care about ones which have sf or df as a
3116 // first parameter.
3117 //
3118 #define P_ "__mips16_call_stub_"
3119 #define MAX_STUB_NUMBER 10
3120 #define T1 P "1", P "2", 0, 0, P "5", P "6", 0, 0, P "9", P "10"
3121 #define T P "0" , T1
3122 #define P P_
3123 static char const * vMips16Helper[MAX_STUB_NUMBER+1] =
3124   {0, T1 };
3125 #undef P
3126 #define P P_ "sf_"
3127 static char const * sfMips16Helper[MAX_STUB_NUMBER+1] =
3128   { T };
3129 #undef P
3130 #define P P_ "df_"
3131 static char const * dfMips16Helper[MAX_STUB_NUMBER+1] =
3132   { T };
3133 #undef P
3134 #define P P_ "sc_"
3135 static char const * scMips16Helper[MAX_STUB_NUMBER+1] =
3136   { T };
3137 #undef P
3138 #define P P_ "dc_"
3139 static char const * dcMips16Helper[MAX_STUB_NUMBER+1] =
3140   { T };
3141 #undef P
3142 #undef P_
3143
3144
3145 const char* MipsTargetLowering::
3146   getMips16HelperFunction
3147     (Type* RetTy, ArgListTy &Args, bool &needHelper) const {
3148   const unsigned int stubNum = getMips16HelperFunctionStubNumber(Args);
3149 #ifndef NDEBUG
3150   const unsigned int maxStubNum = 10;
3151   assert(stubNum <= maxStubNum);
3152   const bool validStubNum[maxStubNum+1] =
3153     {true, true, true, false, false, true, true, false, false, true, true};
3154   assert(validStubNum[stubNum]);
3155 #endif
3156   const char *result;
3157   if (RetTy->isFloatTy()) {
3158     result = sfMips16Helper[stubNum];
3159   }
3160   else if (RetTy ->isDoubleTy()) {
3161     result = dfMips16Helper[stubNum];
3162   }
3163   else if (RetTy->isStructTy()) {
3164     // check if it's complex
3165     if (RetTy->getNumContainedTypes() == 2) {
3166       if ((RetTy->getContainedType(0)->isFloatTy()) &&
3167           (RetTy->getContainedType(1)->isFloatTy())) {
3168         result = scMips16Helper[stubNum];
3169       }
3170       else if ((RetTy->getContainedType(0)->isDoubleTy()) &&
3171                (RetTy->getContainedType(1)->isDoubleTy())) {
3172         result = dcMips16Helper[stubNum];
3173       }
3174       else {
3175         llvm_unreachable("Uncovered condition");
3176       }
3177     }
3178     else {
3179       llvm_unreachable("Uncovered condition");
3180     }
3181   }
3182   else {
3183     if (stubNum == 0) {
3184       needHelper = false;
3185       return "";
3186     }
3187     result = vMips16Helper[stubNum];
3188   }
3189   needHelper = true;
3190   return result;
3191 }
3192
3193 /// LowerCall - functions arguments are copied from virtual regs to
3194 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3195 SDValue
3196 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3197                               SmallVectorImpl<SDValue> &InVals) const {
3198   SelectionDAG &DAG                     = CLI.DAG;
3199   DebugLoc &dl                          = CLI.DL;
3200   SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3201   SmallVector<SDValue, 32> &OutVals     = CLI.OutVals;
3202   SmallVector<ISD::InputArg, 32> &Ins   = CLI.Ins;
3203   SDValue Chain                         = CLI.Chain;
3204   SDValue Callee                        = CLI.Callee;
3205   bool &isTailCall                      = CLI.IsTailCall;
3206   CallingConv::ID CallConv              = CLI.CallConv;
3207   bool isVarArg                         = CLI.IsVarArg;
3208
3209   const char* mips16HelperFunction = 0;
3210   bool needMips16Helper = false;
3211
3212   if (Subtarget->inMips16Mode() && getTargetMachine().Options.UseSoftFloat &&
3213       Mips16HardFloat) {
3214     //
3215     // currently we don't have symbols tagged with the mips16 or mips32
3216     // qualifier so we will assume that we don't know what kind it is.
3217     // and generate the helper
3218     //
3219     bool lookupHelper = true;
3220     if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3221       if (noHelperNeeded.find(S->getSymbol()) != noHelperNeeded.end()) {
3222         lookupHelper = false;
3223       }
3224     }
3225     if (lookupHelper) mips16HelperFunction =
3226       getMips16HelperFunction(CLI.RetTy, CLI.Args, needMips16Helper);
3227
3228   }
3229   MachineFunction &MF = DAG.getMachineFunction();
3230   MachineFrameInfo *MFI = MF.getFrameInfo();
3231   const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
3232   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
3233
3234   // Analyze operands of the call, assigning locations to each operand.
3235   SmallVector<CCValAssign, 16> ArgLocs;
3236   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3237                  getTargetMachine(), ArgLocs, *DAG.getContext());
3238   MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
3239
3240   MipsCCInfo.analyzeCallOperands(Outs, isVarArg);
3241
3242   // Get a count of how many bytes are to be pushed on the stack.
3243   unsigned NextStackOffset = CCInfo.getNextStackOffset();
3244
3245   // Check if it's really possible to do a tail call.
3246   if (isTailCall)
3247     isTailCall =
3248       IsEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
3249                                         *MF.getInfo<MipsFunctionInfo>());
3250
3251   if (isTailCall)
3252     ++NumTailCalls;
3253
3254   // Chain is the output chain of the last Load/Store or CopyToReg node.
3255   // ByValChain is the output chain of the last Memcpy node created for copying
3256   // byval arguments to the stack.
3257   unsigned StackAlignment = TFL->getStackAlignment();
3258   NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
3259   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
3260
3261   if (!isTailCall)
3262     Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
3263
3264   SDValue StackPtr = DAG.getCopyFromReg(Chain, dl,
3265                                         IsN64 ? Mips::SP_64 : Mips::SP,
3266                                         getPointerTy());
3267
3268   // With EABI is it possible to have 16 args on registers.
3269   std::deque< std::pair<unsigned, SDValue> > RegsToPass;
3270   SmallVector<SDValue, 8> MemOpChains;
3271   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3272
3273   // Walk the register/memloc assignments, inserting copies/loads.
3274   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3275     SDValue Arg = OutVals[i];
3276     CCValAssign &VA = ArgLocs[i];
3277     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3278     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3279
3280     // ByVal Arg.
3281     if (Flags.isByVal()) {
3282       assert(Flags.getByValSize() &&
3283              "ByVal args of size 0 should have been ignored by front-end.");
3284       assert(ByValArg != MipsCCInfo.byval_end());
3285       assert(!isTailCall &&
3286              "Do not tail-call optimize if there is a byval argument.");
3287       passByValArg(Chain, dl, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3288                    MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
3289       ++ByValArg;
3290       continue;
3291     }
3292
3293     // Promote the value if needed.
3294     switch (VA.getLocInfo()) {
3295     default: llvm_unreachable("Unknown loc info!");
3296     case CCValAssign::Full:
3297       if (VA.isRegLoc()) {
3298         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3299             (ValVT == MVT::f64 && LocVT == MVT::i64))
3300           Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
3301         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3302           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3303                                    Arg, DAG.getConstant(0, MVT::i32));
3304           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3305                                    Arg, DAG.getConstant(1, MVT::i32));
3306           if (!Subtarget->isLittle())
3307             std::swap(Lo, Hi);
3308           unsigned LocRegLo = VA.getLocReg();
3309           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3310           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3311           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3312           continue;
3313         }
3314       }
3315       break;
3316     case CCValAssign::SExt:
3317       Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
3318       break;
3319     case CCValAssign::ZExt:
3320       Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
3321       break;
3322     case CCValAssign::AExt:
3323       Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
3324       break;
3325     }
3326
3327     // Arguments that can be passed on register must be kept at
3328     // RegsToPass vector
3329     if (VA.isRegLoc()) {
3330       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3331       continue;
3332     }
3333
3334     // Register can't get to this point...
3335     assert(VA.isMemLoc());
3336
3337     // emit ISD::STORE whichs stores the
3338     // parameter value to a stack Location
3339     MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3340                                          Chain, Arg, dl, isTailCall, DAG));
3341   }
3342
3343   // Transform all store nodes into one single node because all store
3344   // nodes are independent of each other.
3345   if (!MemOpChains.empty())
3346     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3347                         &MemOpChains[0], MemOpChains.size());
3348
3349   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3350   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3351   // node so that legalize doesn't hack it.
3352   bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
3353   bool GlobalOrExternal = false, InternalLinkage = false;
3354   SDValue CalleeLo;
3355
3356   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3357     if (IsPICCall) {
3358       InternalLinkage = G->getGlobal()->hasInternalLinkage();
3359
3360       if (InternalLinkage)
3361         Callee = getAddrLocal(Callee, DAG, HasMips64);
3362       else if (LargeGOT)
3363         Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3364                                        MipsII::MO_CALL_LO16);
3365       else
3366         Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3367     } else
3368       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
3369                                           MipsII::MO_NO_FLAG);
3370     GlobalOrExternal = true;
3371   }
3372   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3373     if (!IsN64 && !IsPIC) // !N64 && static
3374       Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3375                                             MipsII::MO_NO_FLAG);
3376     else if (LargeGOT)
3377       Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3378                                      MipsII::MO_CALL_LO16);
3379     else // N64 || PIC
3380       Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3381
3382     GlobalOrExternal = true;
3383   }
3384
3385   SDValue JumpTarget = Callee;
3386
3387   // T9 should contain the address of the callee function if
3388   // -reloction-model=pic or it is an indirect call.
3389   if (IsPICCall || !GlobalOrExternal) {
3390     unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
3391     unsigned V0Reg = Mips::V0;
3392     if (needMips16Helper) {
3393       RegsToPass.push_front(std::make_pair(V0Reg, Callee));
3394       JumpTarget = DAG.getExternalSymbol(
3395         mips16HelperFunction, getPointerTy());
3396       JumpTarget = getAddrGlobal(JumpTarget, DAG, MipsII::MO_GOT);
3397     }
3398     else {
3399       RegsToPass.push_front(std::make_pair(T9Reg, Callee));
3400
3401       if (!Subtarget->inMips16Mode())
3402         JumpTarget = SDValue();
3403     }
3404   }
3405
3406   // Insert node "GP copy globalreg" before call to function.
3407   //
3408   // R_MIPS_CALL* operators (emitted when non-internal functions are called
3409   // in PIC mode) allow symbols to be resolved via lazy binding.
3410   // The lazy binding stub requires GP to point to the GOT.
3411   if (IsPICCall && !InternalLinkage) {
3412     unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
3413     EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
3414     RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
3415   }
3416
3417   // Build a sequence of copy-to-reg nodes chained together with token
3418   // chain and flag operands which copy the outgoing args into registers.
3419   // The InFlag in necessary since all emitted instructions must be
3420   // stuck together.
3421   SDValue InFlag;
3422
3423   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3424     Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3425                              RegsToPass[i].second, InFlag);
3426     InFlag = Chain.getValue(1);
3427   }
3428
3429   // MipsJmpLink = #chain, #target_address, #opt_in_flags...
3430   //             = Chain, Callee, Reg#1, Reg#2, ...
3431   //
3432   // Returns a chain & a flag for retval copy to use.
3433   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3434   SmallVector<SDValue, 8> Ops(1, Chain);
3435
3436   if (JumpTarget.getNode())
3437     Ops.push_back(JumpTarget);
3438
3439   // Add argument registers to the end of the list so that they are
3440   // known live into the call.
3441   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3442     Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3443                                   RegsToPass[i].second.getValueType()));
3444
3445   // Add a register mask operand representing the call-preserved registers.
3446   const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3447   const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3448   assert(Mask && "Missing call preserved mask for calling convention");
3449   Ops.push_back(DAG.getRegisterMask(Mask));
3450
3451   if (InFlag.getNode())
3452     Ops.push_back(InFlag);
3453
3454   if (isTailCall)
3455     return DAG.getNode(MipsISD::TailCall, dl, MVT::Other, &Ops[0], Ops.size());
3456
3457   Chain  = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
3458   InFlag = Chain.getValue(1);
3459
3460   // Create the CALLSEQ_END node.
3461   Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3462                              DAG.getIntPtrConstant(0, true), InFlag);
3463   InFlag = Chain.getValue(1);
3464
3465   // Handle result values, copying them out of physregs into vregs that we
3466   // return.
3467   return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3468                          Ins, dl, DAG, InVals);
3469 }
3470
3471 /// LowerCallResult - Lower the result values of a call into the
3472 /// appropriate copies out of appropriate physical registers.
3473 SDValue
3474 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3475                                     CallingConv::ID CallConv, bool isVarArg,
3476                                     const SmallVectorImpl<ISD::InputArg> &Ins,
3477                                     DebugLoc dl, SelectionDAG &DAG,
3478                                     SmallVectorImpl<SDValue> &InVals) const {
3479   // Assign locations to each value returned by this call.
3480   SmallVector<CCValAssign, 16> RVLocs;
3481   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3482                  getTargetMachine(), RVLocs, *DAG.getContext());
3483
3484   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3485
3486   // Copy all of the result registers out of their specified physreg.
3487   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3488     Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
3489                                RVLocs[i].getValVT(), InFlag).getValue(1);
3490     InFlag = Chain.getValue(2);
3491     InVals.push_back(Chain.getValue(0));
3492   }
3493
3494   return Chain;
3495 }
3496
3497 //===----------------------------------------------------------------------===//
3498 //             Formal Arguments Calling Convention Implementation
3499 //===----------------------------------------------------------------------===//
3500 /// LowerFormalArguments - transform physical registers into virtual registers
3501 /// and generate load operations for arguments places on the stack.
3502 SDValue
3503 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3504                                          CallingConv::ID CallConv,
3505                                          bool isVarArg,
3506                                       const SmallVectorImpl<ISD::InputArg> &Ins,
3507                                          DebugLoc dl, SelectionDAG &DAG,
3508                                          SmallVectorImpl<SDValue> &InVals)
3509                                           const {
3510   MachineFunction &MF = DAG.getMachineFunction();
3511   MachineFrameInfo *MFI = MF.getFrameInfo();
3512   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3513
3514   MipsFI->setVarArgsFrameIndex(0);
3515
3516   // Used with vargs to acumulate store chains.
3517   std::vector<SDValue> OutChains;
3518
3519   // Assign locations to all of the incoming arguments.
3520   SmallVector<CCValAssign, 16> ArgLocs;
3521   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3522                  getTargetMachine(), ArgLocs, *DAG.getContext());
3523   MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
3524
3525   MipsCCInfo.analyzeFormalArguments(Ins);
3526   MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3527                            MipsCCInfo.hasByValArg());
3528
3529   Function::const_arg_iterator FuncArg =
3530     DAG.getMachineFunction().getFunction()->arg_begin();
3531   unsigned CurArgIdx = 0;
3532   MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3533
3534   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3535     CCValAssign &VA = ArgLocs[i];
3536     std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
3537     CurArgIdx = Ins[i].OrigArgIndex;
3538     EVT ValVT = VA.getValVT();
3539     ISD::ArgFlagsTy Flags = Ins[i].Flags;
3540     bool IsRegLoc = VA.isRegLoc();
3541
3542     if (Flags.isByVal()) {
3543       assert(Flags.getByValSize() &&
3544              "ByVal args of size 0 should have been ignored by front-end.");
3545       assert(ByValArg != MipsCCInfo.byval_end());
3546       copyByValRegs(Chain, dl, OutChains, DAG, Flags, InVals, &*FuncArg,
3547                     MipsCCInfo, *ByValArg);
3548       ++ByValArg;
3549       continue;
3550     }
3551
3552     // Arguments stored on registers
3553     if (IsRegLoc) {
3554       EVT RegVT = VA.getLocVT();
3555       unsigned ArgReg = VA.getLocReg();
3556       const TargetRegisterClass *RC;
3557
3558       if (RegVT == MVT::i32)
3559         RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
3560                                         &Mips::CPURegsRegClass;
3561       else if (RegVT == MVT::i64)
3562         RC = &Mips::CPU64RegsRegClass;
3563       else if (RegVT == MVT::f32)
3564         RC = &Mips::FGR32RegClass;
3565       else if (RegVT == MVT::f64)
3566         RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3567       else
3568         llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3569
3570       // Transform the arguments stored on
3571       // physical registers into virtual ones
3572       unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3573       SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3574
3575       // If this is an 8 or 16-bit value, it has been passed promoted
3576       // to 32 bits.  Insert an assert[sz]ext to capture this, then
3577       // truncate to the right size.
3578       if (VA.getLocInfo() != CCValAssign::Full) {
3579         unsigned Opcode = 0;
3580         if (VA.getLocInfo() == CCValAssign::SExt)
3581           Opcode = ISD::AssertSext;
3582         else if (VA.getLocInfo() == CCValAssign::ZExt)
3583           Opcode = ISD::AssertZext;
3584         if (Opcode)
3585           ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3586                                  DAG.getValueType(ValVT));
3587         ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3588       }
3589
3590       // Handle floating point arguments passed in integer registers.
3591       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3592           (RegVT == MVT::i64 && ValVT == MVT::f64))
3593         ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3594       else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3595         unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3596                                   getNextIntArgReg(ArgReg), RC);
3597         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3598         if (!Subtarget->isLittle())
3599           std::swap(ArgValue, ArgValue2);
3600         ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3601                                ArgValue, ArgValue2);
3602       }
3603
3604       InVals.push_back(ArgValue);
3605     } else { // VA.isRegLoc()
3606
3607       // sanity check
3608       assert(VA.isMemLoc());
3609
3610       // The stack pointer offset is relative to the caller stack frame.
3611       int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3612                                       VA.getLocMemOffset(), true);
3613
3614       // Create load nodes to retrieve arguments from the stack
3615       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3616       InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3617                                    MachinePointerInfo::getFixedStack(FI),
3618                                    false, false, false, 0));
3619     }
3620   }
3621
3622   // The mips ABIs for returning structs by value requires that we copy
3623   // the sret argument into $v0 for the return. Save the argument into
3624   // a virtual register so that we can access it from the return points.
3625   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3626     unsigned Reg = MipsFI->getSRetReturnReg();
3627     if (!Reg) {
3628       Reg = MF.getRegInfo().
3629         createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
3630       MipsFI->setSRetReturnReg(Reg);
3631     }
3632     SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3633     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3634   }
3635
3636   if (isVarArg)
3637     writeVarArgRegs(OutChains, MipsCCInfo, Chain, dl, DAG);
3638
3639   // All stores are grouped in one node to allow the matching between
3640   // the size of Ins and InVals. This only happens when on varg functions
3641   if (!OutChains.empty()) {
3642     OutChains.push_back(Chain);
3643     Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3644                         &OutChains[0], OutChains.size());
3645   }
3646
3647   return Chain;
3648 }
3649
3650 //===----------------------------------------------------------------------===//
3651 //               Return Value Calling Convention Implementation
3652 //===----------------------------------------------------------------------===//
3653
3654 bool
3655 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3656                                    MachineFunction &MF, bool isVarArg,
3657                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3658                                    LLVMContext &Context) const {
3659   SmallVector<CCValAssign, 16> RVLocs;
3660   CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
3661                  RVLocs, Context);
3662   return CCInfo.CheckReturn(Outs, RetCC_Mips);
3663 }
3664
3665 SDValue
3666 MipsTargetLowering::LowerReturn(SDValue Chain,
3667                                 CallingConv::ID CallConv, bool isVarArg,
3668                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
3669                                 const SmallVectorImpl<SDValue> &OutVals,
3670                                 DebugLoc dl, SelectionDAG &DAG) const {
3671
3672   // CCValAssign - represent the assignment of
3673   // the return value to a location
3674   SmallVector<CCValAssign, 16> RVLocs;
3675
3676   // CCState - Info about the registers and stack slot.
3677   CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3678                  getTargetMachine(), RVLocs, *DAG.getContext());
3679
3680   // Analize return values.
3681   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3682
3683   SDValue Flag;
3684   SmallVector<SDValue, 4> RetOps(1, Chain);
3685
3686   // Copy the result values into the output registers.
3687   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3688     CCValAssign &VA = RVLocs[i];
3689     assert(VA.isRegLoc() && "Can only return in registers!");
3690
3691     Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3692
3693     // Guarantee that all emitted copies are stuck together with flags.
3694     Flag = Chain.getValue(1);
3695     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3696   }
3697
3698   // The mips ABIs for returning structs by value requires that we copy
3699   // the sret argument into $v0 for the return. We saved the argument into
3700   // a virtual register in the entry block, so now we copy the value out
3701   // and into $v0.
3702   if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3703     MachineFunction &MF      = DAG.getMachineFunction();
3704     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3705     unsigned Reg = MipsFI->getSRetReturnReg();
3706
3707     if (!Reg)
3708       llvm_unreachable("sret virtual register not created in the entry block");
3709     SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3710     unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
3711
3712     Chain = DAG.getCopyToReg(Chain, dl, V0, Val, Flag);
3713     Flag = Chain.getValue(1);
3714     RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3715   }
3716
3717   RetOps[0] = Chain;  // Update chain.
3718
3719   // Add the flag if we have it.
3720   if (Flag.getNode())
3721     RetOps.push_back(Flag);
3722
3723   // Return on Mips is always a "jr $ra"
3724   return DAG.getNode(MipsISD::Ret, dl, MVT::Other, &RetOps[0], RetOps.size());
3725 }
3726
3727 //===----------------------------------------------------------------------===//
3728 //                           Mips Inline Assembly Support
3729 //===----------------------------------------------------------------------===//
3730
3731 /// getConstraintType - Given a constraint letter, return the type of
3732 /// constraint it is for this target.
3733 MipsTargetLowering::ConstraintType MipsTargetLowering::
3734 getConstraintType(const std::string &Constraint) const
3735 {
3736   // Mips specific constrainy
3737   // GCC config/mips/constraints.md
3738   //
3739   // 'd' : An address register. Equivalent to r
3740   //       unless generating MIPS16 code.
3741   // 'y' : Equivalent to r; retained for
3742   //       backwards compatibility.
3743   // 'c' : A register suitable for use in an indirect
3744   //       jump. This will always be $25 for -mabicalls.
3745   // 'l' : The lo register. 1 word storage.
3746   // 'x' : The hilo register pair. Double word storage.
3747   if (Constraint.size() == 1) {
3748     switch (Constraint[0]) {
3749       default : break;
3750       case 'd':
3751       case 'y':
3752       case 'f':
3753       case 'c':
3754       case 'l':
3755       case 'x':
3756         return C_RegisterClass;
3757     }
3758   }
3759   return TargetLowering::getConstraintType(Constraint);
3760 }
3761
3762 /// Examine constraint type and operand type and determine a weight value.
3763 /// This object must already have been set up with the operand type
3764 /// and the current alternative constraint selected.
3765 TargetLowering::ConstraintWeight
3766 MipsTargetLowering::getSingleConstraintMatchWeight(
3767     AsmOperandInfo &info, const char *constraint) const {
3768   ConstraintWeight weight = CW_Invalid;
3769   Value *CallOperandVal = info.CallOperandVal;
3770     // If we don't have a value, we can't do a match,
3771     // but allow it at the lowest weight.
3772   if (CallOperandVal == NULL)
3773     return CW_Default;
3774   Type *type = CallOperandVal->getType();
3775   // Look at the constraint type.
3776   switch (*constraint) {
3777   default:
3778     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3779     break;
3780   case 'd':
3781   case 'y':
3782     if (type->isIntegerTy())
3783       weight = CW_Register;
3784     break;
3785   case 'f':
3786     if (type->isFloatTy())
3787       weight = CW_Register;
3788     break;
3789   case 'c': // $25 for indirect jumps
3790   case 'l': // lo register
3791   case 'x': // hilo register pair
3792       if (type->isIntegerTy())
3793       weight = CW_SpecificReg;
3794       break;
3795   case 'I': // signed 16 bit immediate
3796   case 'J': // integer zero
3797   case 'K': // unsigned 16 bit immediate
3798   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3799   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3800   case 'O': // signed 15 bit immediate (+- 16383)
3801   case 'P': // immediate in the range of 65535 to 1 (inclusive)
3802     if (isa<ConstantInt>(CallOperandVal))
3803       weight = CW_Constant;
3804     break;
3805   }
3806   return weight;
3807 }
3808
3809 /// Given a register class constraint, like 'r', if this corresponds directly
3810 /// to an LLVM register class, return a register of 0 and the register class
3811 /// pointer.
3812 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3813 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3814 {
3815   if (Constraint.size() == 1) {
3816     switch (Constraint[0]) {
3817     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3818     case 'y': // Same as 'r'. Exists for compatibility.
3819     case 'r':
3820       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3821         if (Subtarget->inMips16Mode())
3822           return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3823         return std::make_pair(0U, &Mips::CPURegsRegClass);
3824       }
3825       if (VT == MVT::i64 && !HasMips64)
3826         return std::make_pair(0U, &Mips::CPURegsRegClass);
3827       if (VT == MVT::i64 && HasMips64)
3828         return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3829       // This will generate an error message
3830       return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3831     case 'f':
3832       if (VT == MVT::f32)
3833         return std::make_pair(0U, &Mips::FGR32RegClass);
3834       if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3835         if (Subtarget->isFP64bit())
3836           return std::make_pair(0U, &Mips::FGR64RegClass);
3837         return std::make_pair(0U, &Mips::AFGR64RegClass);
3838       }
3839       break;
3840     case 'c': // register suitable for indirect jump
3841       if (VT == MVT::i32)
3842         return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3843       assert(VT == MVT::i64 && "Unexpected type.");
3844       return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3845     case 'l': // register suitable for indirect jump
3846       if (VT == MVT::i32)
3847         return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3848       return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3849     case 'x': // register suitable for indirect jump
3850       // Fixme: Not triggering the use of both hi and low
3851       // This will generate an error message
3852       return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3853     }
3854   }
3855   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3856 }
3857
3858 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3859 /// vector.  If it is invalid, don't add anything to Ops.
3860 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3861                                                      std::string &Constraint,
3862                                                      std::vector<SDValue>&Ops,
3863                                                      SelectionDAG &DAG) const {
3864   SDValue Result(0, 0);
3865
3866   // Only support length 1 constraints for now.
3867   if (Constraint.length() > 1) return;
3868
3869   char ConstraintLetter = Constraint[0];
3870   switch (ConstraintLetter) {
3871   default: break; // This will fall through to the generic implementation
3872   case 'I': // Signed 16 bit constant
3873     // If this fails, the parent routine will give an error
3874     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3875       EVT Type = Op.getValueType();
3876       int64_t Val = C->getSExtValue();
3877       if (isInt<16>(Val)) {
3878         Result = DAG.getTargetConstant(Val, Type);
3879         break;
3880       }
3881     }
3882     return;
3883   case 'J': // integer zero
3884     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3885       EVT Type = Op.getValueType();
3886       int64_t Val = C->getZExtValue();
3887       if (Val == 0) {
3888         Result = DAG.getTargetConstant(0, Type);
3889         break;
3890       }
3891     }
3892     return;
3893   case 'K': // unsigned 16 bit immediate
3894     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3895       EVT Type = Op.getValueType();
3896       uint64_t Val = (uint64_t)C->getZExtValue();
3897       if (isUInt<16>(Val)) {
3898         Result = DAG.getTargetConstant(Val, Type);
3899         break;
3900       }
3901     }
3902     return;
3903   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3904     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3905       EVT Type = Op.getValueType();
3906       int64_t Val = C->getSExtValue();
3907       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3908         Result = DAG.getTargetConstant(Val, Type);
3909         break;
3910       }
3911     }
3912     return;
3913   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3914     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3915       EVT Type = Op.getValueType();
3916       int64_t Val = C->getSExtValue();
3917       if ((Val >= -65535) && (Val <= -1)) {
3918         Result = DAG.getTargetConstant(Val, Type);
3919         break;
3920       }
3921     }
3922     return;
3923   case 'O': // signed 15 bit immediate
3924     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3925       EVT Type = Op.getValueType();
3926       int64_t Val = C->getSExtValue();
3927       if ((isInt<15>(Val))) {
3928         Result = DAG.getTargetConstant(Val, Type);
3929         break;
3930       }
3931     }
3932     return;
3933   case 'P': // immediate in the range of 1 to 65535 (inclusive)
3934     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3935       EVT Type = Op.getValueType();
3936       int64_t Val = C->getSExtValue();
3937       if ((Val <= 65535) && (Val >= 1)) {
3938         Result = DAG.getTargetConstant(Val, Type);
3939         break;
3940       }
3941     }
3942     return;
3943   }
3944
3945   if (Result.getNode()) {
3946     Ops.push_back(Result);
3947     return;
3948   }
3949
3950   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3951 }
3952
3953 bool
3954 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3955   // No global is ever allowed as a base.
3956   if (AM.BaseGV)
3957     return false;
3958
3959   switch (AM.Scale) {
3960   case 0: // "r+i" or just "i", depending on HasBaseReg.
3961     break;
3962   case 1:
3963     if (!AM.HasBaseReg) // allow "r+i".
3964       break;
3965     return false; // disallow "r+r" or "r+r+i".
3966   default:
3967     return false;
3968   }
3969
3970   return true;
3971 }
3972
3973 bool
3974 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3975   // The Mips target isn't yet aware of offsets.
3976   return false;
3977 }
3978
3979 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3980                                             unsigned SrcAlign,
3981                                             bool IsMemset, bool ZeroMemset,
3982                                             bool MemcpyStrSrc,
3983                                             MachineFunction &MF) const {
3984   if (Subtarget->hasMips64())
3985     return MVT::i64;
3986
3987   return MVT::i32;
3988 }
3989
3990 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3991   if (VT != MVT::f32 && VT != MVT::f64)
3992     return false;
3993   if (Imm.isNegZero())
3994     return false;
3995   return Imm.isZero();
3996 }
3997
3998 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3999   if (IsN64)
4000     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
4001
4002   return TargetLowering::getJumpTableEncoding();
4003 }
4004
4005 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CC, bool IsO32_,
4006                                    CCState &Info)
4007   : CCInfo(Info), CallConv(CC), IsO32(IsO32_) {
4008   // Pre-allocate reserved argument area.
4009   CCInfo.AllocateStack(reservedArgArea(), 1);
4010 }
4011
4012 void MipsTargetLowering::MipsCC::
4013 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
4014                     bool IsVarArg) {
4015   assert((CallConv != CallingConv::Fast || !IsVarArg) &&
4016          "CallingConv::Fast shouldn't be used for vararg functions.");
4017
4018   unsigned NumOpnds = Args.size();
4019   llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
4020
4021   for (unsigned I = 0; I != NumOpnds; ++I) {
4022     MVT ArgVT = Args[I].VT;
4023     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
4024     bool R;
4025
4026     if (ArgFlags.isByVal()) {
4027       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
4028       continue;
4029     }
4030
4031     if (IsVarArg && !Args[I].IsFixed)
4032       R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4033     else
4034       R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4035
4036     if (R) {
4037 #ifndef NDEBUG
4038       dbgs() << "Call operand #" << I << " has unhandled type "
4039              << EVT(ArgVT).getEVTString();
4040 #endif
4041       llvm_unreachable(0);
4042     }
4043   }
4044 }
4045
4046 void MipsTargetLowering::MipsCC::
4047 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args) {
4048   unsigned NumArgs = Args.size();
4049   llvm::CCAssignFn *FixedFn = fixedArgFn();
4050
4051   for (unsigned I = 0; I != NumArgs; ++I) {
4052     MVT ArgVT = Args[I].VT;
4053     ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
4054
4055     if (ArgFlags.isByVal()) {
4056       handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
4057       continue;
4058     }
4059
4060     if (!FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo))
4061       continue;
4062
4063 #ifndef NDEBUG
4064     dbgs() << "Formal Arg #" << I << " has unhandled type "
4065            << EVT(ArgVT).getEVTString();
4066 #endif
4067     llvm_unreachable(0);
4068   }
4069 }
4070
4071 void
4072 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
4073                                            MVT LocVT,
4074                                            CCValAssign::LocInfo LocInfo,
4075                                            ISD::ArgFlagsTy ArgFlags) {
4076   assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
4077
4078   struct ByValArgInfo ByVal;
4079   unsigned RegSize = regSize();
4080   unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
4081   unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
4082                             RegSize * 2);
4083
4084   if (useRegsForByval())
4085     allocateRegs(ByVal, ByValSize, Align);
4086
4087   // Allocate space on caller's stack.
4088   ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
4089                                        Align);
4090   CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
4091                                     LocInfo));
4092   ByValArgs.push_back(ByVal);
4093 }
4094
4095 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
4096   return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
4097 }
4098
4099 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
4100   return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
4101 }
4102
4103 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
4104   return IsO32 ? O32IntRegs : Mips64IntRegs;
4105 }
4106
4107 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
4108   if (CallConv == CallingConv::Fast)
4109     return CC_Mips_FastCC;
4110
4111   return IsO32 ? CC_MipsO32 : CC_MipsN;
4112 }
4113
4114 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
4115   return IsO32 ? CC_MipsO32 : CC_MipsN_VarArg;
4116 }
4117
4118 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
4119   return IsO32 ? O32IntRegs : Mips64DPRegs;
4120 }
4121
4122 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
4123                                               unsigned ByValSize,
4124                                               unsigned Align) {
4125   unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
4126   const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
4127   assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
4128          "Byval argument's size and alignment should be a multiple of"
4129          "RegSize.");
4130
4131   ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
4132
4133   // If Align > RegSize, the first arg register must be even.
4134   if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
4135     CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
4136     ++ByVal.FirstIdx;
4137   }
4138
4139   // Mark the registers allocated.
4140   for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
4141        ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
4142     CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4143 }
4144
4145 void MipsTargetLowering::
4146 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
4147               SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4148               SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4149               const MipsCC &CC, const ByValArgInfo &ByVal) const {
4150   MachineFunction &MF = DAG.getMachineFunction();
4151   MachineFrameInfo *MFI = MF.getFrameInfo();
4152   unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
4153   unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4154   int FrameObjOffset;
4155
4156   if (RegAreaSize)
4157     FrameObjOffset = (int)CC.reservedArgArea() -
4158       (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
4159   else
4160     FrameObjOffset = ByVal.Address;
4161
4162   // Create frame object.
4163   EVT PtrTy = getPointerTy();
4164   int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
4165   SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4166   InVals.push_back(FIN);
4167
4168   if (!ByVal.NumRegs)
4169     return;
4170
4171   // Copy arg registers.
4172   MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
4173   const TargetRegisterClass *RC = getRegClassFor(RegTy);
4174
4175   for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
4176     unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
4177     unsigned VReg = AddLiveIn(MF, ArgReg, RC);
4178     unsigned Offset = I * CC.regSize();
4179     SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4180                                    DAG.getConstant(Offset, PtrTy));
4181     SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4182                                  StorePtr, MachinePointerInfo(FuncArg, Offset),
4183                                  false, false, 0);
4184     OutChains.push_back(Store);
4185   }
4186 }
4187
4188 // Copy byVal arg to registers and stack.
4189 void MipsTargetLowering::
4190 passByValArg(SDValue Chain, DebugLoc DL,
4191              std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
4192              SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
4193              MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
4194              const MipsCC &CC, const ByValArgInfo &ByVal,
4195              const ISD::ArgFlagsTy &Flags, bool isLittle) const {
4196   unsigned ByValSize = Flags.getByValSize();
4197   unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
4198   unsigned RegSize = CC.regSize();
4199   unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
4200   EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
4201
4202   if (ByVal.NumRegs) {
4203     const uint16_t *ArgRegs = CC.intArgRegs();
4204     bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
4205     unsigned I = 0;
4206
4207     // Copy words to registers.
4208     for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
4209       SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4210                                     DAG.getConstant(Offset, PtrTy));
4211       SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4212                                     MachinePointerInfo(), false, false, false,
4213                                     Alignment);
4214       MemOpChains.push_back(LoadVal.getValue(1));
4215       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
4216       RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4217     }
4218
4219     // Return if the struct has been fully copied.
4220     if (ByValSize == Offset)
4221       return;
4222
4223     // Copy the remainder of the byval argument with sub-word loads and shifts.
4224     if (LeftoverBytes) {
4225       assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
4226              "Size of the remainder should be smaller than RegSize.");
4227       SDValue Val;
4228
4229       for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
4230            Offset < ByValSize; LoadSize /= 2) {
4231         unsigned RemSize = ByValSize - Offset;
4232
4233         if (RemSize < LoadSize)
4234           continue;
4235
4236         // Load subword.
4237         SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4238                                       DAG.getConstant(Offset, PtrTy));
4239         SDValue LoadVal =
4240           DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
4241                          MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
4242                          false, false, Alignment);
4243         MemOpChains.push_back(LoadVal.getValue(1));
4244
4245         // Shift the loaded value.
4246         unsigned Shamt;
4247
4248         if (isLittle)
4249           Shamt = TotalSizeLoaded;
4250         else
4251           Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
4252
4253         SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4254                                     DAG.getConstant(Shamt, MVT::i32));
4255
4256         if (Val.getNode())
4257           Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4258         else
4259           Val = Shift;
4260
4261         Offset += LoadSize;
4262         TotalSizeLoaded += LoadSize;
4263         Alignment = std::min(Alignment, LoadSize);
4264       }
4265
4266       unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
4267       RegsToPass.push_back(std::make_pair(ArgReg, Val));
4268       return;
4269     }
4270   }
4271
4272   // Copy remainder of byval arg to it with memcpy.
4273   unsigned MemCpySize = ByValSize - Offset;
4274   SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4275                             DAG.getConstant(Offset, PtrTy));
4276   SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4277                             DAG.getIntPtrConstant(ByVal.Address));
4278   Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4279                         DAG.getConstant(MemCpySize, PtrTy), Alignment,
4280                         /*isVolatile=*/false, /*AlwaysInline=*/false,
4281                         MachinePointerInfo(0), MachinePointerInfo(0));
4282   MemOpChains.push_back(Chain);
4283 }
4284
4285 void
4286 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4287                                     const MipsCC &CC, SDValue Chain,
4288                                     DebugLoc DL, SelectionDAG &DAG) const {
4289   unsigned NumRegs = CC.numIntArgRegs();
4290   const uint16_t *ArgRegs = CC.intArgRegs();
4291   const CCState &CCInfo = CC.getCCInfo();
4292   unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
4293   unsigned RegSize = CC.regSize();
4294   MVT RegTy = MVT::getIntegerVT(RegSize * 8);
4295   const TargetRegisterClass *RC = getRegClassFor(RegTy);
4296   MachineFunction &MF = DAG.getMachineFunction();
4297   MachineFrameInfo *MFI = MF.getFrameInfo();
4298   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4299
4300   // Offset of the first variable argument from stack pointer.
4301   int VaArgOffset;
4302
4303   if (NumRegs == Idx)
4304     VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
4305   else
4306     VaArgOffset =
4307       (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
4308
4309   // Record the frame index of the first variable argument
4310   // which is a value necessary to VASTART.
4311   int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4312   MipsFI->setVarArgsFrameIndex(FI);
4313
4314   // Copy the integer registers that have not been used for argument passing
4315   // to the argument register save area. For O32, the save area is allocated
4316   // in the caller's stack frame, while for N32/64, it is allocated in the
4317   // callee's stack frame.
4318   for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
4319     unsigned Reg = AddLiveIn(MF, ArgRegs[I], RC);
4320     SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4321     FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4322     SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
4323     SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
4324                                  MachinePointerInfo(), false, false, 0);
4325     cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
4326     OutChains.push_back(Store);
4327   }
4328 }