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/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineJumpTableInfo.h"
29 #include "llvm/CodeGen/MachineRegisterInfo.h"
30 #include "llvm/CodeGen/FunctionLoweringInfo.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 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
75 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
76 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
79 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
81 unsigned Flag) const {
82 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
85 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
87 unsigned Flag) const {
88 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
91 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
93 unsigned Flag) const {
94 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
97 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
99 unsigned Flag) const {
100 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
103 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
105 unsigned Flag) const {
106 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
107 N->getOffset(), Flag);
110 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
111 switch ((MipsISD::NodeType)Opcode) {
112 case MipsISD::FIRST_NUMBER: break;
113 case MipsISD::JmpLink: return "MipsISD::JmpLink";
114 case MipsISD::TailCall: return "MipsISD::TailCall";
115 case MipsISD::Highest: return "MipsISD::Highest";
116 case MipsISD::Higher: return "MipsISD::Higher";
117 case MipsISD::Hi: return "MipsISD::Hi";
118 case MipsISD::Lo: return "MipsISD::Lo";
119 case MipsISD::GotHi: return "MipsISD::GotHi";
120 case MipsISD::GPRel: return "MipsISD::GPRel";
121 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
122 case MipsISD::Ret: return "MipsISD::Ret";
123 case MipsISD::ERet: return "MipsISD::ERet";
124 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
125 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
126 case MipsISD::FPCmp: return "MipsISD::FPCmp";
127 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
128 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
129 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
130 case MipsISD::MFHI: return "MipsISD::MFHI";
131 case MipsISD::MFLO: return "MipsISD::MFLO";
132 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
133 case MipsISD::Mult: return "MipsISD::Mult";
134 case MipsISD::Multu: return "MipsISD::Multu";
135 case MipsISD::MAdd: return "MipsISD::MAdd";
136 case MipsISD::MAddu: return "MipsISD::MAddu";
137 case MipsISD::MSub: return "MipsISD::MSub";
138 case MipsISD::MSubu: return "MipsISD::MSubu";
139 case MipsISD::DivRem: return "MipsISD::DivRem";
140 case MipsISD::DivRemU: return "MipsISD::DivRemU";
141 case MipsISD::DivRem16: return "MipsISD::DivRem16";
142 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
143 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
144 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
145 case MipsISD::Wrapper: return "MipsISD::Wrapper";
146 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
147 case MipsISD::Sync: return "MipsISD::Sync";
148 case MipsISD::Ext: return "MipsISD::Ext";
149 case MipsISD::Ins: return "MipsISD::Ins";
150 case MipsISD::CIns: return "MipsISD::CIns";
151 case MipsISD::LWL: return "MipsISD::LWL";
152 case MipsISD::LWR: return "MipsISD::LWR";
153 case MipsISD::SWL: return "MipsISD::SWL";
154 case MipsISD::SWR: return "MipsISD::SWR";
155 case MipsISD::LDL: return "MipsISD::LDL";
156 case MipsISD::LDR: return "MipsISD::LDR";
157 case MipsISD::SDL: return "MipsISD::SDL";
158 case MipsISD::SDR: return "MipsISD::SDR";
159 case MipsISD::EXTP: return "MipsISD::EXTP";
160 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
161 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
162 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
163 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
164 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
165 case MipsISD::SHILO: return "MipsISD::SHILO";
166 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
167 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH";
168 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL";
169 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR";
170 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL";
171 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR";
172 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL";
173 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR";
174 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL";
175 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR";
176 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH";
177 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH";
178 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W";
179 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W";
180 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH";
181 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH";
182 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH";
183 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH";
184 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH";
185 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH";
186 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH";
187 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH";
188 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH";
189 case MipsISD::MULT: return "MipsISD::MULT";
190 case MipsISD::MULTU: return "MipsISD::MULTU";
191 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
192 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
193 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
194 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
195 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
196 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
197 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
198 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
199 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
200 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
201 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
202 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
203 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
204 case MipsISD::VCEQ: return "MipsISD::VCEQ";
205 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
206 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
207 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
208 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
209 case MipsISD::VSMAX: return "MipsISD::VSMAX";
210 case MipsISD::VSMIN: return "MipsISD::VSMIN";
211 case MipsISD::VUMAX: return "MipsISD::VUMAX";
212 case MipsISD::VUMIN: return "MipsISD::VUMIN";
213 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
214 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
215 case MipsISD::VNOR: return "MipsISD::VNOR";
216 case MipsISD::VSHF: return "MipsISD::VSHF";
217 case MipsISD::SHF: return "MipsISD::SHF";
218 case MipsISD::ILVEV: return "MipsISD::ILVEV";
219 case MipsISD::ILVOD: return "MipsISD::ILVOD";
220 case MipsISD::ILVL: return "MipsISD::ILVL";
221 case MipsISD::ILVR: return "MipsISD::ILVR";
222 case MipsISD::PCKEV: return "MipsISD::PCKEV";
223 case MipsISD::PCKOD: return "MipsISD::PCKOD";
224 case MipsISD::INSVE: return "MipsISD::INSVE";
229 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
230 const MipsSubtarget &STI)
231 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
232 // Mips does not have i1 type, so use i32 for
233 // setcc operations results (slt, sgt, ...).
234 setBooleanContents(ZeroOrOneBooleanContent);
235 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
236 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
237 // does. Integer booleans still use 0 and 1.
238 if (Subtarget.hasMips32r6())
239 setBooleanContents(ZeroOrOneBooleanContent,
240 ZeroOrNegativeOneBooleanContent);
242 // Load extented operations for i1 types must be promoted
243 for (MVT VT : MVT::integer_valuetypes()) {
244 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
245 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
246 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
249 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
251 for (MVT VT : MVT::fp_valuetypes()) {
252 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
253 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
256 // Set LoadExtAction for f16 vectors to Expand
257 for (MVT VT : MVT::fp_vector_valuetypes()) {
258 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
260 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
263 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
264 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
266 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
268 // Used by legalize types to correctly generate the setcc result.
269 // Without this, every float setcc comes with a AND/OR with the result,
270 // we don't want this, since the fpcmp result goes to a flag register,
271 // which is used implicitly by brcond and select operations.
272 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
274 // Mips Custom Operations
275 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
276 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
277 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
278 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
279 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
280 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
281 setOperationAction(ISD::SELECT, MVT::f32, Custom);
282 setOperationAction(ISD::SELECT, MVT::f64, Custom);
283 setOperationAction(ISD::SELECT, MVT::i32, Custom);
284 setOperationAction(ISD::SETCC, MVT::f32, Custom);
285 setOperationAction(ISD::SETCC, MVT::f64, Custom);
286 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
287 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
288 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
289 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
291 if (Subtarget.isGP64bit()) {
292 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
293 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
294 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
295 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
296 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
297 setOperationAction(ISD::SELECT, MVT::i64, Custom);
298 setOperationAction(ISD::LOAD, MVT::i64, Custom);
299 setOperationAction(ISD::STORE, MVT::i64, Custom);
300 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
301 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
302 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
303 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
306 if (!Subtarget.isGP64bit()) {
307 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
308 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
309 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
312 setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
313 if (Subtarget.isGP64bit())
314 setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
316 setOperationAction(ISD::SDIV, MVT::i32, Expand);
317 setOperationAction(ISD::SREM, MVT::i32, Expand);
318 setOperationAction(ISD::UDIV, MVT::i32, Expand);
319 setOperationAction(ISD::UREM, MVT::i32, Expand);
320 setOperationAction(ISD::SDIV, MVT::i64, Expand);
321 setOperationAction(ISD::SREM, MVT::i64, Expand);
322 setOperationAction(ISD::UDIV, MVT::i64, Expand);
323 setOperationAction(ISD::UREM, MVT::i64, Expand);
325 // Operations not directly supported by Mips.
326 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
327 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
328 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
329 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
330 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
331 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
332 setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
333 setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
334 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
335 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
336 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
337 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
338 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
339 if (Subtarget.hasCnMips()) {
340 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
341 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
343 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
344 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
346 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
347 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
348 setOperationAction(ISD::ROTL, MVT::i32, Expand);
349 setOperationAction(ISD::ROTL, MVT::i64, Expand);
350 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
351 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
353 if (!Subtarget.hasMips32r2())
354 setOperationAction(ISD::ROTR, MVT::i32, Expand);
356 if (!Subtarget.hasMips64r2())
357 setOperationAction(ISD::ROTR, MVT::i64, Expand);
359 setOperationAction(ISD::FSIN, MVT::f32, Expand);
360 setOperationAction(ISD::FSIN, MVT::f64, Expand);
361 setOperationAction(ISD::FCOS, MVT::f32, Expand);
362 setOperationAction(ISD::FCOS, MVT::f64, Expand);
363 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
364 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
365 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
366 setOperationAction(ISD::FPOW, MVT::f32, Expand);
367 setOperationAction(ISD::FPOW, MVT::f64, Expand);
368 setOperationAction(ISD::FLOG, MVT::f32, Expand);
369 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
370 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
371 setOperationAction(ISD::FEXP, MVT::f32, Expand);
372 setOperationAction(ISD::FMA, MVT::f32, Expand);
373 setOperationAction(ISD::FMA, MVT::f64, Expand);
374 setOperationAction(ISD::FREM, MVT::f32, Expand);
375 setOperationAction(ISD::FREM, MVT::f64, Expand);
377 // Lower f16 conversion operations into library calls
378 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
379 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
380 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
381 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
383 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
385 setOperationAction(ISD::VASTART, MVT::Other, Custom);
386 setOperationAction(ISD::VAARG, MVT::Other, Custom);
387 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
388 setOperationAction(ISD::VAEND, MVT::Other, Expand);
390 // Use the default for now
391 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
392 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
394 if (!Subtarget.isGP64bit()) {
395 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
396 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
400 if (!Subtarget.hasMips32r2()) {
401 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
402 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
405 // MIPS16 lacks MIPS32's clz and clo instructions.
406 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
407 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
408 if (!Subtarget.hasMips64())
409 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
411 if (!Subtarget.hasMips32r2())
412 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
413 if (!Subtarget.hasMips64r2())
414 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
416 if (Subtarget.isGP64bit()) {
417 setLoadExtAction(ISD::SEXTLOAD, MVT::i64, MVT::i32, Custom);
418 setLoadExtAction(ISD::ZEXTLOAD, MVT::i64, MVT::i32, Custom);
419 setLoadExtAction(ISD::EXTLOAD, MVT::i64, MVT::i32, Custom);
420 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
423 setOperationAction(ISD::TRAP, MVT::Other, Legal);
425 setTargetDAGCombine(ISD::SDIVREM);
426 setTargetDAGCombine(ISD::UDIVREM);
427 setTargetDAGCombine(ISD::SELECT);
428 setTargetDAGCombine(ISD::AND);
429 setTargetDAGCombine(ISD::OR);
430 setTargetDAGCombine(ISD::ADD);
431 setTargetDAGCombine(ISD::AssertZext);
432 setTargetDAGCombine(ISD::SHL);
435 // These libcalls are not available in 32-bit.
436 setLibcallName(RTLIB::SHL_I128, nullptr);
437 setLibcallName(RTLIB::SRL_I128, nullptr);
438 setLibcallName(RTLIB::SRA_I128, nullptr);
441 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
443 // The arguments on the stack are defined in terms of 4-byte slots on O32
444 // and 8-byte slots on N32/N64.
445 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
447 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
449 MaxStoresPerMemcpy = 16;
451 isMicroMips = Subtarget.inMicroMipsMode();
454 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
455 const MipsSubtarget &STI) {
456 if (STI.inMips16Mode())
457 return llvm::createMips16TargetLowering(TM, STI);
459 return llvm::createMipsSETargetLowering(TM, STI);
462 // Create a fast isel object.
464 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
465 const TargetLibraryInfo *libInfo) const {
466 const MipsTargetMachine &TM =
467 static_cast<const MipsTargetMachine &>(funcInfo.MF->getTarget());
469 // We support only the standard encoding [MIPS32,MIPS32R5] ISAs.
470 bool UseFastISel = TM.Options.EnableFastISel && Subtarget.hasMips32() &&
471 !Subtarget.hasMips32r6() && !Subtarget.inMips16Mode() &&
472 !Subtarget.inMicroMipsMode();
474 // Disable if we don't generate PIC or the ABI isn't O32.
475 if (!TM.isPositionIndependent() || !TM.getABI().IsO32())
478 return UseFastISel ? Mips::createFastISel(funcInfo, libInfo) : nullptr;
481 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
485 return VT.changeVectorElementTypeToInteger();
488 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
489 TargetLowering::DAGCombinerInfo &DCI,
490 const MipsSubtarget &Subtarget) {
491 if (DCI.isBeforeLegalizeOps())
494 EVT Ty = N->getValueType(0);
495 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
496 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
497 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
501 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
502 N->getOperand(0), N->getOperand(1));
503 SDValue InChain = DAG.getEntryNode();
504 SDValue InGlue = DivRem;
507 if (N->hasAnyUseOfValue(0)) {
508 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
510 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
511 InChain = CopyFromLo.getValue(1);
512 InGlue = CopyFromLo.getValue(2);
516 if (N->hasAnyUseOfValue(1)) {
517 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
519 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
525 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
527 default: llvm_unreachable("Unknown fp condition code!");
529 case ISD::SETOEQ: return Mips::FCOND_OEQ;
530 case ISD::SETUNE: return Mips::FCOND_UNE;
532 case ISD::SETOLT: return Mips::FCOND_OLT;
534 case ISD::SETOGT: return Mips::FCOND_OGT;
536 case ISD::SETOLE: return Mips::FCOND_OLE;
538 case ISD::SETOGE: return Mips::FCOND_OGE;
539 case ISD::SETULT: return Mips::FCOND_ULT;
540 case ISD::SETULE: return Mips::FCOND_ULE;
541 case ISD::SETUGT: return Mips::FCOND_UGT;
542 case ISD::SETUGE: return Mips::FCOND_UGE;
543 case ISD::SETUO: return Mips::FCOND_UN;
544 case ISD::SETO: return Mips::FCOND_OR;
546 case ISD::SETONE: return Mips::FCOND_ONE;
547 case ISD::SETUEQ: return Mips::FCOND_UEQ;
552 /// This function returns true if the floating point conditional branches and
553 /// conditional moves which use condition code CC should be inverted.
554 static bool invertFPCondCodeUser(Mips::CondCode CC) {
555 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
558 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
559 "Illegal Condition Code");
564 // Creates and returns an FPCmp node from a setcc node.
565 // Returns Op if setcc is not a floating point comparison.
566 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
567 // must be a SETCC node
568 if (Op.getOpcode() != ISD::SETCC)
571 SDValue LHS = Op.getOperand(0);
573 if (!LHS.getValueType().isFloatingPoint())
576 SDValue RHS = Op.getOperand(1);
579 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
580 // node if necessary.
581 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
583 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
584 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
587 // Creates and returns a CMovFPT/F node.
588 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
589 SDValue False, const SDLoc &DL) {
590 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
591 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
592 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
594 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
595 True.getValueType(), True, FCC0, False, Cond);
598 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
599 TargetLowering::DAGCombinerInfo &DCI,
600 const MipsSubtarget &Subtarget) {
601 if (DCI.isBeforeLegalizeOps())
604 SDValue SetCC = N->getOperand(0);
606 if ((SetCC.getOpcode() != ISD::SETCC) ||
607 !SetCC.getOperand(0).getValueType().isInteger())
610 SDValue False = N->getOperand(2);
611 EVT FalseTy = False.getValueType();
613 if (!FalseTy.isInteger())
616 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
618 // If the RHS (False) is 0, we swap the order of the operands
619 // of ISD::SELECT (obviously also inverting the condition) so that we can
620 // take advantage of conditional moves using the $0 register.
622 // return (a != 0) ? x : 0;
630 if (!FalseC->getZExtValue()) {
631 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
632 SDValue True = N->getOperand(1);
634 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
635 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
637 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
640 // If both operands are integer constants there's a possibility that we
641 // can do some interesting optimizations.
642 SDValue True = N->getOperand(1);
643 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
645 if (!TrueC || !True.getValueType().isInteger())
648 // We'll also ignore MVT::i64 operands as this optimizations proves
649 // to be ineffective because of the required sign extensions as the result
650 // of a SETCC operator is always MVT::i32 for non-vector types.
651 if (True.getValueType() == MVT::i64)
654 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
656 // 1) (a < x) ? y : y-1
658 // addiu $reg2, $reg1, y-1
660 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
662 // 2) (a < x) ? y-1 : y
664 // xor $reg1, $reg1, 1
665 // addiu $reg2, $reg1, y-1
667 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
668 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
669 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
670 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
673 // Couldn't optimize.
677 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
678 TargetLowering::DAGCombinerInfo &DCI,
679 const MipsSubtarget &Subtarget) {
680 if (DCI.isBeforeLegalizeOps())
683 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
685 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
686 if (!FalseC || FalseC->getZExtValue())
689 // Since RHS (False) is 0, we swap the order of the True/False operands
690 // (obviously also inverting the condition) so that we can
691 // take advantage of conditional moves using the $0 register.
693 // return (a != 0) ? x : 0;
696 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
699 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
700 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
701 ValueIfFalse, FCC, ValueIfTrue, Glue);
704 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
705 TargetLowering::DAGCombinerInfo &DCI,
706 const MipsSubtarget &Subtarget) {
707 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
710 SDValue FirstOperand = N->getOperand(0);
711 unsigned FirstOperandOpc = FirstOperand.getOpcode();
712 SDValue Mask = N->getOperand(1);
713 EVT ValTy = N->getValueType(0);
716 uint64_t Pos = 0, SMPos, SMSize;
721 // Op's second operand must be a shifted mask.
722 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
723 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
726 if (FirstOperandOpc == ISD::SRA || FirstOperandOpc == ISD::SRL) {
727 // Pattern match EXT.
728 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
729 // => ext $dst, $src, pos, size
731 // The second operand of the shift must be an immediate.
732 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
735 Pos = CN->getZExtValue();
737 // Return if the shifted mask does not start at bit 0 or the sum of its size
738 // and Pos exceeds the word's size.
739 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
743 NewOperand = FirstOperand.getOperand(0);
744 } else if (FirstOperandOpc == ISD::SHL && Subtarget.hasCnMips()) {
745 // Pattern match CINS.
746 // $dst = and (shl $src , pos), mask
747 // => cins $dst, $src, pos, size
748 // mask is a shifted mask with consecutive 1's, pos = shift amount,
749 // size = population count.
751 // The second operand of the shift must be an immediate.
752 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))))
755 Pos = CN->getZExtValue();
757 if (SMPos != Pos || Pos >= ValTy.getSizeInBits() || SMSize >= 32 ||
758 Pos + SMSize > ValTy.getSizeInBits())
761 NewOperand = FirstOperand.getOperand(0);
762 // SMSize is 'location' (position) in this case, not size.
766 // Pattern match EXT.
767 // $dst = and $src, (2**size - 1) , if size > 16
768 // => ext $dst, $src, pos, size , pos = 0
770 // If the mask is <= 0xffff, andi can be used instead.
771 if (CN->getZExtValue() <= 0xffff)
774 // Return if the mask doesn't start at position 0.
779 NewOperand = FirstOperand;
781 return DAG.getNode(Opc, DL, ValTy, NewOperand,
782 DAG.getConstant(Pos, DL, MVT::i32),
783 DAG.getConstant(SMSize, DL, MVT::i32));
786 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
787 TargetLowering::DAGCombinerInfo &DCI,
788 const MipsSubtarget &Subtarget) {
789 // Pattern match INS.
790 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
791 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
792 // => ins $dst, $src, size, pos, $src1
793 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
796 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
797 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
798 ConstantSDNode *CN, *CN1;
800 // See if Op's first operand matches (and $src1 , mask0).
801 if (And0.getOpcode() != ISD::AND)
804 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
805 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
808 // See if Op's second operand matches (and (shl $src, pos), mask1).
809 if (And1.getOpcode() == ISD::AND &&
810 And1.getOperand(0).getOpcode() == ISD::SHL) {
812 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
813 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
816 // The shift masks must have the same position and size.
817 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
820 SDValue Shl = And1.getOperand(0);
822 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
825 unsigned Shamt = CN->getZExtValue();
827 // Return if the shift amount and the first bit position of mask are not the
829 EVT ValTy = N->getValueType(0);
830 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
834 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
835 DAG.getConstant(SMPos0, DL, MVT::i32),
836 DAG.getConstant(SMSize0, DL, MVT::i32),
839 // Pattern match DINS.
840 // $dst = or (and $src, mask0), mask1
841 // where mask0 = ((1 << SMSize0) -1) << SMPos0
842 // => dins $dst, $src, pos, size
843 if (~CN->getSExtValue() == ((((int64_t)1 << SMSize0) - 1) << SMPos0) &&
844 ((SMSize0 + SMPos0 <= 64 && Subtarget.hasMips64r2()) ||
845 (SMSize0 + SMPos0 <= 32))) {
846 // Check if AND instruction has constant as argument
847 bool isConstCase = And1.getOpcode() != ISD::AND;
848 if (And1.getOpcode() == ISD::AND) {
849 if (!(CN1 = dyn_cast<ConstantSDNode>(And1->getOperand(1))))
852 if (!(CN1 = dyn_cast<ConstantSDNode>(N->getOperand(1))))
856 EVT ValTy = N->getOperand(0)->getValueType(0);
860 Const1 = DAG.getConstant(SMPos0, DL, MVT::i32);
861 SrlX = DAG.getNode(ISD::SRL, DL, And1->getValueType(0), And1, Const1);
864 MipsISD::Ins, DL, N->getValueType(0),
866 ? DAG.getConstant(CN1->getSExtValue() >> SMPos0, DL, ValTy)
868 DAG.getConstant(SMPos0, DL, MVT::i32),
869 DAG.getConstant(ValTy.getSizeInBits() / 8 < 8 ? SMSize0 & 31
872 And0->getOperand(0));
879 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
880 TargetLowering::DAGCombinerInfo &DCI,
881 const MipsSubtarget &Subtarget) {
882 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
884 if (DCI.isBeforeLegalizeOps())
887 SDValue Add = N->getOperand(1);
889 if (Add.getOpcode() != ISD::ADD)
892 SDValue Lo = Add.getOperand(1);
894 if ((Lo.getOpcode() != MipsISD::Lo) ||
895 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
898 EVT ValTy = N->getValueType(0);
901 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
903 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
906 static SDValue performAssertZextCombine(SDNode *N, SelectionDAG &DAG,
907 TargetLowering::DAGCombinerInfo &DCI,
908 const MipsSubtarget &Subtarget) {
909 SDValue N0 = N->getOperand(0);
910 EVT NarrowerVT = cast<VTSDNode>(N->getOperand(1))->getVT();
912 if (N0.getOpcode() != ISD::TRUNCATE)
915 if (N0.getOperand(0).getOpcode() != ISD::AssertZext)
918 // fold (AssertZext (trunc (AssertZext x))) -> (trunc (AssertZext x))
919 // if the type of the extension of the innermost AssertZext node is
920 // smaller from that of the outermost node, eg:
921 // (AssertZext:i32 (trunc:i32 (AssertZext:i64 X, i32)), i8)
922 // -> (trunc:i32 (AssertZext X, i8))
923 SDValue WiderAssertZext = N0.getOperand(0);
924 EVT WiderVT = cast<VTSDNode>(WiderAssertZext->getOperand(1))->getVT();
926 if (NarrowerVT.bitsLT(WiderVT)) {
927 SDValue NewAssertZext = DAG.getNode(
928 ISD::AssertZext, SDLoc(N), WiderAssertZext.getValueType(),
929 WiderAssertZext.getOperand(0), DAG.getValueType(NarrowerVT));
930 return DAG.getNode(ISD::TRUNCATE, SDLoc(N), N->getValueType(0),
938 static SDValue performSHLCombine(SDNode *N, SelectionDAG &DAG,
939 TargetLowering::DAGCombinerInfo &DCI,
940 const MipsSubtarget &Subtarget) {
941 // Pattern match CINS.
942 // $dst = shl (and $src , imm), pos
943 // => cins $dst, $src, pos, size
945 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasCnMips())
948 SDValue FirstOperand = N->getOperand(0);
949 unsigned FirstOperandOpc = FirstOperand.getOpcode();
950 SDValue SecondOperand = N->getOperand(1);
951 EVT ValTy = N->getValueType(0);
954 uint64_t Pos = 0, SMPos, SMSize;
958 // The second operand of the shift must be an immediate.
959 if (!(CN = dyn_cast<ConstantSDNode>(SecondOperand)))
962 Pos = CN->getZExtValue();
964 if (Pos >= ValTy.getSizeInBits())
967 if (FirstOperandOpc != ISD::AND)
970 // AND's second operand must be a shifted mask.
971 if (!(CN = dyn_cast<ConstantSDNode>(FirstOperand.getOperand(1))) ||
972 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
975 // Return if the shifted mask does not start at bit 0 or the sum of its size
976 // and Pos exceeds the word's size.
977 if (SMPos != 0 || SMSize > 32 || Pos + SMSize > ValTy.getSizeInBits())
980 NewOperand = FirstOperand.getOperand(0);
981 // SMSize is 'location' (position) in this case, not size.
984 return DAG.getNode(MipsISD::CIns, DL, ValTy, NewOperand,
985 DAG.getConstant(Pos, DL, MVT::i32),
986 DAG.getConstant(SMSize, DL, MVT::i32));
989 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
991 SelectionDAG &DAG = DCI.DAG;
992 unsigned Opc = N->getOpcode();
998 return performDivRemCombine(N, DAG, DCI, Subtarget);
1000 return performSELECTCombine(N, DAG, DCI, Subtarget);
1001 case MipsISD::CMovFP_F:
1002 case MipsISD::CMovFP_T:
1003 return performCMovFPCombine(N, DAG, DCI, Subtarget);
1005 return performANDCombine(N, DAG, DCI, Subtarget);
1007 return performORCombine(N, DAG, DCI, Subtarget);
1009 return performADDCombine(N, DAG, DCI, Subtarget);
1010 case ISD::AssertZext:
1011 return performAssertZextCombine(N, DAG, DCI, Subtarget);
1013 return performSHLCombine(N, DAG, DCI, Subtarget);
1019 bool MipsTargetLowering::isCheapToSpeculateCttz() const {
1020 return Subtarget.hasMips32();
1023 bool MipsTargetLowering::isCheapToSpeculateCtlz() const {
1024 return Subtarget.hasMips32();
1028 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1029 SmallVectorImpl<SDValue> &Results,
1030 SelectionDAG &DAG) const {
1031 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1033 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1034 Results.push_back(Res.getValue(I));
1038 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1039 SmallVectorImpl<SDValue> &Results,
1040 SelectionDAG &DAG) const {
1041 return LowerOperationWrapper(N, Results, DAG);
1044 SDValue MipsTargetLowering::
1045 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1047 switch (Op.getOpcode())
1049 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
1050 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
1051 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
1052 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
1053 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
1054 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
1055 case ISD::SELECT: return lowerSELECT(Op, DAG);
1056 case ISD::SETCC: return lowerSETCC(Op, DAG);
1057 case ISD::VASTART: return lowerVASTART(Op, DAG);
1058 case ISD::VAARG: return lowerVAARG(Op, DAG);
1059 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
1060 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
1061 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
1062 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
1063 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
1064 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
1065 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
1066 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
1067 case ISD::LOAD: return lowerLOAD(Op, DAG);
1068 case ISD::STORE: return lowerSTORE(Op, DAG);
1069 case ISD::EH_DWARF_CFA: return lowerEH_DWARF_CFA(Op, DAG);
1070 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
1075 //===----------------------------------------------------------------------===//
1076 // Lower helper functions
1077 //===----------------------------------------------------------------------===//
1079 // addLiveIn - This helper function adds the specified physical register to the
1080 // MachineFunction as a live in value. It also creates a corresponding
1081 // virtual register for it.
1083 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1085 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1086 MF.getRegInfo().addLiveIn(PReg, VReg);
1090 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr &MI,
1091 MachineBasicBlock &MBB,
1092 const TargetInstrInfo &TII,
1093 bool Is64Bit, bool IsMicroMips) {
1097 // Insert instruction "teq $divisor_reg, $zero, 7".
1098 MachineBasicBlock::iterator I(MI);
1099 MachineInstrBuilder MIB;
1100 MachineOperand &Divisor = MI.getOperand(2);
1101 MIB = BuildMI(MBB, std::next(I), MI.getDebugLoc(),
1102 TII.get(IsMicroMips ? Mips::TEQ_MM : Mips::TEQ))
1103 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
1107 // Use the 32-bit sub-register if this is a 64-bit division.
1109 MIB->getOperand(0).setSubReg(Mips::sub_32);
1111 // Clear Divisor's kill flag.
1112 Divisor.setIsKill(false);
1114 // We would normally delete the original instruction here but in this case
1115 // we only needed to inject an additional instruction rather than replace it.
1121 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
1122 MachineBasicBlock *BB) const {
1123 switch (MI.getOpcode()) {
1125 llvm_unreachable("Unexpected instr type to insert");
1126 case Mips::ATOMIC_LOAD_ADD_I8:
1127 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1128 case Mips::ATOMIC_LOAD_ADD_I16:
1129 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1130 case Mips::ATOMIC_LOAD_ADD_I32:
1131 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
1132 case Mips::ATOMIC_LOAD_ADD_I64:
1133 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
1135 case Mips::ATOMIC_LOAD_AND_I8:
1136 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1137 case Mips::ATOMIC_LOAD_AND_I16:
1138 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1139 case Mips::ATOMIC_LOAD_AND_I32:
1140 return emitAtomicBinary(MI, BB, 4, Mips::AND);
1141 case Mips::ATOMIC_LOAD_AND_I64:
1142 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
1144 case Mips::ATOMIC_LOAD_OR_I8:
1145 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1146 case Mips::ATOMIC_LOAD_OR_I16:
1147 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1148 case Mips::ATOMIC_LOAD_OR_I32:
1149 return emitAtomicBinary(MI, BB, 4, Mips::OR);
1150 case Mips::ATOMIC_LOAD_OR_I64:
1151 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
1153 case Mips::ATOMIC_LOAD_XOR_I8:
1154 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1155 case Mips::ATOMIC_LOAD_XOR_I16:
1156 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1157 case Mips::ATOMIC_LOAD_XOR_I32:
1158 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
1159 case Mips::ATOMIC_LOAD_XOR_I64:
1160 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
1162 case Mips::ATOMIC_LOAD_NAND_I8:
1163 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
1164 case Mips::ATOMIC_LOAD_NAND_I16:
1165 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
1166 case Mips::ATOMIC_LOAD_NAND_I32:
1167 return emitAtomicBinary(MI, BB, 4, 0, true);
1168 case Mips::ATOMIC_LOAD_NAND_I64:
1169 return emitAtomicBinary(MI, BB, 8, 0, true);
1171 case Mips::ATOMIC_LOAD_SUB_I8:
1172 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1173 case Mips::ATOMIC_LOAD_SUB_I16:
1174 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1175 case Mips::ATOMIC_LOAD_SUB_I32:
1176 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
1177 case Mips::ATOMIC_LOAD_SUB_I64:
1178 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1180 case Mips::ATOMIC_SWAP_I8:
1181 return emitAtomicBinaryPartword(MI, BB, 1, 0);
1182 case Mips::ATOMIC_SWAP_I16:
1183 return emitAtomicBinaryPartword(MI, BB, 2, 0);
1184 case Mips::ATOMIC_SWAP_I32:
1185 return emitAtomicBinary(MI, BB, 4, 0);
1186 case Mips::ATOMIC_SWAP_I64:
1187 return emitAtomicBinary(MI, BB, 8, 0);
1189 case Mips::ATOMIC_CMP_SWAP_I8:
1190 return emitAtomicCmpSwapPartword(MI, BB, 1);
1191 case Mips::ATOMIC_CMP_SWAP_I16:
1192 return emitAtomicCmpSwapPartword(MI, BB, 2);
1193 case Mips::ATOMIC_CMP_SWAP_I32:
1194 return emitAtomicCmpSwap(MI, BB, 4);
1195 case Mips::ATOMIC_CMP_SWAP_I64:
1196 return emitAtomicCmpSwap(MI, BB, 8);
1197 case Mips::PseudoSDIV:
1198 case Mips::PseudoUDIV:
1203 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false,
1205 case Mips::SDIV_MM_Pseudo:
1206 case Mips::UDIV_MM_Pseudo:
1209 case Mips::DIV_MMR6:
1210 case Mips::DIVU_MMR6:
1211 case Mips::MOD_MMR6:
1212 case Mips::MODU_MMR6:
1213 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false, true);
1214 case Mips::PseudoDSDIV:
1215 case Mips::PseudoDUDIV:
1220 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, false);
1221 case Mips::DDIV_MM64R6:
1222 case Mips::DDIVU_MM64R6:
1223 case Mips::DMOD_MM64R6:
1224 case Mips::DMODU_MM64R6:
1225 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true, true);
1227 case Mips::SEL_D_MMR6:
1228 return emitSEL_D(MI, BB);
1230 case Mips::PseudoSELECT_I:
1231 case Mips::PseudoSELECT_I64:
1232 case Mips::PseudoSELECT_S:
1233 case Mips::PseudoSELECT_D32:
1234 case Mips::PseudoSELECT_D64:
1235 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1236 case Mips::PseudoSELECTFP_F_I:
1237 case Mips::PseudoSELECTFP_F_I64:
1238 case Mips::PseudoSELECTFP_F_S:
1239 case Mips::PseudoSELECTFP_F_D32:
1240 case Mips::PseudoSELECTFP_F_D64:
1241 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1242 case Mips::PseudoSELECTFP_T_I:
1243 case Mips::PseudoSELECTFP_T_I64:
1244 case Mips::PseudoSELECTFP_T_S:
1245 case Mips::PseudoSELECTFP_T_D32:
1246 case Mips::PseudoSELECTFP_T_D64:
1247 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1251 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1252 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1253 MachineBasicBlock *MipsTargetLowering::emitAtomicBinary(MachineInstr &MI,
1254 MachineBasicBlock *BB,
1258 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1260 MachineFunction *MF = BB->getParent();
1261 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1262 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1263 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1264 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1265 DebugLoc DL = MI.getDebugLoc();
1266 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1273 LL = Subtarget.hasMips32r6()
1274 ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1275 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1276 SC = Subtarget.hasMips32r6()
1277 ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1278 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1286 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1287 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1290 ZERO = Mips::ZERO_64;
1294 unsigned OldVal = MI.getOperand(0).getReg();
1295 unsigned Ptr = MI.getOperand(1).getReg();
1296 unsigned Incr = MI.getOperand(2).getReg();
1298 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1299 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1300 unsigned Success = RegInfo.createVirtualRegister(RC);
1302 // insert new blocks after the current block
1303 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1304 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1305 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1306 MachineFunction::iterator It = ++BB->getIterator();
1307 MF->insert(It, loopMBB);
1308 MF->insert(It, exitMBB);
1310 // Transfer the remainder of BB and its successor edges to exitMBB.
1311 exitMBB->splice(exitMBB->begin(), BB,
1312 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1313 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1317 // fallthrough --> loopMBB
1318 BB->addSuccessor(loopMBB);
1319 loopMBB->addSuccessor(loopMBB);
1320 loopMBB->addSuccessor(exitMBB);
1323 // ll oldval, 0(ptr)
1324 // <binop> storeval, oldval, incr
1325 // sc success, storeval, 0(ptr)
1326 // beq success, $0, loopMBB
1328 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1330 // and andres, oldval, incr
1331 // nor storeval, $0, andres
1332 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1333 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1334 } else if (BinOpcode) {
1335 // <binop> storeval, oldval, incr
1336 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1340 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1341 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1343 MI.eraseFromParent(); // The instruction is gone now.
1348 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1349 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1350 unsigned SrcReg) const {
1351 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1352 const DebugLoc &DL = MI.getDebugLoc();
1354 if (Subtarget.hasMips32r2() && Size == 1) {
1355 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1359 if (Subtarget.hasMips32r2() && Size == 2) {
1360 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1364 MachineFunction *MF = BB->getParent();
1365 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1366 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1367 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1370 int64_t ShiftImm = 32 - (Size * 8);
1372 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1373 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1378 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1379 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1381 assert((Size == 1 || Size == 2) &&
1382 "Unsupported size for EmitAtomicBinaryPartial.");
1384 MachineFunction *MF = BB->getParent();
1385 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1386 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1387 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1388 const TargetRegisterClass *RCp =
1389 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1390 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1391 DebugLoc DL = MI.getDebugLoc();
1393 unsigned Dest = MI.getOperand(0).getReg();
1394 unsigned Ptr = MI.getOperand(1).getReg();
1395 unsigned Incr = MI.getOperand(2).getReg();
1397 unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1398 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1399 unsigned Mask = RegInfo.createVirtualRegister(RC);
1400 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1401 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1402 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1403 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1404 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1405 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1406 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1407 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1408 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1409 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1410 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1411 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1412 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1413 unsigned Success = RegInfo.createVirtualRegister(RC);
1420 LL = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1421 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1422 SC = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1423 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1426 // insert new blocks after the current block
1427 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1428 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1429 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1430 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1431 MachineFunction::iterator It = ++BB->getIterator();
1432 MF->insert(It, loopMBB);
1433 MF->insert(It, sinkMBB);
1434 MF->insert(It, exitMBB);
1436 // Transfer the remainder of BB and its successor edges to exitMBB.
1437 exitMBB->splice(exitMBB->begin(), BB,
1438 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1439 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1441 BB->addSuccessor(loopMBB);
1442 loopMBB->addSuccessor(loopMBB);
1443 loopMBB->addSuccessor(sinkMBB);
1444 sinkMBB->addSuccessor(exitMBB);
1447 // addiu masklsb2,$0,-4 # 0xfffffffc
1448 // and alignedaddr,ptr,masklsb2
1449 // andi ptrlsb2,ptr,3
1450 // sll shiftamt,ptrlsb2,3
1451 // ori maskupper,$0,255 # 0xff
1452 // sll mask,maskupper,shiftamt
1453 // nor mask2,$0,mask
1454 // sll incr2,incr,shiftamt
1456 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1457 BuildMI(BB, DL, TII->get(ABI.GetPtrAddiuOp()), MaskLSB2)
1458 .addReg(ABI.GetNullPtr()).addImm(-4);
1459 BuildMI(BB, DL, TII->get(ABI.GetPtrAndOp()), AlignedAddr)
1460 .addReg(Ptr).addReg(MaskLSB2);
1461 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1462 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1463 if (Subtarget.isLittle()) {
1464 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1466 unsigned Off = RegInfo.createVirtualRegister(RC);
1467 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1468 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1469 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1471 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1472 .addReg(Mips::ZERO).addImm(MaskImm);
1473 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1474 .addReg(MaskUpper).addReg(ShiftAmt);
1475 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1476 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1478 // atomic.load.binop
1480 // ll oldval,0(alignedaddr)
1481 // binop binopres,oldval,incr2
1482 // and newval,binopres,mask
1483 // and maskedoldval0,oldval,mask2
1484 // or storeval,maskedoldval0,newval
1485 // sc success,storeval,0(alignedaddr)
1486 // beq success,$0,loopMBB
1490 // ll oldval,0(alignedaddr)
1491 // and newval,incr2,mask
1492 // and maskedoldval0,oldval,mask2
1493 // or storeval,maskedoldval0,newval
1494 // sc success,storeval,0(alignedaddr)
1495 // beq success,$0,loopMBB
1498 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1500 // and andres, oldval, incr2
1501 // nor binopres, $0, andres
1502 // and newval, binopres, mask
1503 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1504 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1505 .addReg(Mips::ZERO).addReg(AndRes);
1506 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1507 } else if (BinOpcode) {
1508 // <binop> binopres, oldval, incr2
1509 // and newval, binopres, mask
1510 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1511 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1512 } else { // atomic.swap
1513 // and newval, incr2, mask
1514 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1517 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1518 .addReg(OldVal).addReg(Mask2);
1519 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1520 .addReg(MaskedOldVal0).addReg(NewVal);
1521 BuildMI(BB, DL, TII->get(SC), Success)
1522 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1523 BuildMI(BB, DL, TII->get(Mips::BEQ))
1524 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1527 // and maskedoldval1,oldval,mask
1528 // srl srlres,maskedoldval1,shiftamt
1529 // sign_extend dest,srlres
1532 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1533 .addReg(OldVal).addReg(Mask);
1534 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1535 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1536 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1538 MI.eraseFromParent(); // The instruction is gone now.
1543 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwap(MachineInstr &MI,
1544 MachineBasicBlock *BB,
1545 unsigned Size) const {
1546 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1548 MachineFunction *MF = BB->getParent();
1549 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1550 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1551 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1552 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1553 DebugLoc DL = MI.getDebugLoc();
1554 unsigned LL, SC, ZERO, BNE, BEQ;
1561 LL = Subtarget.hasMips32r6()
1562 ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1563 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1564 SC = Subtarget.hasMips32r6()
1565 ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1566 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1573 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1574 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1575 ZERO = Mips::ZERO_64;
1580 unsigned Dest = MI.getOperand(0).getReg();
1581 unsigned Ptr = MI.getOperand(1).getReg();
1582 unsigned OldVal = MI.getOperand(2).getReg();
1583 unsigned NewVal = MI.getOperand(3).getReg();
1585 unsigned Success = RegInfo.createVirtualRegister(RC);
1587 // insert new blocks after the current block
1588 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1589 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1590 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1591 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1592 MachineFunction::iterator It = ++BB->getIterator();
1593 MF->insert(It, loop1MBB);
1594 MF->insert(It, loop2MBB);
1595 MF->insert(It, exitMBB);
1597 // Transfer the remainder of BB and its successor edges to exitMBB.
1598 exitMBB->splice(exitMBB->begin(), BB,
1599 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1600 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1604 // fallthrough --> loop1MBB
1605 BB->addSuccessor(loop1MBB);
1606 loop1MBB->addSuccessor(exitMBB);
1607 loop1MBB->addSuccessor(loop2MBB);
1608 loop2MBB->addSuccessor(loop1MBB);
1609 loop2MBB->addSuccessor(exitMBB);
1613 // bne dest, oldval, exitMBB
1615 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1616 BuildMI(BB, DL, TII->get(BNE))
1617 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1620 // sc success, newval, 0(ptr)
1621 // beq success, $0, loop1MBB
1623 BuildMI(BB, DL, TII->get(SC), Success)
1624 .addReg(NewVal).addReg(Ptr).addImm(0);
1625 BuildMI(BB, DL, TII->get(BEQ))
1626 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1628 MI.eraseFromParent(); // The instruction is gone now.
1633 MachineBasicBlock *MipsTargetLowering::emitAtomicCmpSwapPartword(
1634 MachineInstr &MI, MachineBasicBlock *BB, unsigned Size) const {
1635 assert((Size == 1 || Size == 2) &&
1636 "Unsupported size for EmitAtomicCmpSwapPartial.");
1638 MachineFunction *MF = BB->getParent();
1639 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1640 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1641 const bool ArePtrs64bit = ABI.ArePtrs64bit();
1642 const TargetRegisterClass *RCp =
1643 getRegClassFor(ArePtrs64bit ? MVT::i64 : MVT::i32);
1644 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1645 DebugLoc DL = MI.getDebugLoc();
1647 unsigned Dest = MI.getOperand(0).getReg();
1648 unsigned Ptr = MI.getOperand(1).getReg();
1649 unsigned CmpVal = MI.getOperand(2).getReg();
1650 unsigned NewVal = MI.getOperand(3).getReg();
1652 unsigned AlignedAddr = RegInfo.createVirtualRegister(RCp);
1653 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1654 unsigned Mask = RegInfo.createVirtualRegister(RC);
1655 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1656 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1657 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1658 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1659 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1660 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RCp);
1661 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1662 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1663 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1664 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1665 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1666 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1667 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1668 unsigned Success = RegInfo.createVirtualRegister(RC);
1675 LL = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::LL64_R6 : Mips::LL_R6)
1676 : (ArePtrs64bit ? Mips::LL64 : Mips::LL);
1677 SC = Subtarget.hasMips32r6() ? (ArePtrs64bit ? Mips::SC64_R6 : Mips::SC_R6)
1678 : (ArePtrs64bit ? Mips::SC64 : Mips::SC);
1681 // insert new blocks after the current block
1682 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1683 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1684 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1685 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1686 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1687 MachineFunction::iterator It = ++BB->getIterator();
1688 MF->insert(It, loop1MBB);
1689 MF->insert(It, loop2MBB);
1690 MF->insert(It, sinkMBB);
1691 MF->insert(It, exitMBB);
1693 // Transfer the remainder of BB and its successor edges to exitMBB.
1694 exitMBB->splice(exitMBB->begin(), BB,
1695 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1696 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1698 BB->addSuccessor(loop1MBB);
1699 loop1MBB->addSuccessor(sinkMBB);
1700 loop1MBB->addSuccessor(loop2MBB);
1701 loop2MBB->addSuccessor(loop1MBB);
1702 loop2MBB->addSuccessor(sinkMBB);
1703 sinkMBB->addSuccessor(exitMBB);
1705 // FIXME: computation of newval2 can be moved to loop2MBB.
1707 // addiu masklsb2,$0,-4 # 0xfffffffc
1708 // and alignedaddr,ptr,masklsb2
1709 // andi ptrlsb2,ptr,3
1710 // xori ptrlsb2,ptrlsb2,3 # Only for BE
1711 // sll shiftamt,ptrlsb2,3
1712 // ori maskupper,$0,255 # 0xff
1713 // sll mask,maskupper,shiftamt
1714 // nor mask2,$0,mask
1715 // andi maskedcmpval,cmpval,255
1716 // sll shiftedcmpval,maskedcmpval,shiftamt
1717 // andi maskednewval,newval,255
1718 // sll shiftednewval,maskednewval,shiftamt
1719 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1720 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::DADDiu : Mips::ADDiu), MaskLSB2)
1721 .addReg(ABI.GetNullPtr()).addImm(-4);
1722 BuildMI(BB, DL, TII->get(ArePtrs64bit ? Mips::AND64 : Mips::AND), AlignedAddr)
1723 .addReg(Ptr).addReg(MaskLSB2);
1724 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2)
1725 .addReg(Ptr, 0, ArePtrs64bit ? Mips::sub_32 : 0).addImm(3);
1726 if (Subtarget.isLittle()) {
1727 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1729 unsigned Off = RegInfo.createVirtualRegister(RC);
1730 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1731 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1732 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1734 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1735 .addReg(Mips::ZERO).addImm(MaskImm);
1736 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1737 .addReg(MaskUpper).addReg(ShiftAmt);
1738 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1739 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1740 .addReg(CmpVal).addImm(MaskImm);
1741 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1742 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1743 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1744 .addReg(NewVal).addImm(MaskImm);
1745 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1746 .addReg(MaskedNewVal).addReg(ShiftAmt);
1749 // ll oldval,0(alginedaddr)
1750 // and maskedoldval0,oldval,mask
1751 // bne maskedoldval0,shiftedcmpval,sinkMBB
1753 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1754 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1755 .addReg(OldVal).addReg(Mask);
1756 BuildMI(BB, DL, TII->get(Mips::BNE))
1757 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1760 // and maskedoldval1,oldval,mask2
1761 // or storeval,maskedoldval1,shiftednewval
1762 // sc success,storeval,0(alignedaddr)
1763 // beq success,$0,loop1MBB
1765 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1766 .addReg(OldVal).addReg(Mask2);
1767 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1768 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1769 BuildMI(BB, DL, TII->get(SC), Success)
1770 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1771 BuildMI(BB, DL, TII->get(Mips::BEQ))
1772 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1775 // srl srlres,maskedoldval0,shiftamt
1776 // sign_extend dest,srlres
1779 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1780 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1781 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1783 MI.eraseFromParent(); // The instruction is gone now.
1788 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr &MI,
1789 MachineBasicBlock *BB) const {
1790 MachineFunction *MF = BB->getParent();
1791 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1792 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1793 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1794 DebugLoc DL = MI.getDebugLoc();
1795 MachineBasicBlock::iterator II(MI);
1797 unsigned Fc = MI.getOperand(1).getReg();
1798 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1800 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1802 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1805 .addImm(Mips::sub_lo);
1807 // We don't erase the original instruction, we just replace the condition
1808 // register with the 64-bit super-register.
1809 MI.getOperand(1).setReg(Fc2);
1814 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1815 // The first operand is the chain, the second is the condition, the third is
1816 // the block to branch to if the condition is true.
1817 SDValue Chain = Op.getOperand(0);
1818 SDValue Dest = Op.getOperand(2);
1821 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1822 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1824 // Return if flag is not set by a floating point comparison.
1825 if (CondRes.getOpcode() != MipsISD::FPCmp)
1828 SDValue CCNode = CondRes.getOperand(2);
1830 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1831 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1832 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
1833 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1834 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1835 FCC0, Dest, CondRes);
1838 SDValue MipsTargetLowering::
1839 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1841 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1842 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1844 // Return if flag is not set by a floating point comparison.
1845 if (Cond.getOpcode() != MipsISD::FPCmp)
1848 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1852 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1853 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1854 SDValue Cond = createFPCmp(DAG, Op);
1856 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1857 "Floating point operand expected.");
1860 SDValue True = DAG.getConstant(1, DL, MVT::i32);
1861 SDValue False = DAG.getConstant(0, DL, MVT::i32);
1863 return createCMovFP(DAG, Cond, True, False, DL);
1866 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1867 SelectionDAG &DAG) const {
1868 EVT Ty = Op.getValueType();
1869 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1870 const GlobalValue *GV = N->getGlobal();
1872 if (!isPositionIndependent()) {
1873 const MipsTargetObjectFile *TLOF =
1874 static_cast<const MipsTargetObjectFile *>(
1875 getTargetMachine().getObjFileLowering());
1876 const GlobalObject *GO = GV->getBaseObject();
1877 if (GO && TLOF->IsGlobalInSmallSection(GO, getTargetMachine()))
1878 // %gp_rel relocation
1879 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1881 // %hi/%lo relocation
1882 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
1883 // %highest/%higher/%hi/%lo relocation
1884 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
1887 // Every other architecture would use shouldAssumeDSOLocal in here, but
1889 // * In PIC code mips requires got loads even for local statics!
1890 // * To save on got entries, for local statics the got entry contains the
1891 // page and an additional add instruction takes care of the low bits.
1892 // * It is legal to access a hidden symbol with a non hidden undefined,
1893 // so one cannot guarantee that all access to a hidden symbol will know
1895 // * Mips linkers don't support creating a page and a full got entry for
1897 // * Given all that, we have to use a full got entry for hidden symbols :-(
1898 if (GV->hasLocalLinkage())
1899 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1902 return getAddrGlobalLargeGOT(
1903 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
1905 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1907 return getAddrGlobal(
1908 N, SDLoc(N), Ty, DAG,
1909 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT,
1910 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1913 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1914 SelectionDAG &DAG) const {
1915 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1916 EVT Ty = Op.getValueType();
1918 if (!isPositionIndependent())
1919 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
1920 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
1922 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1925 SDValue MipsTargetLowering::
1926 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1928 // If the relocation model is PIC, use the General Dynamic TLS Model or
1929 // Local Dynamic TLS model, otherwise use the Initial Exec or
1930 // Local Exec TLS Model.
1932 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1933 if (DAG.getTarget().Options.EmulatedTLS)
1934 return LowerToTLSEmulatedModel(GA, DAG);
1937 const GlobalValue *GV = GA->getGlobal();
1938 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1940 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1942 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1943 // General Dynamic and Local Dynamic TLS Model.
1944 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1947 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1948 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1949 getGlobalReg(DAG, PtrVT), TGA);
1950 unsigned PtrSize = PtrVT.getSizeInBits();
1951 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1953 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1957 Entry.Node = Argument;
1959 Args.push_back(Entry);
1961 TargetLowering::CallLoweringInfo CLI(DAG);
1963 .setChain(DAG.getEntryNode())
1964 .setLibCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args));
1965 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1967 SDValue Ret = CallResult.first;
1969 if (model != TLSModel::LocalDynamic)
1972 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1973 MipsII::MO_DTPREL_HI);
1974 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1975 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1976 MipsII::MO_DTPREL_LO);
1977 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1978 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1979 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1983 if (model == TLSModel::InitialExec) {
1984 // Initial Exec TLS Model
1985 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1986 MipsII::MO_GOTTPREL);
1987 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1990 DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), TGA, MachinePointerInfo());
1992 // Local Exec TLS Model
1993 assert(model == TLSModel::LocalExec);
1994 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1995 MipsII::MO_TPREL_HI);
1996 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1997 MipsII::MO_TPREL_LO);
1998 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1999 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2000 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2003 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2004 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2007 SDValue MipsTargetLowering::
2008 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2010 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
2011 EVT Ty = Op.getValueType();
2013 if (!isPositionIndependent())
2014 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2015 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2017 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2020 SDValue MipsTargetLowering::
2021 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2023 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
2024 EVT Ty = Op.getValueType();
2026 if (!isPositionIndependent()) {
2027 const MipsTargetObjectFile *TLOF =
2028 static_cast<const MipsTargetObjectFile *>(
2029 getTargetMachine().getObjFileLowering());
2031 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
2032 getTargetMachine()))
2033 // %gp_rel relocation
2034 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
2036 return Subtarget.hasSym32() ? getAddrNonPIC(N, SDLoc(N), Ty, DAG)
2037 : getAddrNonPICSym64(N, SDLoc(N), Ty, DAG);
2040 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
2043 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2044 MachineFunction &MF = DAG.getMachineFunction();
2045 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2048 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2049 getPointerTy(MF.getDataLayout()));
2051 // vastart just stores the address of the VarArgsFrameIndex slot into the
2052 // memory location argument.
2053 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2054 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2055 MachinePointerInfo(SV));
2058 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
2059 SDNode *Node = Op.getNode();
2060 EVT VT = Node->getValueType(0);
2061 SDValue Chain = Node->getOperand(0);
2062 SDValue VAListPtr = Node->getOperand(1);
2063 unsigned Align = Node->getConstantOperandVal(3);
2064 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
2066 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
2068 SDValue VAListLoad = DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain,
2069 VAListPtr, MachinePointerInfo(SV));
2070 SDValue VAList = VAListLoad;
2072 // Re-align the pointer if necessary.
2073 // It should only ever be necessary for 64-bit types on O32 since the minimum
2074 // argument alignment is the same as the maximum type alignment for N32/N64.
2076 // FIXME: We currently align too often. The code generator doesn't notice
2077 // when the pointer is still aligned from the last va_arg (or pair of
2078 // va_args for the i64 on O32 case).
2079 if (Align > getMinStackArgumentAlignment()) {
2080 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
2082 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2083 DAG.getConstant(Align - 1, DL, VAList.getValueType()));
2085 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
2086 DAG.getConstant(-(int64_t)Align, DL,
2087 VAList.getValueType()));
2090 // Increment the pointer, VAList, to the next vaarg.
2091 auto &TD = DAG.getDataLayout();
2092 unsigned ArgSizeInBytes =
2093 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
2095 DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
2096 DAG.getConstant(alignTo(ArgSizeInBytes, ArgSlotSizeInBytes),
2097 DL, VAList.getValueType()));
2098 // Store the incremented VAList to the legalized pointer
2099 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
2100 MachinePointerInfo(SV));
2102 // In big-endian mode we must adjust the pointer when the load size is smaller
2103 // than the argument slot size. We must also reduce the known alignment to
2104 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
2105 // the correct half of the slot, and reduce the alignment from 8 (slot
2106 // alignment) down to 4 (type alignment).
2107 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
2108 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
2109 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
2110 DAG.getIntPtrConstant(Adjustment, DL));
2112 // Load the actual argument out of the pointer VAList
2113 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo());
2116 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
2117 bool HasExtractInsert) {
2118 EVT TyX = Op.getOperand(0).getValueType();
2119 EVT TyY = Op.getOperand(1).getValueType();
2121 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2122 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
2125 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2127 SDValue X = (TyX == MVT::f32) ?
2128 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2129 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2131 SDValue Y = (TyY == MVT::f32) ?
2132 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2133 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2136 if (HasExtractInsert) {
2137 // ext E, Y, 31, 1 ; extract bit31 of Y
2138 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2139 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2140 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2143 // srl SrlX, SllX, 1
2145 // sll SllY, SrlX, 31
2146 // or Or, SrlX, SllY
2147 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2148 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2149 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2150 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2151 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2154 if (TyX == MVT::f32)
2155 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2157 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2159 DAG.getConstant(0, DL, MVT::i32));
2160 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2163 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
2164 bool HasExtractInsert) {
2165 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2166 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2167 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2169 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
2171 // Bitcast to integer nodes.
2172 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2173 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2175 if (HasExtractInsert) {
2176 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2177 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2178 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2179 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
2181 if (WidthX > WidthY)
2182 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2183 else if (WidthY > WidthX)
2184 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2186 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2187 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
2189 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2192 // (d)sll SllX, X, 1
2193 // (d)srl SrlX, SllX, 1
2194 // (d)srl SrlY, Y, width(Y)-1
2195 // (d)sll SllY, SrlX, width(Y)-1
2196 // or Or, SrlX, SllY
2197 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2198 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2199 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2200 DAG.getConstant(WidthY - 1, DL, MVT::i32));
2202 if (WidthX > WidthY)
2203 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2204 else if (WidthY > WidthX)
2205 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2207 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2208 DAG.getConstant(WidthX - 1, DL, MVT::i32));
2209 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2210 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2214 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2215 if (Subtarget.isGP64bit())
2216 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2218 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2221 SDValue MipsTargetLowering::
2222 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2224 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2225 "Frame address can only be determined for current frame.");
2227 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2228 MFI.setFrameAddressIsTaken(true);
2229 EVT VT = Op.getValueType();
2231 SDValue FrameAddr = DAG.getCopyFromReg(
2232 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2236 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2237 SelectionDAG &DAG) const {
2238 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2242 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2243 "Return address can be determined only for current frame.");
2245 MachineFunction &MF = DAG.getMachineFunction();
2246 MachineFrameInfo &MFI = MF.getFrameInfo();
2247 MVT VT = Op.getSimpleValueType();
2248 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2249 MFI.setReturnAddressIsTaken(true);
2251 // Return RA, which contains the return address. Mark it an implicit live-in.
2252 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2253 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2256 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2257 // generated from __builtin_eh_return (offset, handler)
2258 // The effect of this is to adjust the stack pointer by "offset"
2259 // and then branch to "handler".
2260 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2262 MachineFunction &MF = DAG.getMachineFunction();
2263 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2265 MipsFI->setCallsEhReturn();
2266 SDValue Chain = Op.getOperand(0);
2267 SDValue Offset = Op.getOperand(1);
2268 SDValue Handler = Op.getOperand(2);
2270 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2272 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2273 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2274 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2275 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2276 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2277 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2278 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2279 DAG.getRegister(OffsetReg, Ty),
2280 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2284 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2285 SelectionDAG &DAG) const {
2286 // FIXME: Need pseudo-fence for 'singlethread' fences
2287 // FIXME: Set SType for weaker fences where supported/appropriate.
2290 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2291 DAG.getConstant(SType, DL, MVT::i32));
2294 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2295 SelectionDAG &DAG) const {
2297 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2299 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2300 SDValue Shamt = Op.getOperand(2);
2301 // if shamt < (VT.bits):
2302 // lo = (shl lo, shamt)
2303 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2306 // hi = (shl lo, shamt[4:0])
2307 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2308 DAG.getConstant(-1, DL, MVT::i32));
2309 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2310 DAG.getConstant(1, DL, VT));
2311 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2312 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2313 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2314 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2315 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2316 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2317 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2318 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2319 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2321 SDValue Ops[2] = {Lo, Hi};
2322 return DAG.getMergeValues(Ops, DL);
2325 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2328 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2329 SDValue Shamt = Op.getOperand(2);
2330 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2332 // if shamt < (VT.bits):
2333 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2335 // hi = (sra hi, shamt)
2337 // hi = (srl hi, shamt)
2340 // lo = (sra hi, shamt[4:0])
2341 // hi = (sra hi, 31)
2343 // lo = (srl hi, shamt[4:0])
2345 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2346 DAG.getConstant(-1, DL, MVT::i32));
2347 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2348 DAG.getConstant(1, DL, VT));
2349 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2350 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2351 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2352 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2354 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2355 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2356 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2357 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2358 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2359 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2360 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2362 SDValue Ops[2] = {Lo, Hi};
2363 return DAG.getMergeValues(Ops, DL);
2366 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2367 SDValue Chain, SDValue Src, unsigned Offset) {
2368 SDValue Ptr = LD->getBasePtr();
2369 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2370 EVT BasePtrVT = Ptr.getValueType();
2372 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2375 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2376 DAG.getConstant(Offset, DL, BasePtrVT));
2378 SDValue Ops[] = { Chain, Ptr, Src };
2379 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2380 LD->getMemOperand());
2383 // Expand an unaligned 32 or 64-bit integer load node.
2384 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2385 LoadSDNode *LD = cast<LoadSDNode>(Op);
2386 EVT MemVT = LD->getMemoryVT();
2388 if (Subtarget.systemSupportsUnalignedAccess())
2391 // Return if load is aligned or if MemVT is neither i32 nor i64.
2392 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2393 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2396 bool IsLittle = Subtarget.isLittle();
2397 EVT VT = Op.getValueType();
2398 ISD::LoadExtType ExtType = LD->getExtensionType();
2399 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2401 assert((VT == MVT::i32) || (VT == MVT::i64));
2404 // (set dst, (i64 (load baseptr)))
2406 // (set tmp, (ldl (add baseptr, 7), undef))
2407 // (set dst, (ldr baseptr, tmp))
2408 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2409 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2411 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2415 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2417 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2421 // (set dst, (i32 (load baseptr))) or
2422 // (set dst, (i64 (sextload baseptr))) or
2423 // (set dst, (i64 (extload baseptr)))
2425 // (set tmp, (lwl (add baseptr, 3), undef))
2426 // (set dst, (lwr baseptr, tmp))
2427 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2428 (ExtType == ISD::EXTLOAD))
2431 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2434 // (set dst, (i64 (zextload baseptr)))
2436 // (set tmp0, (lwl (add baseptr, 3), undef))
2437 // (set tmp1, (lwr baseptr, tmp0))
2438 // (set tmp2, (shl tmp1, 32))
2439 // (set dst, (srl tmp2, 32))
2441 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2442 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2443 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2444 SDValue Ops[] = { SRL, LWR.getValue(1) };
2445 return DAG.getMergeValues(Ops, DL);
2448 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2449 SDValue Chain, unsigned Offset) {
2450 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2451 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2453 SDVTList VTList = DAG.getVTList(MVT::Other);
2456 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2457 DAG.getConstant(Offset, DL, BasePtrVT));
2459 SDValue Ops[] = { Chain, Value, Ptr };
2460 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2461 SD->getMemOperand());
2464 // Expand an unaligned 32 or 64-bit integer store node.
2465 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2467 SDValue Value = SD->getValue(), Chain = SD->getChain();
2468 EVT VT = Value.getValueType();
2471 // (store val, baseptr) or
2472 // (truncstore val, baseptr)
2474 // (swl val, (add baseptr, 3))
2475 // (swr val, baseptr)
2476 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2477 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2479 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2482 assert(VT == MVT::i64);
2485 // (store val, baseptr)
2487 // (sdl val, (add baseptr, 7))
2488 // (sdr val, baseptr)
2489 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2490 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2493 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2494 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2495 SDValue Val = SD->getValue();
2497 if (Val.getOpcode() != ISD::FP_TO_SINT)
2500 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2501 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2503 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2504 SD->getPointerInfo(), SD->getAlignment(),
2505 SD->getMemOperand()->getFlags());
2508 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2509 StoreSDNode *SD = cast<StoreSDNode>(Op);
2510 EVT MemVT = SD->getMemoryVT();
2512 // Lower unaligned integer stores.
2513 if (!Subtarget.systemSupportsUnalignedAccess() &&
2514 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2515 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2516 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2518 return lowerFP_TO_SINT_STORE(SD, DAG);
2521 SDValue MipsTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
2522 SelectionDAG &DAG) const {
2524 // Return a fixed StackObject with offset 0 which points to the old stack
2526 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2527 EVT ValTy = Op->getValueType(0);
2528 int FI = MFI.CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2529 return DAG.getFrameIndex(FI, ValTy);
2532 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2533 SelectionDAG &DAG) const {
2534 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2535 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2537 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2540 //===----------------------------------------------------------------------===//
2541 // Calling Convention Implementation
2542 //===----------------------------------------------------------------------===//
2544 //===----------------------------------------------------------------------===//
2545 // TODO: Implement a generic logic using tblgen that can support this.
2546 // Mips O32 ABI rules:
2548 // i32 - Passed in A0, A1, A2, A3 and stack
2549 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2550 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2551 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2552 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2553 // not used, it must be shadowed. If only A3 is available, shadow it and
2556 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2557 //===----------------------------------------------------------------------===//
2559 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2560 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2561 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2562 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2563 State.getMachineFunction().getSubtarget());
2565 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2566 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2568 // Do not process byval args here.
2569 if (ArgFlags.isByVal())
2572 // Promote i8 and i16
2573 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2574 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2576 if (ArgFlags.isSExt())
2577 LocInfo = CCValAssign::SExtUpper;
2578 else if (ArgFlags.isZExt())
2579 LocInfo = CCValAssign::ZExtUpper;
2581 LocInfo = CCValAssign::AExtUpper;
2585 // Promote i8 and i16
2586 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2588 if (ArgFlags.isSExt())
2589 LocInfo = CCValAssign::SExt;
2590 else if (ArgFlags.isZExt())
2591 LocInfo = CCValAssign::ZExt;
2593 LocInfo = CCValAssign::AExt;
2598 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2599 // is true: function is vararg, argument is 3rd or higher, there is previous
2600 // argument which is not f32 or f64.
2601 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2602 State.getFirstUnallocated(F32Regs) != ValNo;
2603 unsigned OrigAlign = ArgFlags.getOrigAlign();
2604 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2606 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2607 Reg = State.AllocateReg(IntRegs);
2608 // If this is the first part of an i64 arg,
2609 // the allocated register must be either A0 or A2.
2610 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2611 Reg = State.AllocateReg(IntRegs);
2613 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2614 // Allocate int register and shadow next int register. If first
2615 // available register is Mips::A1 or Mips::A3, shadow it too.
2616 Reg = State.AllocateReg(IntRegs);
2617 if (Reg == Mips::A1 || Reg == Mips::A3)
2618 Reg = State.AllocateReg(IntRegs);
2619 State.AllocateReg(IntRegs);
2621 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2622 // we are guaranteed to find an available float register
2623 if (ValVT == MVT::f32) {
2624 Reg = State.AllocateReg(F32Regs);
2625 // Shadow int register
2626 State.AllocateReg(IntRegs);
2628 Reg = State.AllocateReg(F64Regs);
2629 // Shadow int registers
2630 unsigned Reg2 = State.AllocateReg(IntRegs);
2631 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2632 State.AllocateReg(IntRegs);
2633 State.AllocateReg(IntRegs);
2636 llvm_unreachable("Cannot handle this ValVT.");
2639 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2641 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2643 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2648 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2649 MVT LocVT, CCValAssign::LocInfo LocInfo,
2650 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2651 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2653 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2656 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2657 MVT LocVT, CCValAssign::LocInfo LocInfo,
2658 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2659 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2661 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2664 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2665 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2666 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2668 #include "MipsGenCallingConv.inc"
2670 //===----------------------------------------------------------------------===//
2671 // Call Calling Convention Implementation
2672 //===----------------------------------------------------------------------===//
2674 // Return next O32 integer argument register.
2675 static unsigned getNextIntArgReg(unsigned Reg) {
2676 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2677 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2680 SDValue MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2681 SDValue Chain, SDValue Arg,
2682 const SDLoc &DL, bool IsTailCall,
2683 SelectionDAG &DAG) const {
2686 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2687 DAG.getIntPtrConstant(Offset, DL));
2688 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo());
2691 MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
2692 int FI = MFI.CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2693 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2694 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2695 /* Alignment = */ 0, MachineMemOperand::MOVolatile);
2698 void MipsTargetLowering::
2699 getOpndList(SmallVectorImpl<SDValue> &Ops,
2700 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2701 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2702 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2703 SDValue Chain) const {
2704 // Insert node "GP copy globalreg" before call to function.
2706 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2707 // in PIC mode) allow symbols to be resolved via lazy binding.
2708 // The lazy binding stub requires GP to point to the GOT.
2709 // Note that we don't need GP to point to the GOT for indirect calls
2710 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2711 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2712 // used for the function (that is, Mips linker doesn't generate lazy binding
2713 // stub for a function whose address is taken in the program).
2714 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2715 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2716 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2717 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2720 // Build a sequence of copy-to-reg nodes chained together with token
2721 // chain and flag operands which copy the outgoing args into registers.
2722 // The InFlag in necessary since all emitted instructions must be
2726 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2727 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2728 RegsToPass[i].second, InFlag);
2729 InFlag = Chain.getValue(1);
2732 // Add argument registers to the end of the list so that they are
2733 // known live into the call.
2734 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2735 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2736 RegsToPass[i].second.getValueType()));
2738 // Add a register mask operand representing the call-preserved registers.
2739 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2740 const uint32_t *Mask =
2741 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2742 assert(Mask && "Missing call preserved mask for calling convention");
2743 if (Subtarget.inMips16HardFloat()) {
2744 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2745 llvm::StringRef Sym = G->getGlobal()->getName();
2746 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2747 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2748 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2752 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2754 if (InFlag.getNode())
2755 Ops.push_back(InFlag);
2758 /// LowerCall - functions arguments are copied from virtual regs to
2759 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2761 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2762 SmallVectorImpl<SDValue> &InVals) const {
2763 SelectionDAG &DAG = CLI.DAG;
2765 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2766 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2767 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2768 SDValue Chain = CLI.Chain;
2769 SDValue Callee = CLI.Callee;
2770 bool &IsTailCall = CLI.IsTailCall;
2771 CallingConv::ID CallConv = CLI.CallConv;
2772 bool IsVarArg = CLI.IsVarArg;
2774 MachineFunction &MF = DAG.getMachineFunction();
2775 MachineFrameInfo &MFI = MF.getFrameInfo();
2776 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2777 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2778 bool IsPIC = isPositionIndependent();
2780 // Analyze operands of the call, assigning locations to each operand.
2781 SmallVector<CCValAssign, 16> ArgLocs;
2783 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2784 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2786 // Allocate the reserved argument area. It seems strange to do this from the
2787 // caller side but removing it breaks the frame size calculation.
2788 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2790 const ExternalSymbolSDNode *ES =
2791 dyn_cast_or_null<const ExternalSymbolSDNode>(Callee.getNode());
2792 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(),
2793 ES ? ES->getSymbol() : nullptr);
2795 // Get a count of how many bytes are to be pushed on the stack.
2796 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2798 // Check if it's really possible to do a tail call. Restrict it to functions
2799 // that are part of this compilation unit.
2800 bool InternalLinkage = false;
2802 IsTailCall = isEligibleForTailCallOptimization(
2803 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2804 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2805 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2806 IsTailCall &= (InternalLinkage || G->getGlobal()->hasLocalLinkage() ||
2807 G->getGlobal()->hasPrivateLinkage() ||
2808 G->getGlobal()->hasHiddenVisibility() ||
2809 G->getGlobal()->hasProtectedVisibility());
2812 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2813 report_fatal_error("failed to perform tail call elimination on a call "
2814 "site marked musttail");
2819 // Chain is the output chain of the last Load/Store or CopyToReg node.
2820 // ByValChain is the output chain of the last Memcpy node created for copying
2821 // byval arguments to the stack.
2822 unsigned StackAlignment = TFL->getStackAlignment();
2823 NextStackOffset = alignTo(NextStackOffset, StackAlignment);
2824 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
2827 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffset, 0, DL);
2830 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
2831 getPointerTy(DAG.getDataLayout()));
2833 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2834 SmallVector<SDValue, 8> MemOpChains;
2836 CCInfo.rewindByValRegsInfo();
2838 // Walk the register/memloc assignments, inserting copies/loads.
2839 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2840 SDValue Arg = OutVals[i];
2841 CCValAssign &VA = ArgLocs[i];
2842 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2843 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2844 bool UseUpperBits = false;
2847 if (Flags.isByVal()) {
2848 unsigned FirstByValReg, LastByValReg;
2849 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2850 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2852 assert(Flags.getByValSize() &&
2853 "ByVal args of size 0 should have been ignored by front-end.");
2854 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2855 assert(!IsTailCall &&
2856 "Do not tail-call optimize if there is a byval argument.");
2857 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2858 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2860 CCInfo.nextInRegsParam();
2864 // Promote the value if needed.
2865 switch (VA.getLocInfo()) {
2867 llvm_unreachable("Unknown loc info!");
2868 case CCValAssign::Full:
2869 if (VA.isRegLoc()) {
2870 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2871 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2872 (ValVT == MVT::i64 && LocVT == MVT::f64))
2873 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2874 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2875 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2876 Arg, DAG.getConstant(0, DL, MVT::i32));
2877 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2878 Arg, DAG.getConstant(1, DL, MVT::i32));
2879 if (!Subtarget.isLittle())
2881 unsigned LocRegLo = VA.getLocReg();
2882 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2883 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2884 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2889 case CCValAssign::BCvt:
2890 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2892 case CCValAssign::SExtUpper:
2893 UseUpperBits = true;
2895 case CCValAssign::SExt:
2896 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2898 case CCValAssign::ZExtUpper:
2899 UseUpperBits = true;
2901 case CCValAssign::ZExt:
2902 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2904 case CCValAssign::AExtUpper:
2905 UseUpperBits = true;
2907 case CCValAssign::AExt:
2908 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2913 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2914 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2916 ISD::SHL, DL, VA.getLocVT(), Arg,
2917 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2920 // Arguments that can be passed on register must be kept at
2921 // RegsToPass vector
2922 if (VA.isRegLoc()) {
2923 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2927 // Register can't get to this point...
2928 assert(VA.isMemLoc());
2930 // emit ISD::STORE whichs stores the
2931 // parameter value to a stack Location
2932 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2933 Chain, Arg, DL, IsTailCall, DAG));
2936 // Transform all store nodes into one single node because all store
2937 // nodes are independent of each other.
2938 if (!MemOpChains.empty())
2939 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2941 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2942 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2943 // node so that legalize doesn't hack it.
2946 EVT Ty = Callee.getValueType();
2947 bool GlobalOrExternal = false, IsCallReloc = false;
2949 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2951 const GlobalValue *Val = G->getGlobal();
2952 InternalLinkage = Val->hasInternalLinkage();
2954 if (InternalLinkage)
2955 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
2956 else if (LargeGOT) {
2957 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2958 MipsII::MO_CALL_LO16, Chain,
2959 FuncInfo->callPtrInfo(Val));
2962 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2963 FuncInfo->callPtrInfo(Val));
2967 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
2968 getPointerTy(DAG.getDataLayout()), 0,
2969 MipsII::MO_NO_FLAG);
2970 GlobalOrExternal = true;
2972 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2973 const char *Sym = S->getSymbol();
2975 if (!IsPIC) // static
2976 Callee = DAG.getTargetExternalSymbol(
2977 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
2978 else if (LargeGOT) {
2979 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2980 MipsII::MO_CALL_LO16, Chain,
2981 FuncInfo->callPtrInfo(Sym));
2984 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2985 FuncInfo->callPtrInfo(Sym));
2989 GlobalOrExternal = true;
2992 SmallVector<SDValue, 8> Ops(1, Chain);
2993 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2995 getOpndList(Ops, RegsToPass, IsPIC, GlobalOrExternal, InternalLinkage,
2996 IsCallReloc, CLI, Callee, Chain);
2999 MF.getFrameInfo().setHasTailCall();
3000 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
3003 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
3004 SDValue InFlag = Chain.getValue(1);
3006 // Create the CALLSEQ_END node.
3007 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3008 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
3009 InFlag = Chain.getValue(1);
3011 // Handle result values, copying them out of physregs into vregs that we
3013 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
3017 /// LowerCallResult - Lower the result values of a call into the
3018 /// appropriate copies out of appropriate physical registers.
3019 SDValue MipsTargetLowering::LowerCallResult(
3020 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
3021 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3022 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals,
3023 TargetLowering::CallLoweringInfo &CLI) const {
3024 // Assign locations to each value returned by this call.
3025 SmallVector<CCValAssign, 16> RVLocs;
3026 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
3029 const ExternalSymbolSDNode *ES =
3030 dyn_cast_or_null<const ExternalSymbolSDNode>(CLI.Callee.getNode());
3031 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI.RetTy,
3032 ES ? ES->getSymbol() : nullptr);
3034 // Copy all of the result registers out of their specified physreg.
3035 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3036 CCValAssign &VA = RVLocs[i];
3037 assert(VA.isRegLoc() && "Can only return in registers!");
3039 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3040 RVLocs[i].getLocVT(), InFlag);
3041 Chain = Val.getValue(1);
3042 InFlag = Val.getValue(2);
3044 if (VA.isUpperBitsInLoc()) {
3045 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
3046 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3048 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3050 Shift, DL, VA.getLocVT(), Val,
3051 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3054 switch (VA.getLocInfo()) {
3056 llvm_unreachable("Unknown loc info!");
3057 case CCValAssign::Full:
3059 case CCValAssign::BCvt:
3060 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
3062 case CCValAssign::AExt:
3063 case CCValAssign::AExtUpper:
3064 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3066 case CCValAssign::ZExt:
3067 case CCValAssign::ZExtUpper:
3068 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
3069 DAG.getValueType(VA.getValVT()));
3070 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3072 case CCValAssign::SExt:
3073 case CCValAssign::SExtUpper:
3074 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
3075 DAG.getValueType(VA.getValVT()));
3076 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
3080 InVals.push_back(Val);
3086 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
3087 EVT ArgVT, const SDLoc &DL,
3088 SelectionDAG &DAG) {
3089 MVT LocVT = VA.getLocVT();
3090 EVT ValVT = VA.getValVT();
3092 // Shift into the upper bits if necessary.
3093 switch (VA.getLocInfo()) {
3096 case CCValAssign::AExtUpper:
3097 case CCValAssign::SExtUpper:
3098 case CCValAssign::ZExtUpper: {
3099 unsigned ValSizeInBits = ArgVT.getSizeInBits();
3100 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3102 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
3104 Opcode, DL, VA.getLocVT(), Val,
3105 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3110 // If this is an value smaller than the argument slot size (32-bit for O32,
3111 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
3112 // size. Extract the value and insert any appropriate assertions regarding
3113 // sign/zero extension.
3114 switch (VA.getLocInfo()) {
3116 llvm_unreachable("Unknown loc info!");
3117 case CCValAssign::Full:
3119 case CCValAssign::AExtUpper:
3120 case CCValAssign::AExt:
3121 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3123 case CCValAssign::SExtUpper:
3124 case CCValAssign::SExt:
3125 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
3126 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3128 case CCValAssign::ZExtUpper:
3129 case CCValAssign::ZExt:
3130 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
3131 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
3133 case CCValAssign::BCvt:
3134 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
3141 //===----------------------------------------------------------------------===//
3142 // Formal Arguments Calling Convention Implementation
3143 //===----------------------------------------------------------------------===//
3144 /// LowerFormalArguments - transform physical registers into virtual registers
3145 /// and generate load operations for arguments places on the stack.
3146 SDValue MipsTargetLowering::LowerFormalArguments(
3147 SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
3148 const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
3149 SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
3150 MachineFunction &MF = DAG.getMachineFunction();
3151 MachineFrameInfo &MFI = MF.getFrameInfo();
3152 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3154 MipsFI->setVarArgsFrameIndex(0);
3156 // Used with vargs to acumulate store chains.
3157 std::vector<SDValue> OutChains;
3159 // Assign locations to all of the incoming arguments.
3160 SmallVector<CCValAssign, 16> ArgLocs;
3161 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
3163 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
3164 const Function *Func = DAG.getMachineFunction().getFunction();
3165 Function::const_arg_iterator FuncArg = Func->arg_begin();
3167 if (Func->hasFnAttribute("interrupt") && !Func->arg_empty())
3169 "Functions with the interrupt attribute cannot have arguments!");
3171 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
3172 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3173 CCInfo.getInRegsParamsCount() > 0);
3175 unsigned CurArgIdx = 0;
3176 CCInfo.rewindByValRegsInfo();
3178 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3179 CCValAssign &VA = ArgLocs[i];
3180 if (Ins[i].isOrigArg()) {
3181 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
3182 CurArgIdx = Ins[i].getOrigArgIndex();
3184 EVT ValVT = VA.getValVT();
3185 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3186 bool IsRegLoc = VA.isRegLoc();
3188 if (Flags.isByVal()) {
3189 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
3190 unsigned FirstByValReg, LastByValReg;
3191 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
3192 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
3194 assert(Flags.getByValSize() &&
3195 "ByVal args of size 0 should have been ignored by front-end.");
3196 assert(ByValIdx < CCInfo.getInRegsParamsCount());
3197 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3198 FirstByValReg, LastByValReg, VA, CCInfo);
3199 CCInfo.nextInRegsParam();
3203 // Arguments stored on registers
3205 MVT RegVT = VA.getLocVT();
3206 unsigned ArgReg = VA.getLocReg();
3207 const TargetRegisterClass *RC = getRegClassFor(RegVT);
3209 // Transform the arguments stored on
3210 // physical registers into virtual ones
3211 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3212 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3214 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3216 // Handle floating point arguments passed in integer registers and
3217 // long double arguments passed in floating point registers.
3218 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3219 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3220 (RegVT == MVT::f64 && ValVT == MVT::i64))
3221 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3222 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3223 ValVT == MVT::f64) {
3224 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3225 getNextIntArgReg(ArgReg), RC);
3226 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3227 if (!Subtarget.isLittle())
3228 std::swap(ArgValue, ArgValue2);
3229 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3230 ArgValue, ArgValue2);
3233 InVals.push_back(ArgValue);
3234 } else { // VA.isRegLoc()
3235 MVT LocVT = VA.getLocVT();
3238 // We ought to be able to use LocVT directly but O32 sets it to i32
3239 // when allocating floating point values to integer registers.
3240 // This shouldn't influence how we load the value into registers unless
3241 // we are targeting softfloat.
3242 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3243 LocVT = VA.getValVT();
3247 assert(VA.isMemLoc());
3249 // The stack pointer offset is relative to the caller stack frame.
3250 int FI = MFI.CreateFixedObject(LocVT.getSizeInBits() / 8,
3251 VA.getLocMemOffset(), true);
3253 // Create load nodes to retrieve arguments from the stack
3254 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3255 SDValue ArgValue = DAG.getLoad(
3256 LocVT, DL, Chain, FIN,
3257 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI));
3258 OutChains.push_back(ArgValue.getValue(1));
3260 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3262 InVals.push_back(ArgValue);
3266 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3267 // The mips ABIs for returning structs by value requires that we copy
3268 // the sret argument into $v0 for the return. Save the argument into
3269 // a virtual register so that we can access it from the return points.
3270 if (Ins[i].Flags.isSRet()) {
3271 unsigned Reg = MipsFI->getSRetReturnReg();
3273 Reg = MF.getRegInfo().createVirtualRegister(
3274 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3275 MipsFI->setSRetReturnReg(Reg);
3277 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3278 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3284 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3286 // All stores are grouped in one node to allow the matching between
3287 // the size of Ins and InVals. This only happens when on varg functions
3288 if (!OutChains.empty()) {
3289 OutChains.push_back(Chain);
3290 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3296 //===----------------------------------------------------------------------===//
3297 // Return Value Calling Convention Implementation
3298 //===----------------------------------------------------------------------===//
3301 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3302 MachineFunction &MF, bool IsVarArg,
3303 const SmallVectorImpl<ISD::OutputArg> &Outs,
3304 LLVMContext &Context) const {
3305 SmallVector<CCValAssign, 16> RVLocs;
3306 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3307 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3311 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3312 if (Subtarget.hasMips3() && Subtarget.useSoftFloat()) {
3313 if (Type == MVT::i32)
3320 MipsTargetLowering::LowerInterruptReturn(SmallVectorImpl<SDValue> &RetOps,
3322 SelectionDAG &DAG) const {
3324 MachineFunction &MF = DAG.getMachineFunction();
3325 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3329 return DAG.getNode(MipsISD::ERet, DL, MVT::Other, RetOps);
3333 MipsTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
3335 const SmallVectorImpl<ISD::OutputArg> &Outs,
3336 const SmallVectorImpl<SDValue> &OutVals,
3337 const SDLoc &DL, SelectionDAG &DAG) const {
3338 // CCValAssign - represent the assignment of
3339 // the return value to a location
3340 SmallVector<CCValAssign, 16> RVLocs;
3341 MachineFunction &MF = DAG.getMachineFunction();
3343 // CCState - Info about the registers and stack slot.
3344 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3346 // Analyze return values.
3347 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3350 SmallVector<SDValue, 4> RetOps(1, Chain);
3352 // Copy the result values into the output registers.
3353 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3354 SDValue Val = OutVals[i];
3355 CCValAssign &VA = RVLocs[i];
3356 assert(VA.isRegLoc() && "Can only return in registers!");
3357 bool UseUpperBits = false;
3359 switch (VA.getLocInfo()) {
3361 llvm_unreachable("Unknown loc info!");
3362 case CCValAssign::Full:
3364 case CCValAssign::BCvt:
3365 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3367 case CCValAssign::AExtUpper:
3368 UseUpperBits = true;
3370 case CCValAssign::AExt:
3371 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3373 case CCValAssign::ZExtUpper:
3374 UseUpperBits = true;
3376 case CCValAssign::ZExt:
3377 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3379 case CCValAssign::SExtUpper:
3380 UseUpperBits = true;
3382 case CCValAssign::SExt:
3383 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3388 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3389 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3391 ISD::SHL, DL, VA.getLocVT(), Val,
3392 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3395 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3397 // Guarantee that all emitted copies are stuck together with flags.
3398 Flag = Chain.getValue(1);
3399 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3402 // The mips ABIs for returning structs by value requires that we copy
3403 // the sret argument into $v0 for the return. We saved the argument into
3404 // a virtual register in the entry block, so now we copy the value out
3406 if (MF.getFunction()->hasStructRetAttr()) {
3407 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3408 unsigned Reg = MipsFI->getSRetReturnReg();
3411 llvm_unreachable("sret virtual register not created in the entry block");
3413 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3414 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3416 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3417 Flag = Chain.getValue(1);
3418 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3421 RetOps[0] = Chain; // Update chain.
3423 // Add the flag if we have it.
3425 RetOps.push_back(Flag);
3427 // ISRs must use "eret".
3428 if (DAG.getMachineFunction().getFunction()->hasFnAttribute("interrupt"))
3429 return LowerInterruptReturn(RetOps, DL, DAG);
3431 // Standard return on Mips is a "jr $ra"
3432 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3435 //===----------------------------------------------------------------------===//
3436 // Mips Inline Assembly Support
3437 //===----------------------------------------------------------------------===//
3439 /// getConstraintType - Given a constraint letter, return the type of
3440 /// constraint it is for this target.
3441 MipsTargetLowering::ConstraintType
3442 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3443 // Mips specific constraints
3444 // GCC config/mips/constraints.md
3446 // 'd' : An address register. Equivalent to r
3447 // unless generating MIPS16 code.
3448 // 'y' : Equivalent to r; retained for
3449 // backwards compatibility.
3450 // 'c' : A register suitable for use in an indirect
3451 // jump. This will always be $25 for -mabicalls.
3452 // 'l' : The lo register. 1 word storage.
3453 // 'x' : The hilo register pair. Double word storage.
3454 if (Constraint.size() == 1) {
3455 switch (Constraint[0]) {
3463 return C_RegisterClass;
3469 if (Constraint == "ZC")
3472 return TargetLowering::getConstraintType(Constraint);
3475 /// Examine constraint type and operand type and determine a weight value.
3476 /// This object must already have been set up with the operand type
3477 /// and the current alternative constraint selected.
3478 TargetLowering::ConstraintWeight
3479 MipsTargetLowering::getSingleConstraintMatchWeight(
3480 AsmOperandInfo &info, const char *constraint) const {
3481 ConstraintWeight weight = CW_Invalid;
3482 Value *CallOperandVal = info.CallOperandVal;
3483 // If we don't have a value, we can't do a match,
3484 // but allow it at the lowest weight.
3485 if (!CallOperandVal)
3487 Type *type = CallOperandVal->getType();
3488 // Look at the constraint type.
3489 switch (*constraint) {
3491 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3495 if (type->isIntegerTy())
3496 weight = CW_Register;
3498 case 'f': // FPU or MSA register
3499 if (Subtarget.hasMSA() && type->isVectorTy() &&
3500 cast<VectorType>(type)->getBitWidth() == 128)
3501 weight = CW_Register;
3502 else if (type->isFloatTy())
3503 weight = CW_Register;
3505 case 'c': // $25 for indirect jumps
3506 case 'l': // lo register
3507 case 'x': // hilo register pair
3508 if (type->isIntegerTy())
3509 weight = CW_SpecificReg;
3511 case 'I': // signed 16 bit immediate
3512 case 'J': // integer zero
3513 case 'K': // unsigned 16 bit immediate
3514 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3515 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3516 case 'O': // signed 15 bit immediate (+- 16383)
3517 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3518 if (isa<ConstantInt>(CallOperandVal))
3519 weight = CW_Constant;
3528 /// This is a helper function to parse a physical register string and split it
3529 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3530 /// that is returned indicates whether parsing was successful. The second flag
3531 /// is true if the numeric part exists.
3532 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3533 unsigned long long &Reg) {
3534 if (C.front() != '{' || C.back() != '}')
3535 return std::make_pair(false, false);
3537 // Search for the first numeric character.
3538 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3539 I = std::find_if(B, E, isdigit);
3541 Prefix = StringRef(B, I - B);
3543 // The second flag is set to false if no numeric characters were found.
3545 return std::make_pair(true, false);
3547 // Parse the numeric characters.
3548 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3552 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3553 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3554 const TargetRegisterInfo *TRI =
3555 Subtarget.getRegisterInfo();
3556 const TargetRegisterClass *RC;
3558 unsigned long long Reg;
3560 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3563 return std::make_pair(0U, nullptr);
3565 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3566 // No numeric characters follow "hi" or "lo".
3568 return std::make_pair(0U, nullptr);
3570 RC = TRI->getRegClass(Prefix == "hi" ?
3571 Mips::HI32RegClassID : Mips::LO32RegClassID);
3572 return std::make_pair(*(RC->begin()), RC);
3573 } else if (Prefix.startswith("$msa")) {
3574 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3576 // No numeric characters follow the name.
3578 return std::make_pair(0U, nullptr);
3580 Reg = StringSwitch<unsigned long long>(Prefix)
3581 .Case("$msair", Mips::MSAIR)
3582 .Case("$msacsr", Mips::MSACSR)
3583 .Case("$msaaccess", Mips::MSAAccess)
3584 .Case("$msasave", Mips::MSASave)
3585 .Case("$msamodify", Mips::MSAModify)
3586 .Case("$msarequest", Mips::MSARequest)
3587 .Case("$msamap", Mips::MSAMap)
3588 .Case("$msaunmap", Mips::MSAUnmap)
3592 return std::make_pair(0U, nullptr);
3594 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3595 return std::make_pair(Reg, RC);
3599 return std::make_pair(0U, nullptr);
3601 if (Prefix == "$f") { // Parse $f0-$f31.
3602 // If the size of FP registers is 64-bit or Reg is an even number, select
3603 // the 64-bit register class. Otherwise, select the 32-bit register class.
3604 if (VT == MVT::Other)
3605 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3607 RC = getRegClassFor(VT);
3609 if (RC == &Mips::AFGR64RegClass) {
3610 assert(Reg % 2 == 0);
3613 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3614 RC = TRI->getRegClass(Mips::FCCRegClassID);
3615 else if (Prefix == "$w") { // Parse $w0-$w31.
3616 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3617 } else { // Parse $0-$31.
3618 assert(Prefix == "$");
3619 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3622 assert(Reg < RC->getNumRegs());
3623 return std::make_pair(*(RC->begin() + Reg), RC);
3626 /// Given a register class constraint, like 'r', if this corresponds directly
3627 /// to an LLVM register class, return a register of 0 and the register class
3629 std::pair<unsigned, const TargetRegisterClass *>
3630 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3631 StringRef Constraint,
3633 if (Constraint.size() == 1) {
3634 switch (Constraint[0]) {
3635 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3636 case 'y': // Same as 'r'. Exists for compatibility.
3638 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3639 if (Subtarget.inMips16Mode())
3640 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3641 return std::make_pair(0U, &Mips::GPR32RegClass);
3643 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3644 return std::make_pair(0U, &Mips::GPR32RegClass);
3645 if (VT == MVT::i64 && Subtarget.isGP64bit())
3646 return std::make_pair(0U, &Mips::GPR64RegClass);
3647 // This will generate an error message
3648 return std::make_pair(0U, nullptr);
3649 case 'f': // FPU or MSA register
3650 if (VT == MVT::v16i8)
3651 return std::make_pair(0U, &Mips::MSA128BRegClass);
3652 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3653 return std::make_pair(0U, &Mips::MSA128HRegClass);
3654 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3655 return std::make_pair(0U, &Mips::MSA128WRegClass);
3656 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3657 return std::make_pair(0U, &Mips::MSA128DRegClass);
3658 else if (VT == MVT::f32)
3659 return std::make_pair(0U, &Mips::FGR32RegClass);
3660 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3661 if (Subtarget.isFP64bit())
3662 return std::make_pair(0U, &Mips::FGR64RegClass);
3663 return std::make_pair(0U, &Mips::AFGR64RegClass);
3666 case 'c': // register suitable for indirect jump
3668 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3669 assert(VT == MVT::i64 && "Unexpected type.");
3670 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3671 case 'l': // register suitable for indirect jump
3673 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3674 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3675 case 'x': // register suitable for indirect jump
3676 // Fixme: Not triggering the use of both hi and low
3677 // This will generate an error message
3678 return std::make_pair(0U, nullptr);
3682 std::pair<unsigned, const TargetRegisterClass *> R;
3683 R = parseRegForInlineAsmConstraint(Constraint, VT);
3688 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3691 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3692 /// vector. If it is invalid, don't add anything to Ops.
3693 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3694 std::string &Constraint,
3695 std::vector<SDValue>&Ops,
3696 SelectionDAG &DAG) const {
3700 // Only support length 1 constraints for now.
3701 if (Constraint.length() > 1) return;
3703 char ConstraintLetter = Constraint[0];
3704 switch (ConstraintLetter) {
3705 default: break; // This will fall through to the generic implementation
3706 case 'I': // Signed 16 bit constant
3707 // If this fails, the parent routine will give an error
3708 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3709 EVT Type = Op.getValueType();
3710 int64_t Val = C->getSExtValue();
3711 if (isInt<16>(Val)) {
3712 Result = DAG.getTargetConstant(Val, DL, Type);
3717 case 'J': // integer zero
3718 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3719 EVT Type = Op.getValueType();
3720 int64_t Val = C->getZExtValue();
3722 Result = DAG.getTargetConstant(0, DL, Type);
3727 case 'K': // unsigned 16 bit immediate
3728 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3729 EVT Type = Op.getValueType();
3730 uint64_t Val = (uint64_t)C->getZExtValue();
3731 if (isUInt<16>(Val)) {
3732 Result = DAG.getTargetConstant(Val, DL, Type);
3737 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3738 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3739 EVT Type = Op.getValueType();
3740 int64_t Val = C->getSExtValue();
3741 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3742 Result = DAG.getTargetConstant(Val, DL, Type);
3747 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3748 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3749 EVT Type = Op.getValueType();
3750 int64_t Val = C->getSExtValue();
3751 if ((Val >= -65535) && (Val <= -1)) {
3752 Result = DAG.getTargetConstant(Val, DL, Type);
3757 case 'O': // signed 15 bit immediate
3758 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3759 EVT Type = Op.getValueType();
3760 int64_t Val = C->getSExtValue();
3761 if ((isInt<15>(Val))) {
3762 Result = DAG.getTargetConstant(Val, DL, Type);
3767 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3768 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3769 EVT Type = Op.getValueType();
3770 int64_t Val = C->getSExtValue();
3771 if ((Val <= 65535) && (Val >= 1)) {
3772 Result = DAG.getTargetConstant(Val, DL, Type);
3779 if (Result.getNode()) {
3780 Ops.push_back(Result);
3784 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3787 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3788 const AddrMode &AM, Type *Ty,
3789 unsigned AS) const {
3790 // No global is ever allowed as a base.
3795 case 0: // "r+i" or just "i", depending on HasBaseReg.
3798 if (!AM.HasBaseReg) // allow "r+i".
3800 return false; // disallow "r+r" or "r+r+i".
3809 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3810 // The Mips target isn't yet aware of offsets.
3814 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3816 bool IsMemset, bool ZeroMemset,
3818 MachineFunction &MF) const {
3819 if (Subtarget.hasMips64())
3825 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3826 if (VT != MVT::f32 && VT != MVT::f64)
3828 if (Imm.isNegZero())
3830 return Imm.isZero();
3833 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3835 // FIXME: For space reasons this should be: EK_GPRel32BlockAddress.
3836 if (ABI.IsN64() && isPositionIndependent())
3837 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3839 return TargetLowering::getJumpTableEncoding();
3842 bool MipsTargetLowering::useSoftFloat() const {
3843 return Subtarget.useSoftFloat();
3846 void MipsTargetLowering::copyByValRegs(
3847 SDValue Chain, const SDLoc &DL, std::vector<SDValue> &OutChains,
3848 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3849 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3850 unsigned FirstReg, unsigned LastReg, const CCValAssign &VA,
3851 MipsCCState &State) const {
3852 MachineFunction &MF = DAG.getMachineFunction();
3853 MachineFrameInfo &MFI = MF.getFrameInfo();
3854 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3855 unsigned NumRegs = LastReg - FirstReg;
3856 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3857 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3859 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3863 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3864 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3866 FrameObjOffset = VA.getLocMemOffset();
3868 // Create frame object.
3869 EVT PtrTy = getPointerTy(DAG.getDataLayout());
3870 int FI = MFI.CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3871 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3872 InVals.push_back(FIN);
3877 // Copy arg registers.
3878 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3879 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3881 for (unsigned I = 0; I < NumRegs; ++I) {
3882 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3883 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3884 unsigned Offset = I * GPRSizeInBytes;
3885 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3886 DAG.getConstant(Offset, DL, PtrTy));
3887 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3888 StorePtr, MachinePointerInfo(FuncArg, Offset));
3889 OutChains.push_back(Store);
3893 // Copy byVal arg to registers and stack.
3894 void MipsTargetLowering::passByValArg(
3895 SDValue Chain, const SDLoc &DL,
3896 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3897 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3898 MachineFrameInfo &MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3899 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3900 const CCValAssign &VA) const {
3901 unsigned ByValSizeInBytes = Flags.getByValSize();
3902 unsigned OffsetInBytes = 0; // From beginning of struct
3903 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3904 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3905 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
3906 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3907 unsigned NumRegs = LastReg - FirstReg;
3910 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
3911 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3914 // Copy words to registers.
3915 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3916 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3917 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3918 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3919 MachinePointerInfo(), Alignment);
3920 MemOpChains.push_back(LoadVal.getValue(1));
3921 unsigned ArgReg = ArgRegs[FirstReg + I];
3922 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3925 // Return if the struct has been fully copied.
3926 if (ByValSizeInBytes == OffsetInBytes)
3929 // Copy the remainder of the byval argument with sub-word loads and shifts.
3930 if (LeftoverBytes) {
3933 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3934 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3935 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3937 if (RemainingSizeInBytes < LoadSizeInBytes)
3941 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3942 DAG.getConstant(OffsetInBytes, DL,
3944 SDValue LoadVal = DAG.getExtLoad(
3945 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3946 MVT::getIntegerVT(LoadSizeInBytes * 8), Alignment);
3947 MemOpChains.push_back(LoadVal.getValue(1));
3949 // Shift the loaded value.
3953 Shamt = TotalBytesLoaded * 8;
3955 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3957 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3958 DAG.getConstant(Shamt, DL, MVT::i32));
3961 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3965 OffsetInBytes += LoadSizeInBytes;
3966 TotalBytesLoaded += LoadSizeInBytes;
3967 Alignment = std::min(Alignment, LoadSizeInBytes);
3970 unsigned ArgReg = ArgRegs[FirstReg + I];
3971 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3976 // Copy remainder of byval arg to it with memcpy.
3977 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3978 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3979 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3980 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3981 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
3982 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3983 DAG.getConstant(MemCpySize, DL, PtrTy),
3984 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3985 /*isTailCall=*/false,
3986 MachinePointerInfo(), MachinePointerInfo());
3987 MemOpChains.push_back(Chain);
3990 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3991 SDValue Chain, const SDLoc &DL,
3993 CCState &State) const {
3994 ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
3995 unsigned Idx = State.getFirstUnallocated(ArgRegs);
3996 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3997 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3998 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3999 MachineFunction &MF = DAG.getMachineFunction();
4000 MachineFrameInfo &MFI = MF.getFrameInfo();
4001 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4003 // Offset of the first variable argument from stack pointer.
4006 if (ArgRegs.size() == Idx)
4007 VaArgOffset = alignTo(State.getNextStackOffset(), RegSizeInBytes);
4010 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
4011 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
4014 // Record the frame index of the first variable argument
4015 // which is a value necessary to VASTART.
4016 int FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4017 MipsFI->setVarArgsFrameIndex(FI);
4019 // Copy the integer registers that have not been used for argument passing
4020 // to the argument register save area. For O32, the save area is allocated
4021 // in the caller's stack frame, while for N32/64, it is allocated in the
4022 // callee's stack frame.
4023 for (unsigned I = Idx; I < ArgRegs.size();
4024 ++I, VaArgOffset += RegSizeInBytes) {
4025 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4026 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4027 FI = MFI.CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
4028 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
4030 DAG.getStore(Chain, DL, ArgValue, PtrOff, MachinePointerInfo());
4031 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
4033 OutChains.push_back(Store);
4037 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
4038 unsigned Align) const {
4039 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
4041 assert(Size && "Byval argument's size shouldn't be 0.");
4043 Align = std::min(Align, TFL->getStackAlignment());
4045 unsigned FirstReg = 0;
4046 unsigned NumRegs = 0;
4048 if (State->getCallingConv() != CallingConv::Fast) {
4049 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
4050 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
4051 // FIXME: The O32 case actually describes no shadow registers.
4052 const MCPhysReg *ShadowRegs =
4053 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
4055 // We used to check the size as well but we can't do that anymore since
4056 // CCState::HandleByVal() rounds up the size after calling this function.
4057 assert(!(Align % RegSizeInBytes) &&
4058 "Byval argument's alignment should be a multiple of"
4061 FirstReg = State->getFirstUnallocated(IntArgRegs);
4063 // If Align > RegSizeInBytes, the first arg register must be even.
4064 // FIXME: This condition happens to do the right thing but it's not the
4065 // right way to test it. We want to check that the stack frame offset
4066 // of the register is aligned.
4067 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
4068 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
4072 // Mark the registers allocated.
4073 Size = alignTo(Size, RegSizeInBytes);
4074 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
4075 Size -= RegSizeInBytes, ++I, ++NumRegs)
4076 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4079 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
4082 MachineBasicBlock *MipsTargetLowering::emitPseudoSELECT(MachineInstr &MI,
4083 MachineBasicBlock *BB,
4085 unsigned Opc) const {
4086 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
4087 "Subtarget already supports SELECT nodes with the use of"
4088 "conditional-move instructions.");
4090 const TargetInstrInfo *TII =
4091 Subtarget.getInstrInfo();
4092 DebugLoc DL = MI.getDebugLoc();
4094 // To "insert" a SELECT instruction, we actually have to insert the
4095 // diamond control-flow pattern. The incoming instruction knows the
4096 // destination vreg to set, the condition code register to branch on, the
4097 // true/false values to select between, and a branch opcode to use.
4098 const BasicBlock *LLVM_BB = BB->getBasicBlock();
4099 MachineFunction::iterator It = ++BB->getIterator();
4105 // bNE r1, r0, copy1MBB
4106 // fallthrough --> copy0MBB
4107 MachineBasicBlock *thisMBB = BB;
4108 MachineFunction *F = BB->getParent();
4109 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
4110 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
4111 F->insert(It, copy0MBB);
4112 F->insert(It, sinkMBB);
4114 // Transfer the remainder of BB and its successor edges to sinkMBB.
4115 sinkMBB->splice(sinkMBB->begin(), BB,
4116 std::next(MachineBasicBlock::iterator(MI)), BB->end());
4117 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
4119 // Next, add the true and fallthrough blocks as its successors.
4120 BB->addSuccessor(copy0MBB);
4121 BB->addSuccessor(sinkMBB);
4124 // bc1[tf] cc, sinkMBB
4125 BuildMI(BB, DL, TII->get(Opc))
4126 .addReg(MI.getOperand(1).getReg())
4129 // bne rs, $0, sinkMBB
4130 BuildMI(BB, DL, TII->get(Opc))
4131 .addReg(MI.getOperand(1).getReg())
4137 // %FalseValue = ...
4138 // # fallthrough to sinkMBB
4141 // Update machine-CFG edges
4142 BB->addSuccessor(sinkMBB);
4145 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
4149 BuildMI(*BB, BB->begin(), DL, TII->get(Mips::PHI), MI.getOperand(0).getReg())
4150 .addReg(MI.getOperand(2).getReg())
4152 .addReg(MI.getOperand(3).getReg())
4155 MI.eraseFromParent(); // The pseudo instruction is gone now.
4160 // FIXME? Maybe this could be a TableGen attribute on some registers and
4161 // this table could be generated automatically from RegInfo.
4162 unsigned MipsTargetLowering::getRegisterByName(const char* RegName, EVT VT,
4163 SelectionDAG &DAG) const {
4164 // Named registers is expected to be fairly rare. For now, just support $28
4165 // since the linux kernel uses it.
4166 if (Subtarget.isGP64bit()) {
4167 unsigned Reg = StringSwitch<unsigned>(RegName)
4168 .Case("$28", Mips::GP_64)
4173 unsigned Reg = StringSwitch<unsigned>(RegName)
4174 .Case("$28", Mips::GP)
4179 report_fatal_error("Invalid register name global variable");