1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #include "MipsISelLowering.h"
15 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsCCState.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/FunctionLoweringInfo.h"
26 #include "llvm/CodeGen/MachineFrameInfo.h"
27 #include "llvm/CodeGen/MachineFunction.h"
28 #include "llvm/CodeGen/MachineInstrBuilder.h"
29 #include "llvm/CodeGen/MachineJumpTableInfo.h"
30 #include "llvm/CodeGen/MachineRegisterInfo.h"
31 #include "llvm/CodeGen/SelectionDAGISel.h"
32 #include "llvm/CodeGen/ValueTypes.h"
33 #include "llvm/IR/CallingConv.h"
34 #include "llvm/IR/DerivedTypes.h"
35 #include "llvm/IR/GlobalVariable.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
44 #define DEBUG_TYPE "mips-lower"
46 STATISTIC(NumTailCalls, "Number of tail calls");
49 LargeGOT("mxgot", cl::Hidden,
50 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
53 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
54 cl::desc("MIPS: Don't trap on integer division by zero."),
57 static const MCPhysReg Mips64DPRegs[8] = {
58 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
59 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
62 // If I is a shifted mask, set the size (Size) and the first bit of the
63 // mask (Pos), and return true.
64 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
65 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
66 if (!isShiftedMask_64(I))
69 Size = countPopulation(I);
70 Pos = countTrailingZeros(I);
74 // The MIPS MSA ABI passes vector arguments in the integer register set.
75 // The number of integer registers used is dependant on the ABI used.
76 MVT MipsTargetLowering::getRegisterTypeForCallingConv(MVT VT) const {
77 if (VT.isVector() && Subtarget.hasMSA())
78 return Subtarget.isABI_O32() ? MVT::i32 : MVT::i64;
79 return MipsTargetLowering::getRegisterType(VT);
82 MVT MipsTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
85 if (Subtarget.isABI_O32()) {
88 return (VT.getSizeInBits() == 32) ? MVT::i32 : MVT::i64;
91 return MipsTargetLowering::getRegisterType(Context, VT);
94 unsigned MipsTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
97 return std::max((VT.getSizeInBits() / (Subtarget.isABI_O32() ? 32 : 64)),
99 return MipsTargetLowering::getNumRegisters(Context, VT);
102 unsigned MipsTargetLowering::getVectorTypeBreakdownForCallingConv(
103 LLVMContext &Context, EVT VT, EVT &IntermediateVT,
104 unsigned &NumIntermediates, MVT &RegisterVT) const {
106 // Break down vector types to either 2 i64s or 4 i32s.
107 RegisterVT = getRegisterTypeForCallingConv(Context, VT) ;
108 IntermediateVT = RegisterVT;
109 NumIntermediates = VT.getSizeInBits() < RegisterVT.getSizeInBits()
110 ? VT.getVectorNumElements()
111 : VT.getSizeInBits() / RegisterVT.getSizeInBits();
113 return NumIntermediates;
116 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
117 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
118 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
121 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
123 unsigned Flag) const {
124 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
127 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
129 unsigned Flag) const {
130 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
133 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
135 unsigned Flag) const {
136 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
139 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
141 unsigned Flag) const {
142 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
145 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
147 unsigned Flag) const {
148 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
149 N->getOffset(), Flag);
152 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
153 switch ((MipsISD::NodeType)Opcode) {
154 case MipsISD::FIRST_NUMBER: break;
155 case MipsISD::JmpLink: return "MipsISD::JmpLink";
156 case MipsISD::TailCall: return "MipsISD::TailCall";
157 case MipsISD::Highest: return "MipsISD::Highest";
158 case MipsISD::Higher: return "MipsISD::Higher";
159 case MipsISD::Hi: return "MipsISD::Hi";
160 case MipsISD::Lo: return "MipsISD::Lo";
161 case MipsISD::GotHi: return "MipsISD::GotHi";
162 case MipsISD::GPRel: return "MipsISD::GPRel";
163 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
164 case MipsISD::Ret: return "MipsISD::Ret";
165 case MipsISD::ERet: return "MipsISD::ERet";
166 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
167 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
168 case MipsISD::FPCmp: return "MipsISD::FPCmp";
169 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
170 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
171 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
172 case MipsISD::MFHI: return "MipsISD::MFHI";
173 case MipsISD::MFLO: return "MipsISD::MFLO";
174 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
175 case MipsISD::Mult: return "MipsISD::Mult";
176 case MipsISD::Multu: return "MipsISD::Multu";
177 case MipsISD::MAdd: return "MipsISD::MAdd";
178 case MipsISD::MAddu: return "MipsISD::MAddu";
179 case MipsISD::MSub: return "MipsISD::MSub";
180 case MipsISD::MSubu: return "MipsISD::MSubu";
181 case MipsISD::DivRem: return "MipsISD::DivRem";
182 case MipsISD::DivRemU: return "MipsISD::DivRemU";
183 case MipsISD::DivRem16: return "MipsISD::DivRem16";
184 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
185 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
186 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
187 case MipsISD::Wrapper: return "MipsISD::Wrapper";
188 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
189 case MipsISD::Sync: return "MipsISD::Sync";
190 case MipsISD::Ext: return "MipsISD::Ext";
191 case MipsISD::Ins: return "MipsISD::Ins";
192 case MipsISD::CIns: return "MipsISD::CIns";
193 case MipsISD::LWL: return "MipsISD::LWL";
194 case MipsISD::LWR: return "MipsISD::LWR";
195 case MipsISD::SWL: return "MipsISD::SWL";
196 case MipsISD::SWR: return "MipsISD::SWR";
197 case MipsISD::LDL: return "MipsISD::LDL";
198 case MipsISD::LDR: return "MipsISD::LDR";
199 case MipsISD::SDL: return "MipsISD::SDL";
200 case MipsISD::SDR: return "MipsISD::SDR";
201 case MipsISD::EXTP: return "MipsISD::EXTP";
202 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
203 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
204 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
205 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
206 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
207 case MipsISD::SHILO: return "MipsISD::SHILO";
208 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
209 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH";
210 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL";
211 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR";
212 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL";
213 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR";
214 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL";
215 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR";
216 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL";
217 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR";
218 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH";
219 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH";
220 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W";
221 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W";
222 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH";
223 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH";
224 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH";
225 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH";
226 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH";
227 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH";
228 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH";
229 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH";
230 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH";
231 case MipsISD::MULT: return "MipsISD::MULT";
232 case MipsISD::MULTU: return "MipsISD::MULTU";
233 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
234 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
235 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
236 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
237 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
238 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
239 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
240 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
241 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
242 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
243 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
244 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
245 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
246 case MipsISD::VCEQ: return "MipsISD::VCEQ";
247 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
248 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
249 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
250 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
251 case MipsISD::VSMAX: return "MipsISD::VSMAX";
252 case MipsISD::VSMIN: return "MipsISD::VSMIN";
253 case MipsISD::VUMAX: return "MipsISD::VUMAX";
254 case MipsISD::VUMIN: return "MipsISD::VUMIN";
255 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
256 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
257 case MipsISD::VNOR: return "MipsISD::VNOR";
258 case MipsISD::VSHF: return "MipsISD::VSHF";
259 case MipsISD::SHF: return "MipsISD::SHF";
260 case MipsISD::ILVEV: return "MipsISD::ILVEV";
261 case MipsISD::ILVOD: return "MipsISD::ILVOD";
262 case MipsISD::ILVL: return "MipsISD::ILVL";
263 case MipsISD::ILVR: return "MipsISD::ILVR";
264 case MipsISD::PCKEV: return "MipsISD::PCKEV";
265 case MipsISD::PCKOD: return "MipsISD::PCKOD";
266 case MipsISD::INSVE: return "MipsISD::INSVE";
271 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
272 const MipsSubtarget &STI)
273 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
274 // Mips does not have i1 type, so use i32 for
275 // setcc operations results (slt, sgt, ...).
276 setBooleanContents(ZeroOrOneBooleanContent);
277 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
278 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
279 // does. Integer booleans still use 0 and 1.
280 if (Subtarget.hasMips32r6())
281 setBooleanContents(ZeroOrOneBooleanContent,
282 ZeroOrNegativeOneBooleanContent);
284 // Load extented operations for i1 types must be promoted
285 for (MVT VT : MVT::integer_valuetypes()) {
286 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
287 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
288 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
291 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
293 for (MVT VT : MVT::fp_valuetypes()) {
294 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
295 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
298 // Set LoadExtAction for f16 vectors to Expand
299 for (MVT VT : MVT::fp_vector_valuetypes()) {
300 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
302 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
305 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
306 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
308 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
310 // Used by legalize types to correctly generate the setcc result.
311 // Without this, every float setcc comes with a AND/OR with the result,
312 // we don't want this, since the fpcmp result goes to a flag register,
313 // which is used implicitly by brcond and select operations.
314 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
316 // Mips Custom Operations
317 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
318 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
319 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
320 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
321 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
322 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
323 setOperationAction(ISD::SELECT, MVT::f32, Custom);
324 setOperationAction(ISD::SELECT, MVT::f64, Custom);
325 setOperationAction(ISD::SELECT, MVT::i32, Custom);
326 setOperationAction(ISD::SETCC, MVT::f32, Custom);
327 setOperationAction(ISD::SETCC, MVT::f64, Custom);
328 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
329 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
330 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
331 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
333 if (Subtarget.isGP64bit()) {
334 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
335 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
336 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
337 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
338 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
339 setOperationAction(ISD::SELECT, MVT::i64, Custom);
340 setOperationAction(ISD::LOAD, MVT::i64, Custom);
341 setOperationAction(ISD::STORE, MVT::i64, Custom);
342 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
343 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
344 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
345 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
348 if (!Subtarget.isGP64bit()) {
349 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
350 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
351 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
354 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
355 if (Subtarget.isGP64bit())
356 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
358 setOperationAction(ISD::SDIV, MVT::i32, Expand);
359 setOperationAction(ISD::SREM, MVT::i32, Expand);
360 setOperationAction(ISD::UDIV, MVT::i32, Expand);
361 setOperationAction(ISD::UREM, MVT::i32, Expand);
362 setOperationAction(ISD::SDIV, MVT::i64, Expand);
363 setOperationAction(ISD::SREM, MVT::i64, Expand);
364 setOperationAction(ISD::UDIV, MVT::i64, Expand);
365 setOperationAction(ISD::UREM, MVT::i64, Expand);
367 if (!(Subtarget.hasDSP() && Subtarget.hasMips32r2())) {
368 setOperationAction(ISD::ADDC, MVT::i32, Expand);
369 setOperationAction(ISD::ADDE, MVT::i32, Expand);
372 setOperationAction(ISD::ADDC, MVT::i64, Expand);
373 setOperationAction(ISD::ADDE, MVT::i64, Expand);
374 setOperationAction(ISD::SUBC, MVT::i32, Expand);
375 setOperationAction(ISD::SUBE, MVT::i32, Expand);
376 setOperationAction(ISD::SUBC, MVT::i64, Expand);
377 setOperationAction(ISD::SUBE, MVT::i64, Expand);
379 // Operations not directly supported by Mips.
380 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
381 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
382 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
383 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
384 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
385 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
386 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
387 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
388 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
389 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
390 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
391 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
392 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
393 if (Subtarget.hasCnMips()) {
394 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
395 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
397 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
398 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
400 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
401 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
402 setOperationAction(ISD::ROTL, MVT::i32, Expand);
403 setOperationAction(ISD::ROTL, MVT::i64, Expand);
404 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
405 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
407 if (!Subtarget.hasMips32r2())
408 setOperationAction(ISD::ROTR, MVT::i32, Expand);
410 if (!Subtarget.hasMips64r2())
411 setOperationAction(ISD::ROTR, MVT::i64, Expand);
413 setOperationAction(ISD::FSIN, MVT::f32, Expand);
414 setOperationAction(ISD::FSIN, MVT::f64, Expand);
415 setOperationAction(ISD::FCOS, MVT::f32, Expand);
416 setOperationAction(ISD::FCOS, MVT::f64, Expand);
417 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
418 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
419 setOperationAction(ISD::FPOW, MVT::f32, Expand);
420 setOperationAction(ISD::FPOW, MVT::f64, Expand);
421 setOperationAction(ISD::FLOG, MVT::f32, Expand);
422 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
423 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
424 setOperationAction(ISD::FEXP, MVT::f32, Expand);
425 setOperationAction(ISD::FMA, MVT::f32, Expand);
426 setOperationAction(ISD::FMA, MVT::f64, Expand);
427 setOperationAction(ISD::FREM, MVT::f32, Expand);
428 setOperationAction(ISD::FREM, MVT::f64, Expand);
430 // Lower f16 conversion operations into library calls
431 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
432 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
433 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
434 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
436 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
438 setOperationAction(ISD::VASTART, MVT::Other, Custom);
439 setOperationAction(ISD::VAARG, MVT::Other, Custom);
440 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
441 setOperationAction(ISD::VAEND, MVT::Other, Expand);
443 // Use the default for now
444 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
445 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
447 if (!Subtarget.isGP64bit()) {
448 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
449 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
453 if (!Subtarget.hasMips32r2()) {
454 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
455 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
458 // MIPS16 lacks MIPS32's clz and clo instructions.
459 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
460 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
461 if (!Subtarget.hasMips64())
462 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
464 if (!Subtarget.hasMips32r2())
465 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
466 if (!Subtarget.hasMips64r2())
467 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
469 if (Subtarget.isGP64bit()) {
470 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
471 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
472 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
473 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
476 setOperationAction(ISD::TRAP, MVT::Other, Legal);
478 setTargetDAGCombine(ISD::SDIVREM);
479 setTargetDAGCombine(ISD::UDIVREM);
480 setTargetDAGCombine(ISD::SELECT);
481 setTargetDAGCombine(ISD::AND);
482 setTargetDAGCombine(ISD::OR);
483 setTargetDAGCombine(ISD::ADD);
484 setTargetDAGCombine(ISD::SUB);
485 setTargetDAGCombine(ISD::AssertZext);
486 setTargetDAGCombine(ISD::SHL);
489 // These libcalls are not available in 32-bit.
490 setLibcallName(RTLIB::SHL_I128, nullptr);
491 setLibcallName(RTLIB::SRL_I128, nullptr);
492 setLibcallName(RTLIB::SRA_I128, nullptr);
495 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
497 // The arguments on the stack are defined in terms of 4-byte slots on O32
498 // and 8-byte slots on N32/N64.
499 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
501 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
503 MaxStoresPerMemcpy = 16;
505 isMicroMips = Subtarget.inMicroMipsMode();
508 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
509 const MipsSubtarget &STI) {
510 if (STI.inMips16Mode())
511 return llvm::createMips16TargetLowering(TM, STI);
513 return llvm::createMipsSETargetLowering(TM, STI);
516 // Create a fast isel object.
518 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
519 const TargetLibraryInfo *libInfo) const {
520 const MipsTargetMachine &TM =
521 static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
523 // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
524 bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
525 !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() &&
526 !Subtarget.inMicroMipsMode();
528 // Disable if either of the following is true:
529 // We do not generate PIC, the ABI is not O32, LargeGOT is being used.
530 if (!TM.isPositionIndependent() || !TM.getABI().IsO32() || LargeGOT)
533 return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr;
536 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
540 return VT.changeVectorElementTypeToInteger();
543 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
544 TargetLowering::DAGCombinerInfo &DCI,
545 const MipsSubtarget &Subtarget) {
546 if (DCI.isBeforeLegalizeOps())
549 EVT Ty = N->getValueType(0);
550 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
551 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
552 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
556 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
557 N->getOperand(0), N->getOperand(1));
558 SDValue InChain = DAG.getEntryNode();
559 SDValue InGlue = DivRem;
562 if (N->hasAnyUseOfValue(0)) {
563 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
565 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
566 InChain = CopyFromLo.getValue(1);
567 InGlue = CopyFromLo.getValue(2);
571 if (N->hasAnyUseOfValue(1)) {
572 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
574 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
580 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
582 default: llvm_unreachable("Unknown fp condition code!");
584 case ISD::SETOEQ: return Mips::FCOND_OEQ;
585 case ISD::SETUNE: return Mips::FCOND_UNE;
587 case ISD::SETOLT: return Mips::FCOND_OLT;
589 case ISD::SETOGT: return Mips::FCOND_OGT;
591 case ISD::SETOLE: return Mips::FCOND_OLE;
593 case ISD::SETOGE: return Mips::FCOND_OGE;
594 case ISD::SETULT: return Mips::FCOND_ULT;
595 case ISD::SETULE: return Mips::FCOND_ULE;
596 case ISD::SETUGT: return Mips::FCOND_UGT;
597 case ISD::SETUGE: return Mips::FCOND_UGE;
598 case ISD::SETUO: return Mips::FCOND_UN;
599 case ISD::SETO: return Mips::FCOND_OR;
601 case ISD::SETONE: return Mips::FCOND_ONE;
602 case ISD::SETUEQ: return Mips::FCOND_UEQ;
607 /// This function returns true if the floating point conditional branches and
608 /// conditional moves which use condition code CC should be inverted.
609 static bool invertFPCondCodeUser(Mips::CondCode CC) {
610 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
613 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
614 "Illegal Condition Code");
619 // Creates and returns an FPCmp node from a setcc node.
620 // Returns Op if setcc is not a floating point comparison.
621 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
622 // must be a SETCC node
623 if (Op.getOpcode() != ISD::SETCC)
626 SDValue LHS = Op.getOperand(0);
628 if (!LHS.getValueType().isFloatingPoint())
631 SDValue RHS = Op.getOperand(1);
634 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
635 // node if necessary.
636 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
638 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
639 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
642 // Creates and returns a CMovFPT/F node.
643 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
644 SDValue False, const SDLoc &DL) {
645 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
646 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
647 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
649 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
650 True.getValueType(), True, FCC0, False, Cond);
653 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
654 TargetLowering::DAGCombinerInfo &DCI,
655 const MipsSubtarget &Subtarget) {
656 if (DCI.isBeforeLegalizeOps())
659 SDValue SetCC = N->getOperand(0);
661 if ((SetCC.getOpcode() != ISD::SETCC) ||
662 !SetCC.getOperand(0).getValueType().isInteger())
665 SDValue False = N->getOperand(2);
666 EVT FalseTy = False.getValueType();
668 if (!FalseTy.isInteger())
671 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
673 // If the RHS (False) is 0, we swap the order of the operands
674 // of ISD::SELECT (obviously also inverting the condition) so that we can
675 // take advantage of conditional moves using the $0 register.
677 // return (a != 0) ? x : 0;
685 if (!FalseC->getZExtValue()) {
686 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
687 SDValue True = N->getOperand(1);
689 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
690 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
692 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
695 // If both operands are integer constants there's a possibility that we
696 // can do some interesting optimizations.
697 SDValue True = N->getOperand(1);
698 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
700 if (!TrueC || !True.getValueType().isInteger())
703 // We'll also ignore MVT::i64 operands as this optimizations proves
704 // to be ineffective because of the required sign extensions as the result
705 // of a SETCC operator is always MVT::i32 for non-vector types.
706 if (True.getValueType() == MVT::i64)
709 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
711 // 1) (a < x) ? y : y-1
713 // addiu $reg2, $reg1, y-1
715 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
717 // 2) (a < x) ? y-1 : y
719 // xor $reg1, $reg1, 1
720 // addiu $reg2, $reg1, y-1
722 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
723 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
724 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
725 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
728 // Couldn't optimize.
732 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
733 TargetLowering::DAGCombinerInfo &DCI,
734 const MipsSubtarget &Subtarget) {
735 if (DCI.isBeforeLegalizeOps())
738 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
740 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
741 if (!FalseC || FalseC->getZExtValue())
744 // Since RHS (False) is 0, we swap the order of the True/False operands
745 // (obviously also inverting the condition) so that we can
746 // take advantage of conditional moves using the $0 register.
748 // return (a != 0) ? x : 0;
751 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
754 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
755 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
756 ValueIfFalse, FCC, ValueIfTrue, Glue);
759 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
760 TargetLowering::DAGCombinerInfo &DCI,
761 const MipsSubtarget &Subtarget) {
762 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
765 SDValue FirstOperand = N->getOperand(0);
766 unsigned FirstOperandOpc = FirstOperand.getOpcode();
767 SDValue Mask = N->getOperand(1);
768 EVT ValTy = N->getValueType(0);
771 uint64_t Pos = 0, SMPos, SMSize;
776 // Op's second operand must be a shifted mask.
777 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
778 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
781 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
782 // Pattern match EXT.
783 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
784 // => ext $dst, $src, pos, size
786 // The second operand of the shift must be an immediate.
787 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
790 Pos = CN->getZExtValue();
792 // Return if the shifted mask does not start at bit 0 or the sum of its size
793 // and Pos exceeds the word's size.
794 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
798 NewOperand = FirstOperand.getOperand(0);
799 } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
800 // Pattern match CINS.
801 // $dst = and (shl $src , pos), mask
802 // => cins $dst, $src, pos, size
803 // mask is a shifted mask with consecutive 1's, pos = shift amount,
804 // size = population count.
806 // The second operand of the shift must be an immediate.
807 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
810 Pos = CN->getZExtValue();
812 if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
813 Pos + SMSize > ValTy.getSizeInBits())
816 NewOperand = FirstOperand.getOperand(0);
817 // SMSize is 'location' (position) in this case, not size.
821 // Pattern match EXT.
822 // $dst = and $src, (2**size - 1) , if size > 16
823 // => ext $dst, $src, pos, size , pos = 0
825 // If the mask is <= 0xffff, andi can be used instead.
826 if (CN->getZExtValue() <= 0xffff)
829 // Return if the mask doesn't start at position 0.
834 NewOperand = FirstOperand;
836 return DAG.getNode(Opc, DL, ValTy, NewOperand,
837 DAG.getConstant(Pos, DL, MVT::i32),
838 DAG.getConstant(SMSize, DL, MVT::i32));
841 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
842 TargetLowering::DAGCombinerInfo &DCI,
843 const MipsSubtarget &Subtarget) {
844 // Pattern match INS.
845 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
846 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
847 // => ins $dst, $src, size, pos, $src1
848 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
851 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
852 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
853 ConstantSDNode *CN, *CN1;
855 // See if Op's first operand matches (and $src1 , mask0).
856 if (And0.getOpcode() != ISD::AND)
859 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
860 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
863 // See if Op's second operand matches (and (shl $src, pos), mask1).
864 if (And1.getOpcode() == ISD::AND &&
865 And1.getOperand(0).getOpcode() == ISD::SHL) {
867 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
868 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
871 // The shift masks must have the same position and size.
872 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
875 SDValue Shl = And1.getOperand(0);
877 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
880 unsigned Shamt = CN->getZExtValue();
882 // Return if the shift amount and the first bit position of mask are not the
884 EVT ValTy = N->getValueType(0);
885 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
889 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
890 DAG.getConstant(SMPos0, DL, MVT::i32),
891 DAG.getConstant(SMSize0, DL, MVT::i32),
894 // Pattern match DINS.
895 // $dst = or (and $src, mask0), mask1
896 // where mask0 = ((1 << SMSize0) -1) << SMPos0
897 // => dins $dst, $src, pos, size
898 if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) &&
899 ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
900 (SMSize0 + SMPos0 <= 32))) {
901 // Check if AND instruction has constant as argument
902 bool isConstCase = And1.getOpcode() != ISD::AND;
903 if (And1.getOpcode() == ISD::AND) {
904 if (!(CN1 = dyn_cast<ConstantSDNode>(And1->getOperand(1))))
907 if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
911 EVT ValTy = N->getOperand(0)->getValueType(0);
915 Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
916 SrlX = DAG.getNode(ISD::SRL, DL, And1->getValueType(0), And1, Const1);
919 MipsISD::Ins, DL, N->getValueType(0),
921 ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
923 DAG.getConstant(SMPos0, DL, MVT::i32),
924 DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
927 And0->getOperand(0));
934 static SDValue performMADD_MSUBCombine(SDNode *ROOTNode, SelectionDAG &CurDAG,
935 const MipsSubtarget &Subtarget) {
936 // ROOTNode must have a multiplication as an operand for the match to be
938 if (ROOTNode->getOperand(0).getOpcode() != ISD::MUL &&
939 ROOTNode->getOperand(1).getOpcode() != ISD::MUL)
942 // We don't handle vector types here.
943 if (ROOTNode->getValueType(0).isVector())
946 // For MIPS64, madd / msub instructions are inefficent to use with 64 bit
948 // (add (mul a b) c) =>
949 // let res = (madd (mthi (drotr c 32))x(mtlo c) a b) in
950 // MIPS64: (or (dsll (mfhi res) 32) (dsrl (dsll (mflo res) 32) 32)
952 // MIPS64R2: (dins (mflo res) (mfhi res) 32 32)
954 // The overhead of setting up the Hi/Lo registers and reassembling the
955 // result makes this a dubious optimzation for MIPS64. The core of the
956 // problem is that Hi/Lo contain the upper and lower 32 bits of the
957 // operand and result.
959 // It requires a chain of 4 add/mul for MIPS64R2 to get better code
960 // density than doing it naively, 5 for MIPS64. Additionally, using
961 // madd/msub on MIPS64 requires the operands actually be 32 bit sign
962 // extended operands, not true 64 bit values.
964 // FIXME: For the moment, disable this completely for MIPS64.
965 if (Subtarget.hasMips64())
968 SDValue Mult = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
969 ? ROOTNode->getOperand(0)
970 : ROOTNode->getOperand(1);
972 SDValue AddOperand = ROOTNode->getOperand(0).getOpcode() == ISD::MUL
973 ? ROOTNode->getOperand(1)
974 : ROOTNode->getOperand(0);
976 // Transform this to a MADD only if the user of this node is the add.
977 // If there are other users of the mul, this function returns here.
978 if (!Mult.hasOneUse())
981 // maddu and madd are unusual instructions in that on MIPS64 bits 63..31
982 // must be in canonical form, i.e. sign extended. For MIPS32, the operands
983 // of the multiply must have 32 or more sign bits, otherwise we cannot
984 // perform this optimization. We have to check this here as we're performing
985 // this optimization pre-legalization.
986 SDValue MultLHS = Mult->getOperand(0);
987 SDValue MultRHS = Mult->getOperand(1);
988 unsigned LHSSB = CurDAG.ComputeNumSignBits(MultLHS);
989 unsigned RHSSB = CurDAG.ComputeNumSignBits(MultRHS);
991 if (LHSSB < 32 || RHSSB < 32)
995 APInt::getHighBitsSet(Mult->getValueType(0).getScalarSizeInBits(), 32);
996 bool IsUnsigned = CurDAG.MaskedValueIsZero(Mult->getOperand(0), HighMask) &&
997 CurDAG.MaskedValueIsZero(Mult->getOperand(1), HighMask) &&
998 CurDAG.MaskedValueIsZero(AddOperand, HighMask);
1000 // Initialize accumulator.
1004 BottomHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1005 CurDAG.getIntPtrConstant(0, DL));
1007 TopHalf = CurDAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, AddOperand,
1008 CurDAG.getIntPtrConstant(1, DL));
1009 SDValue ACCIn = CurDAG.getNode(MipsISD::MTLOHI, DL, MVT::Untyped,
1013 // Create MipsMAdd(u) / MipsMSub(u) node.
1014 bool IsAdd = ROOTNode->getOpcode() == ISD::ADD;
1015 unsigned Opcode = IsAdd ? (IsUnsigned ? MipsISD::MAddu : MipsISD::MAdd)
1016 : (IsUnsigned ? MipsISD::MSubu : MipsISD::MSub);
1017 SDValue MAddOps[3] = {
1018 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(0)),
1019 CurDAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mult->getOperand(1)), ACCIn};
1020 EVT VTs[2] = {MVT::i32, MVT::i32};
1021 SDValue MAdd = CurDAG.getNode(Opcode, DL, VTs, MAddOps);
1023 SDValue ResLo = CurDAG.getNode(MipsISD::MFLO, DL, MVT::i32, MAdd);
1024 SDValue ResHi = CurDAG.getNode(MipsISD::MFHI, DL, MVT::i32, MAdd);
1026 CurDAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, ResLo, ResHi);
1030 static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG,
1031 TargetLowering::DAGCombinerInfo &DCI,
1032 const MipsSubtarget &Subtarget) {
1033 // (sub v0 (mul v1, v2)) => (msub v1, v2, v0)
1034 if (DCI.isBeforeLegalizeOps()) {
1035 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1036 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1037 return performMADD_MSUBCombine(N, DAG, Subtarget);
1045 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
1046 TargetLowering::DAGCombinerInfo &DCI,
1047 const MipsSubtarget &Subtarget) {
1048 // (add v0 (mul v1, v2)) => (madd v1, v2, v0)
1049 if (DCI.isBeforeLegalizeOps()) {
1050 if (Subtarget.hasMips32() && !Subtarget.hasMips32r6() &&
1051 !Subtarget.inMips16Mode() && N->getValueType(0) == MVT::i64)
1052 return performMADD_MSUBCombine(N, DAG, Subtarget);
1057 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
1058 SDValue Add = N->getOperand(1);
1060 if (Add.getOpcode() != ISD::ADD)
1063 SDValue Lo = Add.getOperand(1);
1065 if ((Lo.getOpcode() != MipsISD::Lo) ||
1066 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
1069 EVT ValTy = N->getValueType(0);
1072 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
1074 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
1077 static SDValue performAssertZextCombine(SDNode *N, SelectionDAG &DAG,
1078 TargetLowering::DAGCombinerInfo &DCI,
1079 const MipsSubtarget &Subtarget) {
1080 SDValue N0 = N->getOperand(0);
1081 EVT NarrowerVT = cast<VTSDNode>(N->getOperand(1))->getVT();
1083 if (N0.getOpcode() != ISD::TRUNCATE)
1086 if (N0.getOperand(0).getOpcode() != ISD::AssertZext)
1089 // fold (AssertZext (trunc (AssertZext x))) -> (trunc (AssertZext x))
1090 // if the type of the extension of the innermost AssertZext node is
1091 // smaller from that of the outermost node, eg:
1092 // (AssertZext:i32 (trunc:i32 (AssertZext:i64 X, i32)), i8)
1093 // -> (trunc:i32 (AssertZext X, i8))
1094 SDValue WiderAssertZext = N0.getOperand(0);
1095 EVT WiderVT = cast<VTSDNode>(WiderAssertZext->getOperand(1))->getVT();
1097 if (NarrowerVT.bitsLT(WiderVT)) {
1098 SDValue NewAssertZext = DAG.getNode(
1099 ISD::AssertZext, SDLoc(N), WiderAssertZext.getValueType(),
1100 WiderAssertZext.getOperand(0), DAG.getValueType(NarrowerVT));
1101 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0),
1109 static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG,
1110 TargetLowering::DAGCombinerInfo &DCI,
1111 const MipsSubtarget &Subtarget) {
1112 // Pattern match CINS.
1113 // $dst = shl (and $src , imm), pos
1114 // => cins $dst, $src, pos, size
1116 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
1119 SDValue FirstOperand = N->getOperand(0);
1120 unsigned FirstOperandOpc = FirstOperand.getOpcode();
1121 SDValue SecondOperand = N->getOperand(1);
1122 EVT ValTy = N->getValueType(0);
1125 uint64_t Pos = 0, SMPos, SMSize;
1129 // The second operand of the shift must be an immediate.
1130 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
1133 Pos = CN->getZExtValue();
1135 if (Pos >= ValTy.getSizeInBits())
1138 if (FirstOperandOpc != ISD::AND)
1141 // AND's second operand must be a shifted mask.
1142 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
1143 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
1146 // Return if the shifted mask does not start at bit 0 or the sum of its size
1147 // and Pos exceeds the word's size.
1148 if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
1151 NewOperand = FirstOperand.getOperand(0);
1152 // SMSize is 'location' (position) in this case, not size.
1155 return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
1156 DAG.getConstant(Pos, DL, MVT::i32),
1157 DAG.getConstant(SMSize, DL, MVT::i32));
1160 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
1162 SelectionDAG &DAG = DCI.DAG;
1163 unsigned Opc = N->getOpcode();
1169 return performDivRemCombine(N, DAG, DCI, Subtarget);
1171 return performSELECTCombine(N, DAG, DCI, Subtarget);
1172 case MipsISD::CMovFP_F:
1173 case MipsISD::CMovFP_T:
1174 return performCMovFPCombine(N, DAG, DCI, Subtarget);
1176 return performANDCombine(N, DAG, DCI, Subtarget);
1178 return performORCombine(N, DAG, DCI, Subtarget);
1180 return performADDCombine(N, DAG, DCI, Subtarget);
1181 case ISD::AssertZext:
1182 return performAssertZextCombine(N, DAG, DCI, Subtarget);
1184 return performSHLCombine(N, DAG, DCI, Subtarget);
1186 return performSUBCombine(N, DAG, DCI, Subtarget);
1192 bool MipsTargetLowering::isCheapToSpeculateCttz() const {
1193 return Subtarget.hasMips32();
1196 bool MipsTargetLowering::isCheapToSpeculateCtlz() const {
1197 return Subtarget.hasMips32();
1201 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1202 SmallVectorImpl<SDValue> &Results,
1203 SelectionDAG &DAG) const {
1204 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1206 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1207 Results.push_back(Res.getValue(I));
1211 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1212 SmallVectorImpl<SDValue> &Results,
1213 SelectionDAG &DAG) const {
1214 return LowerOperationWrapper(N, Results, DAG);
1217 SDValue MipsTargetLowering::
1218 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1220 switch (Op.getOpcode())
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::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
1234 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
1235 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
1236 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
1237 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
1238 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
1239 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
1240 case ISD::LOAD: return lowerLOAD(Op, DAG);
1241 case ISD::STORE: return lowerSTORE(Op, DAG);
1242 case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG);
1243 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
1248 //===----------------------------------------------------------------------===//
1249 // Lower helper functions
1250 //===----------------------------------------------------------------------===//
1252 // addLiveIn - This helper function adds the specified physical register to the
1253 // MachineFunction as a live in value. It also creates a corresponding
1254 // virtual register for it.
1256 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1258 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1259 MF.getRegInfo().addLiveIn(PReg, VReg);
1263 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr &MI,
1264 MachineBasicBlock &MBB,
1265 const TargetInstrInfo &TII,
1266 bool Is64Bit, bool IsMicroMips) {
1270 // Insert instruction "teq $divisor_reg, $zero, 7".
1271 MachineBasicBlock::iterator I(MI);
1272 MachineInstrBuilder MIB;
1273 MachineOperand &Divisor = MI.getOperand(2);
1274 MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1275 TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ))
1276 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1280 // Use the 32-bit sub-register if this is a 64-bit division.
1282 MIB->getOperand(0).setSubReg(Mips::sub_32);
1284 // Clear Divisor's kill flag.
1285 Divisor.setIsKill(false);
1287 // We would normally delete the original instruction here but in this case
1288 // we only needed to inject an additional instruction rather than replace it.
1294 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1295 MachineBasicBlock *BB) const {
1296 switch (MI.getOpcode()) {
1298 llvm_unreachable("Unexpected instr type to insert");
1299 case Mips::ATOMIC_LOAD_ADD_I8:
1300 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1301 case Mips::ATOMIC_LOAD_ADD_I16:
1302 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1303 case Mips::ATOMIC_LOAD_ADD_I32:
1304 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
1305 case Mips::ATOMIC_LOAD_ADD_I64:
1306 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
1308 case Mips::ATOMIC_LOAD_AND_I8:
1309 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1310 case Mips::ATOMIC_LOAD_AND_I16:
1311 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1312 case Mips::ATOMIC_LOAD_AND_I32:
1313 return emitAtomicBinary(MI, BB, 4, Mips::AND);
1314 case Mips::ATOMIC_LOAD_AND_I64:
1315 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
1317 case Mips::ATOMIC_LOAD_OR_I8:
1318 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1319 case Mips::ATOMIC_LOAD_OR_I16:
1320 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1321 case Mips::ATOMIC_LOAD_OR_I32:
1322 return emitAtomicBinary(MI, BB, 4, Mips::OR);
1323 case Mips::ATOMIC_LOAD_OR_I64:
1324 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
1326 case Mips::ATOMIC_LOAD_XOR_I8:
1327 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1328 case Mips::ATOMIC_LOAD_XOR_I16:
1329 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1330 case Mips::ATOMIC_LOAD_XOR_I32:
1331 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
1332 case Mips::ATOMIC_LOAD_XOR_I64:
1333 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
1335 case Mips::ATOMIC_LOAD_NAND_I8:
1336 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
1337 case Mips::ATOMIC_LOAD_NAND_I16:
1338 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
1339 case Mips::ATOMIC_LOAD_NAND_I32:
1340 return emitAtomicBinary(MI, BB, 4, 0, true);
1341 case Mips::ATOMIC_LOAD_NAND_I64:
1342 return emitAtomicBinary(MI, BB, 8, 0, true);
1344 case Mips::ATOMIC_LOAD_SUB_I8:
1345 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1346 case Mips::ATOMIC_LOAD_SUB_I16:
1347 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1348 case Mips::ATOMIC_LOAD_SUB_I32:
1349 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
1350 case Mips::ATOMIC_LOAD_SUB_I64:
1351 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1353 case Mips::ATOMIC_SWAP_I8:
1354 return emitAtomicBinaryPartword(MI, BB, 1, 0);
1355 case Mips::ATOMIC_SWAP_I16:
1356 return emitAtomicBinaryPartword(MI, BB, 2, 0);
1357 case Mips::ATOMIC_SWAP_I32:
1358 return emitAtomicBinary(MI, BB, 4, 0);
1359 case Mips::ATOMIC_SWAP_I64:
1360 return emitAtomicBinary(MI, BB, 8, 0);
1362 case Mips::ATOMIC_CMP_SWAP_I8:
1363 return emitAtomicCmpSwapPartword(MI, BB, 1);
1364 case Mips::ATOMIC_CMP_SWAP_I16:
1365 return emitAtomicCmpSwapPartword(MI, BB, 2);
1366 case Mips::ATOMIC_CMP_SWAP_I32:
1367 return emitAtomicCmpSwap(MI, BB, 4);
1368 case Mips::ATOMIC_CMP_SWAP_I64:
1369 return emitAtomicCmpSwap(MI, BB, 8);
1370 case Mips::PseudoSDIV:
1371 case Mips::PseudoUDIV:
1376 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1378 case Mips::SDIV_MM_Pseudo:
1379 case Mips::UDIV_MM_Pseudo:
1382 case Mips::DIV_MMR6:
1383 case Mips::DIVU_MMR6:
1384 case Mips::MOD_MMR6:
1385 case Mips::MODU_MMR6:
1386 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true);
1387 case Mips::PseudoDSDIV:
1388 case Mips::PseudoDUDIV:
1393 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false);
1394 case Mips::DDIV_MM64R6:
1395 case Mips::DDIVU_MM64R6:
1396 case Mips::DMOD_MM64R6:
1397 case Mips::DMODU_MM64R6:
1398 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, true);
1400 case Mips::SEL_D_MMR6:
1401 return emitSEL_D(MI, BB);
1403 case Mips::PseudoSELECT_I:
1404 case Mips::PseudoSELECT_I64:
1405 case Mips::PseudoSELECT_S:
1406 case Mips::PseudoSELECT_D32:
1407 case Mips::PseudoSELECT_D64:
1408 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1409 case Mips::PseudoSELECTFP_F_I:
1410 case Mips::PseudoSELECTFP_F_I64:
1411 case Mips::PseudoSELECTFP_F_S:
1412 case Mips::PseudoSELECTFP_F_D32:
1413 case Mips::PseudoSELECTFP_F_D64:
1414 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1415 case Mips::PseudoSELECTFP_T_I:
1416 case Mips::PseudoSELECTFP_T_I64:
1417 case Mips::PseudoSELECTFP_T_S:
1418 case Mips::PseudoSELECTFP_T_D32:
1419 case Mips::PseudoSELECTFP_T_D64:
1420 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1424 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1425 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1426 MachineBasicBlock *MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1427 MachineBasicBlock *BB,
1431 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1433 MachineFunction *MF = BB->getParent();
1434 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1435 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1436 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1437 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1438 DebugLoc DL = MI.getDebugLoc();
1439 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1446 LL = Subtarget.hasMips32r6()
1447 ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1448 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1449 SC = Subtarget.hasMips32r6()
1450 ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1451 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1459 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1460 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1463 ZERO = Mips::ZERO_64;
1467 unsigned OldVal = MI.getOperand(0).getReg();
1468 unsigned Ptr = MI.getOperand(1).getReg();
1469 unsigned Incr = MI.getOperand(2).getReg();
1471 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1472 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1473 unsigned Success = RegInfo.createVirtualRegister(RC);
1475 // insert new blocks after the current block
1476 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1477 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1478 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1479 MachineFunction::iterator It = ++BB->getIterator();
1480 MF->insert(It, loopMBB);
1481 MF->insert(It, exitMBB);
1483 // Transfer the remainder of BB and its successor edges to exitMBB.
1484 exitMBB->splice(exitMBB->begin(), BB,
1485 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1486 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1490 // fallthrough --> loopMBB
1491 BB->addSuccessor(loopMBB);
1492 loopMBB->addSuccessor(loopMBB);
1493 loopMBB->addSuccessor(exitMBB);
1496 // ll oldval, 0(ptr)
1497 // <binop> storeval, oldval, incr
1498 // sc success, storeval, 0(ptr)
1499 // beq success, $0, loopMBB
1501 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1503 // and andres, oldval, incr
1504 // nor storeval, $0, andres
1505 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1506 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1507 } else if (BinOpcode) {
1508 // <binop> storeval, oldval, incr
1509 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1513 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1514 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1516 MI.eraseFromParent(); // The instruction is gone now.
1521 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1522 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1523 unsigned SrcReg) const {
1524 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1525 const DebugLoc &DL = MI.getDebugLoc();
1527 if (Subtarget.hasMips32r2() && Size == 1) {
1528 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1532 if (Subtarget.hasMips32r2() && Size == 2) {
1533 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1537 MachineFunction *MF = BB->getParent();
1538 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1539 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1540 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1543 int64_t ShiftImm = 32 - (Size * 8);
1545 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1546 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1551 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1552 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1554 assert((Size == 1 || Size == 2) &&
1555 "Unsupported size for EmitAtomicBinaryPartial.");
1557 MachineFunction *MF = BB->getParent();
1558 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1559 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1560 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1561 const TargetRegisterClass *RCp =
1562 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1563 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1564 DebugLoc DL = MI.getDebugLoc();
1566 unsigned Dest = MI.getOperand(0).getReg();
1567 unsigned Ptr = MI.getOperand(1).getReg();
1568 unsigned Incr = MI.getOperand(2).getReg();
1570 unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1571 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1572 unsigned Mask = RegInfo.createVirtualRegister(RC);
1573 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1574 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1575 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1576 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1577 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1578 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1579 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1580 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1581 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1582 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1583 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1584 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1585 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1586 unsigned Success = RegInfo.createVirtualRegister(RC);
1593 LL = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1594 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1595 SC = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1596 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1599 // insert new blocks after the current block
1600 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1601 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1602 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1603 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1604 MachineFunction::iterator It = ++BB->getIterator();
1605 MF->insert(It, loopMBB);
1606 MF->insert(It, sinkMBB);
1607 MF->insert(It, exitMBB);
1609 // Transfer the remainder of BB and its successor edges to exitMBB.
1610 exitMBB->splice(exitMBB->begin(), BB,
1611 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1612 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1614 BB->addSuccessor(loopMBB);
1615 loopMBB->addSuccessor(loopMBB);
1616 loopMBB->addSuccessor(sinkMBB);
1617 sinkMBB->addSuccessor(exitMBB);
1620 // addiu masklsb2,$0,-4 # 0xfffffffc
1621 // and alignedaddr,ptr,masklsb2
1622 // andi ptrlsb2,ptr,3
1623 // sll shiftamt,ptrlsb2,3
1624 // ori maskupper,$0,255 # 0xff
1625 // sll mask,maskupper,shiftamt
1626 // nor mask2,$0,mask
1627 // sll incr2,incr,shiftamt
1629 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1630 BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1631 .addReg(ABI.GetNullPtr()).addImm(-4);
1632 BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1633 .addReg(Ptr).addReg(MaskLSB2);
1634 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1635 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1636 if (Subtarget.isLittle()) {
1637 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1639 unsigned Off = RegInfo.createVirtualRegister(RC);
1640 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1641 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1642 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1644 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1645 .addReg(Mips::ZERO).addImm(MaskImm);
1646 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1647 .addReg(MaskUpper).addReg(ShiftAmt);
1648 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1649 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1651 // atomic.load.binop
1653 // ll oldval,0(alignedaddr)
1654 // binop binopres,oldval,incr2
1655 // and newval,binopres,mask
1656 // and maskedoldval0,oldval,mask2
1657 // or storeval,maskedoldval0,newval
1658 // sc success,storeval,0(alignedaddr)
1659 // beq success,$0,loopMBB
1663 // ll oldval,0(alignedaddr)
1664 // and newval,incr2,mask
1665 // and maskedoldval0,oldval,mask2
1666 // or storeval,maskedoldval0,newval
1667 // sc success,storeval,0(alignedaddr)
1668 // beq success,$0,loopMBB
1671 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1673 // and andres, oldval, incr2
1674 // nor binopres, $0, andres
1675 // and newval, binopres, mask
1676 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1677 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1678 .addReg(Mips::ZERO).addReg(AndRes);
1679 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1680 } else if (BinOpcode) {
1681 // <binop> binopres, oldval, incr2
1682 // and newval, binopres, mask
1683 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1684 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1685 } else { // atomic.swap
1686 // and newval, incr2, mask
1687 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1690 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1691 .addReg(OldVal).addReg(Mask2);
1692 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1693 .addReg(MaskedOldVal0).addReg(NewVal);
1694 BuildMI(BB, DL, TII->get(SC), Success)
1695 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1696 BuildMI(BB, DL, TII->get(Mips::BEQ))
1697 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1700 // and maskedoldval1,oldval,mask
1701 // srl srlres,maskedoldval1,shiftamt
1702 // sign_extend dest,srlres
1705 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1706 .addReg(OldVal).addReg(Mask);
1707 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1708 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1709 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1711 MI.eraseFromParent(); // The instruction is gone now.
1716 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1717 MachineBasicBlock *BB,
1718 unsigned Size) const {
1719 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1721 MachineFunction *MF = BB->getParent();
1722 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1723 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1724 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1725 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1726 DebugLoc DL = MI.getDebugLoc();
1727 unsigned LL, SC, ZERO, BNE, BEQ;
1734 LL = Subtarget.hasMips32r6()
1735 ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1736 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1737 SC = Subtarget.hasMips32r6()
1738 ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1739 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1746 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1747 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1748 ZERO = Mips::ZERO_64;
1753 unsigned Dest = MI.getOperand(0).getReg();
1754 unsigned Ptr = MI.getOperand(1).getReg();
1755 unsigned OldVal = MI.getOperand(2).getReg();
1756 unsigned NewVal = MI.getOperand(3).getReg();
1758 unsigned Success = RegInfo.createVirtualRegister(RC);
1760 // insert new blocks after the current block
1761 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1762 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1763 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1764 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1765 MachineFunction::iterator It = ++BB->getIterator();
1766 MF->insert(It, loop1MBB);
1767 MF->insert(It, loop2MBB);
1768 MF->insert(It, exitMBB);
1770 // Transfer the remainder of BB and its successor edges to exitMBB.
1771 exitMBB->splice(exitMBB->begin(), BB,
1772 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1773 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1777 // fallthrough --> loop1MBB
1778 BB->addSuccessor(loop1MBB);
1779 loop1MBB->addSuccessor(exitMBB);
1780 loop1MBB->addSuccessor(loop2MBB);
1781 loop2MBB->addSuccessor(loop1MBB);
1782 loop2MBB->addSuccessor(exitMBB);
1786 // bne dest, oldval, exitMBB
1788 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1789 BuildMI(BB, DL, TII->get(BNE))
1790 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1793 // sc success, newval, 0(ptr)
1794 // beq success, $0, loop1MBB
1796 BuildMI(BB, DL, TII->get(SC), Success)
1797 .addReg(NewVal).addReg(Ptr).addImm(0);
1798 BuildMI(BB, DL, TII->get(BEQ))
1799 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1801 MI.eraseFromParent(); // The instruction is gone now.
1806 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1807 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1808 assert((Size == 1 || Size == 2) &&
1809 "Unsupported size for EmitAtomicCmpSwapPartial.");
1811 MachineFunction *MF = BB->getParent();
1812 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1813 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1814 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1815 const TargetRegisterClass *RCp =
1816 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1817 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1818 DebugLoc DL = MI.getDebugLoc();
1820 unsigned Dest = MI.getOperand(0).getReg();
1821 unsigned Ptr = MI.getOperand(1).getReg();
1822 unsigned CmpVal = MI.getOperand(2).getReg();
1823 unsigned NewVal = MI.getOperand(3).getReg();
1825 unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1826 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1827 unsigned Mask = RegInfo.createVirtualRegister(RC);
1828 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1829 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1830 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1831 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1832 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1833 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1834 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1835 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1836 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1837 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1838 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1839 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1840 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1841 unsigned Success = RegInfo.createVirtualRegister(RC);
1848 LL = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1849 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1850 SC = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1851 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1854 // insert new blocks after the current block
1855 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1856 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1857 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1858 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1859 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1860 MachineFunction::iterator It = ++BB->getIterator();
1861 MF->insert(It, loop1MBB);
1862 MF->insert(It, loop2MBB);
1863 MF->insert(It, sinkMBB);
1864 MF->insert(It, exitMBB);
1866 // Transfer the remainder of BB and its successor edges to exitMBB.
1867 exitMBB->splice(exitMBB->begin(), BB,
1868 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1869 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1871 BB->addSuccessor(loop1MBB);
1872 loop1MBB->addSuccessor(sinkMBB);
1873 loop1MBB->addSuccessor(loop2MBB);
1874 loop2MBB->addSuccessor(loop1MBB);
1875 loop2MBB->addSuccessor(sinkMBB);
1876 sinkMBB->addSuccessor(exitMBB);
1878 // FIXME: computation of newval2 can be moved to loop2MBB.
1880 // addiu masklsb2,$0,-4 # 0xfffffffc
1881 // and alignedaddr,ptr,masklsb2
1882 // andi ptrlsb2,ptr,3
1883 // xori ptrlsb2,ptrlsb2,3 # Only for BE
1884 // sll shiftamt,ptrlsb2,3
1885 // ori maskupper,$0,255 # 0xff
1886 // sll mask,maskupper,shiftamt
1887 // nor mask2,$0,mask
1888 // andi maskedcmpval,cmpval,255
1889 // sll shiftedcmpval,maskedcmpval,shiftamt
1890 // andi maskednewval,newval,255
1891 // sll shiftednewval,maskednewval,shiftamt
1892 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1893 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1894 .addReg(ABI.GetNullPtr()).addImm(-4);
1895 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1896 .addReg(Ptr).addReg(MaskLSB2);
1897 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1898 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1899 if (Subtarget.isLittle()) {
1900 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1902 unsigned Off = RegInfo.createVirtualRegister(RC);
1903 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1904 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1905 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1907 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1908 .addReg(Mips::ZERO).addImm(MaskImm);
1909 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1910 .addReg(MaskUpper).addReg(ShiftAmt);
1911 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1912 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1913 .addReg(CmpVal).addImm(MaskImm);
1914 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1915 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1916 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1917 .addReg(NewVal).addImm(MaskImm);
1918 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1919 .addReg(MaskedNewVal).addReg(ShiftAmt);
1922 // ll oldval,0(alginedaddr)
1923 // and maskedoldval0,oldval,mask
1924 // bne maskedoldval0,shiftedcmpval,sinkMBB
1926 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1927 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1928 .addReg(OldVal).addReg(Mask);
1929 BuildMI(BB, DL, TII->get(Mips::BNE))
1930 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1933 // and maskedoldval1,oldval,mask2
1934 // or storeval,maskedoldval1,shiftednewval
1935 // sc success,storeval,0(alignedaddr)
1936 // beq success,$0,loop1MBB
1938 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1939 .addReg(OldVal).addReg(Mask2);
1940 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1941 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1942 BuildMI(BB, DL, TII->get(SC), Success)
1943 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1944 BuildMI(BB, DL, TII->get(Mips::BEQ))
1945 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1948 // srl srlres,maskedoldval0,shiftamt
1949 // sign_extend dest,srlres
1952 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1953 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1954 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1956 MI.eraseFromParent(); // The instruction is gone now.
1961 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr &MI,
1962 MachineBasicBlock *BB) const {
1963 MachineFunction *MF = BB->getParent();
1964 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1965 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1966 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1967 DebugLoc DL = MI.getDebugLoc();
1968 MachineBasicBlock::iterator II(MI);
1970 unsigned Fc = MI.getOperand(1).getReg();
1971 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1973 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1975 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1978 .addImm(Mips::sub_lo);
1980 // We don't erase the original instruction, we just replace the condition
1981 // register with the 64-bit super-register.
1982 MI.getOperand(1).setReg(Fc2);
1987 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1988 // The first operand is the chain, the second is the condition, the third is
1989 // the block to branch to if the condition is true.
1990 SDValue Chain = Op.getOperand(0);
1991 SDValue Dest = Op.getOperand(2);
1994 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1995 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1997 // Return if flag is not set by a floating point comparison.
1998 if (CondRes.getOpcode() != MipsISD::FPCmp)
2001 SDValue CCNode = CondRes.getOperand(2);
2003 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
2004 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
2005 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
2006 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
2007 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
2008 FCC0, Dest, CondRes);
2011 SDValue MipsTargetLowering::
2012 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
2014 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2015 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
2017 // Return if flag is not set by a floating point comparison.
2018 if (Cond.getOpcode() != MipsISD::FPCmp)
2021 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2025 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2026 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
2027 SDValue Cond = createFPCmp(DAG, Op);
2029 assert(Cond.getOpcode() == MipsISD::FPCmp &&
2030 "Floating point operand expected.");
2033 SDValue True = DAG.getConstant(1, DL, MVT::i32);
2034 SDValue False = DAG.getConstant(0, DL, MVT::i32);
2036 return createCMovFP(DAG, Cond, True, False, DL);
2039 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
2040 SelectionDAG &DAG) const {
2041 EVT Ty = Op.getValueType();
2042 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
2043 const GlobalValue *GV = N->getGlobal();
2045 if (!isPositionIndependent()) {
2046 const MipsTargetObjectFile *TLOF =
2047 static_cast<const MipsTargetObjectFile *>(
2048 getTargetMachine().getObjFileLowering());
2049 const GlobalObject *GO = GV->getBaseObject();
2050 if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
2051 // %gp_rel relocation
2052 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
2054 // %hi/%lo relocation
2055 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2056 // %highest/%higher/%hi/%lo relocation
2057 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2060 // Every other architecture would use shouldAssumeDSOLocal in here, but
2062 // * In PIC code mips requires got loads even for local statics!
2063 // * To save on got entries, for local statics the got entry contains the
2064 // page and an additional add instruction takes care of the low bits.
2065 // * It is legal to access a hidden symbol with a non hidden undefined,
2066 // so one cannot guarantee that all access to a hidden symbol will know
2068 // * Mips linkers don't support creating a page and a full got entry for
2070 // * Given all that, we have to use a full got entry for hidden symbols :-(
2071 if (GV->hasLocalLinkage())
2072 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2075 return getAddrGlobalLargeGOT(
2076 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
2078 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2080 return getAddrGlobal(
2081 N, SDLoc(N), Ty, DAG,
2082 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT,
2083 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
2086 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2087 SelectionDAG &DAG) const {
2088 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
2089 EVT Ty = Op.getValueType();
2091 if (!isPositionIndependent())
2092 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2093 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2095 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2098 SDValue MipsTargetLowering::
2099 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2101 // If the relocation model is PIC, use the General Dynamic TLS Model or
2102 // Local Dynamic TLS model, otherwise use the Initial Exec or
2103 // Local Exec TLS Model.
2105 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2106 if (DAG.getTarget().Options.EmulatedTLS)
2107 return LowerToTLSEmulatedModel(GA, DAG);
2110 const GlobalValue *GV = GA->getGlobal();
2111 EVT PtrVT = getPointerTy(DAG.getDataLayout());
2113 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
2115 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2116 // General Dynamic and Local Dynamic TLS Model.
2117 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2120 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2121 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2122 getGlobalReg(DAG, PtrVT), TGA);
2123 unsigned PtrSize = PtrVT.getSizeInBits();
2124 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2126 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2130 Entry.Node = Argument;
2132 Args.push_back(Entry);
2134 TargetLowering::CallLoweringInfo CLI(DAG);
2136 .setChain(DAG.getEntryNode())
2137 .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
2138 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2140 SDValue Ret = CallResult.first;
2142 if (model != TLSModel::LocalDynamic)
2145 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2146 MipsII::MO_DTPREL_HI);
2147 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
2148 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2149 MipsII::MO_DTPREL_LO);
2150 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2151 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2152 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2156 if (model == TLSModel::InitialExec) {
2157 // Initial Exec TLS Model
2158 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2159 MipsII::MO_GOTTPREL);
2160 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2163 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
2165 // Local Exec TLS Model
2166 assert(model == TLSModel::LocalExec);
2167 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2168 MipsII::MO_TPREL_HI);
2169 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2170 MipsII::MO_TPREL_LO);
2171 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
2172 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2173 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2176 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2177 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2180 SDValue MipsTargetLowering::
2181 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2183 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2184 EVT Ty = Op.getValueType();
2186 if (!isPositionIndependent())
2187 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2188 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2190 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2193 SDValue MipsTargetLowering::
2194 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2196 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2197 EVT Ty = Op.getValueType();
2199 if (!isPositionIndependent()) {
2200 const MipsTargetObjectFile *TLOF =
2201 static_cast<const MipsTargetObjectFile *>(
2202 getTargetMachine().getObjFileLowering());
2204 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2205 getTargetMachine()))
2206 // %gp_rel relocation
2207 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
2209 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2210 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2213 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2216 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2217 MachineFunction &MF = DAG.getMachineFunction();
2218 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2221 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2222 getPointerTy(MF.getDataLayout()));
2224 // vastart just stores the address of the VarArgsFrameIndex slot into the
2225 // memory location argument.
2226 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2227 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2228 MachinePointerInfo(SV));
2231 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2232 SDNode *Node = Op.getNode();
2233 EVT VT = Node->getValueType(0);
2234 SDValue Chain = Node->getOperand(0);
2235 SDValue VAListPtr = Node->getOperand(1);
2236 unsigned Align = Node->getConstantOperandVal(3);
2237 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2239 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2241 SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2242 VAListPtr, MachinePointerInfo(SV));
2243 SDValue VAList = VAListLoad;
2245 // Re-align the pointer if necessary.
2246 // It should only ever be necessary for 64-bit types on O32 since the minimum
2247 // argument alignment is the same as the maximum type alignment for N32/N64.
2249 // FIXME: We currently align too often. The code generator doesn't notice
2250 // when the pointer is still aligned from the last va_arg (or pair of
2251 // va_args for the i64 on O32 case).
2252 if (Align > getMinStackArgumentAlignment()) {
2253 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
2255 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2256 DAG.getConstant(Align - 1, DL, VAList.getValueType()));
2258 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
2259 DAG.getConstant(-(int64_t)Align, DL,
2260 VAList.getValueType()));
2263 // Increment the pointer, VAList, to the next vaarg.
2264 auto &TD = DAG.getDataLayout();
2265 unsigned ArgSizeInBytes =
2266 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
2268 DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2269 DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2270 DL, VAList.getValueType()));
2271 // Store the incremented VAList to the legalized pointer
2272 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2273 MachinePointerInfo(SV));
2275 // In big-endian mode we must adjust the pointer when the load size is smaller
2276 // than the argument slot size. We must also reduce the known alignment to
2277 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2278 // the correct half of the slot, and reduce the alignment from 8 (slot
2279 // alignment) down to 4 (type alignment).
2280 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2281 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2282 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2283 DAG.getIntPtrConstant(Adjustment, DL));
2285 // Load the actual argument out of the pointer VAList
2286 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2289 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
2290 bool HasExtractInsert) {
2291 EVT TyX = Op.getOperand(0).getValueType();
2292 EVT TyY = Op.getOperand(1).getValueType();
2294 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2295 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2298 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2300 SDValue X = (TyX == MVT::f32) ?
2301 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2302 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2304 SDValue Y = (TyY == MVT::f32) ?
2305 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2306 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2309 if (HasExtractInsert) {
2310 // ext E, Y, 31, 1 ; extract bit31 of Y
2311 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2312 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2313 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2316 // srl SrlX, SllX, 1
2318 // sll SllY, SrlX, 31
2319 // or Or, SrlX, SllY
2320 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2321 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2322 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2323 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2324 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2327 if (TyX == MVT::f32)
2328 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2330 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2332 DAG.getConstant(0, DL, MVT::i32));
2333 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2336 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
2337 bool HasExtractInsert) {
2338 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2339 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2340 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2342 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2344 // Bitcast to integer nodes.
2345 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2346 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2348 if (HasExtractInsert) {
2349 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2350 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2351 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2352 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2354 if (WidthX > WidthY)
2355 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2356 else if (WidthY > WidthX)
2357 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2359 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2360 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2362 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2365 // (d)sll SllX, X, 1
2366 // (d)srl SrlX, SllX, 1
2367 // (d)srl SrlY, Y, width(Y)-1
2368 // (d)sll SllY, SrlX, width(Y)-1
2369 // or Or, SrlX, SllY
2370 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2371 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2372 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2373 DAG.getConstant(WidthY - 1, DL, MVT::i32));
2375 if (WidthX > WidthY)
2376 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2377 else if (WidthY > WidthX)
2378 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2380 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2381 DAG.getConstant(WidthX - 1, DL, MVT::i32));
2382 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2383 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2387 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2388 if (Subtarget.isGP64bit())
2389 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2391 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2394 SDValue MipsTargetLowering::
2395 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2397 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2398 "Frame address can only be determined for current frame.");
2400 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2401 MFI.setFrameAddressIsTaken(true);
2402 EVT VT = Op.getValueType();
2404 SDValue FrameAddr = DAG.getCopyFromReg(
2405 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2409 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2410 SelectionDAG &DAG) const {
2411 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2415 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2416 "Return address can be determined only for current frame.");
2418 MachineFunction &MF = DAG.getMachineFunction();
2419 MachineFrameInfo &MFI = MF.getFrameInfo();
2420 MVT VT = Op.getSimpleValueType();
2421 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2422 MFI.setReturnAddressIsTaken(true);
2424 // Return RA, which contains the return address. Mark it an implicit live-in.
2425 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2426 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2429 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2430 // generated from __builtin_eh_return (offset, handler)
2431 // The effect of this is to adjust the stack pointer by "offset"
2432 // and then branch to "handler".
2433 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2435 MachineFunction &MF = DAG.getMachineFunction();
2436 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2438 MipsFI->setCallsEhReturn();
2439 SDValue Chain = Op.getOperand(0);
2440 SDValue Offset = Op.getOperand(1);
2441 SDValue Handler = Op.getOperand(2);
2443 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2445 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2446 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2447 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2448 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2449 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2450 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2451 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2452 DAG.getRegister(OffsetReg, Ty),
2453 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2457 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2458 SelectionDAG &DAG) const {
2459 // FIXME: Need pseudo-fence for 'singlethread' fences
2460 // FIXME: Set SType for weaker fences where supported/appropriate.
2463 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2464 DAG.getConstant(SType, DL, MVT::i32));
2467 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2468 SelectionDAG &DAG) const {
2470 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2472 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2473 SDValue Shamt = Op.getOperand(2);
2474 // if shamt < (VT.bits):
2475 // lo = (shl lo, shamt)
2476 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2479 // hi = (shl lo, shamt[4:0])
2480 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2481 DAG.getConstant(-1, DL, MVT::i32));
2482 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2483 DAG.getConstant(1, DL, VT));
2484 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2485 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2486 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2487 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2488 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2489 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2490 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2491 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2492 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2494 SDValue Ops[2] = {Lo, Hi};
2495 return DAG.getMergeValues(Ops, DL);
2498 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2501 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2502 SDValue Shamt = Op.getOperand(2);
2503 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2505 // if shamt < (VT.bits):
2506 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2508 // hi = (sra hi, shamt)
2510 // hi = (srl hi, shamt)
2513 // lo = (sra hi, shamt[4:0])
2514 // hi = (sra hi, 31)
2516 // lo = (srl hi, shamt[4:0])
2518 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2519 DAG.getConstant(-1, DL, MVT::i32));
2520 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2521 DAG.getConstant(1, DL, VT));
2522 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2523 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2524 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2525 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2527 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2528 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2529 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2530 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2531 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2532 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2533 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2535 SDValue Ops[2] = {Lo, Hi};
2536 return DAG.getMergeValues(Ops, DL);
2539 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2540 SDValue Chain, SDValue Src, unsigned Offset) {
2541 SDValue Ptr = LD->getBasePtr();
2542 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2543 EVT BasePtrVT = Ptr.getValueType();
2545 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2548 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2549 DAG.getConstant(Offset, DL, BasePtrVT));
2551 SDValue Ops[] = { Chain, Ptr, Src };
2552 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2553 LD->getMemOperand());
2556 // Expand an unaligned 32 or 64-bit integer load node.
2557 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2558 LoadSDNode *LD = cast<LoadSDNode>(Op);
2559 EVT MemVT = LD->getMemoryVT();
2561 if (Subtarget.systemSupportsUnalignedAccess())
2564 // Return if load is aligned or if MemVT is neither i32 nor i64.
2565 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2566 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2569 bool IsLittle = Subtarget.isLittle();
2570 EVT VT = Op.getValueType();
2571 ISD::LoadExtType ExtType = LD->getExtensionType();
2572 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2574 assert((VT == MVT::i32) || (VT == MVT::i64));
2577 // (set dst, (i64 (load baseptr)))
2579 // (set tmp, (ldl (add baseptr, 7), undef))
2580 // (set dst, (ldr baseptr, tmp))
2581 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2582 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2584 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2588 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2590 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2594 // (set dst, (i32 (load baseptr))) or
2595 // (set dst, (i64 (sextload baseptr))) or
2596 // (set dst, (i64 (extload baseptr)))
2598 // (set tmp, (lwl (add baseptr, 3), undef))
2599 // (set dst, (lwr baseptr, tmp))
2600 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2601 (ExtType == ISD::EXTLOAD))
2604 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2607 // (set dst, (i64 (zextload baseptr)))
2609 // (set tmp0, (lwl (add baseptr, 3), undef))
2610 // (set tmp1, (lwr baseptr, tmp0))
2611 // (set tmp2, (shl tmp1, 32))
2612 // (set dst, (srl tmp2, 32))
2614 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2615 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2616 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2617 SDValue Ops[] = { SRL, LWR.getValue(1) };
2618 return DAG.getMergeValues(Ops, DL);
2621 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2622 SDValue Chain, unsigned Offset) {
2623 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2624 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2626 SDVTList VTList = DAG.getVTList(MVT::Other);
2629 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2630 DAG.getConstant(Offset, DL, BasePtrVT));
2632 SDValue Ops[] = { Chain, Value, Ptr };
2633 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2634 SD->getMemOperand());
2637 // Expand an unaligned 32 or 64-bit integer store node.
2638 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2640 SDValue Value = SD->getValue(), Chain = SD->getChain();
2641 EVT VT = Value.getValueType();
2644 // (store val, baseptr) or
2645 // (truncstore val, baseptr)
2647 // (swl val, (add baseptr, 3))
2648 // (swr val, baseptr)
2649 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2650 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2652 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2655 assert(VT == MVT::i64);
2658 // (store val, baseptr)
2660 // (sdl val, (add baseptr, 7))
2661 // (sdr val, baseptr)
2662 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2663 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2666 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2667 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2668 SDValue Val = SD->getValue();
2670 if (Val.getOpcode() != ISD::FP_TO_SINT)
2673 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2674 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2676 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2677 SD->getPointerInfo(), SD->getAlignment(),
2678 SD->getMemOperand()->getFlags());
2681 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2682 StoreSDNode *SD = cast<StoreSDNode>(Op);
2683 EVT MemVT = SD->getMemoryVT();
2685 // Lower unaligned integer stores.
2686 if (!Subtarget.systemSupportsUnalignedAccess() &&
2687 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2688 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2689 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2691 return lowerFP_TO_SINT_STORE(SD, DAG);
2694 SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2695 SelectionDAG &DAG) const {
2697 // Return a fixed StackObject with offset 0 which points to the old stack
2699 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2700 EVT ValTy = Op->getValueType(0);
2701 int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2702 return DAG.getFrameIndex(FI, ValTy);
2705 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2706 SelectionDAG &DAG) const {
2707 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2708 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2710 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2713 //===----------------------------------------------------------------------===//
2714 // Calling Convention Implementation
2715 //===----------------------------------------------------------------------===//
2717 //===----------------------------------------------------------------------===//
2718 // TODO: Implement a generic logic using tblgen that can support this.
2719 // Mips O32 ABI rules:
2721 // i32 - Passed in A0, A1, A2, A3 and stack
2722 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2723 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2724 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2725 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2726 // not used, it must be shadowed. If only A3 is available, shadow it and
2728 // vXiX - Received as scalarized i32s, passed in A0 - A3 and the stack.
2729 // vXf32 - Passed in either a pair of registers {A0, A1}, {A2, A3} or {A0 - A3}
2730 // with the remainder spilled to the stack.
2731 // vXf64 - Passed in either {A0, A1, A2, A3} or {A2, A3} and in both cases
2732 // spilling the remainder to the stack.
2734 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2735 //===----------------------------------------------------------------------===//
2737 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2738 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2739 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2740 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2741 State.getMachineFunction().getSubtarget());
2743 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2745 const MipsCCState * MipsState = static_cast<MipsCCState *>(&State);
2747 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2749 static const MCPhysReg FloatVectorIntRegs[] = { Mips::A0, Mips::A2 };
2751 // Do not process byval args here.
2752 if (ArgFlags.isByVal())
2755 // Promote i8 and i16
2756 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2757 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2759 if (ArgFlags.isSExt())
2760 LocInfo = CCValAssign::SExtUpper;
2761 else if (ArgFlags.isZExt())
2762 LocInfo = CCValAssign::ZExtUpper;
2764 LocInfo = CCValAssign::AExtUpper;
2768 // Promote i8 and i16
2769 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2771 if (ArgFlags.isSExt())
2772 LocInfo = CCValAssign::SExt;
2773 else if (ArgFlags.isZExt())
2774 LocInfo = CCValAssign::ZExt;
2776 LocInfo = CCValAssign::AExt;
2781 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2782 // is true: function is vararg, argument is 3rd or higher, there is previous
2783 // argument which is not f32 or f64.
2784 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2785 State.getFirstUnallocated(F32Regs) != ValNo;
2786 unsigned OrigAlign = ArgFlags.getOrigAlign();
2787 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2788 bool isVectorFloat = MipsState->WasOriginalArgVectorFloat(ValNo);
2790 // The MIPS vector ABI for floats passes them in a pair of registers
2791 if (ValVT == MVT::i32 && isVectorFloat) {
2792 // This is the start of an vector that was scalarized into an unknown number
2793 // of components. It doesn't matter how many there are. Allocate one of the
2794 // notional 8 byte aligned registers which map onto the argument stack, and
2795 // shadow the register lost to alignment requirements.
2796 if (ArgFlags.isSplit()) {
2797 Reg = State.AllocateReg(FloatVectorIntRegs);
2798 if (Reg == Mips::A2)
2799 State.AllocateReg(Mips::A1);
2801 State.AllocateReg(Mips::A3);
2803 // If we're an intermediate component of the split, we can just attempt to
2804 // allocate a register directly.
2805 Reg = State.AllocateReg(IntRegs);
2807 } else if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2808 Reg = State.AllocateReg(IntRegs);
2809 // If this is the first part of an i64 arg,
2810 // the allocated register must be either A0 or A2.
2811 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2812 Reg = State.AllocateReg(IntRegs);
2814 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2815 // Allocate int register and shadow next int register. If first
2816 // available register is Mips::A1 or Mips::A3, shadow it too.
2817 Reg = State.AllocateReg(IntRegs);
2818 if (Reg == Mips::A1 || Reg == Mips::A3)
2819 Reg = State.AllocateReg(IntRegs);
2820 State.AllocateReg(IntRegs);
2822 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2823 // we are guaranteed to find an available float register
2824 if (ValVT == MVT::f32) {
2825 Reg = State.AllocateReg(F32Regs);
2826 // Shadow int register
2827 State.AllocateReg(IntRegs);
2829 Reg = State.AllocateReg(F64Regs);
2830 // Shadow int registers
2831 unsigned Reg2 = State.AllocateReg(IntRegs);
2832 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2833 State.AllocateReg(IntRegs);
2834 State.AllocateReg(IntRegs);
2837 llvm_unreachable("Cannot handle this ValVT.");
2840 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2842 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2844 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2849 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2850 MVT LocVT, CCValAssign::LocInfo LocInfo,
2851 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2852 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2854 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2857 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2858 MVT LocVT, CCValAssign::LocInfo LocInfo,
2859 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2860 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2862 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2865 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2866 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2867 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2869 #include "MipsGenCallingConv.inc"
2871 //===----------------------------------------------------------------------===//
2872 // Call Calling Convention Implementation
2873 //===----------------------------------------------------------------------===//
2875 // Return next O32 integer argument register.
2876 static unsigned getNextIntArgReg(unsigned Reg) {
2877 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2878 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2881 SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2882 SDValue Chain, SDValue Arg,
2883 const SDLoc &DL, bool IsTailCall,
2884 SelectionDAG &DAG) const {
2887 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2888 DAG.getIntPtrConstant(Offset, DL));
2889 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
2892 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2893 int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2894 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2895 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2896 /* Alignment = */ 0, MachineMemOperand::MOVolatile);
2899 void MipsTargetLowering::
2900 getOpndList(SmallVectorImpl<SDValue> &Ops,
2901 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2902 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2903 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2904 SDValue Chain) const {
2905 // Insert node "GP copy globalreg" before call to function.
2907 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2908 // in PIC mode) allow symbols to be resolved via lazy binding.
2909 // The lazy binding stub requires GP to point to the GOT.
2910 // Note that we don't need GP to point to the GOT for indirect calls
2911 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2912 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2913 // used for the function (that is, Mips linker doesn't generate lazy binding
2914 // stub for a function whose address is taken in the program).
2915 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2916 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2917 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2918 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2921 // Build a sequence of copy-to-reg nodes chained together with token
2922 // chain and flag operands which copy the outgoing args into registers.
2923 // The InFlag in necessary since all emitted instructions must be
2927 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2928 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2929 RegsToPass[i].second, InFlag);
2930 InFlag = Chain.getValue(1);
2933 // Add argument registers to the end of the list so that they are
2934 // known live into the call.
2935 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2936 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2937 RegsToPass[i].second.getValueType()));
2939 // Add a register mask operand representing the call-preserved registers.
2940 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2941 const uint32_t *Mask =
2942 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2943 assert(Mask && "Missing call preserved mask for calling convention");
2944 if (Subtarget.inMips16HardFloat()) {
2945 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2946 llvm::StringRef Sym = G->getGlobal()->getName();
2947 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2948 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2949 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2953 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2955 if (InFlag.getNode())
2956 Ops.push_back(InFlag);
2959 /// LowerCall - functions arguments are copied from virtual regs to
2960 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2962 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2963 SmallVectorImpl<SDValue> &InVals) const {
2964 SelectionDAG &DAG = CLI.DAG;
2966 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2967 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2968 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2969 SDValue Chain = CLI.Chain;
2970 SDValue Callee = CLI.Callee;
2971 bool &IsTailCall = CLI.IsTailCall;
2972 CallingConv::ID CallConv = CLI.CallConv;
2973 bool IsVarArg = CLI.IsVarArg;
2975 MachineFunction &MF = DAG.getMachineFunction();
2976 MachineFrameInfo &MFI = MF.getFrameInfo();
2977 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2978 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2979 bool IsPIC = isPositionIndependent();
2981 // Analyze operands of the call, assigning locations to each operand.
2982 SmallVector<CCValAssign, 16> ArgLocs;
2984 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2985 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2987 // Allocate the reserved argument area. It seems strange to do this from the
2988 // caller side but removing it breaks the frame size calculation.
2989 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2991 const ExternalSymbolSDNode *ES =
2992 dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
2993 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
2994 ES ? ES->getSymbol() : nullptr);
2996 // Get a count of how many bytes are to be pushed on the stack.
2997 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2999 // Check if it's really possible to do a tail call. Restrict it to functions
3000 // that are part of this compilation unit.
3001 bool InternalLinkage = false;
3003 IsTailCall = isEligibleForTailCallOptimization(
3004 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
3005 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3006 InternalLinkage = G->getGlobal()->hasInternalLinkage();
3007 IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
3008 G->getGlobal()->hasPrivateLinkage() ||
3009 G->getGlobal()->hasHiddenVisibility() ||
3010 G->getGlobal()->hasProtectedVisibility());
3013 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
3014 report_fatal_error("failed to perform tail call elimination on a call "
3015 "site marked musttail");
3020 // Chain is the output chain of the last Load/Store or CopyToReg node.
3021 // ByValChain is the output chain of the last Memcpy node created for copying
3022 // byval arguments to the stack.
3023 unsigned StackAlignment = TFL->getStackAlignment();
3024 NextStackOffset = alignTo(NextStackOffset, StackAlignment);
3025 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
3028 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL);
3031 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
3032 getPointerTy(DAG.getDataLayout()));
3034 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
3035 SmallVector<SDValue, 8> MemOpChains;
3037 CCInfo.rewindByValRegsInfo();
3039 // Walk the register/memloc assignments, inserting copies/loads.
3040 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3041 SDValue Arg = OutVals[i];
3042 CCValAssign &VA = ArgLocs[i];
3043 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3044 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3045 bool UseUpperBits = false;
3048 if (Flags.isByVal()) {
3049 unsigned FirstByValReg, LastByValReg;
3050 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3051 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3053 assert(Flags.getByValSize() &&
3054 "ByVal args of size 0 should have been ignored by front-end.");
3055 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3056 assert(!IsTailCall &&
3057 "Do not tail-call optimize if there is a byval argument.");
3058 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3059 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
3061 CCInfo.nextInRegsParam();
3065 // Promote the value if needed.
3066 switch (VA.getLocInfo()) {
3068 llvm_unreachable("Unknown loc info!");
3069 case CCValAssign::Full:
3070 if (VA.isRegLoc()) {
3071 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3072 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3073 (ValVT == MVT::i64 && LocVT == MVT::f64))
3074 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3075 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3076 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3077 Arg, DAG.getConstant(0, DL, MVT::i32));
3078 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3079 Arg, DAG.getConstant(1, DL, MVT::i32));
3080 if (!Subtarget.isLittle())
3082 unsigned LocRegLo = VA.getLocReg();
3083 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3084 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3085 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3090 case CCValAssign::BCvt:
3091 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3093 case CCValAssign::SExtUpper:
3094 UseUpperBits = true;
3096 case CCValAssign::SExt:
3097 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3099 case CCValAssign::ZExtUpper:
3100 UseUpperBits = true;
3102 case CCValAssign::ZExt:
3103 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3105 case CCValAssign::AExtUpper:
3106 UseUpperBits = true;
3108 case CCValAssign::AExt:
3109 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3114 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3115 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3117 ISD::SHL, DL, VA.getLocVT(), Arg,
3118 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3121 // Arguments that can be passed on register must be kept at
3122 // RegsToPass vector
3123 if (VA.isRegLoc()) {
3124 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3128 // Register can't get to this point...
3129 assert(VA.isMemLoc());
3131 // emit ISD::STORE whichs stores the
3132 // parameter value to a stack Location
3133 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3134 Chain, Arg, DL, IsTailCall, DAG));
3137 // Transform all store nodes into one single node because all store
3138 // nodes are independent of each other.
3139 if (!MemOpChains.empty())
3140 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
3142 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3143 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3144 // node so that legalize doesn't hack it.
3147 EVT Ty = Callee.getValueType();
3148 bool GlobalOrExternal = false, IsCallReloc = false;
3150 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3152 const GlobalValue *Val = G->getGlobal();
3153 InternalLinkage = Val->hasInternalLinkage();
3155 if (InternalLinkage)
3156 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
3157 else if (LargeGOT) {
3158 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3159 MipsII::MO_CALL_LO16, Chain,
3160 FuncInfo->callPtrInfo(Val));
3163 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3164 FuncInfo->callPtrInfo(Val));
3168 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
3169 getPointerTy(DAG.getDataLayout()), 0,
3170 MipsII::MO_NO_FLAG);
3171 GlobalOrExternal = true;
3173 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3174 const char *Sym = S->getSymbol();
3176 if (!IsPIC) // static
3177 Callee = DAG.getTargetExternalSymbol(
3178 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
3179 else if (LargeGOT) {
3180 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
3181 MipsII::MO_CALL_LO16, Chain,
3182 FuncInfo->callPtrInfo(Sym));
3185 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
3186 FuncInfo->callPtrInfo(Sym));
3190 GlobalOrExternal = true;
3193 SmallVector<SDValue, 8> Ops(1, Chain);
3194 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3196 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
3197 IsCallReloc, CLI, Callee, Chain);
3200 MF.getFrameInfo().setHasTailCall();
3201 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3204 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3205 SDValue InFlag = Chain.getValue(1);
3207 // Create the CALLSEQ_END node.
3208 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3209 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3210 InFlag = Chain.getValue(1);
3212 // Handle result values, copying them out of physregs into vregs that we
3214 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3218 /// LowerCallResult - Lower the result values of a call into the
3219 /// appropriate copies out of appropriate physical registers.
3220 SDValue MipsTargetLowering::LowerCallResult(
3221 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
3222 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3223 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3224 TargetLowering::CallLoweringInfo &CLI) const {
3225 // Assign locations to each value returned by this call.
3226 SmallVector<CCValAssign, 16> RVLocs;
3227 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3230 const ExternalSymbolSDNode *ES =
3231 dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3232 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3233 ES ? ES->getSymbol() : nullptr);
3235 // Copy all of the result registers out of their specified physreg.
3236 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3237 CCValAssign &VA = RVLocs[i];
3238 assert(VA.isRegLoc() && "Can only return in registers!");
3240 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3241 RVLocs[i].getLocVT(), InFlag);
3242 Chain = Val.getValue(1);
3243 InFlag = Val.getValue(2);
3245 if (VA.isUpperBitsInLoc()) {
3246 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3247 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3249 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3251 Shift, DL, VA.getLocVT(), Val,
3252 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3255 switch (VA.getLocInfo()) {
3257 llvm_unreachable("Unknown loc info!");
3258 case CCValAssign::Full:
3260 case CCValAssign::BCvt:
3261 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3263 case CCValAssign::AExt:
3264 case CCValAssign::AExtUpper:
3265 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3267 case CCValAssign::ZExt:
3268 case CCValAssign::ZExtUpper:
3269 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3270 DAG.getValueType(VA.getValVT()));
3271 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3273 case CCValAssign::SExt:
3274 case CCValAssign::SExtUpper:
3275 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3276 DAG.getValueType(VA.getValVT()));
3277 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3281 InVals.push_back(Val);
3287 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
3288 EVT ArgVT, const SDLoc &DL,
3289 SelectionDAG &DAG) {
3290 MVT LocVT = VA.getLocVT();
3291 EVT ValVT = VA.getValVT();
3293 // Shift into the upper bits if necessary.
3294 switch (VA.getLocInfo()) {
3297 case CCValAssign::AExtUpper:
3298 case CCValAssign::SExtUpper:
3299 case CCValAssign::ZExtUpper: {
3300 unsigned ValSizeInBits = ArgVT.getSizeInBits();
3301 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3303 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3305 Opcode, DL, VA.getLocVT(), Val,
3306 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3311 // If this is an value smaller than the argument slot size (32-bit for O32,
3312 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3313 // size. Extract the value and insert any appropriate assertions regarding
3314 // sign/zero extension.
3315 switch (VA.getLocInfo()) {
3317 llvm_unreachable("Unknown loc info!");
3318 case CCValAssign::Full:
3320 case CCValAssign::AExtUpper:
3321 case CCValAssign::AExt:
3322 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3324 case CCValAssign::SExtUpper:
3325 case CCValAssign::SExt:
3326 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3327 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3329 case CCValAssign::ZExtUpper:
3330 case CCValAssign::ZExt:
3331 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3332 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3334 case CCValAssign::BCvt:
3335 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3342 //===----------------------------------------------------------------------===//
3343 // Formal Arguments Calling Convention Implementation
3344 //===----------------------------------------------------------------------===//
3345 /// LowerFormalArguments - transform physical registers into virtual registers
3346 /// and generate load operations for arguments places on the stack.
3347 SDValue MipsTargetLowering::LowerFormalArguments(
3348 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3349 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3350 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3351 MachineFunction &MF = DAG.getMachineFunction();
3352 MachineFrameInfo &MFI = MF.getFrameInfo();
3353 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3355 MipsFI->setVarArgsFrameIndex(0);
3357 // Used with vargs to acumulate store chains.
3358 std::vector<SDValue> OutChains;
3360 // Assign locations to all of the incoming arguments.
3361 SmallVector<CCValAssign, 16> ArgLocs;
3362 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3364 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
3365 const Function *Func = DAG.getMachineFunction().getFunction();
3366 Function::const_arg_iterator FuncArg = Func->arg_begin();
3368 if (Func->hasFnAttribute("interrupt") && !Func->arg_empty())
3370 "Functions with the interrupt attribute cannot have arguments!");
3372 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3373 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3374 CCInfo.getInRegsParamsCount() > 0);
3376 unsigned CurArgIdx = 0;
3377 CCInfo.rewindByValRegsInfo();
3379 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3380 CCValAssign &VA = ArgLocs[i];
3381 if (Ins[i].isOrigArg()) {
3382 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3383 CurArgIdx = Ins[i].getOrigArgIndex();
3385 EVT ValVT = VA.getValVT();
3386 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3387 bool IsRegLoc = VA.isRegLoc();
3389 if (Flags.isByVal()) {
3390 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
3391 unsigned FirstByValReg, LastByValReg;
3392 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3393 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3395 assert(Flags.getByValSize() &&
3396 "ByVal args of size 0 should have been ignored by front-end.");
3397 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3398 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3399 FirstByValReg, LastByValReg, VA, CCInfo);
3400 CCInfo.nextInRegsParam();
3404 // Arguments stored on registers
3406 MVT RegVT = VA.getLocVT();
3407 unsigned ArgReg = VA.getLocReg();
3408 const TargetRegisterClass *RC = getRegClassFor(RegVT);
3410 // Transform the arguments stored on
3411 // physical registers into virtual ones
3412 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3413 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3415 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3417 // Handle floating point arguments passed in integer registers and
3418 // long double arguments passed in floating point registers.
3419 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3420 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3421 (RegVT == MVT::f64 && ValVT == MVT::i64))
3422 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3423 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3424 ValVT == MVT::f64) {
3425 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3426 getNextIntArgReg(ArgReg), RC);
3427 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3428 if (!Subtarget.isLittle())
3429 std::swap(ArgValue, ArgValue2);
3430 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3431 ArgValue, ArgValue2);
3434 InVals.push_back(ArgValue);
3435 } else { // VA.isRegLoc()
3436 MVT LocVT = VA.getLocVT();
3439 // We ought to be able to use LocVT directly but O32 sets it to i32
3440 // when allocating floating point values to integer registers.
3441 // This shouldn't influence how we load the value into registers unless
3442 // we are targeting softfloat.
3443 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3444 LocVT = VA.getValVT();
3448 assert(VA.isMemLoc());
3450 // The stack pointer offset is relative to the caller stack frame.
3451 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3452 VA.getLocMemOffset(), true);
3454 // Create load nodes to retrieve arguments from the stack
3455 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3456 SDValue ArgValue = DAG.getLoad(
3457 LocVT, DL, Chain, FIN,
3458 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3459 OutChains.push_back(ArgValue.getValue(1));
3461 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3463 InVals.push_back(ArgValue);
3467 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3468 // The mips ABIs for returning structs by value requires that we copy
3469 // the sret argument into $v0 for the return. Save the argument into
3470 // a virtual register so that we can access it from the return points.
3471 if (Ins[i].Flags.isSRet()) {
3472 unsigned Reg = MipsFI->getSRetReturnReg();
3474 Reg = MF.getRegInfo().createVirtualRegister(
3475 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3476 MipsFI->setSRetReturnReg(Reg);
3478 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3479 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3485 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3487 // All stores are grouped in one node to allow the matching between
3488 // the size of Ins and InVals. This only happens when on varg functions
3489 if (!OutChains.empty()) {
3490 OutChains.push_back(Chain);
3491 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3497 //===----------------------------------------------------------------------===//
3498 // Return Value Calling Convention Implementation
3499 //===----------------------------------------------------------------------===//
3502 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3503 MachineFunction &MF, bool IsVarArg,
3504 const SmallVectorImpl<ISD::OutputArg> &Outs,
3505 LLVMContext &Context) const {
3506 SmallVector<CCValAssign, 16> RVLocs;
3507 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3508 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3512 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3513 if (Subtarget.hasMips3() && Subtarget.useSoftFloat()) {
3514 if (Type == MVT::i32)
3521 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3523 SelectionDAG &DAG) const {
3525 MachineFunction &MF = DAG.getMachineFunction();
3526 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3530 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3534 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3536 const SmallVectorImpl<ISD::OutputArg> &Outs,
3537 const SmallVectorImpl<SDValue> &OutVals,
3538 const SDLoc &DL, SelectionDAG &DAG) const {
3539 // CCValAssign - represent the assignment of
3540 // the return value to a location
3541 SmallVector<CCValAssign, 16> RVLocs;
3542 MachineFunction &MF = DAG.getMachineFunction();
3544 // CCState - Info about the registers and stack slot.
3545 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3547 // Analyze return values.
3548 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3551 SmallVector<SDValue, 4> RetOps(1, Chain);
3553 // Copy the result values into the output registers.
3554 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3555 SDValue Val = OutVals[i];
3556 CCValAssign &VA = RVLocs[i];
3557 assert(VA.isRegLoc() && "Can only return in registers!");
3558 bool UseUpperBits = false;
3560 switch (VA.getLocInfo()) {
3562 llvm_unreachable("Unknown loc info!");
3563 case CCValAssign::Full:
3565 case CCValAssign::BCvt:
3566 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3568 case CCValAssign::AExtUpper:
3569 UseUpperBits = true;
3571 case CCValAssign::AExt:
3572 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3574 case CCValAssign::ZExtUpper:
3575 UseUpperBits = true;
3577 case CCValAssign::ZExt:
3578 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3580 case CCValAssign::SExtUpper:
3581 UseUpperBits = true;
3583 case CCValAssign::SExt:
3584 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3589 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3590 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3592 ISD::SHL, DL, VA.getLocVT(), Val,
3593 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3596 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3598 // Guarantee that all emitted copies are stuck together with flags.
3599 Flag = Chain.getValue(1);
3600 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3603 // The mips ABIs for returning structs by value requires that we copy
3604 // the sret argument into $v0 for the return. We saved the argument into
3605 // a virtual register in the entry block, so now we copy the value out
3607 if (MF.getFunction()->hasStructRetAttr()) {
3608 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3609 unsigned Reg = MipsFI->getSRetReturnReg();
3612 llvm_unreachable("sret virtual register not created in the entry block");
3614 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3615 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3617 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3618 Flag = Chain.getValue(1);
3619 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3622 RetOps[0] = Chain; // Update chain.
3624 // Add the flag if we have it.
3626 RetOps.push_back(Flag);
3628 // ISRs must use "eret".
3629 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt"))
3630 return LowerInterruptReturn(RetOps, DL, DAG);
3632 // Standard return on Mips is a "jr $ra"
3633 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3636 //===----------------------------------------------------------------------===//
3637 // Mips Inline Assembly Support
3638 //===----------------------------------------------------------------------===//
3640 /// getConstraintType - Given a constraint letter, return the type of
3641 /// constraint it is for this target.
3642 MipsTargetLowering::ConstraintType
3643 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3644 // Mips specific constraints
3645 // GCC config/mips/constraints.md
3647 // 'd' : An address register. Equivalent to r
3648 // unless generating MIPS16 code.
3649 // 'y' : Equivalent to r; retained for
3650 // backwards compatibility.
3651 // 'c' : A register suitable for use in an indirect
3652 // jump. This will always be $25 for -mabicalls.
3653 // 'l' : The lo register. 1 word storage.
3654 // 'x' : The hilo register pair. Double word storage.
3655 if (Constraint.size() == 1) {
3656 switch (Constraint[0]) {
3664 return C_RegisterClass;
3670 if (Constraint == "ZC")
3673 return TargetLowering::getConstraintType(Constraint);
3676 /// Examine constraint type and operand type and determine a weight value.
3677 /// This object must already have been set up with the operand type
3678 /// and the current alternative constraint selected.
3679 TargetLowering::ConstraintWeight
3680 MipsTargetLowering::getSingleConstraintMatchWeight(
3681 AsmOperandInfo &info, const char *constraint) const {
3682 ConstraintWeight weight = CW_Invalid;
3683 Value *CallOperandVal = info.CallOperandVal;
3684 // If we don't have a value, we can't do a match,
3685 // but allow it at the lowest weight.
3686 if (!CallOperandVal)
3688 Type *type = CallOperandVal->getType();
3689 // Look at the constraint type.
3690 switch (*constraint) {
3692 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3696 if (type->isIntegerTy())
3697 weight = CW_Register;
3699 case 'f': // FPU or MSA register
3700 if (Subtarget.hasMSA() && type->isVectorTy() &&
3701 cast<VectorType>(type)->getBitWidth() == 128)
3702 weight = CW_Register;
3703 else if (type->isFloatTy())
3704 weight = CW_Register;
3706 case 'c': // $25 for indirect jumps
3707 case 'l': // lo register
3708 case 'x': // hilo register pair
3709 if (type->isIntegerTy())
3710 weight = CW_SpecificReg;
3712 case 'I': // signed 16 bit immediate
3713 case 'J': // integer zero
3714 case 'K': // unsigned 16 bit immediate
3715 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3716 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3717 case 'O': // signed 15 bit immediate (+- 16383)
3718 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3719 if (isa<ConstantInt>(CallOperandVal))
3720 weight = CW_Constant;
3729 /// This is a helper function to parse a physical register string and split it
3730 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3731 /// that is returned indicates whether parsing was successful. The second flag
3732 /// is true if the numeric part exists.
3733 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3734 unsigned long long &Reg) {
3735 if (C.front() != '{' || C.back() != '}')
3736 return std::make_pair(false, false);
3738 // Search for the first numeric character.
3739 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3740 I = std::find_if(B, E, isdigit);
3742 Prefix = StringRef(B, I - B);
3744 // The second flag is set to false if no numeric characters were found.
3746 return std::make_pair(true, false);
3748 // Parse the numeric characters.
3749 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3753 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3754 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3755 const TargetRegisterInfo *TRI =
3756 Subtarget.getRegisterInfo();
3757 const TargetRegisterClass *RC;
3759 unsigned long long Reg;
3761 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3764 return std::make_pair(0U, nullptr);
3766 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3767 // No numeric characters follow "hi" or "lo".
3769 return std::make_pair(0U, nullptr);
3771 RC = TRI->getRegClass(Prefix == "hi" ?
3772 Mips::HI32RegClassID : Mips::LO32RegClassID);
3773 return std::make_pair(*(RC->begin()), RC);
3774 } else if (Prefix.startswith("$msa")) {
3775 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3777 // No numeric characters follow the name.
3779 return std::make_pair(0U, nullptr);
3781 Reg = StringSwitch<unsigned long long>(Prefix)
3782 .Case("$msair", Mips::MSAIR)
3783 .Case("$msacsr", Mips::MSACSR)
3784 .Case("$msaaccess", Mips::MSAAccess)
3785 .Case("$msasave", Mips::MSASave)
3786 .Case("$msamodify", Mips::MSAModify)
3787 .Case("$msarequest", Mips::MSARequest)
3788 .Case("$msamap", Mips::MSAMap)
3789 .Case("$msaunmap", Mips::MSAUnmap)
3793 return std::make_pair(0U, nullptr);
3795 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3796 return std::make_pair(Reg, RC);
3800 return std::make_pair(0U, nullptr);
3802 if (Prefix == "$f") { // Parse $f0-$f31.
3803 // If the size of FP registers is 64-bit or Reg is an even number, select
3804 // the 64-bit register class. Otherwise, select the 32-bit register class.
3805 if (VT == MVT::Other)
3806 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3808 RC = getRegClassFor(VT);
3810 if (RC == &Mips::AFGR64RegClass) {
3811 assert(Reg % 2 == 0);
3814 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3815 RC = TRI->getRegClass(Mips::FCCRegClassID);
3816 else if (Prefix == "$w") { // Parse $w0-$w31.
3817 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3818 } else { // Parse $0-$31.
3819 assert(Prefix == "$");
3820 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3823 assert(Reg < RC->getNumRegs());
3824 return std::make_pair(*(RC->begin() + Reg), RC);
3827 /// Given a register class constraint, like 'r', if this corresponds directly
3828 /// to an LLVM register class, return a register of 0 and the register class
3830 std::pair<unsigned, const TargetRegisterClass *>
3831 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3832 StringRef Constraint,
3834 if (Constraint.size() == 1) {
3835 switch (Constraint[0]) {
3836 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3837 case 'y': // Same as 'r'. Exists for compatibility.
3839 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3840 if (Subtarget.inMips16Mode())
3841 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3842 return std::make_pair(0U, &Mips::GPR32RegClass);
3844 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3845 return std::make_pair(0U, &Mips::GPR32RegClass);
3846 if (VT == MVT::i64 && Subtarget.isGP64bit())
3847 return std::make_pair(0U, &Mips::GPR64RegClass);
3848 // This will generate an error message
3849 return std::make_pair(0U, nullptr);
3850 case 'f': // FPU or MSA register
3851 if (VT == MVT::v16i8)
3852 return std::make_pair(0U, &Mips::MSA128BRegClass);
3853 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3854 return std::make_pair(0U, &Mips::MSA128HRegClass);
3855 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3856 return std::make_pair(0U, &Mips::MSA128WRegClass);
3857 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3858 return std::make_pair(0U, &Mips::MSA128DRegClass);
3859 else if (VT == MVT::f32)
3860 return std::make_pair(0U, &Mips::FGR32RegClass);
3861 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3862 if (Subtarget.isFP64bit())
3863 return std::make_pair(0U, &Mips::FGR64RegClass);
3864 return std::make_pair(0U, &Mips::AFGR64RegClass);
3867 case 'c': // register suitable for indirect jump
3869 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3870 assert(VT == MVT::i64 && "Unexpected type.");
3871 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3872 case 'l': // register suitable for indirect jump
3874 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3875 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3876 case 'x': // register suitable for indirect jump
3877 // Fixme: Not triggering the use of both hi and low
3878 // This will generate an error message
3879 return std::make_pair(0U, nullptr);
3883 std::pair<unsigned, const TargetRegisterClass *> R;
3884 R = parseRegForInlineAsmConstraint(Constraint, VT);
3889 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3892 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3893 /// vector. If it is invalid, don't add anything to Ops.
3894 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3895 std::string &Constraint,
3896 std::vector<SDValue>&Ops,
3897 SelectionDAG &DAG) const {
3901 // Only support length 1 constraints for now.
3902 if (Constraint.length() > 1) return;
3904 char ConstraintLetter = Constraint[0];
3905 switch (ConstraintLetter) {
3906 default: break; // This will fall through to the generic implementation
3907 case 'I': // Signed 16 bit constant
3908 // If this fails, the parent routine will give an error
3909 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3910 EVT Type = Op.getValueType();
3911 int64_t Val = C->getSExtValue();
3912 if (isInt<16>(Val)) {
3913 Result = DAG.getTargetConstant(Val, DL, Type);
3918 case 'J': // integer zero
3919 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3920 EVT Type = Op.getValueType();
3921 int64_t Val = C->getZExtValue();
3923 Result = DAG.getTargetConstant(0, DL, Type);
3928 case 'K': // unsigned 16 bit immediate
3929 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3930 EVT Type = Op.getValueType();
3931 uint64_t Val = (uint64_t)C->getZExtValue();
3932 if (isUInt<16>(Val)) {
3933 Result = DAG.getTargetConstant(Val, DL, Type);
3938 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3939 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3940 EVT Type = Op.getValueType();
3941 int64_t Val = C->getSExtValue();
3942 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3943 Result = DAG.getTargetConstant(Val, DL, Type);
3948 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3949 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3950 EVT Type = Op.getValueType();
3951 int64_t Val = C->getSExtValue();
3952 if ((Val >= -65535) && (Val <= -1)) {
3953 Result = DAG.getTargetConstant(Val, DL, Type);
3958 case 'O': // signed 15 bit immediate
3959 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3960 EVT Type = Op.getValueType();
3961 int64_t Val = C->getSExtValue();
3962 if ((isInt<15>(Val))) {
3963 Result = DAG.getTargetConstant(Val, DL, Type);
3968 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3969 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3970 EVT Type = Op.getValueType();
3971 int64_t Val = C->getSExtValue();
3972 if ((Val <= 65535) && (Val >= 1)) {
3973 Result = DAG.getTargetConstant(Val, DL, Type);
3980 if (Result.getNode()) {
3981 Ops.push_back(Result);
3985 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3988 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3989 const AddrMode &AM, Type *Ty,
3990 unsigned AS) const {
3991 // No global is ever allowed as a base.
3996 case 0: // "r+i" or just "i", depending on HasBaseReg.
3999 if (!AM.HasBaseReg) // allow "r+i".
4001 return false; // disallow "r+r" or "r+r+i".
4010 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4011 // The Mips target isn't yet aware of offsets.
4015 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
4017 bool IsMemset, bool ZeroMemset,
4019 MachineFunction &MF) const {
4020 if (Subtarget.hasMips64())
4026 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4027 if (VT != MVT::f32 && VT != MVT::f64)
4029 if (Imm.isNegZero())
4031 return Imm.isZero();
4034 unsigned MipsTargetLowering::getJumpTableEncoding() const {
4036 // FIXME: For space reasons this should be: EK_GPRel32BlockAddress.
4037 if (ABI.IsN64() && isPositionIndependent())
4038 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
4040 return TargetLowering::getJumpTableEncoding();
4043 bool MipsTargetLowering::useSoftFloat() const {
4044 return Subtarget.useSoftFloat();
4047 void MipsTargetLowering::copyByValRegs(
4048 SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
4049 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4050 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4051 unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
4052 MipsCCState &State) const {
4053 MachineFunction &MF = DAG.getMachineFunction();
4054 MachineFrameInfo &MFI = MF.getFrameInfo();
4055 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
4056 unsigned NumRegs = LastReg - FirstReg;
4057 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
4058 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4060 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
4064 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4065 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
4067 FrameObjOffset = VA.getLocMemOffset();
4069 // Create frame object.
4070 EVT PtrTy = getPointerTy(DAG.getDataLayout());
4071 int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, true);
4072 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4073 InVals.push_back(FIN);
4078 // Copy arg registers.
4079 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
4080 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4082 for (unsigned I = 0; I < NumRegs; ++I) {
4083 unsigned ArgReg = ByValArgRegs[FirstReg + I];
4084 unsigned VReg = addLiveIn(MF, ArgReg, RC);
4085 unsigned Offset = I * GPRSizeInBytes;
4086 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4087 DAG.getConstant(Offset, DL, PtrTy));
4088 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4089 StorePtr, MachinePointerInfo(FuncArg, Offset));
4090 OutChains.push_back(Store);
4094 // Copy byVal arg to registers and stack.
4095 void MipsTargetLowering::passByValArg(
4096 SDValue Chain, const SDLoc &DL,
4097 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
4098 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
4099 MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
4100 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
4101 const CCValAssign &VA) const {
4102 unsigned ByValSizeInBytes = Flags.getByValSize();
4103 unsigned OffsetInBytes = 0; // From beginning of struct
4104 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4105 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
4106 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
4107 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4108 unsigned NumRegs = LastReg - FirstReg;
4111 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
4112 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
4115 // Copy words to registers.
4116 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
4117 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4118 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4119 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4120 MachinePointerInfo(), Alignment);
4121 MemOpChains.push_back(LoadVal.getValue(1));
4122 unsigned ArgReg = ArgRegs[FirstReg + I];
4123 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4126 // Return if the struct has been fully copied.
4127 if (ByValSizeInBytes == OffsetInBytes)
4130 // Copy the remainder of the byval argument with sub-word loads and shifts.
4131 if (LeftoverBytes) {
4134 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
4135 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
4136 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
4138 if (RemainingSizeInBytes < LoadSizeInBytes)
4142 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4143 DAG.getConstant(OffsetInBytes, DL,
4145 SDValue LoadVal = DAG.getExtLoad(
4146 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
4147 MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
4148 MemOpChains.push_back(LoadVal.getValue(1));
4150 // Shift the loaded value.
4154 Shamt = TotalBytesLoaded * 8;
4156 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
4158 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4159 DAG.getConstant(Shamt, DL, MVT::i32));
4162 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4166 OffsetInBytes += LoadSizeInBytes;
4167 TotalBytesLoaded += LoadSizeInBytes;
4168 Alignment = std::min(Alignment, LoadSizeInBytes);
4171 unsigned ArgReg = ArgRegs[FirstReg + I];
4172 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4177 // Copy remainder of byval arg to it with memcpy.
4178 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
4179 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4180 DAG.getConstant(OffsetInBytes, DL, PtrTy));
4181 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4182 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
4183 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4184 DAG.getConstant(MemCpySize, DL, PtrTy),
4185 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
4186 /*isTailCall=*/false,
4187 MachinePointerInfo(), MachinePointerInfo());
4188 MemOpChains.push_back(Chain);
4191 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4192 SDValue Chain, const SDLoc &DL,
4194 CCState &State) const {
4195 ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
4196 unsigned Idx = State.getFirstUnallocated(ArgRegs);
4197 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4198 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
4199 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4200 MachineFunction &MF = DAG.getMachineFunction();
4201 MachineFrameInfo &MFI = MF.getFrameInfo();
4202 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4204 // Offset of the first variable argument from stack pointer.
4207 if (ArgRegs.size() == Idx)
4208 VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
4211 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4212 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4215 // Record the frame index of the first variable argument
4216 // which is a value necessary to VASTART.
4217 int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4218 MipsFI->setVarArgsFrameIndex(FI);
4220 // Copy the integer registers that have not been used for argument passing
4221 // to the argument register save area. For O32, the save area is allocated
4222 // in the caller's stack frame, while for N32/64, it is allocated in the
4223 // callee's stack frame.
4224 for (unsigned I = Idx; I < ArgRegs.size();
4225 ++I, VaArgOffset += RegSizeInBytes) {
4226 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4227 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4228 FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4229 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4231 DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4232 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4234 OutChains.push_back(Store);
4238 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
4239 unsigned Align) const {
4240 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4242 assert(Size && "Byval argument's size shouldn't be 0.");
4244 Align = std::min(Align, TFL->getStackAlignment());
4246 unsigned FirstReg = 0;
4247 unsigned NumRegs = 0;
4249 if (State->getCallingConv() != CallingConv::Fast) {
4250 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4251 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4252 // FIXME: The O32 case actually describes no shadow registers.
4253 const MCPhysReg *ShadowRegs =
4254 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4256 // We used to check the size as well but we can't do that anymore since
4257 // CCState::HandleByVal() rounds up the size after calling this function.
4258 assert(!(Align % RegSizeInBytes) &&
4259 "Byval argument's alignment should be a multiple of"
4262 FirstReg = State->getFirstUnallocated(IntArgRegs);
4264 // If Align > RegSizeInBytes, the first arg register must be even.
4265 // FIXME: This condition happens to do the right thing but it's not the
4266 // right way to test it. We want to check that the stack frame offset
4267 // of the register is aligned.
4268 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
4269 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4273 // Mark the registers allocated.
4274 Size = alignTo(Size, RegSizeInBytes);
4275 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4276 Size -= RegSizeInBytes, ++I, ++NumRegs)
4277 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4280 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4283 MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4284 MachineBasicBlock *BB,
4286 unsigned Opc) const {
4287 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4288 "Subtarget already supports SELECT nodes with the use of"
4289 "conditional-move instructions.");
4291 const TargetInstrInfo *TII =
4292 Subtarget.getInstrInfo();
4293 DebugLoc DL = MI.getDebugLoc();
4295 // To "insert" a SELECT instruction, we actually have to insert the
4296 // diamond control-flow pattern. The incoming instruction knows the
4297 // destination vreg to set, the condition code register to branch on, the
4298 // true/false values to select between, and a branch opcode to use.
4299 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4300 MachineFunction::iterator It = ++BB->getIterator();
4306 // bNE r1, r0, copy1MBB
4307 // fallthrough --> copy0MBB
4308 MachineBasicBlock *thisMBB = BB;
4309 MachineFunction *F = BB->getParent();
4310 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4311 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4312 F->insert(It, copy0MBB);
4313 F->insert(It, sinkMBB);
4315 // Transfer the remainder of BB and its successor edges to sinkMBB.
4316 sinkMBB->splice(sinkMBB->begin(), BB,
4317 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4318 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4320 // Next, add the true and fallthrough blocks as its successors.
4321 BB->addSuccessor(copy0MBB);
4322 BB->addSuccessor(sinkMBB);
4325 // bc1[tf] cc, sinkMBB
4326 BuildMI(BB, DL, TII->get(Opc))
4327 .addReg(MI.getOperand(1).getReg())
4330 // bne rs, $0, sinkMBB
4331 BuildMI(BB, DL, TII->get(Opc))
4332 .addReg(MI.getOperand(1).getReg())
4338 // %FalseValue = ...
4339 // # fallthrough to sinkMBB
4342 // Update machine-CFG edges
4343 BB->addSuccessor(sinkMBB);
4346 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4350 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4351 .addReg(MI.getOperand(2).getReg())
4353 .addReg(MI.getOperand(3).getReg())
4356 MI.eraseFromParent(); // The pseudo instruction is gone now.
4361 // FIXME? Maybe this could be a TableGen attribute on some registers and
4362 // this table could be generated automatically from RegInfo.
4363 unsigned MipsTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4364 SelectionDAG &DAG) const {
4365 // Named registers is expected to be fairly rare. For now, just support $28
4366 // since the linux kernel uses it.
4367 if (Subtarget.isGP64bit()) {
4368 unsigned Reg = StringSwitch<unsigned>(RegName)
4369 .Case("$28", Mips::GP_64)
4374 unsigned Reg = StringSwitch<unsigned>(RegName)
4375 .Case("$28", Mips::GP)
4380 report_fatal_error("Invalid register name global variable");