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