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