1 //===- MipsISelLowering.cpp - Mips DAG Lowering Implementation ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines the interfaces that Mips uses to lower LLVM code into a
10 // selection DAG.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "MipsISelLowering.h"
15 #include "MCTargetDesc/MipsBaseInfo.h"
16 #include "MCTargetDesc/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsMCTargetDesc.h"
18 #include "MipsCCState.h"
19 #include "MipsInstrInfo.h"
20 #include "MipsMachineFunction.h"
21 #include "MipsRegisterInfo.h"
22 #include "MipsSubtarget.h"
23 #include "MipsTargetMachine.h"
24 #include "MipsTargetObjectFile.h"
25 #include "llvm/ADT/APFloat.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/SmallVector.h"
28 #include "llvm/ADT/Statistic.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/StringSwitch.h"
31 #include "llvm/CodeGen/CallingConvLower.h"
32 #include "llvm/CodeGen/FunctionLoweringInfo.h"
33 #include "llvm/CodeGen/ISDOpcodes.h"
34 #include "llvm/CodeGen/MachineBasicBlock.h"
35 #include "llvm/CodeGen/MachineFrameInfo.h"
36 #include "llvm/CodeGen/MachineFunction.h"
37 #include "llvm/CodeGen/MachineInstr.h"
38 #include "llvm/CodeGen/MachineInstrBuilder.h"
39 #include "llvm/CodeGen/MachineJumpTableInfo.h"
40 #include "llvm/CodeGen/MachineMemOperand.h"
41 #include "llvm/CodeGen/MachineOperand.h"
42 #include "llvm/CodeGen/MachineRegisterInfo.h"
43 #include "llvm/CodeGen/RuntimeLibcalls.h"
44 #include "llvm/CodeGen/SelectionDAG.h"
45 #include "llvm/CodeGen/SelectionDAGNodes.h"
46 #include "llvm/CodeGen/TargetFrameLowering.h"
47 #include "llvm/CodeGen/TargetInstrInfo.h"
48 #include "llvm/CodeGen/TargetRegisterInfo.h"
49 #include "llvm/CodeGen/ValueTypes.h"
50 #include "llvm/IR/CallingConv.h"
51 #include "llvm/IR/Constants.h"
52 #include "llvm/IR/DataLayout.h"
53 #include "llvm/IR/DebugLoc.h"
54 #include "llvm/IR/DerivedTypes.h"
55 #include "llvm/IR/Function.h"
56 #include "llvm/IR/GlobalValue.h"
57 #include "llvm/IR/Type.h"
58 #include "llvm/IR/Value.h"
59 #include "llvm/MC/MCContext.h"
60 #include "llvm/MC/MCRegisterInfo.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/CodeGen.h"
63 #include "llvm/Support/CommandLine.h"
64 #include "llvm/Support/Compiler.h"
65 #include "llvm/Support/ErrorHandling.h"
66 #include "llvm/Support/MachineValueType.h"
67 #include "llvm/Support/MathExtras.h"
68 #include "llvm/Target/TargetMachine.h"
69 #include "llvm/Target/TargetOptions.h"
70 #include <algorithm>
71 #include <cassert>
72 #include <cctype>
73 #include <cstdint>
74 #include <deque>
75 #include <iterator>
76 #include <utility>
77 #include <vector>
78 
79 using namespace llvm;
80 
81 #define DEBUG_TYPE "mips-lower"
82 
83 STATISTIC(NumTailCalls, "Number of tail calls");
84 
85 static cl::opt<bool>
86 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
87                cl::desc("MIPS: Don't trap on integer division by zero."),
88                cl::init(false));
89 
90 extern cl::opt<bool> EmitJalrReloc;
91 
92 static const MCPhysReg Mips64DPRegs[8] = {
93   Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
94   Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
95 };
96 
97 // If I is a shifted mask, set the size (Size) and the first bit of the
98 // mask (Pos), and return true.
99 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
100 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
101   if (!isShiftedMask_64(I))
102     return false;
103 
104   Size = countPopulation(I);
105   Pos = countTrailingZeros(I);
106   return true;
107 }
108 
109 // The MIPS MSA ABI passes vector arguments in the integer register set.
110 // The number of integer registers used is dependant on the ABI used.
111 MVT MipsTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
112                                                       CallingConv::ID CC,
113                                                       EVT VT) const {
114   if (!VT.isVector())
115     return getRegisterType(Context, VT);
116 
117   return Subtarget.isABI_O32() || VT.getSizeInBits() == 32 ? MVT::i32
118                                                            : MVT::i64;
119 }
120 
121 unsigned MipsTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
122                                                            CallingConv::ID CC,
123                                                            EVT VT) const {
124   if (VT.isVector())
125     return std::max(((unsigned)VT.getSizeInBits() /
126                      (Subtarget.isABI_O32() ? 32 : 64)),
127                     1U);
128   return MipsTargetLowering::getNumRegisters(Context, VT);
129 }
130 
131 unsigned MipsTargetLowering::getVectorTypeBreakdownForCallingConv(
132     LLVMContext &Context, CallingConv::ID CC, EVT VT, EVT &IntermediateVT,
133     unsigned &NumIntermediates, MVT &RegisterVT) const {
134   // Break down vector types to either 2 i64s or 4 i32s.
135   RegisterVT = getRegisterTypeForCallingConv(Context, CC, VT);
136   IntermediateVT = RegisterVT;
137   NumIntermediates = VT.getSizeInBits() < RegisterVT.getSizeInBits()
138                          ? VT.getVectorNumElements()
139                          : VT.getSizeInBits() / RegisterVT.getSizeInBits();
140 
141   return NumIntermediates;
142 }
143 
144 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
145   MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
146   return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
147 }
148 
149 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
150                                           SelectionDAG &DAG,
151                                           unsigned Flag) const {
152   return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
153 }
154 
155 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
156                                           SelectionDAG &DAG,
157                                           unsigned Flag) const {
158   return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
159 }
160 
161 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
162                                           SelectionDAG &DAG,
163                                           unsigned Flag) const {
164   return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
165 }
166 
167 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
168                                           SelectionDAG &DAG,
169                                           unsigned Flag) const {
170   return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
171 }
172 
173 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
174                                           SelectionDAG &DAG,
175                                           unsigned Flag) const {
176   return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
177                                    N->getOffset(), Flag);
178 }
179 
180 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
181   switch ((MipsISD::NodeType)Opcode) {
182   case MipsISD::FIRST_NUMBER:      break;
183   case MipsISD::JmpLink:           return "MipsISD::JmpLink";
184   case MipsISD::TailCall:          return "MipsISD::TailCall";
185   case MipsISD::Highest:           return "MipsISD::Highest";
186   case MipsISD::Higher:            return "MipsISD::Higher";
187   case MipsISD::Hi:                return "MipsISD::Hi";
188   case MipsISD::Lo:                return "MipsISD::Lo";
189   case MipsISD::GotHi:             return "MipsISD::GotHi";
190   case MipsISD::TlsHi:             return "MipsISD::TlsHi";
191   case MipsISD::GPRel:             return "MipsISD::GPRel";
192   case MipsISD::ThreadPointer:     return "MipsISD::ThreadPointer";
193   case MipsISD::Ret:               return "MipsISD::Ret";
194   case MipsISD::ERet:              return "MipsISD::ERet";
195   case MipsISD::EH_RETURN:         return "MipsISD::EH_RETURN";
196   case MipsISD::FMS:               return "MipsISD::FMS";
197   case MipsISD::FPBrcond:          return "MipsISD::FPBrcond";
198   case MipsISD::FPCmp:             return "MipsISD::FPCmp";
199   case MipsISD::FSELECT:           return "MipsISD::FSELECT";
200   case MipsISD::MTC1_D64:          return "MipsISD::MTC1_D64";
201   case MipsISD::CMovFP_T:          return "MipsISD::CMovFP_T";
202   case MipsISD::CMovFP_F:          return "MipsISD::CMovFP_F";
203   case MipsISD::TruncIntFP:        return "MipsISD::TruncIntFP";
204   case MipsISD::MFHI:              return "MipsISD::MFHI";
205   case MipsISD::MFLO:              return "MipsISD::MFLO";
206   case MipsISD::MTLOHI:            return "MipsISD::MTLOHI";
207   case MipsISD::Mult:              return "MipsISD::Mult";
208   case MipsISD::Multu:             return "MipsISD::Multu";
209   case MipsISD::MAdd:              return "MipsISD::MAdd";
210   case MipsISD::MAddu:             return "MipsISD::MAddu";
211   case MipsISD::MSub:              return "MipsISD::MSub";
212   case MipsISD::MSubu:             return "MipsISD::MSubu";
213   case MipsISD::DivRem:            return "MipsISD::DivRem";
214   case MipsISD::DivRemU:           return "MipsISD::DivRemU";
215   case MipsISD::DivRem16:          return "MipsISD::DivRem16";
216   case MipsISD::DivRemU16:         return "MipsISD::DivRemU16";
217   case MipsISD::BuildPairF64:      return "MipsISD::BuildPairF64";
218   case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
219   case MipsISD::Wrapper:           return "MipsISD::Wrapper";
220   case MipsISD::DynAlloc:          return "MipsISD::DynAlloc";
221   case MipsISD::Sync:              return "MipsISD::Sync";
222   case MipsISD::Ext:               return "MipsISD::Ext";
223   case MipsISD::Ins:               return "MipsISD::Ins";
224   case MipsISD::CIns:              return "MipsISD::CIns";
225   case MipsISD::LWL:               return "MipsISD::LWL";
226   case MipsISD::LWR:               return "MipsISD::LWR";
227   case MipsISD::SWL:               return "MipsISD::SWL";
228   case MipsISD::SWR:               return "MipsISD::SWR";
229   case MipsISD::LDL:               return "MipsISD::LDL";
230   case MipsISD::LDR:               return "MipsISD::LDR";
231   case MipsISD::SDL:               return "MipsISD::SDL";
232   case MipsISD::SDR:               return "MipsISD::SDR";
233   case MipsISD::EXTP:              return "MipsISD::EXTP";
234   case MipsISD::EXTPDP:            return "MipsISD::EXTPDP";
235   case MipsISD::EXTR_S_H:          return "MipsISD::EXTR_S_H";
236   case MipsISD::EXTR_W:            return "MipsISD::EXTR_W";
237   case MipsISD::EXTR_R_W:          return "MipsISD::EXTR_R_W";
238   case MipsISD::EXTR_RS_W:         return "MipsISD::EXTR_RS_W";
239   case MipsISD::SHILO:             return "MipsISD::SHILO";
240   case MipsISD::MTHLIP:            return "MipsISD::MTHLIP";
241   case MipsISD::MULSAQ_S_W_PH:     return "MipsISD::MULSAQ_S_W_PH";
242   case MipsISD::MAQ_S_W_PHL:       return "MipsISD::MAQ_S_W_PHL";
243   case MipsISD::MAQ_S_W_PHR:       return "MipsISD::MAQ_S_W_PHR";
244   case MipsISD::MAQ_SA_W_PHL:      return "MipsISD::MAQ_SA_W_PHL";
245   case MipsISD::MAQ_SA_W_PHR:      return "MipsISD::MAQ_SA_W_PHR";
246   case MipsISD::DPAU_H_QBL:        return "MipsISD::DPAU_H_QBL";
247   case MipsISD::DPAU_H_QBR:        return "MipsISD::DPAU_H_QBR";
248   case MipsISD::DPSU_H_QBL:        return "MipsISD::DPSU_H_QBL";
249   case MipsISD::DPSU_H_QBR:        return "MipsISD::DPSU_H_QBR";
250   case MipsISD::DPAQ_S_W_PH:       return "MipsISD::DPAQ_S_W_PH";
251   case MipsISD::DPSQ_S_W_PH:       return "MipsISD::DPSQ_S_W_PH";
252   case MipsISD::DPAQ_SA_L_W:       return "MipsISD::DPAQ_SA_L_W";
253   case MipsISD::DPSQ_SA_L_W:       return "MipsISD::DPSQ_SA_L_W";
254   case MipsISD::DPA_W_PH:          return "MipsISD::DPA_W_PH";
255   case MipsISD::DPS_W_PH:          return "MipsISD::DPS_W_PH";
256   case MipsISD::DPAQX_S_W_PH:      return "MipsISD::DPAQX_S_W_PH";
257   case MipsISD::DPAQX_SA_W_PH:     return "MipsISD::DPAQX_SA_W_PH";
258   case MipsISD::DPAX_W_PH:         return "MipsISD::DPAX_W_PH";
259   case MipsISD::DPSX_W_PH:         return "MipsISD::DPSX_W_PH";
260   case MipsISD::DPSQX_S_W_PH:      return "MipsISD::DPSQX_S_W_PH";
261   case MipsISD::DPSQX_SA_W_PH:     return "MipsISD::DPSQX_SA_W_PH";
262   case MipsISD::MULSA_W_PH:        return "MipsISD::MULSA_W_PH";
263   case MipsISD::MULT:              return "MipsISD::MULT";
264   case MipsISD::MULTU:             return "MipsISD::MULTU";
265   case MipsISD::MADD_DSP:          return "MipsISD::MADD_DSP";
266   case MipsISD::MADDU_DSP:         return "MipsISD::MADDU_DSP";
267   case MipsISD::MSUB_DSP:          return "MipsISD::MSUB_DSP";
268   case MipsISD::MSUBU_DSP:         return "MipsISD::MSUBU_DSP";
269   case MipsISD::SHLL_DSP:          return "MipsISD::SHLL_DSP";
270   case MipsISD::SHRA_DSP:          return "MipsISD::SHRA_DSP";
271   case MipsISD::SHRL_DSP:          return "MipsISD::SHRL_DSP";
272   case MipsISD::SETCC_DSP:         return "MipsISD::SETCC_DSP";
273   case MipsISD::SELECT_CC_DSP:     return "MipsISD::SELECT_CC_DSP";
274   case MipsISD::VALL_ZERO:         return "MipsISD::VALL_ZERO";
275   case MipsISD::VANY_ZERO:         return "MipsISD::VANY_ZERO";
276   case MipsISD::VALL_NONZERO:      return "MipsISD::VALL_NONZERO";
277   case MipsISD::VANY_NONZERO:      return "MipsISD::VANY_NONZERO";
278   case MipsISD::VCEQ:              return "MipsISD::VCEQ";
279   case MipsISD::VCLE_S:            return "MipsISD::VCLE_S";
280   case MipsISD::VCLE_U:            return "MipsISD::VCLE_U";
281   case MipsISD::VCLT_S:            return "MipsISD::VCLT_S";
282   case MipsISD::VCLT_U:            return "MipsISD::VCLT_U";
283   case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
284   case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
285   case MipsISD::VNOR:              return "MipsISD::VNOR";
286   case MipsISD::VSHF:              return "MipsISD::VSHF";
287   case MipsISD::SHF:               return "MipsISD::SHF";
288   case MipsISD::ILVEV:             return "MipsISD::ILVEV";
289   case MipsISD::ILVOD:             return "MipsISD::ILVOD";
290   case MipsISD::ILVL:              return "MipsISD::ILVL";
291   case MipsISD::ILVR:              return "MipsISD::ILVR";
292   case MipsISD::PCKEV:             return "MipsISD::PCKEV";
293   case MipsISD::PCKOD:             return "MipsISD::PCKOD";
294   case MipsISD::INSVE:             return "MipsISD::INSVE";
295   }
296   return nullptr;
297 }
298 
299 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
300                                        const MipsSubtarget &STI)
301     : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
302   // Mips does not have i1 type, so use i32 for
303   // setcc operations results (slt, sgt, ...).
304   setBooleanContents(ZeroOrOneBooleanContent);
305   setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
306   // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
307   // does. Integer booleans still use 0 and 1.
308   if (Subtarget.hasMips32r6())
309     setBooleanContents(ZeroOrOneBooleanContent,
310                        ZeroOrNegativeOneBooleanContent);
311 
312   // Load extented operations for i1 types must be promoted
313   for (MVT VT : MVT::integer_valuetypes()) {
314     setLoadExtAction(ISD::EXTLOAD,  VT, MVT::i1,  Promote);
315     setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1,  Promote);
316     setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1,  Promote);
317   }
318 
319   // MIPS doesn't have extending float->double load/store.  Set LoadExtAction
320   // for f32, f16
321   for (MVT VT : MVT::fp_valuetypes()) {
322     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
323     setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
324   }
325 
326   // Set LoadExtAction for f16 vectors to Expand
327   for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
328     MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
329     if (F16VT.isValid())
330       setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
331   }
332 
333   setTruncStoreAction(MVT::f32, MVT::f16, Expand);
334   setTruncStoreAction(MVT::f64, MVT::f16, Expand);
335 
336   setTruncStoreAction(MVT::f64, MVT::f32, Expand);
337 
338   // Used by legalize types to correctly generate the setcc result.
339   // Without this, every float setcc comes with a AND/OR with the result,
340   // we don't want this, since the fpcmp result goes to a flag register,
341   // which is used implicitly by brcond and select operations.
342   AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
343 
344   // Mips Custom Operations
345   setOperationAction(ISD::BR_JT,              MVT::Other, Expand);
346   setOperationAction(ISD::GlobalAddress,      MVT::i32,   Custom);
347   setOperationAction(ISD::BlockAddress,       MVT::i32,   Custom);
348   setOperationAction(ISD::GlobalTLSAddress,   MVT::i32,   Custom);
349   setOperationAction(ISD::JumpTable,          MVT::i32,   Custom);
350   setOperationAction(ISD::ConstantPool,       MVT::i32,   Custom);
351   setOperationAction(ISD::SELECT,             MVT::f32,   Custom);
352   setOperationAction(ISD::SELECT,             MVT::f64,   Custom);
353   setOperationAction(ISD::SELECT,             MVT::i32,   Custom);
354   setOperationAction(ISD::SETCC,              MVT::f32,   Custom);
355   setOperationAction(ISD::SETCC,              MVT::f64,   Custom);
356   setOperationAction(ISD::BRCOND,             MVT::Other, Custom);
357   setOperationAction(ISD::FCOPYSIGN,          MVT::f32,   Custom);
358   setOperationAction(ISD::FCOPYSIGN,          MVT::f64,   Custom);
359   setOperationAction(ISD::FP_TO_SINT,         MVT::i32,   Custom);
360 
361   if (!(TM.Options.NoNaNsFPMath || Subtarget.inAbs2008Mode())) {
362     setOperationAction(ISD::FABS, MVT::f32, Custom);
363     setOperationAction(ISD::FABS, MVT::f64, Custom);
364   }
365 
366   if (Subtarget.isGP64bit()) {
367     setOperationAction(ISD::GlobalAddress,      MVT::i64,   Custom);
368     setOperationAction(ISD::BlockAddress,       MVT::i64,   Custom);
369     setOperationAction(ISD::GlobalTLSAddress,   MVT::i64,   Custom);
370     setOperationAction(ISD::JumpTable,          MVT::i64,   Custom);
371     setOperationAction(ISD::ConstantPool,       MVT::i64,   Custom);
372     setOperationAction(ISD::SELECT,             MVT::i64,   Custom);
373     setOperationAction(ISD::LOAD,               MVT::i64,   Custom);
374     setOperationAction(ISD::STORE,              MVT::i64,   Custom);
375     setOperationAction(ISD::FP_TO_SINT,         MVT::i64,   Custom);
376     setOperationAction(ISD::SHL_PARTS,          MVT::i64,   Custom);
377     setOperationAction(ISD::SRA_PARTS,          MVT::i64,   Custom);
378     setOperationAction(ISD::SRL_PARTS,          MVT::i64,   Custom);
379   }
380 
381   if (!Subtarget.isGP64bit()) {
382     setOperationAction(ISD::SHL_PARTS,          MVT::i32,   Custom);
383     setOperationAction(ISD::SRA_PARTS,          MVT::i32,   Custom);
384     setOperationAction(ISD::SRL_PARTS,          MVT::i32,   Custom);
385   }
386 
387   setOperationAction(ISD::EH_DWARF_CFA,         MVT::i32,   Custom);
388   if (Subtarget.isGP64bit())
389     setOperationAction(ISD::EH_DWARF_CFA,       MVT::i64,   Custom);
390 
391   setOperationAction(ISD::SDIV, MVT::i32, Expand);
392   setOperationAction(ISD::SREM, MVT::i32, Expand);
393   setOperationAction(ISD::UDIV, MVT::i32, Expand);
394   setOperationAction(ISD::UREM, MVT::i32, Expand);
395   setOperationAction(ISD::SDIV, MVT::i64, Expand);
396   setOperationAction(ISD::SREM, MVT::i64, Expand);
397   setOperationAction(ISD::UDIV, MVT::i64, Expand);
398   setOperationAction(ISD::UREM, MVT::i64, Expand);
399 
400   // Operations not directly supported by Mips.
401   setOperationAction(ISD::BR_CC,             MVT::f32,   Expand);
402   setOperationAction(ISD::BR_CC,             MVT::f64,   Expand);
403   setOperationAction(ISD::BR_CC,             MVT::i32,   Expand);
404   setOperationAction(ISD::BR_CC,             MVT::i64,   Expand);
405   setOperationAction(ISD::SELECT_CC,         MVT::i32,   Expand);
406   setOperationAction(ISD::SELECT_CC,         MVT::i64,   Expand);
407   setOperationAction(ISD::SELECT_CC,         MVT::f32,   Expand);
408   setOperationAction(ISD::SELECT_CC,         MVT::f64,   Expand);
409   setOperationAction(ISD::UINT_TO_FP,        MVT::i32,   Expand);
410   setOperationAction(ISD::UINT_TO_FP,        MVT::i64,   Expand);
411   setOperationAction(ISD::FP_TO_UINT,        MVT::i32,   Expand);
412   setOperationAction(ISD::FP_TO_UINT,        MVT::i64,   Expand);
413   setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1,    Expand);
414   if (Subtarget.hasCnMips()) {
415     setOperationAction(ISD::CTPOP,           MVT::i32,   Legal);
416     setOperationAction(ISD::CTPOP,           MVT::i64,   Legal);
417   } else {
418     setOperationAction(ISD::CTPOP,           MVT::i32,   Expand);
419     setOperationAction(ISD::CTPOP,           MVT::i64,   Expand);
420   }
421   setOperationAction(ISD::CTTZ,              MVT::i32,   Expand);
422   setOperationAction(ISD::CTTZ,              MVT::i64,   Expand);
423   setOperationAction(ISD::ROTL,              MVT::i32,   Expand);
424   setOperationAction(ISD::ROTL,              MVT::i64,   Expand);
425   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32,  Expand);
426   setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64,  Expand);
427 
428   if (!Subtarget.hasMips32r2())
429     setOperationAction(ISD::ROTR, MVT::i32,   Expand);
430 
431   if (!Subtarget.hasMips64r2())
432     setOperationAction(ISD::ROTR, MVT::i64,   Expand);
433 
434   setOperationAction(ISD::FSIN,              MVT::f32,   Expand);
435   setOperationAction(ISD::FSIN,              MVT::f64,   Expand);
436   setOperationAction(ISD::FCOS,              MVT::f32,   Expand);
437   setOperationAction(ISD::FCOS,              MVT::f64,   Expand);
438   setOperationAction(ISD::FSINCOS,           MVT::f32,   Expand);
439   setOperationAction(ISD::FSINCOS,           MVT::f64,   Expand);
440   setOperationAction(ISD::FPOW,              MVT::f32,   Expand);
441   setOperationAction(ISD::FPOW,              MVT::f64,   Expand);
442   setOperationAction(ISD::FLOG,              MVT::f32,   Expand);
443   setOperationAction(ISD::FLOG2,             MVT::f32,   Expand);
444   setOperationAction(ISD::FLOG10,            MVT::f32,   Expand);
445   setOperationAction(ISD::FEXP,              MVT::f32,   Expand);
446   setOperationAction(ISD::FMA,               MVT::f32,   Expand);
447   setOperationAction(ISD::FMA,               MVT::f64,   Expand);
448   setOperationAction(ISD::FREM,              MVT::f32,   Expand);
449   setOperationAction(ISD::FREM,              MVT::f64,   Expand);
450 
451   // Lower f16 conversion operations into library calls
452   setOperationAction(ISD::FP16_TO_FP,        MVT::f32,   Expand);
453   setOperationAction(ISD::FP_TO_FP16,        MVT::f32,   Expand);
454   setOperationAction(ISD::FP16_TO_FP,        MVT::f64,   Expand);
455   setOperationAction(ISD::FP_TO_FP16,        MVT::f64,   Expand);
456 
457   setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
458 
459   setOperationAction(ISD::VASTART,           MVT::Other, Custom);
460   setOperationAction(ISD::VAARG,             MVT::Other, Custom);
461   setOperationAction(ISD::VACOPY,            MVT::Other, Expand);
462   setOperationAction(ISD::VAEND,             MVT::Other, Expand);
463 
464   // Use the default for now
465   setOperationAction(ISD::STACKSAVE,         MVT::Other, Expand);
466   setOperationAction(ISD::STACKRESTORE,      MVT::Other, Expand);
467 
468   if (!Subtarget.isGP64bit()) {
469     setOperationAction(ISD::ATOMIC_LOAD,     MVT::i64,   Expand);
470     setOperationAction(ISD::ATOMIC_STORE,    MVT::i64,   Expand);
471   }
472 
473   if (!Subtarget.hasMips32r2()) {
474     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8,  Expand);
475     setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
476   }
477 
478   // MIPS16 lacks MIPS32's clz and clo instructions.
479   if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
480     setOperationAction(ISD::CTLZ, MVT::i32, Expand);
481   if (!Subtarget.hasMips64())
482     setOperationAction(ISD::CTLZ, MVT::i64, Expand);
483 
484   if (!Subtarget.hasMips32r2())
485     setOperationAction(ISD::BSWAP, MVT::i32, Expand);
486   if (!Subtarget.hasMips64r2())
487     setOperationAction(ISD::BSWAP, MVT::i64, Expand);
488 
489   if (Subtarget.isGP64bit()) {
490     setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
491     setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
492     setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
493     setTruncStoreAction(MVT::i64, MVT::i32, Custom);
494   }
495 
496   setOperationAction(ISD::TRAP, MVT::Other, Legal);
497 
498   setTargetDAGCombine(ISD::SDIVREM);
499   setTargetDAGCombine(ISD::UDIVREM);
500   setTargetDAGCombine(ISD::SELECT);
501   setTargetDAGCombine(ISD::AND);
502   setTargetDAGCombine(ISD::OR);
503   setTargetDAGCombine(ISD::ADD);
504   setTargetDAGCombine(ISD::SUB);
505   setTargetDAGCombine(ISD::AssertZext);
506   setTargetDAGCombine(ISD::SHL);
507 
508   if (ABI.IsO32()) {
509     // These libcalls are not available in 32-bit.
510     setLibcallName(RTLIB::SHL_I128, nullptr);
511     setLibcallName(RTLIB::SRL_I128, nullptr);
512     setLibcallName(RTLIB::SRA_I128, nullptr);
513   }
514 
515   setMinFunctionAlignment(Subtarget.isGP64bit() ? Align(8) : Align(4));
516 
517   // The arguments on the stack are defined in terms of 4-byte slots on O32
518   // and 8-byte slots on N32/N64.
519   setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? Align(8)
520                                                             : Align(4));
521 
522   setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
523 
524   MaxStoresPerMemcpy = 16;
525 
526   isMicroMips = Subtarget.inMicroMipsMode();
527 }
528 
529 const MipsTargetLowering *
530 MipsTargetLowering::create(const MipsTargetMachine &TM,
531                            const MipsSubtarget &STI) {
532   if (STI.inMips16Mode())
533     return createMips16TargetLowering(TM, STI);
534 
535   return createMipsSETargetLowering(TM, STI);
536 }
537 
538 // Create a fast isel object.
539 FastISel *
540 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
541                                   const TargetLibraryInfo *libInfo) const {
542   const MipsTargetMachine &TM =
543       static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
544 
545   // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
546   bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
547                      !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() &&
548                      !Subtarget.inMicroMipsMode();
549 
550   // Disable if either of the following is true:
551   // We do not generate PIC, the ABI is not O32, XGOT is being used.
552   if (!TM.isPositionIndependent() || !TM.getABI().IsO32() ||
553       Subtarget.useXGOT())
554     UseFastISel = false;
555 
556   return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr;
557 }
558 
559 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
560                                            EVT VT) const {
561   if (!VT.isVector())
562     return MVT::i32;
563   return VT.changeVectorElementTypeToInteger();
564 }
565 
566 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
567                                     TargetLowering::DAGCombinerInfo &DCI,
568                                     const MipsSubtarget &Subtarget) {
569   if (DCI.isBeforeLegalizeOps())
570     return SDValue();
571 
572   EVT Ty = N->getValueType(0);
573   unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
574   unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
575   unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
576                                                   MipsISD::DivRemU16;
577   SDLoc DL(N);
578 
579   SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
580                                N->getOperand(0), N->getOperand(1));
581   SDValue InChain = DAG.getEntryNode();
582   SDValue InGlue = DivRem;
583 
584   // insert MFLO
585   if (N->hasAnyUseOfValue(0)) {
586     SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
587                                             InGlue);
588     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
589     InChain = CopyFromLo.getValue(1);
590     InGlue = CopyFromLo.getValue(2);
591   }
592 
593   // insert MFHI
594   if (N->hasAnyUseOfValue(1)) {
595     SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
596                                             HI, Ty, InGlue);
597     DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
598   }
599 
600   return SDValue();
601 }
602 
603 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
604   switch (CC) {
605   default: llvm_unreachable("Unknown fp condition code!");
606   case ISD::SETEQ:
607   case ISD::SETOEQ: return Mips::FCOND_OEQ;
608   case ISD::SETUNE: return Mips::FCOND_UNE;
609   case ISD::SETLT:
610   case ISD::SETOLT: return Mips::FCOND_OLT;
611   case ISD::SETGT:
612   case ISD::SETOGT: return Mips::FCOND_OGT;
613   case ISD::SETLE:
614   case ISD::SETOLE: return Mips::FCOND_OLE;
615   case ISD::SETGE:
616   case ISD::SETOGE: return Mips::FCOND_OGE;
617   case ISD::SETULT: return Mips::FCOND_ULT;
618   case ISD::SETULE: return Mips::FCOND_ULE;
619   case ISD::SETUGT: return Mips::FCOND_UGT;
620   case ISD::SETUGE: return Mips::FCOND_UGE;
621   case ISD::SETUO:  return Mips::FCOND_UN;
622   case ISD::SETO:   return Mips::FCOND_OR;
623   case ISD::SETNE:
624   case ISD::SETONE: return Mips::FCOND_ONE;
625   case ISD::SETUEQ: return Mips::FCOND_UEQ;
626   }
627 }
628 
629 /// This function returns true if the floating point conditional branches and
630 /// conditional moves which use condition code CC should be inverted.
631 static bool invertFPCondCodeUser(Mips::CondCode CC) {
632   if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
633     return false;
634 
635   assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
636          "Illegal Condition Code");
637 
638   return true;
639 }
640 
641 // Creates and returns an FPCmp node from a setcc node.
642 // Returns Op if setcc is not a floating point comparison.
643 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
644   // must be a SETCC node
645   if (Op.getOpcode() != ISD::SETCC)
646     return Op;
647 
648   SDValue LHS = Op.getOperand(0);
649 
650   if (!LHS.getValueType().isFloatingPoint())
651     return Op;
652 
653   SDValue RHS = Op.getOperand(1);
654   SDLoc DL(Op);
655 
656   // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
657   // node if necessary.
658   ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
659 
660   return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
661                      DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
662 }
663 
664 // Creates and returns a CMovFPT/F node.
665 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
666                             SDValue False, const SDLoc &DL) {
667   ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
668   bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
669   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
670 
671   return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
672                      True.getValueType(), True, FCC0, False, Cond);
673 }
674 
675 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
676                                     TargetLowering::DAGCombinerInfo &DCI,
677                                     const MipsSubtarget &Subtarget) {
678   if (DCI.isBeforeLegalizeOps())
679     return SDValue();
680 
681   SDValue SetCC = N->getOperand(0);
682 
683   if ((SetCC.getOpcode() != ISD::SETCC) ||
684       !SetCC.getOperand(0).getValueType().isInteger())
685     return SDValue();
686 
687   SDValue False = N->getOperand(2);
688   EVT FalseTy = False.getValueType();
689 
690   if (!FalseTy.isInteger())
691     return SDValue();
692 
693   ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
694 
695   // If the RHS (False) is 0, we swap the order of the operands
696   // of ISD::SELECT (obviously also inverting the condition) so that we can
697   // take advantage of conditional moves using the $0 register.
698   // Example:
699   //   return (a != 0) ? x : 0;
700   //     load $reg, x
701   //     movz $reg, $0, a
702   if (!FalseC)
703     return SDValue();
704 
705   const SDLoc DL(N);
706 
707   if (!FalseC->getZExtValue()) {
708     ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
709     SDValue True = N->getOperand(1);
710 
711     SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
712                          SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
713 
714     return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
715   }
716 
717   // If both operands are integer constants there's a possibility that we
718   // can do some interesting optimizations.
719   SDValue True = N->getOperand(1);
720   ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
721 
722   if (!TrueC || !True.getValueType().isInteger())
723     return SDValue();
724 
725   // We'll also ignore MVT::i64 operands as this optimizations proves
726   // to be ineffective because of the required sign extensions as the result
727   // of a SETCC operator is always MVT::i32 for non-vector types.
728   if (True.getValueType() == MVT::i64)
729     return SDValue();
730 
731   int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
732 
733   // 1)  (a < x) ? y : y-1
734   //  slti $reg1, a, x
735   //  addiu $reg2, $reg1, y-1
736   if (Diff == 1)
737     return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
738 
739   // 2)  (a < x) ? y-1 : y
740   //  slti $reg1, a, x
741   //  xor $reg1, $reg1, 1
742   //  addiu $reg2, $reg1, y-1
743   if (Diff == -1) {
744     ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
745     SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
746                          SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
747     return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
748   }
749 
750   // Could not optimize.
751   return SDValue();
752 }
753 
754 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
755                                     TargetLowering::DAGCombinerInfo &DCI,
756                                     const MipsSubtarget &Subtarget) {
757   if (DCI.isBeforeLegalizeOps())
758     return SDValue();
759 
760   SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
761 
762   ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
763   if (!FalseC || FalseC->getZExtValue())
764     return SDValue();
765 
766   // Since RHS (False) is 0, we swap the order of the True/False operands
767   // (obviously also inverting the condition) so that we can
768   // take advantage of conditional moves using the $0 register.
769   // Example:
770   //   return (a != 0) ? x : 0;
771   //     load $reg, x
772   //     movz $reg, $0, a
773   unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
774                                                          MipsISD::CMovFP_T;
775 
776   SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
777   return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
778                      ValueIfFalse, FCC, ValueIfTrue, Glue);
779 }
780 
781 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
782                                  TargetLowering::DAGCombinerInfo &DCI,
783                                  const MipsSubtarget &Subtarget) {
784   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
785     return SDValue();
786 
787   SDValue FirstOperand = N->getOperand(0);
788   unsigned FirstOperandOpc = FirstOperand.getOpcode();
789   SDValue Mask = N->getOperand(1);
790   EVT ValTy = N->getValueType(0);
791   SDLoc DL(N);
792 
793   uint64_t Pos = 0, SMPos, SMSize;
794   ConstantSDNode *CN;
795   SDValue NewOperand;
796   unsigned Opc;
797 
798   // Op's second operand must be a shifted mask.
799   if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
800       !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
801     return SDValue();
802 
803   if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
804     // Pattern match EXT.
805     //  $dst = and ((sra or srl) $src , pos), (2**size - 1)
806     //  => ext $dst, $src, pos, size
807 
808     // The second operand of the shift must be an immediate.
809     if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
810       return SDValue();
811 
812     Pos = CN->getZExtValue();
813 
814     // Return if the shifted mask does not start at bit 0 or the sum of its size
815     // and Pos exceeds the word's size.
816     if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
817       return SDValue();
818 
819     Opc = MipsISD::Ext;
820     NewOperand = FirstOperand.getOperand(0);
821   } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
822     // Pattern match CINS.
823     //  $dst = and (shl $src , pos), mask
824     //  => cins $dst, $src, pos, size
825     // mask is a shifted mask with consecutive 1's, pos = shift amount,
826     // size = population count.
827 
828     // The second operand of the shift must be an immediate.
829     if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
830       return SDValue();
831 
832     Pos = CN->getZExtValue();
833 
834     if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
835         Pos + SMSize > ValTy.getSizeInBits())
836       return SDValue();
837 
838     NewOperand = FirstOperand.getOperand(0);
839     // SMSize is 'location' (position) in this case, not size.
840     SMSize--;
841     Opc = MipsISD::CIns;
842   } else {
843     // Pattern match EXT.
844     //  $dst = and $src, (2**size - 1) , if size > 16
845     //  => ext $dst, $src, pos, size , pos = 0
846 
847     // If the mask is <= 0xffff, andi can be used instead.
848     if (CN->getZExtValue() <= 0xffff)
849       return SDValue();
850 
851     // Return if the mask doesn't start at position 0.
852     if (SMPos)
853       return SDValue();
854 
855     Opc = MipsISD::Ext;
856     NewOperand = FirstOperand;
857   }
858   return DAG.getNode(Opc, DL, ValTy, NewOperand,
859                      DAG.getConstant(Pos, DL, MVT::i32),
860                      DAG.getConstant(SMSize, DL, MVT::i32));
861 }
862 
863 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
864                                 TargetLowering::DAGCombinerInfo &DCI,
865                                 const MipsSubtarget &Subtarget) {
866   // Pattern match INS.
867   //  $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
868   //  where mask1 = (2**size - 1) << pos, mask0 = ~mask1
869   //  => ins $dst, $src, size, pos, $src1
870   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
871     return SDValue();
872 
873   SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
874   uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
875   ConstantSDNode *CN, *CN1;
876 
877   // See if Op's first operand matches (and $src1 , mask0).
878   if (And0.getOpcode() != ISD::AND)
879     return SDValue();
880 
881   if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
882       !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
883     return SDValue();
884 
885   // See if Op's second operand matches (and (shl $src, pos), mask1).
886   if (And1.getOpcode() == ISD::AND &&
887       And1.getOperand(0).getOpcode() == ISD::SHL) {
888 
889     if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
890         !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
891       return SDValue();
892 
893     // The shift masks must have the same position and size.
894     if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
895       return SDValue();
896 
897     SDValue Shl = And1.getOperand(0);
898 
899     if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
900       return SDValue();
901 
902     unsigned Shamt = CN->getZExtValue();
903 
904     // Return if the shift amount and the first bit position of mask are not the
905     // same.
906     EVT ValTy = N->getValueType(0);
907     if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
908       return SDValue();
909 
910     SDLoc DL(N);
911     return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
912                        DAG.getConstant(SMPos0, DL, MVT::i32),
913                        DAG.getConstant(SMSize0, DL, MVT::i32),
914                        And0.getOperand(0));
915   } else {
916     // Pattern match DINS.
917     //  $dst = or (and $src, mask0), mask1
918     //  where mask0 = ((1 << SMSize0) -1) << SMPos0
919     //  => dins $dst, $src, pos, size
920     if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) &&
921         ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
922          (SMSize0 + SMPos0 <= 32))) {
923       // Check if AND instruction has constant as argument
924       bool isConstCase = And1.getOpcode() != ISD::AND;
925       if (And1.getOpcode() == ISD::AND) {
926         if (!(CN1 = dyn_cast<ConstantSDNode>(And1->getOperand(1))))
927           return SDValue();
928       } else {
929         if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
930           return SDValue();
931       }
932       // Don't generate INS if constant OR operand doesn't fit into bits
933       // cleared by constant AND operand.
934       if (CN->getSExtValue() & CN1->getSExtValue())
935         return SDValue();
936 
937       SDLoc DL(N);
938       EVT ValTy = N->getOperand(0)->getValueType(0);
939       SDValue Const1;
940       SDValue SrlX;
941       if (!isConstCase) {
942         Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
943         SrlX = DAG.getNode(ISD::SRL, DL, And1->getValueType(0), And1, Const1);
944       }
945       return DAG.getNode(
946           MipsISD::Ins, DL, N->getValueType(0),
947           isConstCase
948               ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
949               : SrlX,
950           DAG.getConstant(SMPos0, DL, MVT::i32),
951           DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
952                                                         : SMSize0,
953                           DL, MVT::i32),
954           And0->getOperand(0));
955 
956     }
957     return SDValue();
958   }
959 }
960 
961 static SDValue performMADD_MSUBCombine(SDNode *ROOTNode, SelectionDAG &CurDAG,
962                                        const MipsSubtarget &Subtarget) {
963   // ROOTNode must have a multiplication as an operand for the match to be
964   // successful.
965   if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL &&
966       ROOTNode->getOperand(1).getOpcode() != ISD::MUL)
967     return SDValue();
968 
969   // We don't handle vector types here.
970   if (ROOTNode->getValueType(0).isVector())
971     return SDValue();
972 
973   // For MIPS64, madd / msub instructions are inefficent to use with 64 bit
974   // arithmetic. E.g.
975   // (add (mul a b) c) =>
976   //   let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in
977   //   MIPS64:   (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32)
978   //   or
979   //   MIPS64R2: (dins (mflo res) (mfhi res) 32 32)
980   //
981   // The overhead of setting up the Hi/Lo registers and reassembling the
982   // result makes this a dubious optimzation for MIPS64. The core of the
983   // problem is that Hi/Lo contain the upper and lower 32 bits of the
984   // operand and result.
985   //
986   // It requires a chain of 4 add/mul for MIPS64R2 to get better code
987   // density than doing it naively, 5 for MIPS64. Additionally, using
988   // madd/msub on MIPS64 requires the operands actually be 32 bit sign
989   // extended operands, not true 64 bit values.
990   //
991   // FIXME: For the moment, disable this completely for MIPS64.
992   if (Subtarget.hasMips64())
993     return SDValue();
994 
995   SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
996                      ? ROOTNode->getOperand(0)
997                      : ROOTNode->getOperand(1);
998 
999   SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
1000                      ? ROOTNode->getOperand(1)
1001                      : ROOTNode->getOperand(0);
1002 
1003   // Transform this to a MADD only if the user of this node is the add.
1004   // If there are other users of the mul, this function returns here.
1005   if (!Mult.hasOneUse())
1006     return SDValue();
1007 
1008   // maddu and madd are unusual instructions in that on MIPS64 bits 63..31
1009   // must be in canonical form, i.e. sign extended. For MIPS32, the operands
1010   // of the multiply must have 32 or more sign bits, otherwise we cannot
1011   // perform this optimization. We have to check this here as we're performing
1012   // this optimization pre-legalization.
1013   SDValue MultLHS = Mult->getOperand(0);
1014   SDValue MultRHS = Mult->getOperand(1);
1015 
1016   bool IsSigned = MultLHS->getOpcode() == ISD::SIGN_EXTEND &&
1017                   MultRHS->getOpcode() == ISD::SIGN_EXTEND;
1018   bool IsUnsigned = MultLHS->getOpcode() == ISD::ZERO_EXTEND &&
1019                     MultRHS->getOpcode() == ISD::ZERO_EXTEND;
1020 
1021   if (!IsSigned && !IsUnsigned)
1022     return SDValue();
1023 
1024   // Initialize accumulator.
1025   SDLoc DL(ROOTNode);
1026   SDValue TopHalf;
1027   SDValue BottomHalf;
1028   BottomHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1029                               CurDAG.getIntPtrConstant(0, DL));
1030 
1031   TopHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1032                            CurDAG.getIntPtrConstant(1, DL));
1033   SDValue ACCIn = CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped,
1034                                   BottomHalf,
1035                                   TopHalf);
1036 
1037   // Create MipsMAdd(u) / MipsMSub(u) node.
1038   bool IsAdd = ROOTNode->getOpcode() == ISD::ADD;
1039   unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd)
1040                           : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub);
1041   SDValue MAddOps[3] = {
1042       CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)),
1043       CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn};
1044   EVT VTs[2] = {MVT::i32, MVT::i32};
1045   SDValue MAdd = CurDAG.getNode(Opcode, DL, VTs, MAddOps);
1046 
1047   SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
1048   SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
1049   SDValue Combined =
1050       CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi);
1051   return Combined;
1052 }
1053 
1054 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG,
1055                                  TargetLowering::DAGCombinerInfo &DCI,
1056                                  const MipsSubtarget &Subtarget) {
1057   // (sub v0 (mul v1, v2)) => (msub v1, v2, v0)
1058   if (DCI.isBeforeLegalizeOps()) {
1059     if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1060         !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1061       return performMADD_MSUBCombine(N, DAG, Subtarget);
1062 
1063     return SDValue();
1064   }
1065 
1066   return SDValue();
1067 }
1068 
1069 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
1070                                  TargetLowering::DAGCombinerInfo &DCI,
1071                                  const MipsSubtarget &Subtarget) {
1072   // (add v0 (mul v1, v2)) => (madd v1, v2, v0)
1073   if (DCI.isBeforeLegalizeOps()) {
1074     if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1075         !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1076       return performMADD_MSUBCombine(N, DAG, Subtarget);
1077 
1078     return SDValue();
1079   }
1080 
1081   // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
1082   SDValue Add = N->getOperand(1);
1083 
1084   if (Add.getOpcode() != ISD::ADD)
1085     return SDValue();
1086 
1087   SDValue Lo = Add.getOperand(1);
1088 
1089   if ((Lo.getOpcode() != MipsISD::Lo) ||
1090       (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
1091     return SDValue();
1092 
1093   EVT ValTy = N->getValueType(0);
1094   SDLoc DL(N);
1095 
1096   SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
1097                              Add.getOperand(0));
1098   return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
1099 }
1100 
1101 static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG,
1102                                  TargetLowering::DAGCombinerInfo &DCI,
1103                                  const MipsSubtarget &Subtarget) {
1104   // Pattern match CINS.
1105   //  $dst = shl (and $src , imm), pos
1106   //  => cins $dst, $src, pos, size
1107 
1108   if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
1109     return SDValue();
1110 
1111   SDValue FirstOperand = N->getOperand(0);
1112   unsigned FirstOperandOpc = FirstOperand.getOpcode();
1113   SDValue SecondOperand = N->getOperand(1);
1114   EVT ValTy = N->getValueType(0);
1115   SDLoc DL(N);
1116 
1117   uint64_t Pos = 0, SMPos, SMSize;
1118   ConstantSDNode *CN;
1119   SDValue NewOperand;
1120 
1121   // The second operand of the shift must be an immediate.
1122   if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
1123     return SDValue();
1124 
1125   Pos = CN->getZExtValue();
1126 
1127   if (Pos >= ValTy.getSizeInBits())
1128     return SDValue();
1129 
1130   if (FirstOperandOpc != ISD::AND)
1131     return SDValue();
1132 
1133   // AND's second operand must be a shifted mask.
1134   if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
1135       !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
1136     return SDValue();
1137 
1138   // Return if the shifted mask does not start at bit 0 or the sum of its size
1139   // and Pos exceeds the word's size.
1140   if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
1141     return SDValue();
1142 
1143   NewOperand = FirstOperand.getOperand(0);
1144   // SMSize is 'location' (position) in this case, not size.
1145   SMSize--;
1146 
1147   return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
1148                      DAG.getConstant(Pos, DL, MVT::i32),
1149                      DAG.getConstant(SMSize, DL, MVT::i32));
1150 }
1151 
1152 SDValue  MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
1153   const {
1154   SelectionDAG &DAG = DCI.DAG;
1155   unsigned Opc = N->getOpcode();
1156 
1157   switch (Opc) {
1158   default: break;
1159   case ISD::SDIVREM:
1160   case ISD::UDIVREM:
1161     return performDivRemCombine(N, DAG, DCI, Subtarget);
1162   case ISD::SELECT:
1163     return performSELECTCombine(N, DAG, DCI, Subtarget);
1164   case MipsISD::CMovFP_F:
1165   case MipsISD::CMovFP_T:
1166     return performCMovFPCombine(N, DAG, DCI, Subtarget);
1167   case ISD::AND:
1168     return performANDCombine(N, DAG, DCI, Subtarget);
1169   case ISD::OR:
1170     return performORCombine(N, DAG, DCI, Subtarget);
1171   case ISD::ADD:
1172     return performADDCombine(N, DAG, DCI, Subtarget);
1173   case ISD::SHL:
1174     return performSHLCombine(N, DAG, DCI, Subtarget);
1175   case ISD::SUB:
1176     return performSUBCombine(N, DAG, DCI, Subtarget);
1177   }
1178 
1179   return SDValue();
1180 }
1181 
1182 bool MipsTargetLowering::isCheapToSpeculateCttz() const {
1183   return Subtarget.hasMips32();
1184 }
1185 
1186 bool MipsTargetLowering::isCheapToSpeculateCtlz() const {
1187   return Subtarget.hasMips32();
1188 }
1189 
1190 bool MipsTargetLowering::shouldFoldConstantShiftPairToMask(
1191     const SDNode *N, CombineLevel Level) const {
1192   if (N->getOperand(0).getValueType().isVector())
1193     return false;
1194   return true;
1195 }
1196 
1197 void
1198 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1199                                           SmallVectorImpl<SDValue> &Results,
1200                                           SelectionDAG &DAG) const {
1201   SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1202 
1203   if (Res)
1204     for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1205       Results.push_back(Res.getValue(I));
1206 }
1207 
1208 void
1209 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1210                                        SmallVectorImpl<SDValue> &Results,
1211                                        SelectionDAG &DAG) const {
1212   return LowerOperationWrapper(N, Results, DAG);
1213 }
1214 
1215 SDValue MipsTargetLowering::
1216 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1217 {
1218   switch (Op.getOpcode())
1219   {
1220   case ISD::BRCOND:             return lowerBRCOND(Op, DAG);
1221   case ISD::ConstantPool:       return lowerConstantPool(Op, DAG);
1222   case ISD::GlobalAddress:      return lowerGlobalAddress(Op, DAG);
1223   case ISD::BlockAddress:       return lowerBlockAddress(Op, DAG);
1224   case ISD::GlobalTLSAddress:   return lowerGlobalTLSAddress(Op, DAG);
1225   case ISD::JumpTable:          return lowerJumpTable(Op, DAG);
1226   case ISD::SELECT:             return lowerSELECT(Op, DAG);
1227   case ISD::SETCC:              return lowerSETCC(Op, DAG);
1228   case ISD::VASTART:            return lowerVASTART(Op, DAG);
1229   case ISD::VAARG:              return lowerVAARG(Op, DAG);
1230   case ISD::FCOPYSIGN:          return lowerFCOPYSIGN(Op, DAG);
1231   case ISD::FABS:               return lowerFABS(Op, DAG);
1232   case ISD::FRAMEADDR:          return lowerFRAMEADDR(Op, DAG);
1233   case ISD::RETURNADDR:         return lowerRETURNADDR(Op, DAG);
1234   case ISD::EH_RETURN:          return lowerEH_RETURN(Op, DAG);
1235   case ISD::ATOMIC_FENCE:       return lowerATOMIC_FENCE(Op, DAG);
1236   case ISD::SHL_PARTS:          return lowerShiftLeftParts(Op, DAG);
1237   case ISD::SRA_PARTS:          return lowerShiftRightParts(Op, DAG, true);
1238   case ISD::SRL_PARTS:          return lowerShiftRightParts(Op, DAG, false);
1239   case ISD::LOAD:               return lowerLOAD(Op, DAG);
1240   case ISD::STORE:              return lowerSTORE(Op, DAG);
1241   case ISD::EH_DWARF_CFA:       return lowerEH_DWARF_CFA(Op, DAG);
1242   case ISD::FP_TO_SINT:         return lowerFP_TO_SINT(Op, DAG);
1243   }
1244   return SDValue();
1245 }
1246 
1247 //===----------------------------------------------------------------------===//
1248 //  Lower helper functions
1249 //===----------------------------------------------------------------------===//
1250 
1251 // addLiveIn - This helper function adds the specified physical register to the
1252 // MachineFunction as a live in value.  It also creates a corresponding
1253 // virtual register for it.
1254 static unsigned
1255 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1256 {
1257   Register VReg = MF.getRegInfo().createVirtualRegister(RC);
1258   MF.getRegInfo().addLiveIn(PReg, VReg);
1259   return VReg;
1260 }
1261 
1262 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr &MI,
1263                                               MachineBasicBlock &MBB,
1264                                               const TargetInstrInfo &TII,
1265                                               bool Is64Bit, bool IsMicroMips) {
1266   if (NoZeroDivCheck)
1267     return &MBB;
1268 
1269   // Insert instruction "teq $divisor_reg, $zero, 7".
1270   MachineBasicBlock::iterator I(MI);
1271   MachineInstrBuilder MIB;
1272   MachineOperand &Divisor = MI.getOperand(2);
1273   MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1274                 TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ))
1275             .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1276             .addReg(Mips::ZERO)
1277             .addImm(7);
1278 
1279   // Use the 32-bit sub-register if this is a 64-bit division.
1280   if (Is64Bit)
1281     MIB->getOperand(0).setSubReg(Mips::sub_32);
1282 
1283   // Clear Divisor's kill flag.
1284   Divisor.setIsKill(false);
1285 
1286   // We would normally delete the original instruction here but in this case
1287   // we only needed to inject an additional instruction rather than replace it.
1288 
1289   return &MBB;
1290 }
1291 
1292 MachineBasicBlock *
1293 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1294                                                 MachineBasicBlock *BB) const {
1295   switch (MI.getOpcode()) {
1296   default:
1297     llvm_unreachable("Unexpected instr type to insert");
1298   case Mips::ATOMIC_LOAD_ADD_I8:
1299     return emitAtomicBinaryPartword(MI, BB, 1);
1300   case Mips::ATOMIC_LOAD_ADD_I16:
1301     return emitAtomicBinaryPartword(MI, BB, 2);
1302   case Mips::ATOMIC_LOAD_ADD_I32:
1303     return emitAtomicBinary(MI, BB);
1304   case Mips::ATOMIC_LOAD_ADD_I64:
1305     return emitAtomicBinary(MI, BB);
1306 
1307   case Mips::ATOMIC_LOAD_AND_I8:
1308     return emitAtomicBinaryPartword(MI, BB, 1);
1309   case Mips::ATOMIC_LOAD_AND_I16:
1310     return emitAtomicBinaryPartword(MI, BB, 2);
1311   case Mips::ATOMIC_LOAD_AND_I32:
1312     return emitAtomicBinary(MI, BB);
1313   case Mips::ATOMIC_LOAD_AND_I64:
1314     return emitAtomicBinary(MI, BB);
1315 
1316   case Mips::ATOMIC_LOAD_OR_I8:
1317     return emitAtomicBinaryPartword(MI, BB, 1);
1318   case Mips::ATOMIC_LOAD_OR_I16:
1319     return emitAtomicBinaryPartword(MI, BB, 2);
1320   case Mips::ATOMIC_LOAD_OR_I32:
1321     return emitAtomicBinary(MI, BB);
1322   case Mips::ATOMIC_LOAD_OR_I64:
1323     return emitAtomicBinary(MI, BB);
1324 
1325   case Mips::ATOMIC_LOAD_XOR_I8:
1326     return emitAtomicBinaryPartword(MI, BB, 1);
1327   case Mips::ATOMIC_LOAD_XOR_I16:
1328     return emitAtomicBinaryPartword(MI, BB, 2);
1329   case Mips::ATOMIC_LOAD_XOR_I32:
1330     return emitAtomicBinary(MI, BB);
1331   case Mips::ATOMIC_LOAD_XOR_I64:
1332     return emitAtomicBinary(MI, BB);
1333 
1334   case Mips::ATOMIC_LOAD_NAND_I8:
1335     return emitAtomicBinaryPartword(MI, BB, 1);
1336   case Mips::ATOMIC_LOAD_NAND_I16:
1337     return emitAtomicBinaryPartword(MI, BB, 2);
1338   case Mips::ATOMIC_LOAD_NAND_I32:
1339     return emitAtomicBinary(MI, BB);
1340   case Mips::ATOMIC_LOAD_NAND_I64:
1341     return emitAtomicBinary(MI, BB);
1342 
1343   case Mips::ATOMIC_LOAD_SUB_I8:
1344     return emitAtomicBinaryPartword(MI, BB, 1);
1345   case Mips::ATOMIC_LOAD_SUB_I16:
1346     return emitAtomicBinaryPartword(MI, BB, 2);
1347   case Mips::ATOMIC_LOAD_SUB_I32:
1348     return emitAtomicBinary(MI, BB);
1349   case Mips::ATOMIC_LOAD_SUB_I64:
1350     return emitAtomicBinary(MI, BB);
1351 
1352   case Mips::ATOMIC_SWAP_I8:
1353     return emitAtomicBinaryPartword(MI, BB, 1);
1354   case Mips::ATOMIC_SWAP_I16:
1355     return emitAtomicBinaryPartword(MI, BB, 2);
1356   case Mips::ATOMIC_SWAP_I32:
1357     return emitAtomicBinary(MI, BB);
1358   case Mips::ATOMIC_SWAP_I64:
1359     return emitAtomicBinary(MI, BB);
1360 
1361   case Mips::ATOMIC_CMP_SWAP_I8:
1362     return emitAtomicCmpSwapPartword(MI, BB, 1);
1363   case Mips::ATOMIC_CMP_SWAP_I16:
1364     return emitAtomicCmpSwapPartword(MI, BB, 2);
1365   case Mips::ATOMIC_CMP_SWAP_I32:
1366     return emitAtomicCmpSwap(MI, BB);
1367   case Mips::ATOMIC_CMP_SWAP_I64:
1368     return emitAtomicCmpSwap(MI, BB);
1369 
1370   case Mips::ATOMIC_LOAD_MIN_I8:
1371     return emitAtomicBinaryPartword(MI, BB, 1);
1372   case Mips::ATOMIC_LOAD_MIN_I16:
1373     return emitAtomicBinaryPartword(MI, BB, 2);
1374   case Mips::ATOMIC_LOAD_MIN_I32:
1375     return emitAtomicBinary(MI, BB);
1376   case Mips::ATOMIC_LOAD_MIN_I64:
1377     return emitAtomicBinary(MI, BB);
1378 
1379   case Mips::ATOMIC_LOAD_MAX_I8:
1380     return emitAtomicBinaryPartword(MI, BB, 1);
1381   case Mips::ATOMIC_LOAD_MAX_I16:
1382     return emitAtomicBinaryPartword(MI, BB, 2);
1383   case Mips::ATOMIC_LOAD_MAX_I32:
1384     return emitAtomicBinary(MI, BB);
1385   case Mips::ATOMIC_LOAD_MAX_I64:
1386     return emitAtomicBinary(MI, BB);
1387 
1388   case Mips::ATOMIC_LOAD_UMIN_I8:
1389     return emitAtomicBinaryPartword(MI, BB, 1);
1390   case Mips::ATOMIC_LOAD_UMIN_I16:
1391     return emitAtomicBinaryPartword(MI, BB, 2);
1392   case Mips::ATOMIC_LOAD_UMIN_I32:
1393     return emitAtomicBinary(MI, BB);
1394   case Mips::ATOMIC_LOAD_UMIN_I64:
1395     return emitAtomicBinary(MI, BB);
1396 
1397   case Mips::ATOMIC_LOAD_UMAX_I8:
1398     return emitAtomicBinaryPartword(MI, BB, 1);
1399   case Mips::ATOMIC_LOAD_UMAX_I16:
1400     return emitAtomicBinaryPartword(MI, BB, 2);
1401   case Mips::ATOMIC_LOAD_UMAX_I32:
1402     return emitAtomicBinary(MI, BB);
1403   case Mips::ATOMIC_LOAD_UMAX_I64:
1404     return emitAtomicBinary(MI, BB);
1405 
1406   case Mips::PseudoSDIV:
1407   case Mips::PseudoUDIV:
1408   case Mips::DIV:
1409   case Mips::DIVU:
1410   case Mips::MOD:
1411   case Mips::MODU:
1412     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1413                                false);
1414   case Mips::SDIV_MM_Pseudo:
1415   case Mips::UDIV_MM_Pseudo:
1416   case Mips::SDIV_MM:
1417   case Mips::UDIV_MM:
1418   case Mips::DIV_MMR6:
1419   case Mips::DIVU_MMR6:
1420   case Mips::MOD_MMR6:
1421   case Mips::MODU_MMR6:
1422     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true);
1423   case Mips::PseudoDSDIV:
1424   case Mips::PseudoDUDIV:
1425   case Mips::DDIV:
1426   case Mips::DDIVU:
1427   case Mips::DMOD:
1428   case Mips::DMODU:
1429     return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false);
1430 
1431   case Mips::PseudoSELECT_I:
1432   case Mips::PseudoSELECT_I64:
1433   case Mips::PseudoSELECT_S:
1434   case Mips::PseudoSELECT_D32:
1435   case Mips::PseudoSELECT_D64:
1436     return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1437   case Mips::PseudoSELECTFP_F_I:
1438   case Mips::PseudoSELECTFP_F_I64:
1439   case Mips::PseudoSELECTFP_F_S:
1440   case Mips::PseudoSELECTFP_F_D32:
1441   case Mips::PseudoSELECTFP_F_D64:
1442     return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1443   case Mips::PseudoSELECTFP_T_I:
1444   case Mips::PseudoSELECTFP_T_I64:
1445   case Mips::PseudoSELECTFP_T_S:
1446   case Mips::PseudoSELECTFP_T_D32:
1447   case Mips::PseudoSELECTFP_T_D64:
1448     return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1449   case Mips::PseudoD_SELECT_I:
1450   case Mips::PseudoD_SELECT_I64:
1451     return emitPseudoD_SELECT(MI, BB);
1452   }
1453 }
1454 
1455 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1456 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1457 MachineBasicBlock *
1458 MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1459                                      MachineBasicBlock *BB) const {
1460 
1461   MachineFunction *MF = BB->getParent();
1462   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1463   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1464   DebugLoc DL = MI.getDebugLoc();
1465 
1466   unsigned AtomicOp;
1467   bool NeedsAdditionalReg = false;
1468   switch (MI.getOpcode()) {
1469   case Mips::ATOMIC_LOAD_ADD_I32:
1470     AtomicOp = Mips::ATOMIC_LOAD_ADD_I32_POSTRA;
1471     break;
1472   case Mips::ATOMIC_LOAD_SUB_I32:
1473     AtomicOp = Mips::ATOMIC_LOAD_SUB_I32_POSTRA;
1474     break;
1475   case Mips::ATOMIC_LOAD_AND_I32:
1476     AtomicOp = Mips::ATOMIC_LOAD_AND_I32_POSTRA;
1477     break;
1478   case Mips::ATOMIC_LOAD_OR_I32:
1479     AtomicOp = Mips::ATOMIC_LOAD_OR_I32_POSTRA;
1480     break;
1481   case Mips::ATOMIC_LOAD_XOR_I32:
1482     AtomicOp = Mips::ATOMIC_LOAD_XOR_I32_POSTRA;
1483     break;
1484   case Mips::ATOMIC_LOAD_NAND_I32:
1485     AtomicOp = Mips::ATOMIC_LOAD_NAND_I32_POSTRA;
1486     break;
1487   case Mips::ATOMIC_SWAP_I32:
1488     AtomicOp = Mips::ATOMIC_SWAP_I32_POSTRA;
1489     break;
1490   case Mips::ATOMIC_LOAD_ADD_I64:
1491     AtomicOp = Mips::ATOMIC_LOAD_ADD_I64_POSTRA;
1492     break;
1493   case Mips::ATOMIC_LOAD_SUB_I64:
1494     AtomicOp = Mips::ATOMIC_LOAD_SUB_I64_POSTRA;
1495     break;
1496   case Mips::ATOMIC_LOAD_AND_I64:
1497     AtomicOp = Mips::ATOMIC_LOAD_AND_I64_POSTRA;
1498     break;
1499   case Mips::ATOMIC_LOAD_OR_I64:
1500     AtomicOp = Mips::ATOMIC_LOAD_OR_I64_POSTRA;
1501     break;
1502   case Mips::ATOMIC_LOAD_XOR_I64:
1503     AtomicOp = Mips::ATOMIC_LOAD_XOR_I64_POSTRA;
1504     break;
1505   case Mips::ATOMIC_LOAD_NAND_I64:
1506     AtomicOp = Mips::ATOMIC_LOAD_NAND_I64_POSTRA;
1507     break;
1508   case Mips::ATOMIC_SWAP_I64:
1509     AtomicOp = Mips::ATOMIC_SWAP_I64_POSTRA;
1510     break;
1511   case Mips::ATOMIC_LOAD_MIN_I32:
1512     AtomicOp = Mips::ATOMIC_LOAD_MIN_I32_POSTRA;
1513     NeedsAdditionalReg = true;
1514     break;
1515   case Mips::ATOMIC_LOAD_MAX_I32:
1516     AtomicOp = Mips::ATOMIC_LOAD_MAX_I32_POSTRA;
1517     NeedsAdditionalReg = true;
1518     break;
1519   case Mips::ATOMIC_LOAD_UMIN_I32:
1520     AtomicOp = Mips::ATOMIC_LOAD_UMIN_I32_POSTRA;
1521     NeedsAdditionalReg = true;
1522     break;
1523   case Mips::ATOMIC_LOAD_UMAX_I32:
1524     AtomicOp = Mips::ATOMIC_LOAD_UMAX_I32_POSTRA;
1525     NeedsAdditionalReg = true;
1526     break;
1527   case Mips::ATOMIC_LOAD_MIN_I64:
1528     AtomicOp = Mips::ATOMIC_LOAD_MIN_I64_POSTRA;
1529     NeedsAdditionalReg = true;
1530     break;
1531   case Mips::ATOMIC_LOAD_MAX_I64:
1532     AtomicOp = Mips::ATOMIC_LOAD_MAX_I64_POSTRA;
1533     NeedsAdditionalReg = true;
1534     break;
1535   case Mips::ATOMIC_LOAD_UMIN_I64:
1536     AtomicOp = Mips::ATOMIC_LOAD_UMIN_I64_POSTRA;
1537     NeedsAdditionalReg = true;
1538     break;
1539   case Mips::ATOMIC_LOAD_UMAX_I64:
1540     AtomicOp = Mips::ATOMIC_LOAD_UMAX_I64_POSTRA;
1541     NeedsAdditionalReg = true;
1542     break;
1543   default:
1544     llvm_unreachable("Unknown pseudo atomic for replacement!");
1545   }
1546 
1547   Register OldVal = MI.getOperand(0).getReg();
1548   Register Ptr = MI.getOperand(1).getReg();
1549   Register Incr = MI.getOperand(2).getReg();
1550   Register Scratch = RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1551 
1552   MachineBasicBlock::iterator II(MI);
1553 
1554   // The scratch registers here with the EarlyClobber | Define | Implicit
1555   // flags is used to persuade the register allocator and the machine
1556   // verifier to accept the usage of this register. This has to be a real
1557   // register which has an UNDEF value but is dead after the instruction which
1558   // is unique among the registers chosen for the instruction.
1559 
1560   // The EarlyClobber flag has the semantic properties that the operand it is
1561   // attached to is clobbered before the rest of the inputs are read. Hence it
1562   // must be unique among the operands to the instruction.
1563   // The Define flag is needed to coerce the machine verifier that an Undef
1564   // value isn't a problem.
1565   // The Dead flag is needed as the value in scratch isn't used by any other
1566   // instruction. Kill isn't used as Dead is more precise.
1567   // The implicit flag is here due to the interaction between the other flags
1568   // and the machine verifier.
1569 
1570   // For correctness purpose, a new pseudo is introduced here. We need this
1571   // new pseudo, so that FastRegisterAllocator does not see an ll/sc sequence
1572   // that is spread over >1 basic blocks. A register allocator which
1573   // introduces (or any codegen infact) a store, can violate the expectations
1574   // of the hardware.
1575   //
1576   // An atomic read-modify-write sequence starts with a linked load
1577   // instruction and ends with a store conditional instruction. The atomic
1578   // read-modify-write sequence fails if any of the following conditions
1579   // occur between the execution of ll and sc:
1580   //   * A coherent store is completed by another process or coherent I/O
1581   //     module into the block of synchronizable physical memory containing
1582   //     the word. The size and alignment of the block is
1583   //     implementation-dependent.
1584   //   * A coherent store is executed between an LL and SC sequence on the
1585   //     same processor to the block of synchornizable physical memory
1586   //     containing the word.
1587   //
1588 
1589   Register PtrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Ptr));
1590   Register IncrCopy = RegInfo.createVirtualRegister(RegInfo.getRegClass(Incr));
1591 
1592   BuildMI(*BB, II, DL, TII->get(Mips::COPY), IncrCopy).addReg(Incr);
1593   BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1594 
1595   MachineInstrBuilder MIB =
1596       BuildMI(*BB, II, DL, TII->get(AtomicOp))
1597           .addReg(OldVal, RegState::Define | RegState::EarlyClobber)
1598           .addReg(PtrCopy)
1599           .addReg(IncrCopy)
1600           .addReg(Scratch, RegState::Define | RegState::EarlyClobber |
1601                                RegState::Implicit | RegState::Dead);
1602   if (NeedsAdditionalReg) {
1603     Register Scratch2 =
1604         RegInfo.createVirtualRegister(RegInfo.getRegClass(OldVal));
1605     MIB.addReg(Scratch2, RegState::Define | RegState::EarlyClobber |
1606                              RegState::Implicit | RegState::Dead);
1607   }
1608 
1609   MI.eraseFromParent();
1610 
1611   return BB;
1612 }
1613 
1614 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1615     MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1616     unsigned SrcReg) const {
1617   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1618   const DebugLoc &DL = MI.getDebugLoc();
1619 
1620   if (Subtarget.hasMips32r2() && Size == 1) {
1621     BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1622     return BB;
1623   }
1624 
1625   if (Subtarget.hasMips32r2() && Size == 2) {
1626     BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1627     return BB;
1628   }
1629 
1630   MachineFunction *MF = BB->getParent();
1631   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1632   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1633   Register ScrReg = RegInfo.createVirtualRegister(RC);
1634 
1635   assert(Size < 32);
1636   int64_t ShiftImm = 32 - (Size * 8);
1637 
1638   BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1639   BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1640 
1641   return BB;
1642 }
1643 
1644 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1645     MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1646   assert((Size == 1 || Size == 2) &&
1647          "Unsupported size for EmitAtomicBinaryPartial.");
1648 
1649   MachineFunction *MF = BB->getParent();
1650   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1651   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1652   const bool ArePtrs64bit = ABI.ArePtrs64bit();
1653   const TargetRegisterClass *RCp =
1654     getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1655   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1656   DebugLoc DL = MI.getDebugLoc();
1657 
1658   Register Dest = MI.getOperand(0).getReg();
1659   Register Ptr = MI.getOperand(1).getReg();
1660   Register Incr = MI.getOperand(2).getReg();
1661 
1662   Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1663   Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1664   Register Mask = RegInfo.createVirtualRegister(RC);
1665   Register Mask2 = RegInfo.createVirtualRegister(RC);
1666   Register Incr2 = RegInfo.createVirtualRegister(RC);
1667   Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1668   Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1669   Register MaskUpper = RegInfo.createVirtualRegister(RC);
1670   Register Scratch = RegInfo.createVirtualRegister(RC);
1671   Register Scratch2 = RegInfo.createVirtualRegister(RC);
1672   Register Scratch3 = RegInfo.createVirtualRegister(RC);
1673 
1674   unsigned AtomicOp = 0;
1675   bool NeedsAdditionalReg = false;
1676   switch (MI.getOpcode()) {
1677   case Mips::ATOMIC_LOAD_NAND_I8:
1678     AtomicOp = Mips::ATOMIC_LOAD_NAND_I8_POSTRA;
1679     break;
1680   case Mips::ATOMIC_LOAD_NAND_I16:
1681     AtomicOp = Mips::ATOMIC_LOAD_NAND_I16_POSTRA;
1682     break;
1683   case Mips::ATOMIC_SWAP_I8:
1684     AtomicOp = Mips::ATOMIC_SWAP_I8_POSTRA;
1685     break;
1686   case Mips::ATOMIC_SWAP_I16:
1687     AtomicOp = Mips::ATOMIC_SWAP_I16_POSTRA;
1688     break;
1689   case Mips::ATOMIC_LOAD_ADD_I8:
1690     AtomicOp = Mips::ATOMIC_LOAD_ADD_I8_POSTRA;
1691     break;
1692   case Mips::ATOMIC_LOAD_ADD_I16:
1693     AtomicOp = Mips::ATOMIC_LOAD_ADD_I16_POSTRA;
1694     break;
1695   case Mips::ATOMIC_LOAD_SUB_I8:
1696     AtomicOp = Mips::ATOMIC_LOAD_SUB_I8_POSTRA;
1697     break;
1698   case Mips::ATOMIC_LOAD_SUB_I16:
1699     AtomicOp = Mips::ATOMIC_LOAD_SUB_I16_POSTRA;
1700     break;
1701   case Mips::ATOMIC_LOAD_AND_I8:
1702     AtomicOp = Mips::ATOMIC_LOAD_AND_I8_POSTRA;
1703     break;
1704   case Mips::ATOMIC_LOAD_AND_I16:
1705     AtomicOp = Mips::ATOMIC_LOAD_AND_I16_POSTRA;
1706     break;
1707   case Mips::ATOMIC_LOAD_OR_I8:
1708     AtomicOp = Mips::ATOMIC_LOAD_OR_I8_POSTRA;
1709     break;
1710   case Mips::ATOMIC_LOAD_OR_I16:
1711     AtomicOp = Mips::ATOMIC_LOAD_OR_I16_POSTRA;
1712     break;
1713   case Mips::ATOMIC_LOAD_XOR_I8:
1714     AtomicOp = Mips::ATOMIC_LOAD_XOR_I8_POSTRA;
1715     break;
1716   case Mips::ATOMIC_LOAD_XOR_I16:
1717     AtomicOp = Mips::ATOMIC_LOAD_XOR_I16_POSTRA;
1718     break;
1719   case Mips::ATOMIC_LOAD_MIN_I8:
1720     AtomicOp = Mips::ATOMIC_LOAD_MIN_I8_POSTRA;
1721     NeedsAdditionalReg = true;
1722     break;
1723   case Mips::ATOMIC_LOAD_MIN_I16:
1724     AtomicOp = Mips::ATOMIC_LOAD_MIN_I16_POSTRA;
1725     NeedsAdditionalReg = true;
1726     break;
1727   case Mips::ATOMIC_LOAD_MAX_I8:
1728     AtomicOp = Mips::ATOMIC_LOAD_MAX_I8_POSTRA;
1729     NeedsAdditionalReg = true;
1730     break;
1731   case Mips::ATOMIC_LOAD_MAX_I16:
1732     AtomicOp = Mips::ATOMIC_LOAD_MAX_I16_POSTRA;
1733     NeedsAdditionalReg = true;
1734     break;
1735   case Mips::ATOMIC_LOAD_UMIN_I8:
1736     AtomicOp = Mips::ATOMIC_LOAD_UMIN_I8_POSTRA;
1737     NeedsAdditionalReg = true;
1738     break;
1739   case Mips::ATOMIC_LOAD_UMIN_I16:
1740     AtomicOp = Mips::ATOMIC_LOAD_UMIN_I16_POSTRA;
1741     NeedsAdditionalReg = true;
1742     break;
1743   case Mips::ATOMIC_LOAD_UMAX_I8:
1744     AtomicOp = Mips::ATOMIC_LOAD_UMAX_I8_POSTRA;
1745     NeedsAdditionalReg = true;
1746     break;
1747   case Mips::ATOMIC_LOAD_UMAX_I16:
1748     AtomicOp = Mips::ATOMIC_LOAD_UMAX_I16_POSTRA;
1749     NeedsAdditionalReg = true;
1750     break;
1751   default:
1752     llvm_unreachable("Unknown subword atomic pseudo for expansion!");
1753   }
1754 
1755   // insert new blocks after the current block
1756   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1757   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1758   MachineFunction::iterator It = ++BB->getIterator();
1759   MF->insert(It, exitMBB);
1760 
1761   // Transfer the remainder of BB and its successor edges to exitMBB.
1762   exitMBB->splice(exitMBB->begin(), BB,
1763                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1764   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1765 
1766   BB->addSuccessor(exitMBB, BranchProbability::getOne());
1767 
1768   //  thisMBB:
1769   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1770   //    and     alignedaddr,ptr,masklsb2
1771   //    andi    ptrlsb2,ptr,3
1772   //    sll     shiftamt,ptrlsb2,3
1773   //    ori     maskupper,$0,255               # 0xff
1774   //    sll     mask,maskupper,shiftamt
1775   //    nor     mask2,$0,mask
1776   //    sll     incr2,incr,shiftamt
1777 
1778   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1779   BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1780     .addReg(ABI.GetNullPtr()).addImm(-4);
1781   BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1782     .addReg(Ptr).addReg(MaskLSB2);
1783   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1784       .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1785   if (Subtarget.isLittle()) {
1786     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1787   } else {
1788     Register Off = RegInfo.createVirtualRegister(RC);
1789     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1790       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1791     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1792   }
1793   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1794     .addReg(Mips::ZERO).addImm(MaskImm);
1795   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1796     .addReg(MaskUpper).addReg(ShiftAmt);
1797   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1798   BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1799 
1800 
1801   // The purposes of the flags on the scratch registers is explained in
1802   // emitAtomicBinary. In summary, we need a scratch register which is going to
1803   // be undef, that is unique among registers chosen for the instruction.
1804 
1805   MachineInstrBuilder MIB =
1806       BuildMI(BB, DL, TII->get(AtomicOp))
1807           .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1808           .addReg(AlignedAddr)
1809           .addReg(Incr2)
1810           .addReg(Mask)
1811           .addReg(Mask2)
1812           .addReg(ShiftAmt)
1813           .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
1814                                RegState::Dead | RegState::Implicit)
1815           .addReg(Scratch2, RegState::EarlyClobber | RegState::Define |
1816                                 RegState::Dead | RegState::Implicit)
1817           .addReg(Scratch3, RegState::EarlyClobber | RegState::Define |
1818                                 RegState::Dead | RegState::Implicit);
1819   if (NeedsAdditionalReg) {
1820     Register Scratch4 = RegInfo.createVirtualRegister(RC);
1821     MIB.addReg(Scratch4, RegState::EarlyClobber | RegState::Define |
1822                              RegState::Dead | RegState::Implicit);
1823   }
1824 
1825   MI.eraseFromParent(); // The instruction is gone now.
1826 
1827   return exitMBB;
1828 }
1829 
1830 // Lower atomic compare and swap to a pseudo instruction, taking care to
1831 // define a scratch register for the pseudo instruction's expansion. The
1832 // instruction is expanded after the register allocator as to prevent
1833 // the insertion of stores between the linked load and the store conditional.
1834 
1835 MachineBasicBlock *
1836 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1837                                       MachineBasicBlock *BB) const {
1838 
1839   assert((MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ||
1840           MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I64) &&
1841          "Unsupported atomic pseudo for EmitAtomicCmpSwap.");
1842 
1843   const unsigned Size = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32 ? 4 : 8;
1844 
1845   MachineFunction *MF = BB->getParent();
1846   MachineRegisterInfo &MRI = MF->getRegInfo();
1847   const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1848   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1849   DebugLoc DL = MI.getDebugLoc();
1850 
1851   unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I32
1852                           ? Mips::ATOMIC_CMP_SWAP_I32_POSTRA
1853                           : Mips::ATOMIC_CMP_SWAP_I64_POSTRA;
1854   Register Dest = MI.getOperand(0).getReg();
1855   Register Ptr = MI.getOperand(1).getReg();
1856   Register OldVal = MI.getOperand(2).getReg();
1857   Register NewVal = MI.getOperand(3).getReg();
1858 
1859   Register Scratch = MRI.createVirtualRegister(RC);
1860   MachineBasicBlock::iterator II(MI);
1861 
1862   // We need to create copies of the various registers and kill them at the
1863   // atomic pseudo. If the copies are not made, when the atomic is expanded
1864   // after fast register allocation, the spills will end up outside of the
1865   // blocks that their values are defined in, causing livein errors.
1866 
1867   Register PtrCopy = MRI.createVirtualRegister(MRI.getRegClass(Ptr));
1868   Register OldValCopy = MRI.createVirtualRegister(MRI.getRegClass(OldVal));
1869   Register NewValCopy = MRI.createVirtualRegister(MRI.getRegClass(NewVal));
1870 
1871   BuildMI(*BB, II, DL, TII->get(Mips::COPY), PtrCopy).addReg(Ptr);
1872   BuildMI(*BB, II, DL, TII->get(Mips::COPY), OldValCopy).addReg(OldVal);
1873   BuildMI(*BB, II, DL, TII->get(Mips::COPY), NewValCopy).addReg(NewVal);
1874 
1875   // The purposes of the flags on the scratch registers is explained in
1876   // emitAtomicBinary. In summary, we need a scratch register which is going to
1877   // be undef, that is unique among registers chosen for the instruction.
1878 
1879   BuildMI(*BB, II, DL, TII->get(AtomicOp))
1880       .addReg(Dest, RegState::Define | RegState::EarlyClobber)
1881       .addReg(PtrCopy, RegState::Kill)
1882       .addReg(OldValCopy, RegState::Kill)
1883       .addReg(NewValCopy, RegState::Kill)
1884       .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
1885                            RegState::Dead | RegState::Implicit);
1886 
1887   MI.eraseFromParent(); // The instruction is gone now.
1888 
1889   return BB;
1890 }
1891 
1892 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1893     MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1894   assert((Size == 1 || Size == 2) &&
1895       "Unsupported size for EmitAtomicCmpSwapPartial.");
1896 
1897   MachineFunction *MF = BB->getParent();
1898   MachineRegisterInfo &RegInfo = MF->getRegInfo();
1899   const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1900   const bool ArePtrs64bit = ABI.ArePtrs64bit();
1901   const TargetRegisterClass *RCp =
1902     getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1903   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1904   DebugLoc DL = MI.getDebugLoc();
1905 
1906   Register Dest = MI.getOperand(0).getReg();
1907   Register Ptr = MI.getOperand(1).getReg();
1908   Register CmpVal = MI.getOperand(2).getReg();
1909   Register NewVal = MI.getOperand(3).getReg();
1910 
1911   Register AlignedAddr = RegInfo.createVirtualRegister(RCp);
1912   Register ShiftAmt = RegInfo.createVirtualRegister(RC);
1913   Register Mask = RegInfo.createVirtualRegister(RC);
1914   Register Mask2 = RegInfo.createVirtualRegister(RC);
1915   Register ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1916   Register ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1917   Register MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1918   Register PtrLSB2 = RegInfo.createVirtualRegister(RC);
1919   Register MaskUpper = RegInfo.createVirtualRegister(RC);
1920   Register MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1921   Register MaskedNewVal = RegInfo.createVirtualRegister(RC);
1922   unsigned AtomicOp = MI.getOpcode() == Mips::ATOMIC_CMP_SWAP_I8
1923                           ? Mips::ATOMIC_CMP_SWAP_I8_POSTRA
1924                           : Mips::ATOMIC_CMP_SWAP_I16_POSTRA;
1925 
1926   // The scratch registers here with the EarlyClobber | Define | Dead | Implicit
1927   // flags are used to coerce the register allocator and the machine verifier to
1928   // accept the usage of these registers.
1929   // The EarlyClobber flag has the semantic properties that the operand it is
1930   // attached to is clobbered before the rest of the inputs are read. Hence it
1931   // must be unique among the operands to the instruction.
1932   // The Define flag is needed to coerce the machine verifier that an Undef
1933   // value isn't a problem.
1934   // The Dead flag is needed as the value in scratch isn't used by any other
1935   // instruction. Kill isn't used as Dead is more precise.
1936   Register Scratch = RegInfo.createVirtualRegister(RC);
1937   Register Scratch2 = RegInfo.createVirtualRegister(RC);
1938 
1939   // insert new blocks after the current block
1940   const BasicBlock *LLVM_BB = BB->getBasicBlock();
1941   MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1942   MachineFunction::iterator It = ++BB->getIterator();
1943   MF->insert(It, exitMBB);
1944 
1945   // Transfer the remainder of BB and its successor edges to exitMBB.
1946   exitMBB->splice(exitMBB->begin(), BB,
1947                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
1948   exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1949 
1950   BB->addSuccessor(exitMBB, BranchProbability::getOne());
1951 
1952   //  thisMBB:
1953   //    addiu   masklsb2,$0,-4                # 0xfffffffc
1954   //    and     alignedaddr,ptr,masklsb2
1955   //    andi    ptrlsb2,ptr,3
1956   //    xori    ptrlsb2,ptrlsb2,3              # Only for BE
1957   //    sll     shiftamt,ptrlsb2,3
1958   //    ori     maskupper,$0,255               # 0xff
1959   //    sll     mask,maskupper,shiftamt
1960   //    nor     mask2,$0,mask
1961   //    andi    maskedcmpval,cmpval,255
1962   //    sll     shiftedcmpval,maskedcmpval,shiftamt
1963   //    andi    maskednewval,newval,255
1964   //    sll     shiftednewval,maskednewval,shiftamt
1965   int64_t MaskImm = (Size == 1) ? 255 : 65535;
1966   BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1967     .addReg(ABI.GetNullPtr()).addImm(-4);
1968   BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1969     .addReg(Ptr).addReg(MaskLSB2);
1970   BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1971       .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1972   if (Subtarget.isLittle()) {
1973     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1974   } else {
1975     Register Off = RegInfo.createVirtualRegister(RC);
1976     BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1977       .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1978     BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1979   }
1980   BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1981     .addReg(Mips::ZERO).addImm(MaskImm);
1982   BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1983     .addReg(MaskUpper).addReg(ShiftAmt);
1984   BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1985   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1986     .addReg(CmpVal).addImm(MaskImm);
1987   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1988     .addReg(MaskedCmpVal).addReg(ShiftAmt);
1989   BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1990     .addReg(NewVal).addImm(MaskImm);
1991   BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1992     .addReg(MaskedNewVal).addReg(ShiftAmt);
1993 
1994   // The purposes of the flags on the scratch registers are explained in
1995   // emitAtomicBinary. In summary, we need a scratch register which is going to
1996   // be undef, that is unique among the register chosen for the instruction.
1997 
1998   BuildMI(BB, DL, TII->get(AtomicOp))
1999       .addReg(Dest, RegState::Define | RegState::EarlyClobber)
2000       .addReg(AlignedAddr)
2001       .addReg(Mask)
2002       .addReg(ShiftedCmpVal)
2003       .addReg(Mask2)
2004       .addReg(ShiftedNewVal)
2005       .addReg(ShiftAmt)
2006       .addReg(Scratch, RegState::EarlyClobber | RegState::Define |
2007                            RegState::Dead | RegState::Implicit)
2008       .addReg(Scratch2, RegState::EarlyClobber | RegState::Define |
2009                             RegState::Dead | RegState::Implicit);
2010 
2011   MI.eraseFromParent(); // The instruction is gone now.
2012 
2013   return exitMBB;
2014 }
2015 
2016 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
2017   // The first operand is the chain, the second is the condition, the third is
2018   // the block to branch to if the condition is true.
2019   SDValue Chain = Op.getOperand(0);
2020   SDValue Dest = Op.getOperand(2);
2021   SDLoc DL(Op);
2022 
2023   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2024   SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
2025 
2026   // Return if flag is not set by a floating point comparison.
2027   if (CondRes.getOpcode() != MipsISD::FPCmp)
2028     return Op;
2029 
2030   SDValue CCNode  = CondRes.getOperand(2);
2031   Mips::CondCode CC =
2032     (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
2033   unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
2034   SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
2035   SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
2036   return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
2037                      FCC0, Dest, CondRes);
2038 }
2039 
2040 SDValue MipsTargetLowering::
2041 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
2042 {
2043   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2044   SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
2045 
2046   // Return if flag is not set by a floating point comparison.
2047   if (Cond.getOpcode() != MipsISD::FPCmp)
2048     return Op;
2049 
2050   return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2051                       SDLoc(Op));
2052 }
2053 
2054 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2055   assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2056   SDValue Cond = createFPCmp(DAG, Op);
2057 
2058   assert(Cond.getOpcode() == MipsISD::FPCmp &&
2059          "Floating point operand expected.");
2060 
2061   SDLoc DL(Op);
2062   SDValue True  = DAG.getConstant(1, DL, MVT::i32);
2063   SDValue False = DAG.getConstant(0, DL, MVT::i32);
2064 
2065   return createCMovFP(DAG, Cond, True, False, DL);
2066 }
2067 
2068 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
2069                                                SelectionDAG &DAG) const {
2070   EVT Ty = Op.getValueType();
2071   GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2072   const GlobalValue *GV = N->getGlobal();
2073 
2074   if (!isPositionIndependent()) {
2075     const MipsTargetObjectFile *TLOF =
2076         static_cast<const MipsTargetObjectFile *>(
2077             getTargetMachine().getObjFileLowering());
2078     const GlobalObject *GO = GV->getBaseObject();
2079     if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
2080       // %gp_rel relocation
2081       return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2082 
2083                                 // %hi/%lo relocation
2084     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2085                                 // %highest/%higher/%hi/%lo relocation
2086                                 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2087   }
2088 
2089   // Every other architecture would use shouldAssumeDSOLocal in here, but
2090   // mips is special.
2091   // * In PIC code mips requires got loads even for local statics!
2092   // * To save on got entries, for local statics the got entry contains the
2093   //   page and an additional add instruction takes care of the low bits.
2094   // * It is legal to access a hidden symbol with a non hidden undefined,
2095   //   so one cannot guarantee that all access to a hidden symbol will know
2096   //   it is hidden.
2097   // * Mips linkers don't support creating a page and a full got entry for
2098   //   the same symbol.
2099   // * Given all that, we have to use a full got entry for hidden symbols :-(
2100   if (GV->hasLocalLinkage())
2101     return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2102 
2103   if (Subtarget.useXGOT())
2104     return getAddrGlobalLargeGOT(
2105         N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
2106         DAG.getEntryNode(),
2107         MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2108 
2109   return getAddrGlobal(
2110       N, SDLoc(N), Ty, DAG,
2111       (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT,
2112       DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2113 }
2114 
2115 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2116                                               SelectionDAG &DAG) const {
2117   BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2118   EVT Ty = Op.getValueType();
2119 
2120   if (!isPositionIndependent())
2121     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2122                                 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2123 
2124   return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2125 }
2126 
2127 SDValue MipsTargetLowering::
2128 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2129 {
2130   // If the relocation model is PIC, use the General Dynamic TLS Model or
2131   // Local Dynamic TLS model, otherwise use the Initial Exec or
2132   // Local Exec TLS Model.
2133 
2134   GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2135   if (DAG.getTarget().useEmulatedTLS())
2136     return LowerToTLSEmulatedModel(GA, DAG);
2137 
2138   SDLoc DL(GA);
2139   const GlobalValue *GV = GA->getGlobal();
2140   EVT PtrVT = getPointerTy(DAG.getDataLayout());
2141 
2142   TLSModel::Model model = getTargetMachine().getTLSModel(GV);
2143 
2144   if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2145     // General Dynamic and Local Dynamic TLS Model.
2146     unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2147                                                       : MipsII::MO_TLSGD;
2148 
2149     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2150     SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2151                                    getGlobalReg(DAG, PtrVT), TGA);
2152     unsigned PtrSize = PtrVT.getSizeInBits();
2153     IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2154 
2155     SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2156 
2157     ArgListTy Args;
2158     ArgListEntry Entry;
2159     Entry.Node = Argument;
2160     Entry.Ty = PtrTy;
2161     Args.push_back(Entry);
2162 
2163     TargetLowering::CallLoweringInfo CLI(DAG);
2164     CLI.setDebugLoc(DL)
2165         .setChain(DAG.getEntryNode())
2166         .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2167     std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2168 
2169     SDValue Ret = CallResult.first;
2170 
2171     if (model != TLSModel::LocalDynamic)
2172       return Ret;
2173 
2174     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2175                                                MipsII::MO_DTPREL_HI);
2176     SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2177     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2178                                                MipsII::MO_DTPREL_LO);
2179     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2180     SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2181     return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2182   }
2183 
2184   SDValue Offset;
2185   if (model == TLSModel::InitialExec) {
2186     // Initial Exec TLS Model
2187     SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2188                                              MipsII::MO_GOTTPREL);
2189     TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2190                       TGA);
2191     Offset =
2192         DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2193   } else {
2194     // Local Exec TLS Model
2195     assert(model == TLSModel::LocalExec);
2196     SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2197                                                MipsII::MO_TPREL_HI);
2198     SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2199                                                MipsII::MO_TPREL_LO);
2200     SDValue Hi = DAG.getNode(MipsISD::TlsHi, DL, PtrVT, TGAHi);
2201     SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2202     Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2203   }
2204 
2205   SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2206   return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2207 }
2208 
2209 SDValue MipsTargetLowering::
2210 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2211 {
2212   JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2213   EVT Ty = Op.getValueType();
2214 
2215   if (!isPositionIndependent())
2216     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2217                                 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2218 
2219   return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2220 }
2221 
2222 SDValue MipsTargetLowering::
2223 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2224 {
2225   ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2226   EVT Ty = Op.getValueType();
2227 
2228   if (!isPositionIndependent()) {
2229     const MipsTargetObjectFile *TLOF =
2230         static_cast<const MipsTargetObjectFile *>(
2231             getTargetMachine().getObjFileLowering());
2232 
2233     if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2234                                        getTargetMachine()))
2235       // %gp_rel relocation
2236       return getAddrGPRel(N, SDLoc(N), Ty, DAG, ABI.IsN64());
2237 
2238     return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2239                                 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2240   }
2241 
2242  return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2243 }
2244 
2245 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2246   MachineFunction &MF = DAG.getMachineFunction();
2247   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2248 
2249   SDLoc DL(Op);
2250   SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2251                                  getPointerTy(MF.getDataLayout()));
2252 
2253   // vastart just stores the address of the VarArgsFrameIndex slot into the
2254   // memory location argument.
2255   const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2256   return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2257                       MachinePointerInfo(SV));
2258 }
2259 
2260 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2261   SDNode *Node = Op.getNode();
2262   EVT VT = Node->getValueType(0);
2263   SDValue Chain = Node->getOperand(0);
2264   SDValue VAListPtr = Node->getOperand(1);
2265   const Align Align =
2266       llvm::MaybeAlign(Node->getConstantOperandVal(3)).valueOrOne();
2267   const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2268   SDLoc DL(Node);
2269   unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2270 
2271   SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2272                                    VAListPtr, MachinePointerInfo(SV));
2273   SDValue VAList = VAListLoad;
2274 
2275   // Re-align the pointer if necessary.
2276   // It should only ever be necessary for 64-bit types on O32 since the minimum
2277   // argument alignment is the same as the maximum type alignment for N32/N64.
2278   //
2279   // FIXME: We currently align too often. The code generator doesn't notice
2280   //        when the pointer is still aligned from the last va_arg (or pair of
2281   //        va_args for the i64 on O32 case).
2282   if (Align > getMinStackArgumentAlignment()) {
2283     VAList = DAG.getNode(
2284         ISD::ADD, DL, VAList.getValueType(), VAList,
2285         DAG.getConstant(Align.value() - 1, DL, VAList.getValueType()));
2286 
2287     VAList = DAG.getNode(
2288         ISD::AND, DL, VAList.getValueType(), VAList,
2289         DAG.getConstant(-(int64_t)Align.value(), DL, VAList.getValueType()));
2290   }
2291 
2292   // Increment the pointer, VAList, to the next vaarg.
2293   auto &TD = DAG.getDataLayout();
2294   unsigned ArgSizeInBytes =
2295       TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
2296   SDValue Tmp3 =
2297       DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2298                   DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2299                                   DL, VAList.getValueType()));
2300   // Store the incremented VAList to the legalized pointer
2301   Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2302                        MachinePointerInfo(SV));
2303 
2304   // In big-endian mode we must adjust the pointer when the load size is smaller
2305   // than the argument slot size. We must also reduce the known alignment to
2306   // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2307   // the correct half of the slot, and reduce the alignment from 8 (slot
2308   // alignment) down to 4 (type alignment).
2309   if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2310     unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2311     VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2312                          DAG.getIntPtrConstant(Adjustment, DL));
2313   }
2314   // Load the actual argument out of the pointer VAList
2315   return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2316 }
2317 
2318 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
2319                                 bool HasExtractInsert) {
2320   EVT TyX = Op.getOperand(0).getValueType();
2321   EVT TyY = Op.getOperand(1).getValueType();
2322   SDLoc DL(Op);
2323   SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2324   SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2325   SDValue Res;
2326 
2327   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2328   // to i32.
2329   SDValue X = (TyX == MVT::f32) ?
2330     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2331     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2332                 Const1);
2333   SDValue Y = (TyY == MVT::f32) ?
2334     DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2335     DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2336                 Const1);
2337 
2338   if (HasExtractInsert) {
2339     // ext  E, Y, 31, 1  ; extract bit31 of Y
2340     // ins  X, E, 31, 1  ; insert extracted bit at bit31 of X
2341     SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2342     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2343   } else {
2344     // sll SllX, X, 1
2345     // srl SrlX, SllX, 1
2346     // srl SrlY, Y, 31
2347     // sll SllY, SrlX, 31
2348     // or  Or, SrlX, SllY
2349     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2350     SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2351     SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2352     SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2353     Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2354   }
2355 
2356   if (TyX == MVT::f32)
2357     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2358 
2359   SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2360                              Op.getOperand(0),
2361                              DAG.getConstant(0, DL, MVT::i32));
2362   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2363 }
2364 
2365 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
2366                                 bool HasExtractInsert) {
2367   unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2368   unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2369   EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2370   SDLoc DL(Op);
2371   SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2372 
2373   // Bitcast to integer nodes.
2374   SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2375   SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2376 
2377   if (HasExtractInsert) {
2378     // ext  E, Y, width(Y) - 1, 1  ; extract bit width(Y)-1 of Y
2379     // ins  X, E, width(X) - 1, 1  ; insert extracted bit at bit width(X)-1 of X
2380     SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2381                             DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2382 
2383     if (WidthX > WidthY)
2384       E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2385     else if (WidthY > WidthX)
2386       E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2387 
2388     SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2389                             DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2390                             X);
2391     return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2392   }
2393 
2394   // (d)sll SllX, X, 1
2395   // (d)srl SrlX, SllX, 1
2396   // (d)srl SrlY, Y, width(Y)-1
2397   // (d)sll SllY, SrlX, width(Y)-1
2398   // or     Or, SrlX, SllY
2399   SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2400   SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2401   SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2402                              DAG.getConstant(WidthY - 1, DL, MVT::i32));
2403 
2404   if (WidthX > WidthY)
2405     SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2406   else if (WidthY > WidthX)
2407     SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2408 
2409   SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2410                              DAG.getConstant(WidthX - 1, DL, MVT::i32));
2411   SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2412   return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2413 }
2414 
2415 SDValue
2416 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2417   if (Subtarget.isGP64bit())
2418     return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2419 
2420   return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2421 }
2422 
2423 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG,
2424                            bool HasExtractInsert) {
2425   SDLoc DL(Op);
2426   SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2427 
2428   // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2429   // to i32.
2430   SDValue X = (Op.getValueType() == MVT::f32)
2431                   ? DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0))
2432                   : DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2433                                 Op.getOperand(0), Const1);
2434 
2435   // Clear MSB.
2436   if (HasExtractInsert)
2437     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2438                       DAG.getRegister(Mips::ZERO, MVT::i32),
2439                       DAG.getConstant(31, DL, MVT::i32), Const1, X);
2440   else {
2441     // TODO: Provide DAG patterns which transform (and x, cst)
2442     // back to a (shl (srl x (clz cst)) (clz cst)) sequence.
2443     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2444     Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2445   }
2446 
2447   if (Op.getValueType() == MVT::f32)
2448     return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2449 
2450   // FIXME: For mips32r2, the sequence of (BuildPairF64 (ins (ExtractElementF64
2451   // Op 1), $zero, 31 1) (ExtractElementF64 Op 0)) and the Op has one use, we
2452   // should be able to drop the usage of mfc1/mtc1 and rewrite the register in
2453   // place.
2454   SDValue LowX =
2455       DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2456                   DAG.getConstant(0, DL, MVT::i32));
2457   return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2458 }
2459 
2460 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG,
2461                            bool HasExtractInsert) {
2462   SDLoc DL(Op);
2463   SDValue Res, Const1 = DAG.getConstant(1, DL, MVT::i32);
2464 
2465   // Bitcast to integer node.
2466   SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2467 
2468   // Clear MSB.
2469   if (HasExtractInsert)
2470     Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2471                       DAG.getRegister(Mips::ZERO_64, MVT::i64),
2472                       DAG.getConstant(63, DL, MVT::i32), Const1, X);
2473   else {
2474     SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2475     Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2476   }
2477 
2478   return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2479 }
2480 
2481 SDValue MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
2482   if ((ABI.IsN32() || ABI.IsN64()) && (Op.getValueType() == MVT::f64))
2483     return lowerFABS64(Op, DAG, Subtarget.hasExtractInsert());
2484 
2485   return lowerFABS32(Op, DAG, Subtarget.hasExtractInsert());
2486 }
2487 
2488 SDValue MipsTargetLowering::
2489 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2490   // check the depth
2491   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2492     DAG.getContext()->emitError(
2493         "return address can be determined only for current frame");
2494     return SDValue();
2495   }
2496 
2497   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2498   MFI.setFrameAddressIsTaken(true);
2499   EVT VT = Op.getValueType();
2500   SDLoc DL(Op);
2501   SDValue FrameAddr = DAG.getCopyFromReg(
2502       DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2503   return FrameAddr;
2504 }
2505 
2506 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2507                                             SelectionDAG &DAG) const {
2508   if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2509     return SDValue();
2510 
2511   // check the depth
2512   if (cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() != 0) {
2513     DAG.getContext()->emitError(
2514         "return address can be determined only for current frame");
2515     return SDValue();
2516   }
2517 
2518   MachineFunction &MF = DAG.getMachineFunction();
2519   MachineFrameInfo &MFI = MF.getFrameInfo();
2520   MVT VT = Op.getSimpleValueType();
2521   unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2522   MFI.setReturnAddressIsTaken(true);
2523 
2524   // Return RA, which contains the return address. Mark it an implicit live-in.
2525   unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2526   return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2527 }
2528 
2529 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2530 // generated from __builtin_eh_return (offset, handler)
2531 // The effect of this is to adjust the stack pointer by "offset"
2532 // and then branch to "handler".
2533 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2534                                                                      const {
2535   MachineFunction &MF = DAG.getMachineFunction();
2536   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2537 
2538   MipsFI->setCallsEhReturn();
2539   SDValue Chain     = Op.getOperand(0);
2540   SDValue Offset    = Op.getOperand(1);
2541   SDValue Handler   = Op.getOperand(2);
2542   SDLoc DL(Op);
2543   EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2544 
2545   // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2546   // EH_RETURN nodes, so that instructions are emitted back-to-back.
2547   unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2548   unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2549   Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2550   Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2551   return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2552                      DAG.getRegister(OffsetReg, Ty),
2553                      DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2554                      Chain.getValue(1));
2555 }
2556 
2557 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2558                                               SelectionDAG &DAG) const {
2559   // FIXME: Need pseudo-fence for 'singlethread' fences
2560   // FIXME: Set SType for weaker fences where supported/appropriate.
2561   unsigned SType = 0;
2562   SDLoc DL(Op);
2563   return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2564                      DAG.getConstant(SType, DL, MVT::i32));
2565 }
2566 
2567 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2568                                                 SelectionDAG &DAG) const {
2569   SDLoc DL(Op);
2570   MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2571 
2572   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2573   SDValue Shamt = Op.getOperand(2);
2574   // if shamt < (VT.bits):
2575   //  lo = (shl lo, shamt)
2576   //  hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2577   // else:
2578   //  lo = 0
2579   //  hi = (shl lo, shamt[4:0])
2580   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2581                             DAG.getConstant(-1, DL, MVT::i32));
2582   SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2583                                       DAG.getConstant(1, DL, VT));
2584   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2585   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2586   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2587   SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2588   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2589                              DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2590   Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2591                    DAG.getConstant(0, DL, VT), ShiftLeftLo);
2592   Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2593 
2594   SDValue Ops[2] = {Lo, Hi};
2595   return DAG.getMergeValues(Ops, DL);
2596 }
2597 
2598 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2599                                                  bool IsSRA) const {
2600   SDLoc DL(Op);
2601   SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2602   SDValue Shamt = Op.getOperand(2);
2603   MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2604 
2605   // if shamt < (VT.bits):
2606   //  lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2607   //  if isSRA:
2608   //    hi = (sra hi, shamt)
2609   //  else:
2610   //    hi = (srl hi, shamt)
2611   // else:
2612   //  if isSRA:
2613   //   lo = (sra hi, shamt[4:0])
2614   //   hi = (sra hi, 31)
2615   //  else:
2616   //   lo = (srl hi, shamt[4:0])
2617   //   hi = 0
2618   SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2619                             DAG.getConstant(-1, DL, MVT::i32));
2620   SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2621                                      DAG.getConstant(1, DL, VT));
2622   SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2623   SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2624   SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2625   SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2626                                      DL, VT, Hi, Shamt);
2627   SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2628                              DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2629   SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2630                             DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2631 
2632   if (!(Subtarget.hasMips4() || Subtarget.hasMips32())) {
2633     SDVTList VTList = DAG.getVTList(VT, VT);
2634     return DAG.getNode(Subtarget.isGP64bit() ? Mips::PseudoD_SELECT_I64
2635                                              : Mips::PseudoD_SELECT_I,
2636                        DL, VTList, Cond, ShiftRightHi,
2637                        IsSRA ? Ext : DAG.getConstant(0, DL, VT), Or,
2638                        ShiftRightHi);
2639   }
2640 
2641   Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2642   Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2643                    IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2644 
2645   SDValue Ops[2] = {Lo, Hi};
2646   return DAG.getMergeValues(Ops, DL);
2647 }
2648 
2649 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2650                             SDValue Chain, SDValue Src, unsigned Offset) {
2651   SDValue Ptr = LD->getBasePtr();
2652   EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2653   EVT BasePtrVT = Ptr.getValueType();
2654   SDLoc DL(LD);
2655   SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2656 
2657   if (Offset)
2658     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2659                       DAG.getConstant(Offset, DL, BasePtrVT));
2660 
2661   SDValue Ops[] = { Chain, Ptr, Src };
2662   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2663                                  LD->getMemOperand());
2664 }
2665 
2666 // Expand an unaligned 32 or 64-bit integer load node.
2667 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2668   LoadSDNode *LD = cast<LoadSDNode>(Op);
2669   EVT MemVT = LD->getMemoryVT();
2670 
2671   if (Subtarget.systemSupportsUnalignedAccess())
2672     return Op;
2673 
2674   // Return if load is aligned or if MemVT is neither i32 nor i64.
2675   if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2676       ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2677     return SDValue();
2678 
2679   bool IsLittle = Subtarget.isLittle();
2680   EVT VT = Op.getValueType();
2681   ISD::LoadExtType ExtType = LD->getExtensionType();
2682   SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2683 
2684   assert((VT == MVT::i32) || (VT == MVT::i64));
2685 
2686   // Expand
2687   //  (set dst, (i64 (load baseptr)))
2688   // to
2689   //  (set tmp, (ldl (add baseptr, 7), undef))
2690   //  (set dst, (ldr baseptr, tmp))
2691   if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2692     SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2693                                IsLittle ? 7 : 0);
2694     return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2695                         IsLittle ? 0 : 7);
2696   }
2697 
2698   SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2699                              IsLittle ? 3 : 0);
2700   SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2701                              IsLittle ? 0 : 3);
2702 
2703   // Expand
2704   //  (set dst, (i32 (load baseptr))) or
2705   //  (set dst, (i64 (sextload baseptr))) or
2706   //  (set dst, (i64 (extload baseptr)))
2707   // to
2708   //  (set tmp, (lwl (add baseptr, 3), undef))
2709   //  (set dst, (lwr baseptr, tmp))
2710   if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2711       (ExtType == ISD::EXTLOAD))
2712     return LWR;
2713 
2714   assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2715 
2716   // Expand
2717   //  (set dst, (i64 (zextload baseptr)))
2718   // to
2719   //  (set tmp0, (lwl (add baseptr, 3), undef))
2720   //  (set tmp1, (lwr baseptr, tmp0))
2721   //  (set tmp2, (shl tmp1, 32))
2722   //  (set dst, (srl tmp2, 32))
2723   SDLoc DL(LD);
2724   SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2725   SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2726   SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2727   SDValue Ops[] = { SRL, LWR.getValue(1) };
2728   return DAG.getMergeValues(Ops, DL);
2729 }
2730 
2731 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2732                              SDValue Chain, unsigned Offset) {
2733   SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2734   EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2735   SDLoc DL(SD);
2736   SDVTList VTList = DAG.getVTList(MVT::Other);
2737 
2738   if (Offset)
2739     Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2740                       DAG.getConstant(Offset, DL, BasePtrVT));
2741 
2742   SDValue Ops[] = { Chain, Value, Ptr };
2743   return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2744                                  SD->getMemOperand());
2745 }
2746 
2747 // Expand an unaligned 32 or 64-bit integer store node.
2748 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2749                                       bool IsLittle) {
2750   SDValue Value = SD->getValue(), Chain = SD->getChain();
2751   EVT VT = Value.getValueType();
2752 
2753   // Expand
2754   //  (store val, baseptr) or
2755   //  (truncstore val, baseptr)
2756   // to
2757   //  (swl val, (add baseptr, 3))
2758   //  (swr val, baseptr)
2759   if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2760     SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2761                                 IsLittle ? 3 : 0);
2762     return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2763   }
2764 
2765   assert(VT == MVT::i64);
2766 
2767   // Expand
2768   //  (store val, baseptr)
2769   // to
2770   //  (sdl val, (add baseptr, 7))
2771   //  (sdr val, baseptr)
2772   SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2773   return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2774 }
2775 
2776 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2777 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG,
2778                                      bool SingleFloat) {
2779   SDValue Val = SD->getValue();
2780 
2781   if (Val.getOpcode() != ISD::FP_TO_SINT ||
2782       (Val.getValueSizeInBits() > 32 && SingleFloat))
2783     return SDValue();
2784 
2785   EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2786   SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2787                            Val.getOperand(0));
2788   return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2789                       SD->getPointerInfo(), SD->getAlignment(),
2790                       SD->getMemOperand()->getFlags());
2791 }
2792 
2793 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2794   StoreSDNode *SD = cast<StoreSDNode>(Op);
2795   EVT MemVT = SD->getMemoryVT();
2796 
2797   // Lower unaligned integer stores.
2798   if (!Subtarget.systemSupportsUnalignedAccess() &&
2799       (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2800       ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2801     return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2802 
2803   return lowerFP_TO_SINT_STORE(SD, DAG, Subtarget.isSingleFloat());
2804 }
2805 
2806 SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2807                                               SelectionDAG &DAG) const {
2808 
2809   // Return a fixed StackObject with offset 0 which points to the old stack
2810   // pointer.
2811   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2812   EVT ValTy = Op->getValueType(0);
2813   int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2814   return DAG.getFrameIndex(FI, ValTy);
2815 }
2816 
2817 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2818                                             SelectionDAG &DAG) const {
2819   if (Op.getValueSizeInBits() > 32 && Subtarget.isSingleFloat())
2820     return SDValue();
2821 
2822   EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2823   SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2824                               Op.getOperand(0));
2825   return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2826 }
2827 
2828 //===----------------------------------------------------------------------===//
2829 //                      Calling Convention Implementation
2830 //===----------------------------------------------------------------------===//
2831 
2832 //===----------------------------------------------------------------------===//
2833 // TODO: Implement a generic logic using tblgen that can support this.
2834 // Mips O32 ABI rules:
2835 // ---
2836 // i32 - Passed in A0, A1, A2, A3 and stack
2837 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2838 //       an argument. Otherwise, passed in A1, A2, A3 and stack.
2839 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2840 //       yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2841 //       not used, it must be shadowed. If only A3 is available, shadow it and
2842 //       go to stack.
2843 // vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
2844 // vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
2845 //         with the remainder spilled to the stack.
2846 // vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
2847 //         spilling the remainder to the stack.
2848 //
2849 //  For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2850 //===----------------------------------------------------------------------===//
2851 
2852 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2853                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2854                        CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2855   const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2856       State.getMachineFunction().getSubtarget());
2857 
2858   static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2859 
2860   const MipsCCState * MipsState = static_cast<MipsCCState *>(&State);
2861 
2862   static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2863 
2864   static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 };
2865 
2866   // Do not process byval args here.
2867   if (ArgFlags.isByVal())
2868     return true;
2869 
2870   // Promote i8 and i16
2871   if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2872     if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2873       LocVT = MVT::i32;
2874       if (ArgFlags.isSExt())
2875         LocInfo = CCValAssign::SExtUpper;
2876       else if (ArgFlags.isZExt())
2877         LocInfo = CCValAssign::ZExtUpper;
2878       else
2879         LocInfo = CCValAssign::AExtUpper;
2880     }
2881   }
2882 
2883   // Promote i8 and i16
2884   if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2885     LocVT = MVT::i32;
2886     if (ArgFlags.isSExt())
2887       LocInfo = CCValAssign::SExt;
2888     else if (ArgFlags.isZExt())
2889       LocInfo = CCValAssign::ZExt;
2890     else
2891       LocInfo = CCValAssign::AExt;
2892   }
2893 
2894   unsigned Reg;
2895 
2896   // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2897   // is true: function is vararg, argument is 3rd or higher, there is previous
2898   // argument which is not f32 or f64.
2899   bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2900                                 State.getFirstUnallocated(F32Regs) != ValNo;
2901   unsigned OrigAlign = ArgFlags.getOrigAlign();
2902   bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2903   bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo);
2904 
2905   // The MIPS vector ABI for floats passes them in a pair of registers
2906   if (ValVT == MVT::i32 && isVectorFloat) {
2907     // This is the start of an vector that was scalarized into an unknown number
2908     // of components. It doesn't matter how many there are. Allocate one of the
2909     // notional 8 byte aligned registers which map onto the argument stack, and
2910     // shadow the register lost to alignment requirements.
2911     if (ArgFlags.isSplit()) {
2912       Reg = State.AllocateReg(FloatVectorIntRegs);
2913       if (Reg == Mips::A2)
2914         State.AllocateReg(Mips::A1);
2915       else if (Reg == 0)
2916         State.AllocateReg(Mips::A3);
2917     } else {
2918       // If we're an intermediate component of the split, we can just attempt to
2919       // allocate a register directly.
2920       Reg = State.AllocateReg(IntRegs);
2921     }
2922   } else if (ValVT == MVT::i32 ||
2923              (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2924     Reg = State.AllocateReg(IntRegs);
2925     // If this is the first part of an i64 arg,
2926     // the allocated register must be either A0 or A2.
2927     if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2928       Reg = State.AllocateReg(IntRegs);
2929     LocVT = MVT::i32;
2930   } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2931     // Allocate int register and shadow next int register. If first
2932     // available register is Mips::A1 or Mips::A3, shadow it too.
2933     Reg = State.AllocateReg(IntRegs);
2934     if (Reg == Mips::A1 || Reg == Mips::A3)
2935       Reg = State.AllocateReg(IntRegs);
2936     State.AllocateReg(IntRegs);
2937     LocVT = MVT::i32;
2938   } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2939     // we are guaranteed to find an available float register
2940     if (ValVT == MVT::f32) {
2941       Reg = State.AllocateReg(F32Regs);
2942       // Shadow int register
2943       State.AllocateReg(IntRegs);
2944     } else {
2945       Reg = State.AllocateReg(F64Regs);
2946       // Shadow int registers
2947       unsigned Reg2 = State.AllocateReg(IntRegs);
2948       if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2949         State.AllocateReg(IntRegs);
2950       State.AllocateReg(IntRegs);
2951     }
2952   } else
2953     llvm_unreachable("Cannot handle this ValVT.");
2954 
2955   if (!Reg) {
2956     unsigned Offset = State.AllocateStack(ValVT.getStoreSize(), OrigAlign);
2957     State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2958   } else
2959     State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2960 
2961   return false;
2962 }
2963 
2964 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2965                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2966                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2967   static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2968 
2969   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2970 }
2971 
2972 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2973                             MVT LocVT, CCValAssign::LocInfo LocInfo,
2974                             ISD::ArgFlagsTy ArgFlags, CCState &State) {
2975   static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2976 
2977   return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2978 }
2979 
2980 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2981                        CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2982                        CCState &State) LLVM_ATTRIBUTE_UNUSED;
2983 
2984 #include "MipsGenCallingConv.inc"
2985 
2986  CCAssignFn *MipsTargetLowering::CCAssignFnForCall() const{
2987    return CC_Mips_FixedArg;
2988  }
2989 
2990  CCAssignFn *MipsTargetLowering::CCAssignFnForReturn() const{
2991    return RetCC_Mips;
2992  }
2993 //===----------------------------------------------------------------------===//
2994 //                  Call Calling Convention Implementation
2995 //===----------------------------------------------------------------------===//
2996 
2997 // Return next O32 integer argument register.
2998 static unsigned getNextIntArgReg(unsigned Reg) {
2999   assert((Reg == Mips::A0) || (Reg == Mips::A2));
3000   return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
3001 }
3002 
3003 SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
3004                                            SDValue Chain, SDValue Arg,
3005                                            const SDLoc &DL, bool IsTailCall,
3006                                            SelectionDAG &DAG) const {
3007   if (!IsTailCall) {
3008     SDValue PtrOff =
3009         DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
3010                     DAG.getIntPtrConstant(Offset, DL));
3011     return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
3012   }
3013 
3014   MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
3015   int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
3016   SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3017   return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
3018                       /* Alignment = */ 0, MachineMemOperand::MOVolatile);
3019 }
3020 
3021 void MipsTargetLowering::
3022 getOpndList(SmallVectorImpl<SDValue> &Ops,
3023             std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3024             bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
3025             bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
3026             SDValue Chain) const {
3027   // Insert node "GP copy globalreg" before call to function.
3028   //
3029   // R_MIPS_CALL* operators (emitted when non-internal functions are called
3030   // in PIC mode) allow symbols to be resolved via lazy binding.
3031   // The lazy binding stub requires GP to point to the GOT.
3032   // Note that we don't need GP to point to the GOT for indirect calls
3033   // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
3034   // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
3035   // used for the function (that is, Mips linker doesn't generate lazy binding
3036   // stub for a function whose address is taken in the program).
3037   if (IsPICCall && !InternalLinkage && IsCallReloc) {
3038     unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
3039     EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
3040     RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
3041   }
3042 
3043   // Build a sequence of copy-to-reg nodes chained together with token
3044   // chain and flag operands which copy the outgoing args into registers.
3045   // The InFlag in necessary since all emitted instructions must be
3046   // stuck together.
3047   SDValue InFlag;
3048 
3049   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3050     Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
3051                                  RegsToPass[i].second, InFlag);
3052     InFlag = Chain.getValue(1);
3053   }
3054 
3055   // Add argument registers to the end of the list so that they are
3056   // known live into the call.
3057   for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3058     Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
3059                                       RegsToPass[i].second.getValueType()));
3060 
3061   // Add a register mask operand representing the call-preserved registers.
3062   const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
3063   const uint32_t *Mask =
3064       TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
3065   assert(Mask && "Missing call preserved mask for calling convention");
3066   if (Subtarget.inMips16HardFloat()) {
3067     if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
3068       StringRef Sym = G->getGlobal()->getName();
3069       Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3070       if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3071         Mask = MipsRegisterInfo::getMips16RetHelperMask();
3072       }
3073     }
3074   }
3075   Ops.push_back(CLI.DAG.getRegisterMask(Mask));
3076 
3077   if (InFlag.getNode())
3078     Ops.push_back(InFlag);
3079 }
3080 
3081 void MipsTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
3082                                                        SDNode *Node) const {
3083   switch (MI.getOpcode()) {
3084     default:
3085       return;
3086     case Mips::JALR:
3087     case Mips::JALRPseudo:
3088     case Mips::JALR64:
3089     case Mips::JALR64Pseudo:
3090     case Mips::JALR16_MM:
3091     case Mips::JALRC16_MMR6:
3092     case Mips::TAILCALLREG:
3093     case Mips::TAILCALLREG64:
3094     case Mips::TAILCALLR6REG:
3095     case Mips::TAILCALL64R6REG:
3096     case Mips::TAILCALLREG_MM:
3097     case Mips::TAILCALLREG_MMR6: {
3098       if (!EmitJalrReloc ||
3099           Subtarget.inMips16Mode() ||
3100           !isPositionIndependent() ||
3101           Node->getNumOperands() < 1 ||
3102           Node->getOperand(0).getNumOperands() < 2) {
3103         return;
3104       }
3105       // We are after the callee address, set by LowerCall().
3106       // If added to MI, asm printer will emit .reloc R_MIPS_JALR for the
3107       // symbol.
3108       const SDValue TargetAddr = Node->getOperand(0).getOperand(1);
3109       StringRef Sym;
3110       if (const GlobalAddressSDNode *G =
3111               dyn_cast_or_null<const GlobalAddressSDNode>(TargetAddr)) {
3112         Sym = G->getGlobal()->getName();
3113       }
3114       else if (const ExternalSymbolSDNode *ES =
3115                    dyn_cast_or_null<const ExternalSymbolSDNode>(TargetAddr)) {
3116         Sym = ES->getSymbol();
3117       }
3118 
3119       if (Sym.empty())
3120         return;
3121 
3122       MachineFunction *MF = MI.getParent()->getParent();
3123       MCSymbol *S = MF->getContext().getOrCreateSymbol(Sym);
3124       MI.addOperand(MachineOperand::CreateMCSymbol(S, MipsII::MO_JALR));
3125     }
3126   }
3127 }
3128 
3129 /// LowerCall - functions arguments are copied from virtual regs to
3130 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3131 SDValue
3132 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3133                               SmallVectorImpl<SDValue> &InVals) const {
3134   SelectionDAG &DAG                     = CLI.DAG;
3135   SDLoc DL                              = CLI.DL;
3136   SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
3137   SmallVectorImpl<SDValue> &OutVals     = CLI.OutVals;
3138   SmallVectorImpl<ISD::InputArg> &Ins   = CLI.Ins;
3139   SDValue Chain                         = CLI.Chain;
3140   SDValue Callee                        = CLI.Callee;
3141   bool &IsTailCall                      = CLI.IsTailCall;
3142   CallingConv::ID CallConv              = CLI.CallConv;
3143   bool IsVarArg                         = CLI.IsVarArg;
3144 
3145   MachineFunction &MF = DAG.getMachineFunction();
3146   MachineFrameInfo &MFI = MF.getFrameInfo();
3147   const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3148   MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
3149   bool IsPIC = isPositionIndependent();
3150 
3151   // Analyze operands of the call, assigning locations to each operand.
3152   SmallVector<CCValAssign, 16> ArgLocs;
3153   MipsCCState CCInfo(
3154       CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
3155       MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
3156 
3157   const ExternalSymbolSDNode *ES =
3158       dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
3159 
3160   // There is one case where CALLSEQ_START..CALLSEQ_END can be nested, which
3161   // is during the lowering of a call with a byval argument which produces
3162   // a call to memcpy. For the O32 case, this causes the caller to allocate
3163   // stack space for the reserved argument area for the callee, then recursively
3164   // again for the memcpy call. In the NEWABI case, this doesn't occur as those
3165   // ABIs mandate that the callee allocates the reserved argument area. We do
3166   // still produce nested CALLSEQ_START..CALLSEQ_END with zero space though.
3167   //
3168   // If the callee has a byval argument and memcpy is used, we are mandated
3169   // to already have produced a reserved argument area for the callee for O32.
3170   // Therefore, the reserved argument area can be reused for both calls.
3171   //
3172   // Other cases of calling memcpy cannot have a chain with a CALLSEQ_START
3173   // present, as we have yet to hook that node onto the chain.
3174   //
3175   // Hence, the CALLSEQ_START and CALLSEQ_END nodes can be eliminated in this
3176   // case. GCC does a similar trick, in that wherever possible, it calculates
3177   // the maximum out going argument area (including the reserved area), and
3178   // preallocates the stack space on entrance to the caller.
3179   //
3180   // FIXME: We should do the same for efficiency and space.
3181 
3182   // Note: The check on the calling convention below must match
3183   //       MipsABIInfo::GetCalleeAllocdArgSizeInBytes().
3184   bool MemcpyInByVal = ES &&
3185                        StringRef(ES->getSymbol()) == StringRef("memcpy") &&
3186                        CallConv != CallingConv::Fast &&
3187                        Chain.getOpcode() == ISD::CALLSEQ_START;
3188 
3189   // Allocate the reserved argument area. It seems strange to do this from the
3190   // caller side but removing it breaks the frame size calculation.
3191   unsigned ReservedArgArea =
3192       MemcpyInByVal ? 0 : ABI.GetCalleeAllocdArgSizeInBytes(CallConv);
3193   CCInfo.AllocateStack(ReservedArgArea, 1);
3194 
3195   CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
3196                              ES ? ES->getSymbol() : nullptr);
3197 
3198   // Get a count of how many bytes are to be pushed on the stack.
3199   unsigned NextStackOffset = CCInfo.getNextStackOffset();
3200 
3201   // Check if it's really possible to do a tail call. Restrict it to functions
3202   // that are part of this compilation unit.
3203   bool InternalLinkage = false;
3204   if (IsTailCall) {
3205     IsTailCall = isEligibleForTailCallOptimization(
3206         CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
3207      if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3208       InternalLinkage = G->getGlobal()->hasInternalLinkage();
3209       IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
3210                      G->getGlobal()->hasPrivateLinkage() ||
3211                      G->getGlobal()->hasHiddenVisibility() ||
3212                      G->getGlobal()->hasProtectedVisibility());
3213      }
3214   }
3215   if (!IsTailCall && CLI.CS && CLI.CS.isMustTailCall())
3216     report_fatal_error("failed to perform tail call elimination on a call "
3217                        "site marked musttail");
3218 
3219   if (IsTailCall)
3220     ++NumTailCalls;
3221 
3222   // Chain is the output chain of the last Load/Store or CopyToReg node.
3223   // ByValChain is the output chain of the last Memcpy node created for copying
3224   // byval arguments to the stack.
3225   unsigned StackAlignment = TFL->getStackAlignment();
3226   NextStackOffset = alignTo(NextStackOffset, StackAlignment);
3227   SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
3228 
3229   if (!(IsTailCall || MemcpyInByVal))
3230     Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL);
3231 
3232   SDValue StackPtr =
3233       DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
3234                          getPointerTy(DAG.getDataLayout()));
3235 
3236   std::deque<std::pair<unsigned, SDValue>> RegsToPass;
3237   SmallVector<SDValue, 8> MemOpChains;
3238 
3239   CCInfo.rewindByValRegsInfo();
3240 
3241   // Walk the register/memloc assignments, inserting copies/loads.
3242   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3243     SDValue Arg = OutVals[i];
3244     CCValAssign &VA = ArgLocs[i];
3245     MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3246     ISD::ArgFlagsTy Flags = Outs[i].Flags;
3247     bool UseUpperBits = false;
3248 
3249     // ByVal Arg.
3250     if (Flags.isByVal()) {
3251       unsigned FirstByValReg, LastByValReg;
3252       unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3253       CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3254 
3255       assert(Flags.getByValSize() &&
3256              "ByVal args of size 0 should have been ignored by front-end.");
3257       assert(ByValIdx < CCInfo.getInRegsParamsCount());
3258       assert(!IsTailCall &&
3259              "Do not tail-call optimize if there is a byval argument.");
3260       passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3261                    FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3262                    VA);
3263       CCInfo.nextInRegsParam();
3264       continue;
3265     }
3266 
3267     // Promote the value if needed.
3268     switch (VA.getLocInfo()) {
3269     default:
3270       llvm_unreachable("Unknown loc info!");
3271     case CCValAssign::Full:
3272       if (VA.isRegLoc()) {
3273         if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3274             (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3275             (ValVT == MVT::i64 && LocVT == MVT::f64))
3276           Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3277         else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3278           SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3279                                    Arg, DAG.getConstant(0, DL, MVT::i32));
3280           SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3281                                    Arg, DAG.getConstant(1, DL, MVT::i32));
3282           if (!Subtarget.isLittle())
3283             std::swap(Lo, Hi);
3284           Register LocRegLo = VA.getLocReg();
3285           unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3286           RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3287           RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3288           continue;
3289         }
3290       }
3291       break;
3292     case CCValAssign::BCvt:
3293       Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3294       break;
3295     case CCValAssign::SExtUpper:
3296       UseUpperBits = true;
3297       LLVM_FALLTHROUGH;
3298     case CCValAssign::SExt:
3299       Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3300       break;
3301     case CCValAssign::ZExtUpper:
3302       UseUpperBits = true;
3303       LLVM_FALLTHROUGH;
3304     case CCValAssign::ZExt:
3305       Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3306       break;
3307     case CCValAssign::AExtUpper:
3308       UseUpperBits = true;
3309       LLVM_FALLTHROUGH;
3310     case CCValAssign::AExt:
3311       Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3312       break;
3313     }
3314 
3315     if (UseUpperBits) {
3316       unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3317       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3318       Arg = DAG.getNode(
3319           ISD::SHL, DL, VA.getLocVT(), Arg,
3320           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3321     }
3322 
3323     // Arguments that can be passed on register must be kept at
3324     // RegsToPass vector
3325     if (VA.isRegLoc()) {
3326       RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3327       continue;
3328     }
3329 
3330     // Register can't get to this point...
3331     assert(VA.isMemLoc());
3332 
3333     // emit ISD::STORE whichs stores the
3334     // parameter value to a stack Location
3335     MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3336                                          Chain, Arg, DL, IsTailCall, DAG));
3337   }
3338 
3339   // Transform all store nodes into one single node because all store
3340   // nodes are independent of each other.
3341   if (!MemOpChains.empty())
3342     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3343 
3344   // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3345   // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3346   // node so that legalize doesn't hack it.
3347 
3348   EVT Ty = Callee.getValueType();
3349   bool GlobalOrExternal = false, IsCallReloc = false;
3350 
3351   // The long-calls feature is ignored in case of PIC.
3352   // While we do not support -mshared / -mno-shared properly,
3353   // ignore long-calls in case of -mabicalls too.
3354   if (!Subtarget.isABICalls() && !IsPIC) {
3355     // If the function should be called using "long call",
3356     // get its address into a register to prevent using
3357     // of the `jal` instruction for the direct call.
3358     if (auto *N = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3359       if (Subtarget.useLongCalls())
3360         Callee = Subtarget.hasSym32()
3361                      ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3362                      : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3363     } else if (auto *N = dyn_cast<GlobalAddressSDNode>(Callee)) {
3364       bool UseLongCalls = Subtarget.useLongCalls();
3365       // If the function has long-call/far/near attribute
3366       // it overrides command line switch pased to the backend.
3367       if (auto *F = dyn_cast<Function>(N->getGlobal())) {
3368         if (F->hasFnAttribute("long-call"))
3369           UseLongCalls = true;
3370         else if (F->hasFnAttribute("short-call"))
3371           UseLongCalls = false;
3372       }
3373       if (UseLongCalls)
3374         Callee = Subtarget.hasSym32()
3375                      ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
3376                      : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
3377     }
3378   }
3379 
3380   if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3381     if (IsPIC) {
3382       const GlobalValue *Val = G->getGlobal();
3383       InternalLinkage = Val->hasInternalLinkage();
3384 
3385       if (InternalLinkage)
3386         Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3387       else if (Subtarget.useXGOT()) {
3388         Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3389                                        MipsII::MO_CALL_LO16, Chain,
3390                                        FuncInfo->callPtrInfo(Val));
3391         IsCallReloc = true;
3392       } else {
3393         Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3394                                FuncInfo->callPtrInfo(Val));
3395         IsCallReloc = true;
3396       }
3397     } else
3398       Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3399                                           getPointerTy(DAG.getDataLayout()), 0,
3400                                           MipsII::MO_NO_FLAG);
3401     GlobalOrExternal = true;
3402   }
3403   else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3404     const char *Sym = S->getSymbol();
3405 
3406     if (!IsPIC) // static
3407       Callee = DAG.getTargetExternalSymbol(
3408           Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
3409     else if (Subtarget.useXGOT()) {
3410       Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3411                                      MipsII::MO_CALL_LO16, Chain,
3412                                      FuncInfo->callPtrInfo(Sym));
3413       IsCallReloc = true;
3414     } else { // PIC
3415       Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3416                              FuncInfo->callPtrInfo(Sym));
3417       IsCallReloc = true;
3418     }
3419 
3420     GlobalOrExternal = true;
3421   }
3422 
3423   SmallVector<SDValue, 8> Ops(1, Chain);
3424   SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3425 
3426   getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3427               IsCallReloc, CLI, Callee, Chain);
3428 
3429   if (IsTailCall) {
3430     MF.getFrameInfo().setHasTailCall();
3431     return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3432   }
3433 
3434   Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3435   SDValue InFlag = Chain.getValue(1);
3436 
3437   // Create the CALLSEQ_END node in the case of where it is not a call to
3438   // memcpy.
3439   if (!(MemcpyInByVal)) {
3440     Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3441                                DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3442     InFlag = Chain.getValue(1);
3443   }
3444 
3445   // Handle result values, copying them out of physregs into vregs that we
3446   // return.
3447   return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3448                          InVals, CLI);
3449 }
3450 
3451 /// LowerCallResult - Lower the result values of a call into the
3452 /// appropriate copies out of appropriate physical registers.
3453 SDValue MipsTargetLowering::LowerCallResult(
3454     SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
3455     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3456     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3457     TargetLowering::CallLoweringInfo &CLI) const {
3458   // Assign locations to each value returned by this call.
3459   SmallVector<CCValAssign, 16> RVLocs;
3460   MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3461                      *DAG.getContext());
3462 
3463   const ExternalSymbolSDNode *ES =
3464       dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3465   CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3466                            ES ? ES->getSymbol() : nullptr);
3467 
3468   // Copy all of the result registers out of their specified physreg.
3469   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3470     CCValAssign &VA = RVLocs[i];
3471     assert(VA.isRegLoc() && "Can only return in registers!");
3472 
3473     SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3474                                      RVLocs[i].getLocVT(), InFlag);
3475     Chain = Val.getValue(1);
3476     InFlag = Val.getValue(2);
3477 
3478     if (VA.isUpperBitsInLoc()) {
3479       unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3480       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3481       unsigned Shift =
3482           VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3483       Val = DAG.getNode(
3484           Shift, DL, VA.getLocVT(), Val,
3485           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3486     }
3487 
3488     switch (VA.getLocInfo()) {
3489     default:
3490       llvm_unreachable("Unknown loc info!");
3491     case CCValAssign::Full:
3492       break;
3493     case CCValAssign::BCvt:
3494       Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3495       break;
3496     case CCValAssign::AExt:
3497     case CCValAssign::AExtUpper:
3498       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3499       break;
3500     case CCValAssign::ZExt:
3501     case CCValAssign::ZExtUpper:
3502       Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3503                         DAG.getValueType(VA.getValVT()));
3504       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3505       break;
3506     case CCValAssign::SExt:
3507     case CCValAssign::SExtUpper:
3508       Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3509                         DAG.getValueType(VA.getValVT()));
3510       Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3511       break;
3512     }
3513 
3514     InVals.push_back(Val);
3515   }
3516 
3517   return Chain;
3518 }
3519 
3520 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
3521                                       EVT ArgVT, const SDLoc &DL,
3522                                       SelectionDAG &DAG) {
3523   MVT LocVT = VA.getLocVT();
3524   EVT ValVT = VA.getValVT();
3525 
3526   // Shift into the upper bits if necessary.
3527   switch (VA.getLocInfo()) {
3528   default:
3529     break;
3530   case CCValAssign::AExtUpper:
3531   case CCValAssign::SExtUpper:
3532   case CCValAssign::ZExtUpper: {
3533     unsigned ValSizeInBits = ArgVT.getSizeInBits();
3534     unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3535     unsigned Opcode =
3536         VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3537     Val = DAG.getNode(
3538         Opcode, DL, VA.getLocVT(), Val,
3539         DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3540     break;
3541   }
3542   }
3543 
3544   // If this is an value smaller than the argument slot size (32-bit for O32,
3545   // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3546   // size. Extract the value and insert any appropriate assertions regarding
3547   // sign/zero extension.
3548   switch (VA.getLocInfo()) {
3549   default:
3550     llvm_unreachable("Unknown loc info!");
3551   case CCValAssign::Full:
3552     break;
3553   case CCValAssign::AExtUpper:
3554   case CCValAssign::AExt:
3555     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3556     break;
3557   case CCValAssign::SExtUpper:
3558   case CCValAssign::SExt:
3559     Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3560     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3561     break;
3562   case CCValAssign::ZExtUpper:
3563   case CCValAssign::ZExt:
3564     Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3565     Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3566     break;
3567   case CCValAssign::BCvt:
3568     Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3569     break;
3570   }
3571 
3572   return Val;
3573 }
3574 
3575 //===----------------------------------------------------------------------===//
3576 //             Formal Arguments Calling Convention Implementation
3577 //===----------------------------------------------------------------------===//
3578 /// LowerFormalArguments - transform physical registers into virtual registers
3579 /// and generate load operations for arguments places on the stack.
3580 SDValue MipsTargetLowering::LowerFormalArguments(
3581     SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3582     const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3583     SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3584   MachineFunction &MF = DAG.getMachineFunction();
3585   MachineFrameInfo &MFI = MF.getFrameInfo();
3586   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3587 
3588   MipsFI->setVarArgsFrameIndex(0);
3589 
3590   // Used with vargs to acumulate store chains.
3591   std::vector<SDValue> OutChains;
3592 
3593   // Assign locations to all of the incoming arguments.
3594   SmallVector<CCValAssign, 16> ArgLocs;
3595   MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3596                      *DAG.getContext());
3597   CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
3598   const Function &Func = DAG.getMachineFunction().getFunction();
3599   Function::const_arg_iterator FuncArg = Func.arg_begin();
3600 
3601   if (Func.hasFnAttribute("interrupt") && !Func.arg_empty())
3602     report_fatal_error(
3603         "Functions with the interrupt attribute cannot have arguments!");
3604 
3605   CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3606   MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3607                            CCInfo.getInRegsParamsCount() > 0);
3608 
3609   unsigned CurArgIdx = 0;
3610   CCInfo.rewindByValRegsInfo();
3611 
3612   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3613     CCValAssign &VA = ArgLocs[i];
3614     if (Ins[i].isOrigArg()) {
3615       std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3616       CurArgIdx = Ins[i].getOrigArgIndex();
3617     }
3618     EVT ValVT = VA.getValVT();
3619     ISD::ArgFlagsTy Flags = Ins[i].Flags;
3620     bool IsRegLoc = VA.isRegLoc();
3621 
3622     if (Flags.isByVal()) {
3623       assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
3624       unsigned FirstByValReg, LastByValReg;
3625       unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3626       CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3627 
3628       assert(Flags.getByValSize() &&
3629              "ByVal args of size 0 should have been ignored by front-end.");
3630       assert(ByValIdx < CCInfo.getInRegsParamsCount());
3631       copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3632                     FirstByValReg, LastByValReg, VA, CCInfo);
3633       CCInfo.nextInRegsParam();
3634       continue;
3635     }
3636 
3637     // Arguments stored on registers
3638     if (IsRegLoc) {
3639       MVT RegVT = VA.getLocVT();
3640       Register ArgReg = VA.getLocReg();
3641       const TargetRegisterClass *RC = getRegClassFor(RegVT);
3642 
3643       // Transform the arguments stored on
3644       // physical registers into virtual ones
3645       unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3646       SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3647 
3648       ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3649 
3650       // Handle floating point arguments passed in integer registers and
3651       // long double arguments passed in floating point registers.
3652       if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3653           (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3654           (RegVT == MVT::f64 && ValVT == MVT::i64))
3655         ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3656       else if (ABI.IsO32() && RegVT == MVT::i32 &&
3657                ValVT == MVT::f64) {
3658         unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3659                                   getNextIntArgReg(ArgReg), RC);
3660         SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3661         if (!Subtarget.isLittle())
3662           std::swap(ArgValue, ArgValue2);
3663         ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3664                                ArgValue, ArgValue2);
3665       }
3666 
3667       InVals.push_back(ArgValue);
3668     } else { // VA.isRegLoc()
3669       MVT LocVT = VA.getLocVT();
3670 
3671       if (ABI.IsO32()) {
3672         // We ought to be able to use LocVT directly but O32 sets it to i32
3673         // when allocating floating point values to integer registers.
3674         // This shouldn't influence how we load the value into registers unless
3675         // we are targeting softfloat.
3676         if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3677           LocVT = VA.getValVT();
3678       }
3679 
3680       // sanity check
3681       assert(VA.isMemLoc());
3682 
3683       // The stack pointer offset is relative to the caller stack frame.
3684       int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3685                                      VA.getLocMemOffset(), true);
3686 
3687       // Create load nodes to retrieve arguments from the stack
3688       SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3689       SDValue ArgValue = DAG.getLoad(
3690           LocVT, DL, Chain, FIN,
3691           MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3692       OutChains.push_back(ArgValue.getValue(1));
3693 
3694       ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3695 
3696       InVals.push_back(ArgValue);
3697     }
3698   }
3699 
3700   for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3701     // The mips ABIs for returning structs by value requires that we copy
3702     // the sret argument into $v0 for the return. Save the argument into
3703     // a virtual register so that we can access it from the return points.
3704     if (Ins[i].Flags.isSRet()) {
3705       unsigned Reg = MipsFI->getSRetReturnReg();
3706       if (!Reg) {
3707         Reg = MF.getRegInfo().createVirtualRegister(
3708             getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3709         MipsFI->setSRetReturnReg(Reg);
3710       }
3711       SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3712       Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3713       break;
3714     }
3715   }
3716 
3717   if (IsVarArg)
3718     writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3719 
3720   // All stores are grouped in one node to allow the matching between
3721   // the size of Ins and InVals. This only happens when on varg functions
3722   if (!OutChains.empty()) {
3723     OutChains.push_back(Chain);
3724     Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3725   }
3726 
3727   return Chain;
3728 }
3729 
3730 //===----------------------------------------------------------------------===//
3731 //               Return Value Calling Convention Implementation
3732 //===----------------------------------------------------------------------===//
3733 
3734 bool
3735 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3736                                    MachineFunction &MF, bool IsVarArg,
3737                                    const SmallVectorImpl<ISD::OutputArg> &Outs,
3738                                    LLVMContext &Context) const {
3739   SmallVector<CCValAssign, 16> RVLocs;
3740   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3741   return CCInfo.CheckReturn(Outs, RetCC_Mips);
3742 }
3743 
3744 bool MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type,
3745                                                        bool IsSigned) const {
3746   if ((ABI.IsN32() || ABI.IsN64()) && Type == MVT::i32)
3747       return true;
3748 
3749   return IsSigned;
3750 }
3751 
3752 SDValue
3753 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3754                                          const SDLoc &DL,
3755                                          SelectionDAG &DAG) const {
3756   MachineFunction &MF = DAG.getMachineFunction();
3757   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3758 
3759   MipsFI->setISR();
3760 
3761   return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3762 }
3763 
3764 SDValue
3765 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3766                                 bool IsVarArg,
3767                                 const SmallVectorImpl<ISD::OutputArg> &Outs,
3768                                 const SmallVectorImpl<SDValue> &OutVals,
3769                                 const SDLoc &DL, SelectionDAG &DAG) const {
3770   // CCValAssign - represent the assignment of
3771   // the return value to a location
3772   SmallVector<CCValAssign, 16> RVLocs;
3773   MachineFunction &MF = DAG.getMachineFunction();
3774 
3775   // CCState - Info about the registers and stack slot.
3776   MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3777 
3778   // Analyze return values.
3779   CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3780 
3781   SDValue Flag;
3782   SmallVector<SDValue, 4> RetOps(1, Chain);
3783 
3784   // Copy the result values into the output registers.
3785   for (unsigned i = 0; i != RVLocs.size(); ++i) {
3786     SDValue Val = OutVals[i];
3787     CCValAssign &VA = RVLocs[i];
3788     assert(VA.isRegLoc() && "Can only return in registers!");
3789     bool UseUpperBits = false;
3790 
3791     switch (VA.getLocInfo()) {
3792     default:
3793       llvm_unreachable("Unknown loc info!");
3794     case CCValAssign::Full:
3795       break;
3796     case CCValAssign::BCvt:
3797       Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3798       break;
3799     case CCValAssign::AExtUpper:
3800       UseUpperBits = true;
3801       LLVM_FALLTHROUGH;
3802     case CCValAssign::AExt:
3803       Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3804       break;
3805     case CCValAssign::ZExtUpper:
3806       UseUpperBits = true;
3807       LLVM_FALLTHROUGH;
3808     case CCValAssign::ZExt:
3809       Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3810       break;
3811     case CCValAssign::SExtUpper:
3812       UseUpperBits = true;
3813       LLVM_FALLTHROUGH;
3814     case CCValAssign::SExt:
3815       Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3816       break;
3817     }
3818 
3819     if (UseUpperBits) {
3820       unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3821       unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3822       Val = DAG.getNode(
3823           ISD::SHL, DL, VA.getLocVT(), Val,
3824           DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3825     }
3826 
3827     Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3828 
3829     // Guarantee that all emitted copies are stuck together with flags.
3830     Flag = Chain.getValue(1);
3831     RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3832   }
3833 
3834   // The mips ABIs for returning structs by value requires that we copy
3835   // the sret argument into $v0 for the return. We saved the argument into
3836   // a virtual register in the entry block, so now we copy the value out
3837   // and into $v0.
3838   if (MF.getFunction().hasStructRetAttr()) {
3839     MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3840     unsigned Reg = MipsFI->getSRetReturnReg();
3841 
3842     if (!Reg)
3843       llvm_unreachable("sret virtual register not created in the entry block");
3844     SDValue Val =
3845         DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3846     unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3847 
3848     Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3849     Flag = Chain.getValue(1);
3850     RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3851   }
3852 
3853   RetOps[0] = Chain;  // Update chain.
3854 
3855   // Add the flag if we have it.
3856   if (Flag.getNode())
3857     RetOps.push_back(Flag);
3858 
3859   // ISRs must use "eret".
3860   if (DAG.getMachineFunction().getFunction().hasFnAttribute("interrupt"))
3861     return LowerInterruptReturn(RetOps, DL, DAG);
3862 
3863   // Standard return on Mips is a "jr $ra"
3864   return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3865 }
3866 
3867 //===----------------------------------------------------------------------===//
3868 //                           Mips Inline Assembly Support
3869 //===----------------------------------------------------------------------===//
3870 
3871 /// getConstraintType - Given a constraint letter, return the type of
3872 /// constraint it is for this target.
3873 MipsTargetLowering::ConstraintType
3874 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3875   // Mips specific constraints
3876   // GCC config/mips/constraints.md
3877   //
3878   // 'd' : An address register. Equivalent to r
3879   //       unless generating MIPS16 code.
3880   // 'y' : Equivalent to r; retained for
3881   //       backwards compatibility.
3882   // 'c' : A register suitable for use in an indirect
3883   //       jump. This will always be $25 for -mabicalls.
3884   // 'l' : The lo register. 1 word storage.
3885   // 'x' : The hilo register pair. Double word storage.
3886   if (Constraint.size() == 1) {
3887     switch (Constraint[0]) {
3888       default : break;
3889       case 'd':
3890       case 'y':
3891       case 'f':
3892       case 'c':
3893       case 'l':
3894       case 'x':
3895         return C_RegisterClass;
3896       case 'R':
3897         return C_Memory;
3898     }
3899   }
3900 
3901   if (Constraint == "ZC")
3902     return C_Memory;
3903 
3904   return TargetLowering::getConstraintType(Constraint);
3905 }
3906 
3907 /// Examine constraint type and operand type and determine a weight value.
3908 /// This object must already have been set up with the operand type
3909 /// and the current alternative constraint selected.
3910 TargetLowering::ConstraintWeight
3911 MipsTargetLowering::getSingleConstraintMatchWeight(
3912     AsmOperandInfo &info, const char *constraint) const {
3913   ConstraintWeight weight = CW_Invalid;
3914   Value *CallOperandVal = info.CallOperandVal;
3915     // If we don't have a value, we can't do a match,
3916     // but allow it at the lowest weight.
3917   if (!CallOperandVal)
3918     return CW_Default;
3919   Type *type = CallOperandVal->getType();
3920   // Look at the constraint type.
3921   switch (*constraint) {
3922   default:
3923     weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3924     break;
3925   case 'd':
3926   case 'y':
3927     if (type->isIntegerTy())
3928       weight = CW_Register;
3929     break;
3930   case 'f': // FPU or MSA register
3931     if (Subtarget.hasMSA() && type->isVectorTy() &&
3932         cast<VectorType>(type)->getBitWidth() == 128)
3933       weight = CW_Register;
3934     else if (type->isFloatTy())
3935       weight = CW_Register;
3936     break;
3937   case 'c': // $25 for indirect jumps
3938   case 'l': // lo register
3939   case 'x': // hilo register pair
3940     if (type->isIntegerTy())
3941       weight = CW_SpecificReg;
3942     break;
3943   case 'I': // signed 16 bit immediate
3944   case 'J': // integer zero
3945   case 'K': // unsigned 16 bit immediate
3946   case 'L': // signed 32 bit immediate where lower 16 bits are 0
3947   case 'N': // immediate in the range of -65535 to -1 (inclusive)
3948   case 'O': // signed 15 bit immediate (+- 16383)
3949   case 'P': // immediate in the range of 65535 to 1 (inclusive)
3950     if (isa<ConstantInt>(CallOperandVal))
3951       weight = CW_Constant;
3952     break;
3953   case 'R':
3954     weight = CW_Memory;
3955     break;
3956   }
3957   return weight;
3958 }
3959 
3960 /// This is a helper function to parse a physical register string and split it
3961 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3962 /// that is returned indicates whether parsing was successful. The second flag
3963 /// is true if the numeric part exists.
3964 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3965                                               unsigned long long &Reg) {
3966   if (C.front() != '{' || C.back() != '}')
3967     return std::make_pair(false, false);
3968 
3969   // Search for the first numeric character.
3970   StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3971   I = std::find_if(B, E, isdigit);
3972 
3973   Prefix = StringRef(B, I - B);
3974 
3975   // The second flag is set to false if no numeric characters were found.
3976   if (I == E)
3977     return std::make_pair(true, false);
3978 
3979   // Parse the numeric characters.
3980   return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3981                         true);
3982 }
3983 
3984 EVT MipsTargetLowering::getTypeForExtReturn(LLVMContext &Context, EVT VT,
3985                                             ISD::NodeType) const {
3986   bool Cond = !Subtarget.isABI_O32() && VT.getSizeInBits() == 32;
3987   EVT MinVT = getRegisterType(Context, Cond ? MVT::i64 : MVT::i32);
3988   return VT.bitsLT(MinVT) ? MinVT : VT;
3989 }
3990 
3991 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3992 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3993   const TargetRegisterInfo *TRI =
3994       Subtarget.getRegisterInfo();
3995   const TargetRegisterClass *RC;
3996   StringRef Prefix;
3997   unsigned long long Reg;
3998 
3999   std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
4000 
4001   if (!R.first)
4002     return std::make_pair(0U, nullptr);
4003 
4004   if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
4005     // No numeric characters follow "hi" or "lo".
4006     if (R.second)
4007       return std::make_pair(0U, nullptr);
4008 
4009     RC = TRI->getRegClass(Prefix == "hi" ?
4010                           Mips::HI32RegClassID : Mips::LO32RegClassID);
4011     return std::make_pair(*(RC->begin()), RC);
4012   } else if (Prefix.startswith("$msa")) {
4013     // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
4014 
4015     // No numeric characters follow the name.
4016     if (R.second)
4017       return std::make_pair(0U, nullptr);
4018 
4019     Reg = StringSwitch<unsigned long long>(Prefix)
4020               .Case("$msair", Mips::MSAIR)
4021               .Case("$msacsr", Mips::MSACSR)
4022               .Case("$msaaccess", Mips::MSAAccess)
4023               .Case("$msasave", Mips::MSASave)
4024               .Case("$msamodify", Mips::MSAModify)
4025               .Case("$msarequest", Mips::MSARequest)
4026               .Case("$msamap", Mips::MSAMap)
4027               .Case("$msaunmap", Mips::MSAUnmap)
4028               .Default(0);
4029 
4030     if (!Reg)
4031       return std::make_pair(0U, nullptr);
4032 
4033     RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
4034     return std::make_pair(Reg, RC);
4035   }
4036 
4037   if (!R.second)
4038     return std::make_pair(0U, nullptr);
4039 
4040   if (Prefix == "$f") { // Parse $f0-$f31.
4041     // If the size of FP registers is 64-bit or Reg is an even number, select
4042     // the 64-bit register class. Otherwise, select the 32-bit register class.
4043     if (VT == MVT::Other)
4044       VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
4045 
4046     RC = getRegClassFor(VT);
4047 
4048     if (RC == &Mips::AFGR64RegClass) {
4049       assert(Reg % 2 == 0);
4050       Reg >>= 1;
4051     }
4052   } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
4053     RC = TRI->getRegClass(Mips::FCCRegClassID);
4054   else if (Prefix == "$w") { // Parse $w0-$w31.
4055     RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
4056   } else { // Parse $0-$31.
4057     assert(Prefix == "$");
4058     RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
4059   }
4060 
4061   assert(Reg < RC->getNumRegs());
4062   return std::make_pair(*(RC->begin() + Reg), RC);
4063 }
4064 
4065 /// Given a register class constraint, like 'r', if this corresponds directly
4066 /// to an LLVM register class, return a register of 0 and the register class
4067 /// pointer.
4068 std::pair<unsigned, const TargetRegisterClass *>
4069 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
4070                                                  StringRef Constraint,
4071                                                  MVT VT) const {
4072   if (Constraint.size() == 1) {
4073     switch (Constraint[0]) {
4074     case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
4075     case 'y': // Same as 'r'. Exists for compatibility.
4076     case 'r':
4077       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
4078         if (Subtarget.inMips16Mode())
4079           return std::make_pair(0U, &Mips::CPU16RegsRegClass);
4080         return std::make_pair(0U, &Mips::GPR32RegClass);
4081       }
4082       if (VT == MVT::i64 && !Subtarget.isGP64bit())
4083         return std::make_pair(0U, &Mips::GPR32RegClass);
4084       if (VT == MVT::i64 && Subtarget.isGP64bit())
4085         return std::make_pair(0U, &Mips::GPR64RegClass);
4086       // This will generate an error message
4087       return std::make_pair(0U, nullptr);
4088     case 'f': // FPU or MSA register
4089       if (VT == MVT::v16i8)
4090         return std::make_pair(0U, &Mips::MSA128BRegClass);
4091       else if (VT == MVT::v8i16 || VT == MVT::v8f16)
4092         return std::make_pair(0U, &Mips::MSA128HRegClass);
4093       else if (VT == MVT::v4i32 || VT == MVT::v4f32)
4094         return std::make_pair(0U, &Mips::MSA128WRegClass);
4095       else if (VT == MVT::v2i64 || VT == MVT::v2f64)
4096         return std::make_pair(0U, &Mips::MSA128DRegClass);
4097       else if (VT == MVT::f32)
4098         return std::make_pair(0U, &Mips::FGR32RegClass);
4099       else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
4100         if (Subtarget.isFP64bit())
4101           return std::make_pair(0U, &Mips::FGR64RegClass);
4102         return std::make_pair(0U, &Mips::AFGR64RegClass);
4103       }
4104       break;
4105     case 'c': // register suitable for indirect jump
4106       if (VT == MVT::i32)
4107         return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
4108       if (VT == MVT::i64)
4109         return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
4110       // This will generate an error message
4111       return std::make_pair(0U, nullptr);
4112     case 'l': // use the `lo` register to store values
4113               // that are no bigger than a word
4114       if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
4115         return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
4116       return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
4117     case 'x': // use the concatenated `hi` and `lo` registers
4118               // to store doubleword values
4119       // Fixme: Not triggering the use of both hi and low
4120       // This will generate an error message
4121       return std::make_pair(0U, nullptr);
4122     }
4123   }
4124 
4125   if (!Constraint.empty()) {
4126     std::pair<unsigned, const TargetRegisterClass *> R;
4127     R = parseRegForInlineAsmConstraint(Constraint, VT);
4128 
4129     if (R.second)
4130       return R;
4131   }
4132 
4133   return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
4134 }
4135 
4136 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
4137 /// vector.  If it is invalid, don't add anything to Ops.
4138 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
4139                                                      std::string &Constraint,
4140                                                      std::vector<SDValue>&Ops,
4141                                                      SelectionDAG &DAG) const {
4142   SDLoc DL(Op);
4143   SDValue Result;
4144 
4145   // Only support length 1 constraints for now.
4146   if (Constraint.length() > 1) return;
4147 
4148   char ConstraintLetter = Constraint[0];
4149   switch (ConstraintLetter) {
4150   default: break; // This will fall through to the generic implementation
4151   case 'I': // Signed 16 bit constant
4152     // If this fails, the parent routine will give an error
4153     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4154       EVT Type = Op.getValueType();
4155       int64_t Val = C->getSExtValue();
4156       if (isInt<16>(Val)) {
4157         Result = DAG.getTargetConstant(Val, DL, Type);
4158         break;
4159       }
4160     }
4161     return;
4162   case 'J': // integer zero
4163     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4164       EVT Type = Op.getValueType();
4165       int64_t Val = C->getZExtValue();
4166       if (Val == 0) {
4167         Result = DAG.getTargetConstant(0, DL, Type);
4168         break;
4169       }
4170     }
4171     return;
4172   case 'K': // unsigned 16 bit immediate
4173     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4174       EVT Type = Op.getValueType();
4175       uint64_t Val = (uint64_t)C->getZExtValue();
4176       if (isUInt<16>(Val)) {
4177         Result = DAG.getTargetConstant(Val, DL, Type);
4178         break;
4179       }
4180     }
4181     return;
4182   case 'L': // signed 32 bit immediate where lower 16 bits are 0
4183     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4184       EVT Type = Op.getValueType();
4185       int64_t Val = C->getSExtValue();
4186       if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
4187         Result = DAG.getTargetConstant(Val, DL, Type);
4188         break;
4189       }
4190     }
4191     return;
4192   case 'N': // immediate in the range of -65535 to -1 (inclusive)
4193     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4194       EVT Type = Op.getValueType();
4195       int64_t Val = C->getSExtValue();
4196       if ((Val >= -65535) && (Val <= -1)) {
4197         Result = DAG.getTargetConstant(Val, DL, Type);
4198         break;
4199       }
4200     }
4201     return;
4202   case 'O': // signed 15 bit immediate
4203     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4204       EVT Type = Op.getValueType();
4205       int64_t Val = C->getSExtValue();
4206       if ((isInt<15>(Val))) {
4207         Result = DAG.getTargetConstant(Val, DL, Type);
4208         break;
4209       }
4210     }
4211     return;
4212   case 'P': // immediate in the range of 1 to 65535 (inclusive)
4213     if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4214       EVT Type = Op.getValueType();
4215       int64_t Val = C->getSExtValue();
4216       if ((Val <= 65535) && (Val >= 1)) {
4217         Result = DAG.getTargetConstant(Val, DL, Type);
4218         break;
4219       }
4220     }
4221     return;
4222   }
4223 
4224   if (Result.getNode()) {
4225     Ops.push_back(Result);
4226     return;
4227   }
4228 
4229   TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4230 }
4231 
4232 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
4233                                                const AddrMode &AM, Type *Ty,
4234                                                unsigned AS,
4235                                                Instruction *I) const {
4236   // No global is ever allowed as a base.
4237   if (AM.BaseGV)
4238     return false;
4239 
4240   switch (AM.Scale) {
4241   case 0: // "r+i" or just "i", depending on HasBaseReg.
4242     break;
4243   case 1:
4244     if (!AM.HasBaseReg) // allow "r+i".
4245       break;
4246     return false; // disallow "r+r" or "r+r+i".
4247   default:
4248     return false;
4249   }
4250 
4251   return true;
4252 }
4253 
4254 bool
4255 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4256   // The Mips target isn't yet aware of offsets.
4257   return false;
4258 }
4259 
4260 EVT MipsTargetLowering::getOptimalMemOpType(
4261     uint64_t Size, unsigned DstAlign, unsigned SrcAlign, bool IsMemset,
4262     bool ZeroMemset, bool MemcpyStrSrc,
4263     const AttributeList &FuncAttributes) const {
4264   if (Subtarget.hasMips64())
4265     return MVT::i64;
4266 
4267   return MVT::i32;
4268 }
4269 
4270 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
4271                                       bool ForCodeSize) const {
4272   if (VT != MVT::f32 && VT != MVT::f64)
4273     return false;
4274   if (Imm.isNegZero())
4275     return false;
4276   return Imm.isZero();
4277 }
4278 
4279 unsigned MipsTargetLowering::getJumpTableEncoding() const {
4280 
4281   // FIXME: For space reasons this should be: EK_GPRel32BlockAddress.
4282   if (ABI.IsN64() && isPositionIndependent())
4283     return MachineJumpTableInfo::EK_GPRel64BlockAddress;
4284 
4285   return TargetLowering::getJumpTableEncoding();
4286 }
4287 
4288 bool MipsTargetLowering::useSoftFloat() const {
4289   return Subtarget.useSoftFloat();
4290 }
4291 
4292 void MipsTargetLowering::copyByValRegs(
4293     SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4294     SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4295     SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4296     unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4297     MipsCCState &State) const {
4298   MachineFunction &MF = DAG.getMachineFunction();
4299   MachineFrameInfo &MFI = MF.getFrameInfo();
4300   unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4301   unsigned NumRegs = LastReg - FirstReg;
4302   unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4303   unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4304   int FrameObjOffset;
4305   ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4306 
4307   if (RegAreaSize)
4308     FrameObjOffset =
4309         (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4310         (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4311   else
4312     FrameObjOffset = VA.getLocMemOffset();
4313 
4314   // Create frame object.
4315   EVT PtrTy = getPointerTy(DAG.getDataLayout());
4316   // Make the fixed object stored to mutable so that the load instructions
4317   // referencing it have their memory dependencies added.
4318   // Set the frame object as isAliased which clears the underlying objects
4319   // vector in ScheduleDAGInstrs::buildSchedGraph() resulting in addition of all
4320   // stores as dependencies for loads referencing this fixed object.
4321   int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, false, true);
4322   SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4323   InVals.push_back(FIN);
4324 
4325   if (!NumRegs)
4326     return;
4327 
4328   // Copy arg registers.
4329   MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4330   const TargetRegisterClass *RC = getRegClassFor(RegTy);
4331 
4332   for (unsigned I = 0; I < NumRegs; ++I) {
4333     unsigned ArgReg = ByValArgRegs[FirstReg + I];
4334     unsigned VReg = addLiveIn(MF, ArgReg, RC);
4335     unsigned Offset = I * GPRSizeInBytes;
4336     SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4337                                    DAG.getConstant(Offset, DL, PtrTy));
4338     SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4339                                  StorePtr, MachinePointerInfo(FuncArg, Offset));
4340     OutChains.push_back(Store);
4341   }
4342 }
4343 
4344 // Copy byVal arg to registers and stack.
4345 void MipsTargetLowering::passByValArg(
4346     SDValue Chain, const SDLoc &DL,
4347     std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4348     SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4349     MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4350     unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4351     const CCValAssign &VA) const {
4352   unsigned ByValSizeInBytes = Flags.getByValSize();
4353   unsigned OffsetInBytes = 0; // From beginning of struct
4354   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4355   unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
4356   EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4357       RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4358   unsigned NumRegs = LastReg - FirstReg;
4359 
4360   if (NumRegs) {
4361     ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
4362     bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4363     unsigned I = 0;
4364 
4365     // Copy words to registers.
4366     for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4367       SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4368                                     DAG.getConstant(OffsetInBytes, DL, PtrTy));
4369       SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4370                                     MachinePointerInfo(), Alignment);
4371       MemOpChains.push_back(LoadVal.getValue(1));
4372       unsigned ArgReg = ArgRegs[FirstReg + I];
4373       RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4374     }
4375 
4376     // Return if the struct has been fully copied.
4377     if (ByValSizeInBytes == OffsetInBytes)
4378       return;
4379 
4380     // Copy the remainder of the byval argument with sub-word loads and shifts.
4381     if (LeftoverBytes) {
4382       SDValue Val;
4383 
4384       for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4385            OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4386         unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4387 
4388         if (RemainingSizeInBytes < LoadSizeInBytes)
4389           continue;
4390 
4391         // Load subword.
4392         SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4393                                       DAG.getConstant(OffsetInBytes, DL,
4394                                                       PtrTy));
4395         SDValue LoadVal = DAG.getExtLoad(
4396             ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4397             MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4398         MemOpChains.push_back(LoadVal.getValue(1));
4399 
4400         // Shift the loaded value.
4401         unsigned Shamt;
4402 
4403         if (isLittle)
4404           Shamt = TotalBytesLoaded * 8;
4405         else
4406           Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4407 
4408         SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4409                                     DAG.getConstant(Shamt, DL, MVT::i32));
4410 
4411         if (Val.getNode())
4412           Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4413         else
4414           Val = Shift;
4415 
4416         OffsetInBytes += LoadSizeInBytes;
4417         TotalBytesLoaded += LoadSizeInBytes;
4418         Alignment = std::min(Alignment, LoadSizeInBytes);
4419       }
4420 
4421       unsigned ArgReg = ArgRegs[FirstReg + I];
4422       RegsToPass.push_back(std::make_pair(ArgReg, Val));
4423       return;
4424     }
4425   }
4426 
4427   // Copy remainder of byval arg to it with memcpy.
4428   unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4429   SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4430                             DAG.getConstant(OffsetInBytes, DL, PtrTy));
4431   SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4432                             DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
4433   Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4434                         DAG.getConstant(MemCpySize, DL, PtrTy),
4435                         Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
4436                         /*isTailCall=*/false,
4437                         MachinePointerInfo(), MachinePointerInfo());
4438   MemOpChains.push_back(Chain);
4439 }
4440 
4441 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4442                                          SDValue Chain, const SDLoc &DL,
4443                                          SelectionDAG &DAG,
4444                                          CCState &State) const {
4445   ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
4446   unsigned Idx = State.getFirstUnallocated(ArgRegs);
4447   unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4448   MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4449   const TargetRegisterClass *RC = getRegClassFor(RegTy);
4450   MachineFunction &MF = DAG.getMachineFunction();
4451   MachineFrameInfo &MFI = MF.getFrameInfo();
4452   MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4453 
4454   // Offset of the first variable argument from stack pointer.
4455   int VaArgOffset;
4456 
4457   if (ArgRegs.size() == Idx)
4458     VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
4459   else {
4460     VaArgOffset =
4461         (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4462         (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4463   }
4464 
4465   // Record the frame index of the first variable argument
4466   // which is a value necessary to VASTART.
4467   int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4468   MipsFI->setVarArgsFrameIndex(FI);
4469 
4470   // Copy the integer registers that have not been used for argument passing
4471   // to the argument register save area. For O32, the save area is allocated
4472   // in the caller's stack frame, while for N32/64, it is allocated in the
4473   // callee's stack frame.
4474   for (unsigned I = Idx; I < ArgRegs.size();
4475        ++I, VaArgOffset += RegSizeInBytes) {
4476     unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4477     SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4478     FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4479     SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4480     SDValue Store =
4481         DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4482     cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4483         (Value *)nullptr);
4484     OutChains.push_back(Store);
4485   }
4486 }
4487 
4488 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
4489                                      unsigned Align) const {
4490   const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4491 
4492   assert(Size && "Byval argument's size shouldn't be 0.");
4493 
4494   Align = std::min(Align, TFL->getStackAlignment());
4495 
4496   unsigned FirstReg = 0;
4497   unsigned NumRegs = 0;
4498 
4499   if (State->getCallingConv() != CallingConv::Fast) {
4500     unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4501     ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4502     // FIXME: The O32 case actually describes no shadow registers.
4503     const MCPhysReg *ShadowRegs =
4504         ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4505 
4506     // We used to check the size as well but we can't do that anymore since
4507     // CCState::HandleByVal() rounds up the size after calling this function.
4508     assert(!(Align % RegSizeInBytes) &&
4509            "Byval argument's alignment should be a multiple of"
4510            "RegSizeInBytes.");
4511 
4512     FirstReg = State->getFirstUnallocated(IntArgRegs);
4513 
4514     // If Align > RegSizeInBytes, the first arg register must be even.
4515     // FIXME: This condition happens to do the right thing but it's not the
4516     //        right way to test it. We want to check that the stack frame offset
4517     //        of the register is aligned.
4518     if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
4519       State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4520       ++FirstReg;
4521     }
4522 
4523     // Mark the registers allocated.
4524     Size = alignTo(Size, RegSizeInBytes);
4525     for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4526          Size -= RegSizeInBytes, ++I, ++NumRegs)
4527       State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4528   }
4529 
4530   State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4531 }
4532 
4533 MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4534                                                         MachineBasicBlock *BB,
4535                                                         bool isFPCmp,
4536                                                         unsigned Opc) const {
4537   assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4538          "Subtarget already supports SELECT nodes with the use of"
4539          "conditional-move instructions.");
4540 
4541   const TargetInstrInfo *TII =
4542       Subtarget.getInstrInfo();
4543   DebugLoc DL = MI.getDebugLoc();
4544 
4545   // To "insert" a SELECT instruction, we actually have to insert the
4546   // diamond control-flow pattern.  The incoming instruction knows the
4547   // destination vreg to set, the condition code register to branch on, the
4548   // true/false values to select between, and a branch opcode to use.
4549   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4550   MachineFunction::iterator It = ++BB->getIterator();
4551 
4552   //  thisMBB:
4553   //  ...
4554   //   TrueVal = ...
4555   //   setcc r1, r2, r3
4556   //   bNE   r1, r0, copy1MBB
4557   //   fallthrough --> copy0MBB
4558   MachineBasicBlock *thisMBB  = BB;
4559   MachineFunction *F = BB->getParent();
4560   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4561   MachineBasicBlock *sinkMBB  = F->CreateMachineBasicBlock(LLVM_BB);
4562   F->insert(It, copy0MBB);
4563   F->insert(It, sinkMBB);
4564 
4565   // Transfer the remainder of BB and its successor edges to sinkMBB.
4566   sinkMBB->splice(sinkMBB->begin(), BB,
4567                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
4568   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4569 
4570   // Next, add the true and fallthrough blocks as its successors.
4571   BB->addSuccessor(copy0MBB);
4572   BB->addSuccessor(sinkMBB);
4573 
4574   if (isFPCmp) {
4575     // bc1[tf] cc, sinkMBB
4576     BuildMI(BB, DL, TII->get(Opc))
4577         .addReg(MI.getOperand(1).getReg())
4578         .addMBB(sinkMBB);
4579   } else {
4580     // bne rs, $0, sinkMBB
4581     BuildMI(BB, DL, TII->get(Opc))
4582         .addReg(MI.getOperand(1).getReg())
4583         .addReg(Mips::ZERO)
4584         .addMBB(sinkMBB);
4585   }
4586 
4587   //  copy0MBB:
4588   //   %FalseValue = ...
4589   //   # fallthrough to sinkMBB
4590   BB = copy0MBB;
4591 
4592   // Update machine-CFG edges
4593   BB->addSuccessor(sinkMBB);
4594 
4595   //  sinkMBB:
4596   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4597   //  ...
4598   BB = sinkMBB;
4599 
4600   BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4601       .addReg(MI.getOperand(2).getReg())
4602       .addMBB(thisMBB)
4603       .addReg(MI.getOperand(3).getReg())
4604       .addMBB(copy0MBB);
4605 
4606   MI.eraseFromParent(); // The pseudo instruction is gone now.
4607 
4608   return BB;
4609 }
4610 
4611 MachineBasicBlock *
4612 MipsTargetLowering::emitPseudoD_SELECT(MachineInstr &MI,
4613                                        MachineBasicBlock *BB) const {
4614   assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4615          "Subtarget already supports SELECT nodes with the use of"
4616          "conditional-move instructions.");
4617 
4618   const TargetInstrInfo *TII = Subtarget.getInstrInfo();
4619   DebugLoc DL = MI.getDebugLoc();
4620 
4621   // D_SELECT substitutes two SELECT nodes that goes one after another and
4622   // have the same condition operand. On machines which don't have
4623   // conditional-move instruction, it reduces unnecessary branch instructions
4624   // which are result of using two diamond patterns that are result of two
4625   // SELECT pseudo instructions.
4626   const BasicBlock *LLVM_BB = BB->getBasicBlock();
4627   MachineFunction::iterator It = ++BB->getIterator();
4628 
4629   //  thisMBB:
4630   //  ...
4631   //   TrueVal = ...
4632   //   setcc r1, r2, r3
4633   //   bNE   r1, r0, copy1MBB
4634   //   fallthrough --> copy0MBB
4635   MachineBasicBlock *thisMBB = BB;
4636   MachineFunction *F = BB->getParent();
4637   MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4638   MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4639   F->insert(It, copy0MBB);
4640   F->insert(It, sinkMBB);
4641 
4642   // Transfer the remainder of BB and its successor edges to sinkMBB.
4643   sinkMBB->splice(sinkMBB->begin(), BB,
4644                   std::next(MachineBasicBlock::iterator(MI)), BB->end());
4645   sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4646 
4647   // Next, add the true and fallthrough blocks as its successors.
4648   BB->addSuccessor(copy0MBB);
4649   BB->addSuccessor(sinkMBB);
4650 
4651   // bne rs, $0, sinkMBB
4652   BuildMI(BB, DL, TII->get(Mips::BNE))
4653       .addReg(MI.getOperand(2).getReg())
4654       .addReg(Mips::ZERO)
4655       .addMBB(sinkMBB);
4656 
4657   //  copy0MBB:
4658   //   %FalseValue = ...
4659   //   # fallthrough to sinkMBB
4660   BB = copy0MBB;
4661 
4662   // Update machine-CFG edges
4663   BB->addSuccessor(sinkMBB);
4664 
4665   //  sinkMBB:
4666   //   %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4667   //  ...
4668   BB = sinkMBB;
4669 
4670   // Use two PHI nodes to select two reults
4671   BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4672       .addReg(MI.getOperand(3).getReg())
4673       .addMBB(thisMBB)
4674       .addReg(MI.getOperand(5).getReg())
4675       .addMBB(copy0MBB);
4676   BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(1).getReg())
4677       .addReg(MI.getOperand(4).getReg())
4678       .addMBB(thisMBB)
4679       .addReg(MI.getOperand(6).getReg())
4680       .addMBB(copy0MBB);
4681 
4682   MI.eraseFromParent(); // The pseudo instruction is gone now.
4683 
4684   return BB;
4685 }
4686 
4687 // FIXME? Maybe this could be a TableGen attribute on some registers and
4688 // this table could be generated automatically from RegInfo.
4689 Register
4690 MipsTargetLowering::getRegisterByName(const char *RegName, EVT VT,
4691                                       const MachineFunction &MF) const {
4692   // Named registers is expected to be fairly rare. For now, just support $28
4693   // since the linux kernel uses it.
4694   if (Subtarget.isGP64bit()) {
4695     Register Reg = StringSwitch<Register>(RegName)
4696                          .Case("$28", Mips::GP_64)
4697                          .Default(Register());
4698     if (Reg)
4699       return Reg;
4700   } else {
4701     Register Reg = StringSwitch<Register>(RegName)
4702                          .Case("$28", Mips::GP)
4703                          .Default(Register());
4704     if (Reg)
4705       return Reg;
4706   }
4707   report_fatal_error("Invalid register name global variable");
4708 }
4709