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