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