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