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