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