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