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