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