Remove most of the TargetMachine::getSubtarget/getSubtargetImpl
[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         (const MipsTargetObjectFile &)getObjFileLowering();
1603
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         (const MipsTargetObjectFile &)getObjFileLowering();
1737
1738     if (TLOF.IsConstantInSmallSection(N->getConstVal(), getTargetMachine()))
1739       // %gp_rel relocation
1740       return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1741
1742     return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1743   }
1744
1745   return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1746 }
1747
1748 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1749   MachineFunction &MF = DAG.getMachineFunction();
1750   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1751
1752   SDLoc DL(Op);
1753   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1754                                  getPointerTy());
1755
1756   // vastart just stores the address of the VarArgsFrameIndex slot into the
1757   // memory location argument.
1758   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1759   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1760                       MachinePointerInfo(SV), false, false, 0);
1761 }
1762
1763 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1764   SDNode *Node = Op.getNode();
1765   EVT VT = Node->getValueType(0);
1766   SDValue Chain = Node->getOperand(0);
1767   SDValue VAListPtr = Node->getOperand(1);
1768   unsigned Align = Node->getConstantOperandVal(3);
1769   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1770   SDLoc DL(Node);
1771   unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
1772
1773   SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1774                                    MachinePointerInfo(SV), false, false, false,
1775                                    0);
1776   SDValue VAList = VAListLoad;
1777
1778   // Re-align the pointer if necessary.
1779   // It should only ever be necessary for 64-bit types on O32 since the minimum
1780   // argument alignment is the same as the maximum type alignment for N32/N64.
1781   //
1782   // FIXME: We currently align too often. The code generator doesn't notice
1783   //        when the pointer is still aligned from the last va_arg (or pair of
1784   //        va_args for the i64 on O32 case).
1785   if (Align > getMinStackArgumentAlignment()) {
1786     assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1787
1788     VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1789                          DAG.getConstant(Align - 1,
1790                                          VAList.getValueType()));
1791
1792     VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1793                          DAG.getConstant(-(int64_t)Align,
1794                                          VAList.getValueType()));
1795   }
1796
1797   // Increment the pointer, VAList, to the next vaarg.
1798   unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1799   SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1800                              DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1801                                              VAList.getValueType()));
1802   // Store the incremented VAList to the legalized pointer
1803   Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1804                       MachinePointerInfo(SV), false, false, 0);
1805
1806   // In big-endian mode we must adjust the pointer when the load size is smaller
1807   // than the argument slot size. We must also reduce the known alignment to
1808   // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1809   // the correct half of the slot, and reduce the alignment from 8 (slot
1810   // alignment) down to 4 (type alignment).
1811   if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1812     unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1813     VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1814                          DAG.getIntPtrConstant(Adjustment));
1815   }
1816   // Load the actual argument out of the pointer VAList
1817   return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1818                      false, 0);
1819 }
1820
1821 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1822                                 bool HasExtractInsert) {
1823   EVT TyX = Op.getOperand(0).getValueType();
1824   EVT TyY = Op.getOperand(1).getValueType();
1825   SDValue Const1 = DAG.getConstant(1, MVT::i32);
1826   SDValue Const31 = DAG.getConstant(31, MVT::i32);
1827   SDLoc DL(Op);
1828   SDValue Res;
1829
1830   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1831   // to i32.
1832   SDValue X = (TyX == MVT::f32) ?
1833     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1834     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1835                 Const1);
1836   SDValue Y = (TyY == MVT::f32) ?
1837     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1838     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1839                 Const1);
1840
1841   if (HasExtractInsert) {
1842     // ext  E, Y, 31, 1  ; extract bit31 of Y
1843     // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
1844     SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1845     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1846   } else {
1847     // sll SllX, X, 1
1848     // srl SrlX, SllX, 1
1849     // srl SrlY, Y, 31
1850     // sll SllY, SrlX, 31
1851     // or  Or, SrlX, SllY
1852     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1853     SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1854     SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1855     SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1856     Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1857   }
1858
1859   if (TyX == MVT::f32)
1860     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1861
1862   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1863                              Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1864   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1865 }
1866
1867 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1868                                 bool HasExtractInsert) {
1869   unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1870   unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1871   EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1872   SDValue Const1 = DAG.getConstant(1, MVT::i32);
1873   SDLoc DL(Op);
1874
1875   // Bitcast to integer nodes.
1876   SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1877   SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1878
1879   if (HasExtractInsert) {
1880     // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
1881     // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
1882     SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1883                             DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1884
1885     if (WidthX > WidthY)
1886       E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1887     else if (WidthY > WidthX)
1888       E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1889
1890     SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1891                             DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1892     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1893   }
1894
1895   // (d)sll SllX, X, 1
1896   // (d)srl SrlX, SllX, 1
1897   // (d)srl SrlY, Y, width(Y)-1
1898   // (d)sll SllY, SrlX, width(Y)-1
1899   // or     Or, SrlX, SllY
1900   SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1901   SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1902   SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1903                              DAG.getConstant(WidthY - 1, MVT::i32));
1904
1905   if (WidthX > WidthY)
1906     SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1907   else if (WidthY > WidthX)
1908     SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1909
1910   SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1911                              DAG.getConstant(WidthX - 1, MVT::i32));
1912   SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1913   return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1914 }
1915
1916 SDValue
1917 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1918   if (Subtarget.isGP64bit())
1919     return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
1920
1921   return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
1922 }
1923
1924 SDValue MipsTargetLowering::
1925 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1926   // check the depth
1927   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1928          "Frame address can only be determined for current frame.");
1929
1930   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1931   MFI->setFrameAddressIsTaken(true);
1932   EVT VT = Op.getValueType();
1933   SDLoc DL(Op);
1934   SDValue FrameAddr = DAG.getCopyFromReg(
1935       DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
1936   return FrameAddr;
1937 }
1938
1939 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1940                                             SelectionDAG &DAG) const {
1941   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1942     return SDValue();
1943
1944   // check the depth
1945   assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1946          "Return address can be determined only for current frame.");
1947
1948   MachineFunction &MF = DAG.getMachineFunction();
1949   MachineFrameInfo *MFI = MF.getFrameInfo();
1950   MVT VT = Op.getSimpleValueType();
1951   unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
1952   MFI->setReturnAddressIsTaken(true);
1953
1954   // Return RA, which contains the return address. Mark it an implicit live-in.
1955   unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1956   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1957 }
1958
1959 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1960 // generated from __builtin_eh_return (offset, handler)
1961 // The effect of this is to adjust the stack pointer by "offset"
1962 // and then branch to "handler".
1963 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1964                                                                      const {
1965   MachineFunction &MF = DAG.getMachineFunction();
1966   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1967
1968   MipsFI->setCallsEhReturn();
1969   SDValue Chain     = Op.getOperand(0);
1970   SDValue Offset    = Op.getOperand(1);
1971   SDValue Handler   = Op.getOperand(2);
1972   SDLoc DL(Op);
1973   EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
1974
1975   // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1976   // EH_RETURN nodes, so that instructions are emitted back-to-back.
1977   unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
1978   unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
1979   Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1980   Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1981   return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1982                      DAG.getRegister(OffsetReg, Ty),
1983                      DAG.getRegister(AddrReg, getPointerTy()),
1984                      Chain.getValue(1));
1985 }
1986
1987 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1988                                               SelectionDAG &DAG) const {
1989   // FIXME: Need pseudo-fence for 'singlethread' fences
1990   // FIXME: Set SType for weaker fences where supported/appropriate.
1991   unsigned SType = 0;
1992   SDLoc DL(Op);
1993   return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1994                      DAG.getConstant(SType, MVT::i32));
1995 }
1996
1997 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1998                                                 SelectionDAG &DAG) const {
1999   SDLoc DL(Op);
2000   MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2001
2002   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2003   SDValue Shamt = Op.getOperand(2);
2004   // if shamt < (VT.bits):
2005   //  lo = (shl lo, shamt)
2006   //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2007   // else:
2008   //  lo = 0
2009   //  hi = (shl lo, shamt[4:0])
2010   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2011                             DAG.getConstant(-1, MVT::i32));
2012   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2013                                       DAG.getConstant(1, VT));
2014   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2015   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2016   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2017   SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2018   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2019                              DAG.getConstant(0x20, MVT::i32));
2020   Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2021                    DAG.getConstant(0, VT), ShiftLeftLo);
2022   Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2023
2024   SDValue Ops[2] = {Lo, Hi};
2025   return DAG.getMergeValues(Ops, DL);
2026 }
2027
2028 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2029                                                  bool IsSRA) const {
2030   SDLoc DL(Op);
2031   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2032   SDValue Shamt = Op.getOperand(2);
2033   MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2034
2035   // if shamt < (VT.bits):
2036   //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2037   //  if isSRA:
2038   //    hi = (sra hi, shamt)
2039   //  else:
2040   //    hi = (srl hi, shamt)
2041   // else:
2042   //  if isSRA:
2043   //   lo = (sra hi, shamt[4:0])
2044   //   hi = (sra hi, 31)
2045   //  else:
2046   //   lo = (srl hi, shamt[4:0])
2047   //   hi = 0
2048   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2049                             DAG.getConstant(-1, MVT::i32));
2050   SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2051                                      DAG.getConstant(1, VT));
2052   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2053   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2054   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2055   SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2056                                      DL, VT, Hi, Shamt);
2057   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2058                              DAG.getConstant(0x20, MVT::i32));
2059   SDValue Shift31 = DAG.getNode(ISD::SRA, DL, VT, Hi, DAG.getConstant(31, VT));
2060   Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2061   Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2062                    IsSRA ? Shift31 : DAG.getConstant(0, VT), ShiftRightHi);
2063
2064   SDValue Ops[2] = {Lo, Hi};
2065   return DAG.getMergeValues(Ops, DL);
2066 }
2067
2068 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2069                             SDValue Chain, SDValue Src, unsigned Offset) {
2070   SDValue Ptr = LD->getBasePtr();
2071   EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2072   EVT BasePtrVT = Ptr.getValueType();
2073   SDLoc DL(LD);
2074   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2075
2076   if (Offset)
2077     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2078                       DAG.getConstant(Offset, BasePtrVT));
2079
2080   SDValue Ops[] = { Chain, Ptr, Src };
2081   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2082                                  LD->getMemOperand());
2083 }
2084
2085 // Expand an unaligned 32 or 64-bit integer load node.
2086 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2087   LoadSDNode *LD = cast<LoadSDNode>(Op);
2088   EVT MemVT = LD->getMemoryVT();
2089
2090   if (Subtarget.systemSupportsUnalignedAccess())
2091     return Op;
2092
2093   // Return if load is aligned or if MemVT is neither i32 nor i64.
2094   if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2095       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2096     return SDValue();
2097
2098   bool IsLittle = Subtarget.isLittle();
2099   EVT VT = Op.getValueType();
2100   ISD::LoadExtType ExtType = LD->getExtensionType();
2101   SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2102
2103   assert((VT == MVT::i32) || (VT == MVT::i64));
2104
2105   // Expand
2106   //  (set dst, (i64 (load baseptr)))
2107   // to
2108   //  (set tmp, (ldl (add baseptr, 7), undef))
2109   //  (set dst, (ldr baseptr, tmp))
2110   if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2111     SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2112                                IsLittle ? 7 : 0);
2113     return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2114                         IsLittle ? 0 : 7);
2115   }
2116
2117   SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2118                              IsLittle ? 3 : 0);
2119   SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2120                              IsLittle ? 0 : 3);
2121
2122   // Expand
2123   //  (set dst, (i32 (load baseptr))) or
2124   //  (set dst, (i64 (sextload baseptr))) or
2125   //  (set dst, (i64 (extload baseptr)))
2126   // to
2127   //  (set tmp, (lwl (add baseptr, 3), undef))
2128   //  (set dst, (lwr baseptr, tmp))
2129   if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2130       (ExtType == ISD::EXTLOAD))
2131     return LWR;
2132
2133   assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2134
2135   // Expand
2136   //  (set dst, (i64 (zextload baseptr)))
2137   // to
2138   //  (set tmp0, (lwl (add baseptr, 3), undef))
2139   //  (set tmp1, (lwr baseptr, tmp0))
2140   //  (set tmp2, (shl tmp1, 32))
2141   //  (set dst, (srl tmp2, 32))
2142   SDLoc DL(LD);
2143   SDValue Const32 = DAG.getConstant(32, MVT::i32);
2144   SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2145   SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2146   SDValue Ops[] = { SRL, LWR.getValue(1) };
2147   return DAG.getMergeValues(Ops, DL);
2148 }
2149
2150 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2151                              SDValue Chain, unsigned Offset) {
2152   SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2153   EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2154   SDLoc DL(SD);
2155   SDVTList VTList = DAG.getVTList(MVT::Other);
2156
2157   if (Offset)
2158     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2159                       DAG.getConstant(Offset, BasePtrVT));
2160
2161   SDValue Ops[] = { Chain, Value, Ptr };
2162   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2163                                  SD->getMemOperand());
2164 }
2165
2166 // Expand an unaligned 32 or 64-bit integer store node.
2167 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2168                                       bool IsLittle) {
2169   SDValue Value = SD->getValue(), Chain = SD->getChain();
2170   EVT VT = Value.getValueType();
2171
2172   // Expand
2173   //  (store val, baseptr) or
2174   //  (truncstore val, baseptr)
2175   // to
2176   //  (swl val, (add baseptr, 3))
2177   //  (swr val, baseptr)
2178   if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2179     SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2180                                 IsLittle ? 3 : 0);
2181     return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2182   }
2183
2184   assert(VT == MVT::i64);
2185
2186   // Expand
2187   //  (store val, baseptr)
2188   // to
2189   //  (sdl val, (add baseptr, 7))
2190   //  (sdr val, baseptr)
2191   SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2192   return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2193 }
2194
2195 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2196 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2197   SDValue Val = SD->getValue();
2198
2199   if (Val.getOpcode() != ISD::FP_TO_SINT)
2200     return SDValue();
2201
2202   EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2203   SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2204                            Val.getOperand(0));
2205
2206   return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2207                       SD->getPointerInfo(), SD->isVolatile(),
2208                       SD->isNonTemporal(), SD->getAlignment());
2209 }
2210
2211 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2212   StoreSDNode *SD = cast<StoreSDNode>(Op);
2213   EVT MemVT = SD->getMemoryVT();
2214
2215   // Lower unaligned integer stores.
2216   if (!Subtarget.systemSupportsUnalignedAccess() &&
2217       (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2218       ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2219     return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2220
2221   return lowerFP_TO_SINT_STORE(SD, DAG);
2222 }
2223
2224 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2225   if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2226       || cast<ConstantSDNode>
2227         (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2228       || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2229     return SDValue();
2230
2231   // The pattern
2232   //   (add (frameaddr 0), (frame_to_args_offset))
2233   // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2234   //   (add FrameObject, 0)
2235   // where FrameObject is a fixed StackObject with offset 0 which points to
2236   // the old stack pointer.
2237   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2238   EVT ValTy = Op->getValueType(0);
2239   int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2240   SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2241   return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2242                      DAG.getConstant(0, ValTy));
2243 }
2244
2245 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2246                                             SelectionDAG &DAG) const {
2247   EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2248   SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2249                               Op.getOperand(0));
2250   return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2251 }
2252
2253 //===----------------------------------------------------------------------===//
2254 //                      Calling Convention Implementation
2255 //===----------------------------------------------------------------------===//
2256
2257 //===----------------------------------------------------------------------===//
2258 // TODO: Implement a generic logic using tblgen that can support this.
2259 // Mips O32 ABI rules:
2260 // ---
2261 // i32 - Passed in A0, A1, A2, A3 and stack
2262 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2263 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
2264 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2265 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2266 //       not used, it must be shadowed. If only A3 is available, shadow it and
2267 //       go to stack.
2268 //
2269 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2270 //===----------------------------------------------------------------------===//
2271
2272 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2273                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2274                        CCState &State, const MCPhysReg *F64Regs) {
2275   const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2276       State.getMachineFunction().getSubtarget());
2277
2278   static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2279
2280   static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2281   static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2282
2283   // Do not process byval args here.
2284   if (ArgFlags.isByVal())
2285     return true;
2286
2287   // Promote i8 and i16
2288   if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2289     if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2290       LocVT = MVT::i32;
2291       if (ArgFlags.isSExt())
2292         LocInfo = CCValAssign::SExtUpper;
2293       else if (ArgFlags.isZExt())
2294         LocInfo = CCValAssign::ZExtUpper;
2295       else
2296         LocInfo = CCValAssign::AExtUpper;
2297     }
2298   }
2299
2300   // Promote i8 and i16
2301   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2302     LocVT = MVT::i32;
2303     if (ArgFlags.isSExt())
2304       LocInfo = CCValAssign::SExt;
2305     else if (ArgFlags.isZExt())
2306       LocInfo = CCValAssign::ZExt;
2307     else
2308       LocInfo = CCValAssign::AExt;
2309   }
2310
2311   unsigned Reg;
2312
2313   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2314   // is true: function is vararg, argument is 3rd or higher, there is previous
2315   // argument which is not f32 or f64.
2316   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2317       || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2318   unsigned OrigAlign = ArgFlags.getOrigAlign();
2319   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2320
2321   if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2322     Reg = State.AllocateReg(IntRegs, IntRegsSize);
2323     // If this is the first part of an i64 arg,
2324     // the allocated register must be either A0 or A2.
2325     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2326       Reg = State.AllocateReg(IntRegs, IntRegsSize);
2327     LocVT = MVT::i32;
2328   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2329     // Allocate int register and shadow next int register. If first
2330     // available register is Mips::A1 or Mips::A3, shadow it too.
2331     Reg = State.AllocateReg(IntRegs, IntRegsSize);
2332     if (Reg == Mips::A1 || Reg == Mips::A3)
2333       Reg = State.AllocateReg(IntRegs, IntRegsSize);
2334     State.AllocateReg(IntRegs, IntRegsSize);
2335     LocVT = MVT::i32;
2336   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2337     // we are guaranteed to find an available float register
2338     if (ValVT == MVT::f32) {
2339       Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2340       // Shadow int register
2341       State.AllocateReg(IntRegs, IntRegsSize);
2342     } else {
2343       Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2344       // Shadow int registers
2345       unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2346       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2347         State.AllocateReg(IntRegs, IntRegsSize);
2348       State.AllocateReg(IntRegs, IntRegsSize);
2349     }
2350   } else
2351     llvm_unreachable("Cannot handle this ValVT.");
2352
2353   if (!Reg) {
2354     unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2355                                           OrigAlign);
2356     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2357   } else
2358     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2359
2360   return false;
2361 }
2362
2363 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2364                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2365                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2366   static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2367
2368   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2369 }
2370
2371 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2372                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2373                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2374   static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2375
2376   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2377 }
2378
2379 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2380                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2381                        CCState &State) LLVM_ATTRIBUTE_UNUSED;
2382
2383 #include "MipsGenCallingConv.inc"
2384
2385 //===----------------------------------------------------------------------===//
2386 //                  Call Calling Convention Implementation
2387 //===----------------------------------------------------------------------===//
2388
2389 // Return next O32 integer argument register.
2390 static unsigned getNextIntArgReg(unsigned Reg) {
2391   assert((Reg == Mips::A0) || (Reg == Mips::A2));
2392   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2393 }
2394
2395 SDValue
2396 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2397                                    SDValue Chain, SDValue Arg, SDLoc DL,
2398                                    bool IsTailCall, SelectionDAG &DAG) const {
2399   if (!IsTailCall) {
2400     SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2401                                  DAG.getIntPtrConstant(Offset));
2402     return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2403                         false, 0);
2404   }
2405
2406   MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2407   int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2408   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2409   return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2410                       /*isVolatile=*/ true, false, 0);
2411 }
2412
2413 void MipsTargetLowering::
2414 getOpndList(SmallVectorImpl<SDValue> &Ops,
2415             std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2416             bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2417             bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2418             SDValue Chain) const {
2419   // Insert node "GP copy globalreg" before call to function.
2420   //
2421   // R_MIPS_CALL* operators (emitted when non-internal functions are called
2422   // in PIC mode) allow symbols to be resolved via lazy binding.
2423   // The lazy binding stub requires GP to point to the GOT.
2424   // Note that we don't need GP to point to the GOT for indirect calls
2425   // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2426   // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2427   // used for the function (that is, Mips linker doesn't generate lazy binding
2428   // stub for a function whose address is taken in the program).
2429   if (IsPICCall && !InternalLinkage && IsCallReloc) {
2430     unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2431     EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2432     RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2433   }
2434
2435   // Build a sequence of copy-to-reg nodes chained together with token
2436   // chain and flag operands which copy the outgoing args into registers.
2437   // The InFlag in necessary since all emitted instructions must be
2438   // stuck together.
2439   SDValue InFlag;
2440
2441   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2442     Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2443                                  RegsToPass[i].second, InFlag);
2444     InFlag = Chain.getValue(1);
2445   }
2446
2447   // Add argument registers to the end of the list so that they are
2448   // known live into the call.
2449   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2450     Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2451                                       RegsToPass[i].second.getValueType()));
2452
2453   // Add a register mask operand representing the call-preserved registers.
2454   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2455   const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2456   assert(Mask && "Missing call preserved mask for calling convention");
2457   if (Subtarget.inMips16HardFloat()) {
2458     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2459       llvm::StringRef Sym = G->getGlobal()->getName();
2460       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2461       if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2462         Mask = MipsRegisterInfo::getMips16RetHelperMask();
2463       }
2464     }
2465   }
2466   Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2467
2468   if (InFlag.getNode())
2469     Ops.push_back(InFlag);
2470 }
2471
2472 /// LowerCall - functions arguments are copied from virtual regs to
2473 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2474 SDValue
2475 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2476                               SmallVectorImpl<SDValue> &InVals) const {
2477   SelectionDAG &DAG                     = CLI.DAG;
2478   SDLoc DL                              = CLI.DL;
2479   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2480   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
2481   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
2482   SDValue Chain                         = CLI.Chain;
2483   SDValue Callee                        = CLI.Callee;
2484   bool &IsTailCall                      = CLI.IsTailCall;
2485   CallingConv::ID CallConv              = CLI.CallConv;
2486   bool IsVarArg                         = CLI.IsVarArg;
2487
2488   MachineFunction &MF = DAG.getMachineFunction();
2489   MachineFrameInfo *MFI = MF.getFrameInfo();
2490   const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2491   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2492   bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2493
2494   // Analyze operands of the call, assigning locations to each operand.
2495   SmallVector<CCValAssign, 16> ArgLocs;
2496   MipsCCState CCInfo(
2497       CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2498       MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2499
2500   // Allocate the reserved argument area. It seems strange to do this from the
2501   // caller side but removing it breaks the frame size calculation.
2502   CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2503
2504   CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2505
2506   // Get a count of how many bytes are to be pushed on the stack.
2507   unsigned NextStackOffset = CCInfo.getNextStackOffset();
2508
2509   // Check if it's really possible to do a tail call.
2510   if (IsTailCall)
2511     IsTailCall = isEligibleForTailCallOptimization(
2512         CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2513
2514   if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2515     report_fatal_error("failed to perform tail call elimination on a call "
2516                        "site marked musttail");
2517
2518   if (IsTailCall)
2519     ++NumTailCalls;
2520
2521   // Chain is the output chain of the last Load/Store or CopyToReg node.
2522   // ByValChain is the output chain of the last Memcpy node created for copying
2523   // byval arguments to the stack.
2524   unsigned StackAlignment = TFL->getStackAlignment();
2525   NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2526   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2527
2528   if (!IsTailCall)
2529     Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2530
2531   SDValue StackPtr = DAG.getCopyFromReg(
2532       Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP, getPointerTy());
2533
2534   // With EABI is it possible to have 16 args on registers.
2535   std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2536   SmallVector<SDValue, 8> MemOpChains;
2537
2538   CCInfo.rewindByValRegsInfo();
2539
2540   // Walk the register/memloc assignments, inserting copies/loads.
2541   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2542     SDValue Arg = OutVals[i];
2543     CCValAssign &VA = ArgLocs[i];
2544     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2545     ISD::ArgFlagsTy Flags = Outs[i].Flags;
2546     bool UseUpperBits = false;
2547
2548     // ByVal Arg.
2549     if (Flags.isByVal()) {
2550       unsigned FirstByValReg, LastByValReg;
2551       unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2552       CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2553
2554       assert(Flags.getByValSize() &&
2555              "ByVal args of size 0 should have been ignored by front-end.");
2556       assert(ByValIdx < CCInfo.getInRegsParamsCount());
2557       assert(!IsTailCall &&
2558              "Do not tail-call optimize if there is a byval argument.");
2559       passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2560                    FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2561                    VA);
2562       CCInfo.nextInRegsParam();
2563       continue;
2564     }
2565
2566     // Promote the value if needed.
2567     switch (VA.getLocInfo()) {
2568     default:
2569       llvm_unreachable("Unknown loc info!");
2570     case CCValAssign::Full:
2571       if (VA.isRegLoc()) {
2572         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2573             (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2574             (ValVT == MVT::i64 && LocVT == MVT::f64))
2575           Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2576         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2577           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2578                                    Arg, DAG.getConstant(0, MVT::i32));
2579           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2580                                    Arg, DAG.getConstant(1, MVT::i32));
2581           if (!Subtarget.isLittle())
2582             std::swap(Lo, Hi);
2583           unsigned LocRegLo = VA.getLocReg();
2584           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2585           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2586           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2587           continue;
2588         }
2589       }
2590       break;
2591     case CCValAssign::BCvt:
2592       Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2593       break;
2594     case CCValAssign::SExtUpper:
2595       UseUpperBits = true;
2596       // Fallthrough
2597     case CCValAssign::SExt:
2598       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2599       break;
2600     case CCValAssign::ZExtUpper:
2601       UseUpperBits = true;
2602       // Fallthrough
2603     case CCValAssign::ZExt:
2604       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2605       break;
2606     case CCValAssign::AExtUpper:
2607       UseUpperBits = true;
2608       // Fallthrough
2609     case CCValAssign::AExt:
2610       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2611       break;
2612     }
2613
2614     if (UseUpperBits) {
2615       unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2616       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2617       Arg = DAG.getNode(
2618           ISD::SHL, DL, VA.getLocVT(), Arg,
2619           DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2620     }
2621
2622     // Arguments that can be passed on register must be kept at
2623     // RegsToPass vector
2624     if (VA.isRegLoc()) {
2625       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2626       continue;
2627     }
2628
2629     // Register can't get to this point...
2630     assert(VA.isMemLoc());
2631
2632     // emit ISD::STORE whichs stores the
2633     // parameter value to a stack Location
2634     MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2635                                          Chain, Arg, DL, IsTailCall, DAG));
2636   }
2637
2638   // Transform all store nodes into one single node because all store
2639   // nodes are independent of each other.
2640   if (!MemOpChains.empty())
2641     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2642
2643   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2644   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2645   // node so that legalize doesn't hack it.
2646   bool IsPICCall = (ABI.IsN64() || IsPIC); // true if calls are translated to
2647                                            // jalr $25
2648   bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2649   SDValue CalleeLo;
2650   EVT Ty = Callee.getValueType();
2651
2652   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2653     if (IsPICCall) {
2654       const GlobalValue *Val = G->getGlobal();
2655       InternalLinkage = Val->hasInternalLinkage();
2656
2657       if (InternalLinkage)
2658         Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
2659       else if (LargeGOT) {
2660         Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2661                                        MipsII::MO_CALL_LO16, Chain,
2662                                        FuncInfo->callPtrInfo(Val));
2663         IsCallReloc = true;
2664       } else {
2665         Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2666                                FuncInfo->callPtrInfo(Val));
2667         IsCallReloc = true;
2668       }
2669     } else
2670       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2671                                           MipsII::MO_NO_FLAG);
2672     GlobalOrExternal = true;
2673   }
2674   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2675     const char *Sym = S->getSymbol();
2676
2677     if (!ABI.IsN64() && !IsPIC) // !N64 && static
2678       Callee =
2679           DAG.getTargetExternalSymbol(Sym, getPointerTy(), MipsII::MO_NO_FLAG);
2680     else if (LargeGOT) {
2681       Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2682                                      MipsII::MO_CALL_LO16, Chain,
2683                                      FuncInfo->callPtrInfo(Sym));
2684       IsCallReloc = true;
2685     } else { // N64 || PIC
2686       Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2687                              FuncInfo->callPtrInfo(Sym));
2688       IsCallReloc = true;
2689     }
2690
2691     GlobalOrExternal = true;
2692   }
2693
2694   SmallVector<SDValue, 8> Ops(1, Chain);
2695   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2696
2697   getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2698               IsCallReloc, CLI, Callee, Chain);
2699
2700   if (IsTailCall)
2701     return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2702
2703   Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2704   SDValue InFlag = Chain.getValue(1);
2705
2706   // Create the CALLSEQ_END node.
2707   Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2708                              DAG.getIntPtrConstant(0, true), InFlag, DL);
2709   InFlag = Chain.getValue(1);
2710
2711   // Handle result values, copying them out of physregs into vregs that we
2712   // return.
2713   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2714                          InVals, CLI);
2715 }
2716
2717 /// LowerCallResult - Lower the result values of a call into the
2718 /// appropriate copies out of appropriate physical registers.
2719 SDValue MipsTargetLowering::LowerCallResult(
2720     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2721     const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2722     SmallVectorImpl<SDValue> &InVals,
2723     TargetLowering::CallLoweringInfo &CLI) const {
2724   // Assign locations to each value returned by this call.
2725   SmallVector<CCValAssign, 16> RVLocs;
2726   MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2727                      *DAG.getContext());
2728   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2729
2730   // Copy all of the result registers out of their specified physreg.
2731   for (unsigned i = 0; i != RVLocs.size(); ++i) {
2732     CCValAssign &VA = RVLocs[i];
2733     assert(VA.isRegLoc() && "Can only return in registers!");
2734
2735     SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2736                                      RVLocs[i].getLocVT(), InFlag);
2737     Chain = Val.getValue(1);
2738     InFlag = Val.getValue(2);
2739
2740     if (VA.isUpperBitsInLoc()) {
2741       unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2742       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2743       unsigned Shift =
2744           VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2745       Val = DAG.getNode(
2746           Shift, DL, VA.getLocVT(), Val,
2747           DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2748     }
2749
2750     switch (VA.getLocInfo()) {
2751     default:
2752       llvm_unreachable("Unknown loc info!");
2753     case CCValAssign::Full:
2754       break;
2755     case CCValAssign::BCvt:
2756       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2757       break;
2758     case CCValAssign::AExt:
2759     case CCValAssign::AExtUpper:
2760       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2761       break;
2762     case CCValAssign::ZExt:
2763     case CCValAssign::ZExtUpper:
2764       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2765                         DAG.getValueType(VA.getValVT()));
2766       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2767       break;
2768     case CCValAssign::SExt:
2769     case CCValAssign::SExtUpper:
2770       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2771                         DAG.getValueType(VA.getValVT()));
2772       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2773       break;
2774     }
2775
2776     InVals.push_back(Val);
2777   }
2778
2779   return Chain;
2780 }
2781
2782 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2783                                       EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2784   MVT LocVT = VA.getLocVT();
2785   EVT ValVT = VA.getValVT();
2786
2787   // Shift into the upper bits if necessary.
2788   switch (VA.getLocInfo()) {
2789   default:
2790     break;
2791   case CCValAssign::AExtUpper:
2792   case CCValAssign::SExtUpper:
2793   case CCValAssign::ZExtUpper: {
2794     unsigned ValSizeInBits = ArgVT.getSizeInBits();
2795     unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2796     unsigned Opcode =
2797         VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2798     Val = DAG.getNode(
2799         Opcode, DL, VA.getLocVT(), Val,
2800         DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2801     break;
2802   }
2803   }
2804
2805   // If this is an value smaller than the argument slot size (32-bit for O32,
2806   // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2807   // size. Extract the value and insert any appropriate assertions regarding
2808   // sign/zero extension.
2809   switch (VA.getLocInfo()) {
2810   default:
2811     llvm_unreachable("Unknown loc info!");
2812   case CCValAssign::Full:
2813     break;
2814   case CCValAssign::AExtUpper:
2815   case CCValAssign::AExt:
2816     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2817     break;
2818   case CCValAssign::SExtUpper:
2819   case CCValAssign::SExt:
2820     Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2821     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2822     break;
2823   case CCValAssign::ZExtUpper:
2824   case CCValAssign::ZExt:
2825     Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2826     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2827     break;
2828   case CCValAssign::BCvt:
2829     Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2830     break;
2831   }
2832
2833   return Val;
2834 }
2835
2836 //===----------------------------------------------------------------------===//
2837 //             Formal Arguments Calling Convention Implementation
2838 //===----------------------------------------------------------------------===//
2839 /// LowerFormalArguments - transform physical registers into virtual registers
2840 /// and generate load operations for arguments places on the stack.
2841 SDValue
2842 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2843                                          CallingConv::ID CallConv,
2844                                          bool IsVarArg,
2845                                       const SmallVectorImpl<ISD::InputArg> &Ins,
2846                                          SDLoc DL, SelectionDAG &DAG,
2847                                          SmallVectorImpl<SDValue> &InVals)
2848                                           const {
2849   MachineFunction &MF = DAG.getMachineFunction();
2850   MachineFrameInfo *MFI = MF.getFrameInfo();
2851   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2852
2853   MipsFI->setVarArgsFrameIndex(0);
2854
2855   // Used with vargs to acumulate store chains.
2856   std::vector<SDValue> OutChains;
2857
2858   // Assign locations to all of the incoming arguments.
2859   SmallVector<CCValAssign, 16> ArgLocs;
2860   MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2861                      *DAG.getContext());
2862   CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2863   Function::const_arg_iterator FuncArg =
2864     DAG.getMachineFunction().getFunction()->arg_begin();
2865
2866   CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2867   MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2868                            CCInfo.getInRegsParamsCount() > 0);
2869
2870   unsigned CurArgIdx = 0;
2871   CCInfo.rewindByValRegsInfo();
2872
2873   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2874     CCValAssign &VA = ArgLocs[i];
2875     std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2876     CurArgIdx = Ins[i].OrigArgIndex;
2877     EVT ValVT = VA.getValVT();
2878     ISD::ArgFlagsTy Flags = Ins[i].Flags;
2879     bool IsRegLoc = VA.isRegLoc();
2880
2881     if (Flags.isByVal()) {
2882       unsigned FirstByValReg, LastByValReg;
2883       unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2884       CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2885
2886       assert(Flags.getByValSize() &&
2887              "ByVal args of size 0 should have been ignored by front-end.");
2888       assert(ByValIdx < CCInfo.getInRegsParamsCount());
2889       copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2890                     FirstByValReg, LastByValReg, VA, CCInfo);
2891       CCInfo.nextInRegsParam();
2892       continue;
2893     }
2894
2895     // Arguments stored on registers
2896     if (IsRegLoc) {
2897       MVT RegVT = VA.getLocVT();
2898       unsigned ArgReg = VA.getLocReg();
2899       const TargetRegisterClass *RC = getRegClassFor(RegVT);
2900
2901       // Transform the arguments stored on
2902       // physical registers into virtual ones
2903       unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2904       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2905
2906       ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2907
2908       // Handle floating point arguments passed in integer registers and
2909       // long double arguments passed in floating point registers.
2910       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2911           (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2912           (RegVT == MVT::f64 && ValVT == MVT::i64))
2913         ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2914       else if (ABI.IsO32() && RegVT == MVT::i32 &&
2915                ValVT == MVT::f64) {
2916         unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2917                                   getNextIntArgReg(ArgReg), RC);
2918         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2919         if (!Subtarget.isLittle())
2920           std::swap(ArgValue, ArgValue2);
2921         ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2922                                ArgValue, ArgValue2);
2923       }
2924
2925       InVals.push_back(ArgValue);
2926     } else { // VA.isRegLoc()
2927       MVT LocVT = VA.getLocVT();
2928
2929       if (ABI.IsO32()) {
2930         // We ought to be able to use LocVT directly but O32 sets it to i32
2931         // when allocating floating point values to integer registers.
2932         // This shouldn't influence how we load the value into registers unless
2933         // we are targetting softfloat.
2934         if (VA.getValVT().isFloatingPoint() && !Subtarget.abiUsesSoftFloat())
2935           LocVT = VA.getValVT();
2936       }
2937
2938       // sanity check
2939       assert(VA.isMemLoc());
2940
2941       // The stack pointer offset is relative to the caller stack frame.
2942       int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
2943                                       VA.getLocMemOffset(), true);
2944
2945       // Create load nodes to retrieve arguments from the stack
2946       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2947       SDValue ArgValue = DAG.getLoad(LocVT, DL, Chain, FIN,
2948                                      MachinePointerInfo::getFixedStack(FI),
2949                                      false, false, false, 0);
2950       OutChains.push_back(ArgValue.getValue(1));
2951
2952       ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2953
2954       InVals.push_back(ArgValue);
2955     }
2956   }
2957
2958   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2959     // The mips ABIs for returning structs by value requires that we copy
2960     // the sret argument into $v0 for the return. Save the argument into
2961     // a virtual register so that we can access it from the return points.
2962     if (Ins[i].Flags.isSRet()) {
2963       unsigned Reg = MipsFI->getSRetReturnReg();
2964       if (!Reg) {
2965         Reg = MF.getRegInfo().createVirtualRegister(
2966             getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
2967         MipsFI->setSRetReturnReg(Reg);
2968       }
2969       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
2970       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2971       break;
2972     }
2973   }
2974
2975   if (IsVarArg)
2976     writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
2977
2978   // All stores are grouped in one node to allow the matching between
2979   // the size of Ins and InVals. This only happens when on varg functions
2980   if (!OutChains.empty()) {
2981     OutChains.push_back(Chain);
2982     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2983   }
2984
2985   return Chain;
2986 }
2987
2988 //===----------------------------------------------------------------------===//
2989 //               Return Value Calling Convention Implementation
2990 //===----------------------------------------------------------------------===//
2991
2992 bool
2993 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2994                                    MachineFunction &MF, bool IsVarArg,
2995                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
2996                                    LLVMContext &Context) const {
2997   SmallVector<CCValAssign, 16> RVLocs;
2998   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
2999   return CCInfo.CheckReturn(Outs, RetCC_Mips);
3000 }
3001
3002 SDValue
3003 MipsTargetLowering::LowerReturn(SDValue Chain,
3004                                 CallingConv::ID CallConv, bool IsVarArg,
3005                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
3006                                 const SmallVectorImpl<SDValue> &OutVals,
3007                                 SDLoc DL, SelectionDAG &DAG) const {
3008   // CCValAssign - represent the assignment of
3009   // the return value to a location
3010   SmallVector<CCValAssign, 16> RVLocs;
3011   MachineFunction &MF = DAG.getMachineFunction();
3012
3013   // CCState - Info about the registers and stack slot.
3014   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3015
3016   // Analyze return values.
3017   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3018
3019   SDValue Flag;
3020   SmallVector<SDValue, 4> RetOps(1, Chain);
3021
3022   // Copy the result values into the output registers.
3023   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3024     SDValue Val = OutVals[i];
3025     CCValAssign &VA = RVLocs[i];
3026     assert(VA.isRegLoc() && "Can only return in registers!");
3027     bool UseUpperBits = false;
3028
3029     switch (VA.getLocInfo()) {
3030     default:
3031       llvm_unreachable("Unknown loc info!");
3032     case CCValAssign::Full:
3033       break;
3034     case CCValAssign::BCvt:
3035       Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3036       break;
3037     case CCValAssign::AExtUpper:
3038       UseUpperBits = true;
3039       // Fallthrough
3040     case CCValAssign::AExt:
3041       Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3042       break;
3043     case CCValAssign::ZExtUpper:
3044       UseUpperBits = true;
3045       // Fallthrough
3046     case CCValAssign::ZExt:
3047       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3048       break;
3049     case CCValAssign::SExtUpper:
3050       UseUpperBits = true;
3051       // Fallthrough
3052     case CCValAssign::SExt:
3053       Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3054       break;
3055     }
3056
3057     if (UseUpperBits) {
3058       unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3059       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3060       Val = DAG.getNode(
3061           ISD::SHL, DL, VA.getLocVT(), Val,
3062           DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3063     }
3064
3065     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3066
3067     // Guarantee that all emitted copies are stuck together with flags.
3068     Flag = Chain.getValue(1);
3069     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3070   }
3071
3072   // The mips ABIs for returning structs by value requires that we copy
3073   // the sret argument into $v0 for the return. We saved the argument into
3074   // a virtual register in the entry block, so now we copy the value out
3075   // and into $v0.
3076   if (MF.getFunction()->hasStructRetAttr()) {
3077     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3078     unsigned Reg = MipsFI->getSRetReturnReg();
3079
3080     if (!Reg)
3081       llvm_unreachable("sret virtual register not created in the entry block");
3082     SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3083     unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3084
3085     Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3086     Flag = Chain.getValue(1);
3087     RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3088   }
3089
3090   RetOps[0] = Chain;  // Update chain.
3091
3092   // Add the flag if we have it.
3093   if (Flag.getNode())
3094     RetOps.push_back(Flag);
3095
3096   // Return on Mips is always a "jr $ra"
3097   return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3098 }
3099
3100 //===----------------------------------------------------------------------===//
3101 //                           Mips Inline Assembly Support
3102 //===----------------------------------------------------------------------===//
3103
3104 /// getConstraintType - Given a constraint letter, return the type of
3105 /// constraint it is for this target.
3106 MipsTargetLowering::ConstraintType MipsTargetLowering::
3107 getConstraintType(const std::string &Constraint) const
3108 {
3109   // Mips specific constraints
3110   // GCC config/mips/constraints.md
3111   //
3112   // 'd' : An address register. Equivalent to r
3113   //       unless generating MIPS16 code.
3114   // 'y' : Equivalent to r; retained for
3115   //       backwards compatibility.
3116   // 'c' : A register suitable for use in an indirect
3117   //       jump. This will always be $25 for -mabicalls.
3118   // 'l' : The lo register. 1 word storage.
3119   // 'x' : The hilo register pair. Double word storage.
3120   if (Constraint.size() == 1) {
3121     switch (Constraint[0]) {
3122       default : break;
3123       case 'd':
3124       case 'y':
3125       case 'f':
3126       case 'c':
3127       case 'l':
3128       case 'x':
3129         return C_RegisterClass;
3130       case 'R':
3131         return C_Memory;
3132     }
3133   }
3134   return TargetLowering::getConstraintType(Constraint);
3135 }
3136
3137 /// Examine constraint type and operand type and determine a weight value.
3138 /// This object must already have been set up with the operand type
3139 /// and the current alternative constraint selected.
3140 TargetLowering::ConstraintWeight
3141 MipsTargetLowering::getSingleConstraintMatchWeight(
3142     AsmOperandInfo &info, const char *constraint) const {
3143   ConstraintWeight weight = CW_Invalid;
3144   Value *CallOperandVal = info.CallOperandVal;
3145     // If we don't have a value, we can't do a match,
3146     // but allow it at the lowest weight.
3147   if (!CallOperandVal)
3148     return CW_Default;
3149   Type *type = CallOperandVal->getType();
3150   // Look at the constraint type.
3151   switch (*constraint) {
3152   default:
3153     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3154     break;
3155   case 'd':
3156   case 'y':
3157     if (type->isIntegerTy())
3158       weight = CW_Register;
3159     break;
3160   case 'f': // FPU or MSA register
3161     if (Subtarget.hasMSA() && type->isVectorTy() &&
3162         cast<VectorType>(type)->getBitWidth() == 128)
3163       weight = CW_Register;
3164     else if (type->isFloatTy())
3165       weight = CW_Register;
3166     break;
3167   case 'c': // $25 for indirect jumps
3168   case 'l': // lo register
3169   case 'x': // hilo register pair
3170     if (type->isIntegerTy())
3171       weight = CW_SpecificReg;
3172     break;
3173   case 'I': // signed 16 bit immediate
3174   case 'J': // integer zero
3175   case 'K': // unsigned 16 bit immediate
3176   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3177   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3178   case 'O': // signed 15 bit immediate (+- 16383)
3179   case 'P': // immediate in the range of 65535 to 1 (inclusive)
3180     if (isa<ConstantInt>(CallOperandVal))
3181       weight = CW_Constant;
3182     break;
3183   case 'R':
3184     weight = CW_Memory;
3185     break;
3186   }
3187   return weight;
3188 }
3189
3190 /// This is a helper function to parse a physical register string and split it
3191 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3192 /// that is returned indicates whether parsing was successful. The second flag
3193 /// is true if the numeric part exists.
3194 static std::pair<bool, bool>
3195 parsePhysicalReg(StringRef C, std::string &Prefix,
3196                  unsigned long long &Reg) {
3197   if (C.front() != '{' || C.back() != '}')
3198     return std::make_pair(false, false);
3199
3200   // Search for the first numeric character.
3201   StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3202   I = std::find_if(B, E, std::ptr_fun(isdigit));
3203
3204   Prefix.assign(B, I - B);
3205
3206   // The second flag is set to false if no numeric characters were found.
3207   if (I == E)
3208     return std::make_pair(true, false);
3209
3210   // Parse the numeric characters.
3211   return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3212                         true);
3213 }
3214
3215 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3216 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3217   const TargetRegisterInfo *TRI =
3218       Subtarget.getRegisterInfo();
3219   const TargetRegisterClass *RC;
3220   std::string Prefix;
3221   unsigned long long Reg;
3222
3223   std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3224
3225   if (!R.first)
3226     return std::make_pair(0U, nullptr);
3227
3228   if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3229     // No numeric characters follow "hi" or "lo".
3230     if (R.second)
3231       return std::make_pair(0U, nullptr);
3232
3233     RC = TRI->getRegClass(Prefix == "hi" ?
3234                           Mips::HI32RegClassID : Mips::LO32RegClassID);
3235     return std::make_pair(*(RC->begin()), RC);
3236   } else if (Prefix.compare(0, 4, "$msa") == 0) {
3237     // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3238
3239     // No numeric characters follow the name.
3240     if (R.second)
3241       return std::make_pair(0U, nullptr);
3242
3243     Reg = StringSwitch<unsigned long long>(Prefix)
3244               .Case("$msair", Mips::MSAIR)
3245               .Case("$msacsr", Mips::MSACSR)
3246               .Case("$msaaccess", Mips::MSAAccess)
3247               .Case("$msasave", Mips::MSASave)
3248               .Case("$msamodify", Mips::MSAModify)
3249               .Case("$msarequest", Mips::MSARequest)
3250               .Case("$msamap", Mips::MSAMap)
3251               .Case("$msaunmap", Mips::MSAUnmap)
3252               .Default(0);
3253
3254     if (!Reg)
3255       return std::make_pair(0U, nullptr);
3256
3257     RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3258     return std::make_pair(Reg, RC);
3259   }
3260
3261   if (!R.second)
3262     return std::make_pair(0U, nullptr);
3263
3264   if (Prefix == "$f") { // Parse $f0-$f31.
3265     // If the size of FP registers is 64-bit or Reg is an even number, select
3266     // the 64-bit register class. Otherwise, select the 32-bit register class.
3267     if (VT == MVT::Other)
3268       VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3269
3270     RC = getRegClassFor(VT);
3271
3272     if (RC == &Mips::AFGR64RegClass) {
3273       assert(Reg % 2 == 0);
3274       Reg >>= 1;
3275     }
3276   } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3277     RC = TRI->getRegClass(Mips::FCCRegClassID);
3278   else if (Prefix == "$w") { // Parse $w0-$w31.
3279     RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3280   } else { // Parse $0-$31.
3281     assert(Prefix == "$");
3282     RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3283   }
3284
3285   assert(Reg < RC->getNumRegs());
3286   return std::make_pair(*(RC->begin() + Reg), RC);
3287 }
3288
3289 /// Given a register class constraint, like 'r', if this corresponds directly
3290 /// to an LLVM register class, return a register of 0 and the register class
3291 /// pointer.
3292 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3293 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3294 {
3295   if (Constraint.size() == 1) {
3296     switch (Constraint[0]) {
3297     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3298     case 'y': // Same as 'r'. Exists for compatibility.
3299     case 'r':
3300       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3301         if (Subtarget.inMips16Mode())
3302           return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3303         return std::make_pair(0U, &Mips::GPR32RegClass);
3304       }
3305       if (VT == MVT::i64 && !Subtarget.isGP64bit())
3306         return std::make_pair(0U, &Mips::GPR32RegClass);
3307       if (VT == MVT::i64 && Subtarget.isGP64bit())
3308         return std::make_pair(0U, &Mips::GPR64RegClass);
3309       // This will generate an error message
3310       return std::make_pair(0U, nullptr);
3311     case 'f': // FPU or MSA register
3312       if (VT == MVT::v16i8)
3313         return std::make_pair(0U, &Mips::MSA128BRegClass);
3314       else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3315         return std::make_pair(0U, &Mips::MSA128HRegClass);
3316       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3317         return std::make_pair(0U, &Mips::MSA128WRegClass);
3318       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3319         return std::make_pair(0U, &Mips::MSA128DRegClass);
3320       else if (VT == MVT::f32)
3321         return std::make_pair(0U, &Mips::FGR32RegClass);
3322       else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3323         if (Subtarget.isFP64bit())
3324           return std::make_pair(0U, &Mips::FGR64RegClass);
3325         return std::make_pair(0U, &Mips::AFGR64RegClass);
3326       }
3327       break;
3328     case 'c': // register suitable for indirect jump
3329       if (VT == MVT::i32)
3330         return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3331       assert(VT == MVT::i64 && "Unexpected type.");
3332       return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3333     case 'l': // register suitable for indirect jump
3334       if (VT == MVT::i32)
3335         return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3336       return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3337     case 'x': // register suitable for indirect jump
3338       // Fixme: Not triggering the use of both hi and low
3339       // This will generate an error message
3340       return std::make_pair(0U, nullptr);
3341     }
3342   }
3343
3344   std::pair<unsigned, const TargetRegisterClass *> R;
3345   R = parseRegForInlineAsmConstraint(Constraint, VT);
3346
3347   if (R.second)
3348     return R;
3349
3350   return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3351 }
3352
3353 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3354 /// vector.  If it is invalid, don't add anything to Ops.
3355 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3356                                                      std::string &Constraint,
3357                                                      std::vector<SDValue>&Ops,
3358                                                      SelectionDAG &DAG) const {
3359   SDValue Result;
3360
3361   // Only support length 1 constraints for now.
3362   if (Constraint.length() > 1) return;
3363
3364   char ConstraintLetter = Constraint[0];
3365   switch (ConstraintLetter) {
3366   default: break; // This will fall through to the generic implementation
3367   case 'I': // Signed 16 bit constant
3368     // If this fails, the parent routine will give an error
3369     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3370       EVT Type = Op.getValueType();
3371       int64_t Val = C->getSExtValue();
3372       if (isInt<16>(Val)) {
3373         Result = DAG.getTargetConstant(Val, Type);
3374         break;
3375       }
3376     }
3377     return;
3378   case 'J': // integer zero
3379     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3380       EVT Type = Op.getValueType();
3381       int64_t Val = C->getZExtValue();
3382       if (Val == 0) {
3383         Result = DAG.getTargetConstant(0, Type);
3384         break;
3385       }
3386     }
3387     return;
3388   case 'K': // unsigned 16 bit immediate
3389     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3390       EVT Type = Op.getValueType();
3391       uint64_t Val = (uint64_t)C->getZExtValue();
3392       if (isUInt<16>(Val)) {
3393         Result = DAG.getTargetConstant(Val, Type);
3394         break;
3395       }
3396     }
3397     return;
3398   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3399     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3400       EVT Type = Op.getValueType();
3401       int64_t Val = C->getSExtValue();
3402       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3403         Result = DAG.getTargetConstant(Val, Type);
3404         break;
3405       }
3406     }
3407     return;
3408   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3409     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3410       EVT Type = Op.getValueType();
3411       int64_t Val = C->getSExtValue();
3412       if ((Val >= -65535) && (Val <= -1)) {
3413         Result = DAG.getTargetConstant(Val, Type);
3414         break;
3415       }
3416     }
3417     return;
3418   case 'O': // signed 15 bit immediate
3419     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3420       EVT Type = Op.getValueType();
3421       int64_t Val = C->getSExtValue();
3422       if ((isInt<15>(Val))) {
3423         Result = DAG.getTargetConstant(Val, Type);
3424         break;
3425       }
3426     }
3427     return;
3428   case 'P': // immediate in the range of 1 to 65535 (inclusive)
3429     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3430       EVT Type = Op.getValueType();
3431       int64_t Val = C->getSExtValue();
3432       if ((Val <= 65535) && (Val >= 1)) {
3433         Result = DAG.getTargetConstant(Val, Type);
3434         break;
3435       }
3436     }
3437     return;
3438   }
3439
3440   if (Result.getNode()) {
3441     Ops.push_back(Result);
3442     return;
3443   }
3444
3445   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3446 }
3447
3448 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3449                                                Type *Ty) const {
3450   // No global is ever allowed as a base.
3451   if (AM.BaseGV)
3452     return false;
3453
3454   switch (AM.Scale) {
3455   case 0: // "r+i" or just "i", depending on HasBaseReg.
3456     break;
3457   case 1:
3458     if (!AM.HasBaseReg) // allow "r+i".
3459       break;
3460     return false; // disallow "r+r" or "r+r+i".
3461   default:
3462     return false;
3463   }
3464
3465   return true;
3466 }
3467
3468 bool
3469 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3470   // The Mips target isn't yet aware of offsets.
3471   return false;
3472 }
3473
3474 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3475                                             unsigned SrcAlign,
3476                                             bool IsMemset, bool ZeroMemset,
3477                                             bool MemcpyStrSrc,
3478                                             MachineFunction &MF) const {
3479   if (Subtarget.hasMips64())
3480     return MVT::i64;
3481
3482   return MVT::i32;
3483 }
3484
3485 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3486   if (VT != MVT::f32 && VT != MVT::f64)
3487     return false;
3488   if (Imm.isNegZero())
3489     return false;
3490   return Imm.isZero();
3491 }
3492
3493 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3494   if (ABI.IsN64())
3495     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3496
3497   return TargetLowering::getJumpTableEncoding();
3498 }
3499
3500 void MipsTargetLowering::copyByValRegs(
3501     SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3502     const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3503     const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3504     const CCValAssign &VA, MipsCCState &State) const {
3505   MachineFunction &MF = DAG.getMachineFunction();
3506   MachineFrameInfo *MFI = MF.getFrameInfo();
3507   unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3508   unsigned NumRegs = LastReg - FirstReg;
3509   unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3510   unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3511   int FrameObjOffset;
3512   ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3513
3514   if (RegAreaSize)
3515     FrameObjOffset =
3516         (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3517         (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3518   else
3519     FrameObjOffset = VA.getLocMemOffset();
3520
3521   // Create frame object.
3522   EVT PtrTy = getPointerTy();
3523   int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3524   SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3525   InVals.push_back(FIN);
3526
3527   if (!NumRegs)
3528     return;
3529
3530   // Copy arg registers.
3531   MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3532   const TargetRegisterClass *RC = getRegClassFor(RegTy);
3533
3534   for (unsigned I = 0; I < NumRegs; ++I) {
3535     unsigned ArgReg = ByValArgRegs[FirstReg + I];
3536     unsigned VReg = addLiveIn(MF, ArgReg, RC);
3537     unsigned Offset = I * GPRSizeInBytes;
3538     SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3539                                    DAG.getConstant(Offset, PtrTy));
3540     SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3541                                  StorePtr, MachinePointerInfo(FuncArg, Offset),
3542                                  false, false, 0);
3543     OutChains.push_back(Store);
3544   }
3545 }
3546
3547 // Copy byVal arg to registers and stack.
3548 void MipsTargetLowering::passByValArg(
3549     SDValue Chain, SDLoc DL,
3550     std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3551     SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3552     MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3553     unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3554     const CCValAssign &VA) const {
3555   unsigned ByValSizeInBytes = Flags.getByValSize();
3556   unsigned OffsetInBytes = 0; // From beginning of struct
3557   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3558   unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3559   EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3560   unsigned NumRegs = LastReg - FirstReg;
3561
3562   if (NumRegs) {
3563     const ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
3564     bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3565     unsigned I = 0;
3566
3567     // Copy words to registers.
3568     for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3569       SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3570                                     DAG.getConstant(OffsetInBytes, PtrTy));
3571       SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3572                                     MachinePointerInfo(), false, false, false,
3573                                     Alignment);
3574       MemOpChains.push_back(LoadVal.getValue(1));
3575       unsigned ArgReg = ArgRegs[FirstReg + I];
3576       RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3577     }
3578
3579     // Return if the struct has been fully copied.
3580     if (ByValSizeInBytes == OffsetInBytes)
3581       return;
3582
3583     // Copy the remainder of the byval argument with sub-word loads and shifts.
3584     if (LeftoverBytes) {
3585       SDValue Val;
3586
3587       for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3588            OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3589         unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3590
3591         if (RemainingSizeInBytes < LoadSizeInBytes)
3592           continue;
3593
3594         // Load subword.
3595         SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3596                                       DAG.getConstant(OffsetInBytes, PtrTy));
3597         SDValue LoadVal = DAG.getExtLoad(
3598             ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3599             MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3600             Alignment);
3601         MemOpChains.push_back(LoadVal.getValue(1));
3602
3603         // Shift the loaded value.
3604         unsigned Shamt;
3605
3606         if (isLittle)
3607           Shamt = TotalBytesLoaded * 8;
3608         else
3609           Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3610
3611         SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3612                                     DAG.getConstant(Shamt, MVT::i32));
3613
3614         if (Val.getNode())
3615           Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3616         else
3617           Val = Shift;
3618
3619         OffsetInBytes += LoadSizeInBytes;
3620         TotalBytesLoaded += LoadSizeInBytes;
3621         Alignment = std::min(Alignment, LoadSizeInBytes);
3622       }
3623
3624       unsigned ArgReg = ArgRegs[FirstReg + I];
3625       RegsToPass.push_back(std::make_pair(ArgReg, Val));
3626       return;
3627     }
3628   }
3629
3630   // Copy remainder of byval arg to it with memcpy.
3631   unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3632   SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3633                             DAG.getConstant(OffsetInBytes, PtrTy));
3634   SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3635                             DAG.getIntPtrConstant(VA.getLocMemOffset()));
3636   Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3637                         Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3638                         MachinePointerInfo(), MachinePointerInfo());
3639   MemOpChains.push_back(Chain);
3640 }
3641
3642 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3643                                          SDValue Chain, SDLoc DL,
3644                                          SelectionDAG &DAG,
3645                                          CCState &State) const {
3646   const ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
3647   unsigned Idx = State.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3648   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3649   MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3650   const TargetRegisterClass *RC = getRegClassFor(RegTy);
3651   MachineFunction &MF = DAG.getMachineFunction();
3652   MachineFrameInfo *MFI = MF.getFrameInfo();
3653   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3654
3655   // Offset of the first variable argument from stack pointer.
3656   int VaArgOffset;
3657
3658   if (ArgRegs.size() == Idx)
3659     VaArgOffset =
3660         RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3661   else {
3662     VaArgOffset =
3663         (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3664         (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3665   }
3666
3667   // Record the frame index of the first variable argument
3668   // which is a value necessary to VASTART.
3669   int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3670   MipsFI->setVarArgsFrameIndex(FI);
3671
3672   // Copy the integer registers that have not been used for argument passing
3673   // to the argument register save area. For O32, the save area is allocated
3674   // in the caller's stack frame, while for N32/64, it is allocated in the
3675   // callee's stack frame.
3676   for (unsigned I = Idx; I < ArgRegs.size();
3677        ++I, VaArgOffset += RegSizeInBytes) {
3678     unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3679     SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3680     FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3681     SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3682     SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3683                                  MachinePointerInfo(), false, false, 0);
3684     cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3685         (Value *)nullptr);
3686     OutChains.push_back(Store);
3687   }
3688 }
3689
3690 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3691                                      unsigned Align) const {
3692   const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3693
3694   assert(Size && "Byval argument's size shouldn't be 0.");
3695
3696   Align = std::min(Align, TFL->getStackAlignment());
3697
3698   unsigned FirstReg = 0;
3699   unsigned NumRegs = 0;
3700
3701   if (State->getCallingConv() != CallingConv::Fast) {
3702     unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3703     const ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
3704     // FIXME: The O32 case actually describes no shadow registers.
3705     const MCPhysReg *ShadowRegs =
3706         ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
3707
3708     // We used to check the size as well but we can't do that anymore since
3709     // CCState::HandleByVal() rounds up the size after calling this function.
3710     assert(!(Align % RegSizeInBytes) &&
3711            "Byval argument's alignment should be a multiple of"
3712            "RegSizeInBytes.");
3713
3714     FirstReg = State->getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3715
3716     // If Align > RegSizeInBytes, the first arg register must be even.
3717     // FIXME: This condition happens to do the right thing but it's not the
3718     //        right way to test it. We want to check that the stack frame offset
3719     //        of the register is aligned.
3720     if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3721       State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3722       ++FirstReg;
3723     }
3724
3725     // Mark the registers allocated.
3726     Size = RoundUpToAlignment(Size, RegSizeInBytes);
3727     for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3728          Size -= RegSizeInBytes, ++I, ++NumRegs)
3729       State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3730   }
3731
3732   State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3733 }
3734
3735 MachineBasicBlock *
3736 MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3737                                      bool isFPCmp, unsigned Opc) const {
3738   assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3739          "Subtarget already supports SELECT nodes with the use of"
3740          "conditional-move instructions.");
3741
3742   const TargetInstrInfo *TII =
3743       Subtarget.getInstrInfo();
3744   DebugLoc DL = MI->getDebugLoc();
3745
3746   // To "insert" a SELECT instruction, we actually have to insert the
3747   // diamond control-flow pattern.  The incoming instruction knows the
3748   // destination vreg to set, the condition code register to branch on, the
3749   // true/false values to select between, and a branch opcode to use.
3750   const BasicBlock *LLVM_BB = BB->getBasicBlock();
3751   MachineFunction::iterator It = BB;
3752   ++It;
3753
3754   //  thisMBB:
3755   //  ...
3756   //   TrueVal = ...
3757   //   setcc r1, r2, r3
3758   //   bNE   r1, r0, copy1MBB
3759   //   fallthrough --> copy0MBB
3760   MachineBasicBlock *thisMBB  = BB;
3761   MachineFunction *F = BB->getParent();
3762   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3763   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
3764   F->insert(It, copy0MBB);
3765   F->insert(It, sinkMBB);
3766
3767   // Transfer the remainder of BB and its successor edges to sinkMBB.
3768   sinkMBB->splice(sinkMBB->begin(), BB,
3769                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
3770   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3771
3772   // Next, add the true and fallthrough blocks as its successors.
3773   BB->addSuccessor(copy0MBB);
3774   BB->addSuccessor(sinkMBB);
3775
3776   if (isFPCmp) {
3777     // bc1[tf] cc, sinkMBB
3778     BuildMI(BB, DL, TII->get(Opc))
3779       .addReg(MI->getOperand(1).getReg())
3780       .addMBB(sinkMBB);
3781   } else {
3782     // bne rs, $0, sinkMBB
3783     BuildMI(BB, DL, TII->get(Opc))
3784       .addReg(MI->getOperand(1).getReg())
3785       .addReg(Mips::ZERO)
3786       .addMBB(sinkMBB);
3787   }
3788
3789   //  copy0MBB:
3790   //   %FalseValue = ...
3791   //   # fallthrough to sinkMBB
3792   BB = copy0MBB;
3793
3794   // Update machine-CFG edges
3795   BB->addSuccessor(sinkMBB);
3796
3797   //  sinkMBB:
3798   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3799   //  ...
3800   BB = sinkMBB;
3801
3802   BuildMI(*BB, BB->begin(), DL,
3803           TII->get(Mips::PHI), MI->getOperand(0).getReg())
3804     .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3805     .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3806
3807   MI->eraseFromParent();   // The pseudo instruction is gone now.
3808
3809   return BB;
3810 }
3811
3812 // FIXME? Maybe this could be a TableGen attribute on some registers and
3813 // this table could be generated automatically from RegInfo.
3814 unsigned MipsTargetLowering::getRegisterByName(const char* RegName,
3815                                                EVT VT) const {
3816   // Named registers is expected to be fairly rare. For now, just support $28
3817   // since the linux kernel uses it.
3818   if (Subtarget.isGP64bit()) {
3819     unsigned Reg = StringSwitch<unsigned>(RegName)
3820                          .Case("$28", Mips::GP_64)
3821                          .Default(0);
3822     if (Reg)
3823       return Reg;
3824   } else {
3825     unsigned Reg = StringSwitch<unsigned>(RegName)
3826                          .Case("$28", Mips::GP)
3827                          .Default(0);
3828     if (Reg)
3829       return Reg;
3830   }
3831   report_fatal_error("Invalid register name global variable");
3832 }