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