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