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::Hi: return "MipsISD::Hi";
116 case MipsISD::Lo: return "MipsISD::Lo";
117 case MipsISD::GPRel: return "MipsISD::GPRel";
118 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
119 case MipsISD::Ret: return "MipsISD::Ret";
120 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
121 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
122 case MipsISD::FPCmp: return "MipsISD::FPCmp";
123 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
124 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
125 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
126 case MipsISD::MFHI: return "MipsISD::MFHI";
127 case MipsISD::MFLO: return "MipsISD::MFLO";
128 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
129 case MipsISD::Mult: return "MipsISD::Mult";
130 case MipsISD::Multu: return "MipsISD::Multu";
131 case MipsISD::MAdd: return "MipsISD::MAdd";
132 case MipsISD::MAddu: return "MipsISD::MAddu";
133 case MipsISD::MSub: return "MipsISD::MSub";
134 case MipsISD::MSubu: return "MipsISD::MSubu";
135 case MipsISD::DivRem: return "MipsISD::DivRem";
136 case MipsISD::DivRemU: return "MipsISD::DivRemU";
137 case MipsISD::DivRem16: return "MipsISD::DivRem16";
138 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
139 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
140 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
141 case MipsISD::Wrapper: return "MipsISD::Wrapper";
142 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
143 case MipsISD::Sync: return "MipsISD::Sync";
144 case MipsISD::Ext: return "MipsISD::Ext";
145 case MipsISD::Ins: return "MipsISD::Ins";
146 case MipsISD::LWL: return "MipsISD::LWL";
147 case MipsISD::LWR: return "MipsISD::LWR";
148 case MipsISD::SWL: return "MipsISD::SWL";
149 case MipsISD::SWR: return "MipsISD::SWR";
150 case MipsISD::LDL: return "MipsISD::LDL";
151 case MipsISD::LDR: return "MipsISD::LDR";
152 case MipsISD::SDL: return "MipsISD::SDL";
153 case MipsISD::SDR: return "MipsISD::SDR";
154 case MipsISD::EXTP: return "MipsISD::EXTP";
155 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
156 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
157 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
158 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
159 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
160 case MipsISD::SHILO: return "MipsISD::SHILO";
161 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
162 case MipsISD::MULSAQ_S_W_PH: return "MipsISD::MULSAQ_S_W_PH";
163 case MipsISD::MAQ_S_W_PHL: return "MipsISD::MAQ_S_W_PHL";
164 case MipsISD::MAQ_S_W_PHR: return "MipsISD::MAQ_S_W_PHR";
165 case MipsISD::MAQ_SA_W_PHL: return "MipsISD::MAQ_SA_W_PHL";
166 case MipsISD::MAQ_SA_W_PHR: return "MipsISD::MAQ_SA_W_PHR";
167 case MipsISD::DPAU_H_QBL: return "MipsISD::DPAU_H_QBL";
168 case MipsISD::DPAU_H_QBR: return "MipsISD::DPAU_H_QBR";
169 case MipsISD::DPSU_H_QBL: return "MipsISD::DPSU_H_QBL";
170 case MipsISD::DPSU_H_QBR: return "MipsISD::DPSU_H_QBR";
171 case MipsISD::DPAQ_S_W_PH: return "MipsISD::DPAQ_S_W_PH";
172 case MipsISD::DPSQ_S_W_PH: return "MipsISD::DPSQ_S_W_PH";
173 case MipsISD::DPAQ_SA_L_W: return "MipsISD::DPAQ_SA_L_W";
174 case MipsISD::DPSQ_SA_L_W: return "MipsISD::DPSQ_SA_L_W";
175 case MipsISD::DPA_W_PH: return "MipsISD::DPA_W_PH";
176 case MipsISD::DPS_W_PH: return "MipsISD::DPS_W_PH";
177 case MipsISD::DPAQX_S_W_PH: return "MipsISD::DPAQX_S_W_PH";
178 case MipsISD::DPAQX_SA_W_PH: return "MipsISD::DPAQX_SA_W_PH";
179 case MipsISD::DPAX_W_PH: return "MipsISD::DPAX_W_PH";
180 case MipsISD::DPSX_W_PH: return "MipsISD::DPSX_W_PH";
181 case MipsISD::DPSQX_S_W_PH: return "MipsISD::DPSQX_S_W_PH";
182 case MipsISD::DPSQX_SA_W_PH: return "MipsISD::DPSQX_SA_W_PH";
183 case MipsISD::MULSA_W_PH: return "MipsISD::MULSA_W_PH";
184 case MipsISD::MULT: return "MipsISD::MULT";
185 case MipsISD::MULTU: return "MipsISD::MULTU";
186 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
187 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
188 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
189 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
190 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
191 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
192 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
193 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
194 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
195 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
196 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
197 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
198 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
199 case MipsISD::VCEQ: return "MipsISD::VCEQ";
200 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
201 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
202 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
203 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
204 case MipsISD::VSMAX: return "MipsISD::VSMAX";
205 case MipsISD::VSMIN: return "MipsISD::VSMIN";
206 case MipsISD::VUMAX: return "MipsISD::VUMAX";
207 case MipsISD::VUMIN: return "MipsISD::VUMIN";
208 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
209 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
210 case MipsISD::VNOR: return "MipsISD::VNOR";
211 case MipsISD::VSHF: return "MipsISD::VSHF";
212 case MipsISD::SHF: return "MipsISD::SHF";
213 case MipsISD::ILVEV: return "MipsISD::ILVEV";
214 case MipsISD::ILVOD: return "MipsISD::ILVOD";
215 case MipsISD::ILVL: return "MipsISD::ILVL";
216 case MipsISD::ILVR: return "MipsISD::ILVR";
217 case MipsISD::PCKEV: return "MipsISD::PCKEV";
218 case MipsISD::PCKOD: return "MipsISD::PCKOD";
219 case MipsISD::INSVE: return "MipsISD::INSVE";
224 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
225 const MipsSubtarget &STI)
226 : TargetLowering(TM), Subtarget(STI), ABI(TM.getABI()) {
227 // Mips does not have i1 type, so use i32 for
228 // setcc operations results (slt, sgt, ...).
229 setBooleanContents(ZeroOrOneBooleanContent);
230 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
231 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
232 // does. Integer booleans still use 0 and 1.
233 if (Subtarget.hasMips32r6())
234 setBooleanContents(ZeroOrOneBooleanContent,
235 ZeroOrNegativeOneBooleanContent);
237 // Load extented operations for i1 types must be promoted
238 for (MVT VT : MVT::integer_valuetypes()) {
239 setLoadExtAction(ISD::EXTLOAD, VT, MVT::i1, Promote);
240 setLoadExtAction(ISD::ZEXTLOAD, VT, MVT::i1, Promote);
241 setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Promote);
244 // MIPS doesn't have extending float->double load/store. Set LoadExtAction
246 for (MVT VT : MVT::fp_valuetypes()) {
247 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
248 setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
251 // Set LoadExtAction for f16 vectors to Expand
252 for (MVT VT : MVT::fp_vector_valuetypes()) {
253 MVT F16VT = MVT::getVectorVT(MVT::f16, VT.getVectorNumElements());
255 setLoadExtAction(ISD::EXTLOAD, VT, F16VT, Expand);
258 setTruncStoreAction(MVT::f32, MVT::f16, Expand);
259 setTruncStoreAction(MVT::f64, MVT::f16, Expand);
261 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
263 // Used by legalize types to correctly generate the setcc result.
264 // Without this, every float setcc comes with a AND/OR with the result,
265 // we don't want this, since the fpcmp result goes to a flag register,
266 // which is used implicitly by brcond and select operations.
267 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
269 // Mips Custom Operations
270 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
271 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
272 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
273 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
274 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
275 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
276 setOperationAction(ISD::SELECT, MVT::f32, Custom);
277 setOperationAction(ISD::SELECT, MVT::f64, Custom);
278 setOperationAction(ISD::SELECT, MVT::i32, Custom);
279 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
280 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
281 setOperationAction(ISD::SETCC, MVT::f32, Custom);
282 setOperationAction(ISD::SETCC, MVT::f64, Custom);
283 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
284 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
285 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
286 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
288 if (Subtarget.isGP64bit()) {
289 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
290 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
291 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
292 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
293 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
294 setOperationAction(ISD::SELECT, MVT::i64, Custom);
295 setOperationAction(ISD::LOAD, MVT::i64, Custom);
296 setOperationAction(ISD::STORE, MVT::i64, Custom);
297 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
298 setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
299 setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
300 setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
303 if (!Subtarget.isGP64bit()) {
304 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
305 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
306 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
309 setOperationAction(ISD::ADD, MVT::i32, Custom);
310 if (Subtarget.isGP64bit())
311 setOperationAction(ISD::ADD, MVT::i64, Custom);
313 setOperationAction(ISD::SDIV, MVT::i32, Expand);
314 setOperationAction(ISD::SREM, MVT::i32, Expand);
315 setOperationAction(ISD::UDIV, MVT::i32, Expand);
316 setOperationAction(ISD::UREM, MVT::i32, Expand);
317 setOperationAction(ISD::SDIV, MVT::i64, Expand);
318 setOperationAction(ISD::SREM, MVT::i64, Expand);
319 setOperationAction(ISD::UDIV, MVT::i64, Expand);
320 setOperationAction(ISD::UREM, MVT::i64, Expand);
322 // Operations not directly supported by Mips.
323 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
324 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
325 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
326 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
327 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
328 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
329 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
330 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
331 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
332 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
333 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
334 if (Subtarget.hasCnMips()) {
335 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
336 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
338 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
339 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
341 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
342 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
343 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
344 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
345 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
346 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
347 setOperationAction(ISD::ROTL, MVT::i32, Expand);
348 setOperationAction(ISD::ROTL, MVT::i64, Expand);
349 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
350 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
352 if (!Subtarget.hasMips32r2())
353 setOperationAction(ISD::ROTR, MVT::i32, Expand);
355 if (!Subtarget.hasMips64r2())
356 setOperationAction(ISD::ROTR, MVT::i64, Expand);
358 setOperationAction(ISD::FSIN, MVT::f32, Expand);
359 setOperationAction(ISD::FSIN, MVT::f64, Expand);
360 setOperationAction(ISD::FCOS, MVT::f32, Expand);
361 setOperationAction(ISD::FCOS, MVT::f64, Expand);
362 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
363 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
364 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
365 setOperationAction(ISD::FPOW, MVT::f32, Expand);
366 setOperationAction(ISD::FPOW, MVT::f64, Expand);
367 setOperationAction(ISD::FLOG, MVT::f32, Expand);
368 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
369 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
370 setOperationAction(ISD::FEXP, MVT::f32, Expand);
371 setOperationAction(ISD::FMA, MVT::f32, Expand);
372 setOperationAction(ISD::FMA, MVT::f64, Expand);
373 setOperationAction(ISD::FREM, MVT::f32, Expand);
374 setOperationAction(ISD::FREM, MVT::f64, Expand);
376 // Lower f16 conversion operations into library calls
377 setOperationAction(ISD::FP16_TO_FP, MVT::f32, Expand);
378 setOperationAction(ISD::FP_TO_FP16, MVT::f32, Expand);
379 setOperationAction(ISD::FP16_TO_FP, MVT::f64, Expand);
380 setOperationAction(ISD::FP_TO_FP16, MVT::f64, Expand);
382 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
384 setOperationAction(ISD::VASTART, MVT::Other, Custom);
385 setOperationAction(ISD::VAARG, MVT::Other, Custom);
386 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
387 setOperationAction(ISD::VAEND, MVT::Other, Expand);
389 // Use the default for now
390 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
391 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
393 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
394 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
395 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
396 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
398 setInsertFencesForAtomic(true);
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);
432 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
434 // The arguments on the stack are defined in terms of 4-byte slots on O32
435 // and 8-byte slots on N32/N64.
436 setMinStackArgumentAlignment((ABI.IsN32() || ABI.IsN64()) ? 8 : 4);
438 setStackPointerRegisterToSaveRestore(ABI.IsN64() ? Mips::SP_64 : Mips::SP);
440 setExceptionPointerRegister(ABI.IsN64() ? Mips::A0_64 : Mips::A0);
441 setExceptionSelectorRegister(ABI.IsN64() ? Mips::A1_64 : Mips::A1);
443 MaxStoresPerMemcpy = 16;
445 isMicroMips = Subtarget.inMicroMipsMode();
448 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
449 const MipsSubtarget &STI) {
450 if (STI.inMips16Mode())
451 return llvm::createMips16TargetLowering(TM, STI);
453 return llvm::createMipsSETargetLowering(TM, STI);
456 // Create a fast isel object.
458 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
459 const TargetLibraryInfo *libInfo) const {
460 if (!funcInfo.MF->getTarget().Options.EnableFastISel)
461 return TargetLowering::createFastISel(funcInfo, libInfo);
462 return Mips::createFastISel(funcInfo, libInfo);
465 EVT MipsTargetLowering::getSetCCResultType(const DataLayout &, LLVMContext &,
469 return VT.changeVectorElementTypeToInteger();
472 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
473 TargetLowering::DAGCombinerInfo &DCI,
474 const MipsSubtarget &Subtarget) {
475 if (DCI.isBeforeLegalizeOps())
478 EVT Ty = N->getValueType(0);
479 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
480 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
481 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
485 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
486 N->getOperand(0), N->getOperand(1));
487 SDValue InChain = DAG.getEntryNode();
488 SDValue InGlue = DivRem;
491 if (N->hasAnyUseOfValue(0)) {
492 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
494 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
495 InChain = CopyFromLo.getValue(1);
496 InGlue = CopyFromLo.getValue(2);
500 if (N->hasAnyUseOfValue(1)) {
501 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
503 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
509 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
511 default: llvm_unreachable("Unknown fp condition code!");
513 case ISD::SETOEQ: return Mips::FCOND_OEQ;
514 case ISD::SETUNE: return Mips::FCOND_UNE;
516 case ISD::SETOLT: return Mips::FCOND_OLT;
518 case ISD::SETOGT: return Mips::FCOND_OGT;
520 case ISD::SETOLE: return Mips::FCOND_OLE;
522 case ISD::SETOGE: return Mips::FCOND_OGE;
523 case ISD::SETULT: return Mips::FCOND_ULT;
524 case ISD::SETULE: return Mips::FCOND_ULE;
525 case ISD::SETUGT: return Mips::FCOND_UGT;
526 case ISD::SETUGE: return Mips::FCOND_UGE;
527 case ISD::SETUO: return Mips::FCOND_UN;
528 case ISD::SETO: return Mips::FCOND_OR;
530 case ISD::SETONE: return Mips::FCOND_ONE;
531 case ISD::SETUEQ: return Mips::FCOND_UEQ;
536 /// This function returns true if the floating point conditional branches and
537 /// conditional moves which use condition code CC should be inverted.
538 static bool invertFPCondCodeUser(Mips::CondCode CC) {
539 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
542 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
543 "Illegal Condition Code");
548 // Creates and returns an FPCmp node from a setcc node.
549 // Returns Op if setcc is not a floating point comparison.
550 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
551 // must be a SETCC node
552 if (Op.getOpcode() != ISD::SETCC)
555 SDValue LHS = Op.getOperand(0);
557 if (!LHS.getValueType().isFloatingPoint())
560 SDValue RHS = Op.getOperand(1);
563 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
564 // node if necessary.
565 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
567 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
568 DAG.getConstant(condCodeToFCC(CC), DL, MVT::i32));
571 // Creates and returns a CMovFPT/F node.
572 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
573 SDValue False, SDLoc DL) {
574 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
575 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
576 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
578 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
579 True.getValueType(), True, FCC0, False, Cond);
582 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
583 TargetLowering::DAGCombinerInfo &DCI,
584 const MipsSubtarget &Subtarget) {
585 if (DCI.isBeforeLegalizeOps())
588 SDValue SetCC = N->getOperand(0);
590 if ((SetCC.getOpcode() != ISD::SETCC) ||
591 !SetCC.getOperand(0).getValueType().isInteger())
594 SDValue False = N->getOperand(2);
595 EVT FalseTy = False.getValueType();
597 if (!FalseTy.isInteger())
600 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
602 // If the RHS (False) is 0, we swap the order of the operands
603 // of ISD::SELECT (obviously also inverting the condition) so that we can
604 // take advantage of conditional moves using the $0 register.
606 // return (a != 0) ? x : 0;
614 if (!FalseC->getZExtValue()) {
615 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
616 SDValue True = N->getOperand(1);
618 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
619 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
621 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
624 // If both operands are integer constants there's a possibility that we
625 // can do some interesting optimizations.
626 SDValue True = N->getOperand(1);
627 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
629 if (!TrueC || !True.getValueType().isInteger())
632 // We'll also ignore MVT::i64 operands as this optimizations proves
633 // to be ineffective because of the required sign extensions as the result
634 // of a SETCC operator is always MVT::i32 for non-vector types.
635 if (True.getValueType() == MVT::i64)
638 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
640 // 1) (a < x) ? y : y-1
642 // addiu $reg2, $reg1, y-1
644 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
646 // 2) (a < x) ? y-1 : y
648 // xor $reg1, $reg1, 1
649 // addiu $reg2, $reg1, y-1
651 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
652 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
653 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
654 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
657 // Couldn't optimize.
661 static SDValue performCMovFPCombine(SDNode *N, SelectionDAG &DAG,
662 TargetLowering::DAGCombinerInfo &DCI,
663 const MipsSubtarget &Subtarget) {
664 if (DCI.isBeforeLegalizeOps())
667 SDValue ValueIfTrue = N->getOperand(0), ValueIfFalse = N->getOperand(2);
669 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(ValueIfFalse);
670 if (!FalseC || FalseC->getZExtValue())
673 // Since RHS (False) is 0, we swap the order of the True/False operands
674 // (obviously also inverting the condition) so that we can
675 // take advantage of conditional moves using the $0 register.
677 // return (a != 0) ? x : 0;
680 unsigned Opc = (N->getOpcode() == MipsISD::CMovFP_T) ? MipsISD::CMovFP_F :
683 SDValue FCC = N->getOperand(1), Glue = N->getOperand(3);
684 return DAG.getNode(Opc, SDLoc(N), ValueIfFalse.getValueType(),
685 ValueIfFalse, FCC, ValueIfTrue, Glue);
688 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
689 TargetLowering::DAGCombinerInfo &DCI,
690 const MipsSubtarget &Subtarget) {
691 // Pattern match EXT.
692 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
693 // => ext $dst, $src, size, pos
694 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
697 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
698 unsigned ShiftRightOpc = ShiftRight.getOpcode();
700 // Op's first operand must be a shift right.
701 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
704 // The second operand of the shift must be an immediate.
706 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
709 uint64_t Pos = CN->getZExtValue();
710 uint64_t SMPos, SMSize;
712 // Op's second operand must be a shifted mask.
713 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
714 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
717 // Return if the shifted mask does not start at bit 0 or the sum of its size
718 // and Pos exceeds the word's size.
719 EVT ValTy = N->getValueType(0);
720 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
724 return DAG.getNode(MipsISD::Ext, DL, ValTy,
725 ShiftRight.getOperand(0),
726 DAG.getConstant(Pos, DL, MVT::i32),
727 DAG.getConstant(SMSize, DL, MVT::i32));
730 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
731 TargetLowering::DAGCombinerInfo &DCI,
732 const MipsSubtarget &Subtarget) {
733 // Pattern match INS.
734 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
735 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
736 // => ins $dst, $src, size, pos, $src1
737 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
740 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
741 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
744 // See if Op's first operand matches (and $src1 , mask0).
745 if (And0.getOpcode() != ISD::AND)
748 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
749 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
752 // See if Op's second operand matches (and (shl $src, pos), mask1).
753 if (And1.getOpcode() != ISD::AND)
756 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
757 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
760 // The shift masks must have the same position and size.
761 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
764 SDValue Shl = And1.getOperand(0);
765 if (Shl.getOpcode() != ISD::SHL)
768 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
771 unsigned Shamt = CN->getZExtValue();
773 // Return if the shift amount and the first bit position of mask are not the
775 EVT ValTy = N->getValueType(0);
776 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
780 return DAG.getNode(MipsISD::Ins, DL, ValTy, Shl.getOperand(0),
781 DAG.getConstant(SMPos0, DL, MVT::i32),
782 DAG.getConstant(SMSize0, DL, MVT::i32),
786 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
787 TargetLowering::DAGCombinerInfo &DCI,
788 const MipsSubtarget &Subtarget) {
789 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
791 if (DCI.isBeforeLegalizeOps())
794 SDValue Add = N->getOperand(1);
796 if (Add.getOpcode() != ISD::ADD)
799 SDValue Lo = Add.getOperand(1);
801 if ((Lo.getOpcode() != MipsISD::Lo) ||
802 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
805 EVT ValTy = N->getValueType(0);
808 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
810 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
813 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
815 SelectionDAG &DAG = DCI.DAG;
816 unsigned Opc = N->getOpcode();
822 return performDivRemCombine(N, DAG, DCI, Subtarget);
824 return performSELECTCombine(N, DAG, DCI, Subtarget);
825 case MipsISD::CMovFP_F:
826 case MipsISD::CMovFP_T:
827 return performCMovFPCombine(N, DAG, DCI, Subtarget);
829 return performANDCombine(N, DAG, DCI, Subtarget);
831 return performORCombine(N, DAG, DCI, Subtarget);
833 return performADDCombine(N, DAG, DCI, Subtarget);
840 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
841 SmallVectorImpl<SDValue> &Results,
842 SelectionDAG &DAG) const {
843 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
845 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
846 Results.push_back(Res.getValue(I));
850 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
851 SmallVectorImpl<SDValue> &Results,
852 SelectionDAG &DAG) const {
853 return LowerOperationWrapper(N, Results, DAG);
856 SDValue MipsTargetLowering::
857 LowerOperation(SDValue Op, SelectionDAG &DAG) const
859 switch (Op.getOpcode())
861 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
862 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
863 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
864 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
865 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
866 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
867 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
868 case ISD::SELECT: return lowerSELECT(Op, DAG);
869 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
870 case ISD::SETCC: return lowerSETCC(Op, DAG);
871 case ISD::VASTART: return lowerVASTART(Op, DAG);
872 case ISD::VAARG: return lowerVAARG(Op, DAG);
873 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
874 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
875 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
876 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
877 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
878 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
879 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
880 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
881 case ISD::LOAD: return lowerLOAD(Op, DAG);
882 case ISD::STORE: return lowerSTORE(Op, DAG);
883 case ISD::ADD: return lowerADD(Op, DAG);
884 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
889 //===----------------------------------------------------------------------===//
890 // Lower helper functions
891 //===----------------------------------------------------------------------===//
893 // addLiveIn - This helper function adds the specified physical register to the
894 // MachineFunction as a live in value. It also creates a corresponding
895 // virtual register for it.
897 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
899 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
900 MF.getRegInfo().addLiveIn(PReg, VReg);
904 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
905 MachineBasicBlock &MBB,
906 const TargetInstrInfo &TII,
911 // Insert instruction "teq $divisor_reg, $zero, 7".
912 MachineBasicBlock::iterator I(MI);
913 MachineInstrBuilder MIB;
914 MachineOperand &Divisor = MI->getOperand(2);
915 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
916 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
917 .addReg(Mips::ZERO).addImm(7);
919 // Use the 32-bit sub-register if this is a 64-bit division.
921 MIB->getOperand(0).setSubReg(Mips::sub_32);
923 // Clear Divisor's kill flag.
924 Divisor.setIsKill(false);
926 // We would normally delete the original instruction here but in this case
927 // we only needed to inject an additional instruction rather than replace it.
933 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
934 MachineBasicBlock *BB) const {
935 switch (MI->getOpcode()) {
937 llvm_unreachable("Unexpected instr type to insert");
938 case Mips::ATOMIC_LOAD_ADD_I8:
939 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
940 case Mips::ATOMIC_LOAD_ADD_I16:
941 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
942 case Mips::ATOMIC_LOAD_ADD_I32:
943 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
944 case Mips::ATOMIC_LOAD_ADD_I64:
945 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
947 case Mips::ATOMIC_LOAD_AND_I8:
948 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
949 case Mips::ATOMIC_LOAD_AND_I16:
950 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
951 case Mips::ATOMIC_LOAD_AND_I32:
952 return emitAtomicBinary(MI, BB, 4, Mips::AND);
953 case Mips::ATOMIC_LOAD_AND_I64:
954 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
956 case Mips::ATOMIC_LOAD_OR_I8:
957 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
958 case Mips::ATOMIC_LOAD_OR_I16:
959 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
960 case Mips::ATOMIC_LOAD_OR_I32:
961 return emitAtomicBinary(MI, BB, 4, Mips::OR);
962 case Mips::ATOMIC_LOAD_OR_I64:
963 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
965 case Mips::ATOMIC_LOAD_XOR_I8:
966 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
967 case Mips::ATOMIC_LOAD_XOR_I16:
968 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
969 case Mips::ATOMIC_LOAD_XOR_I32:
970 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
971 case Mips::ATOMIC_LOAD_XOR_I64:
972 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
974 case Mips::ATOMIC_LOAD_NAND_I8:
975 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
976 case Mips::ATOMIC_LOAD_NAND_I16:
977 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
978 case Mips::ATOMIC_LOAD_NAND_I32:
979 return emitAtomicBinary(MI, BB, 4, 0, true);
980 case Mips::ATOMIC_LOAD_NAND_I64:
981 return emitAtomicBinary(MI, BB, 8, 0, true);
983 case Mips::ATOMIC_LOAD_SUB_I8:
984 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
985 case Mips::ATOMIC_LOAD_SUB_I16:
986 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
987 case Mips::ATOMIC_LOAD_SUB_I32:
988 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
989 case Mips::ATOMIC_LOAD_SUB_I64:
990 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
992 case Mips::ATOMIC_SWAP_I8:
993 return emitAtomicBinaryPartword(MI, BB, 1, 0);
994 case Mips::ATOMIC_SWAP_I16:
995 return emitAtomicBinaryPartword(MI, BB, 2, 0);
996 case Mips::ATOMIC_SWAP_I32:
997 return emitAtomicBinary(MI, BB, 4, 0);
998 case Mips::ATOMIC_SWAP_I64:
999 return emitAtomicBinary(MI, BB, 8, 0);
1001 case Mips::ATOMIC_CMP_SWAP_I8:
1002 return emitAtomicCmpSwapPartword(MI, BB, 1);
1003 case Mips::ATOMIC_CMP_SWAP_I16:
1004 return emitAtomicCmpSwapPartword(MI, BB, 2);
1005 case Mips::ATOMIC_CMP_SWAP_I32:
1006 return emitAtomicCmpSwap(MI, BB, 4);
1007 case Mips::ATOMIC_CMP_SWAP_I64:
1008 return emitAtomicCmpSwap(MI, BB, 8);
1009 case Mips::PseudoSDIV:
1010 case Mips::PseudoUDIV:
1015 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), false);
1016 case Mips::PseudoDSDIV:
1017 case Mips::PseudoDUDIV:
1022 return insertDivByZeroTrap(MI, *BB, *Subtarget.getInstrInfo(), true);
1024 return emitSEL_D(MI, BB);
1026 case Mips::PseudoSELECT_I:
1027 case Mips::PseudoSELECT_I64:
1028 case Mips::PseudoSELECT_S:
1029 case Mips::PseudoSELECT_D32:
1030 case Mips::PseudoSELECT_D64:
1031 return emitPseudoSELECT(MI, BB, false, Mips::BNE);
1032 case Mips::PseudoSELECTFP_F_I:
1033 case Mips::PseudoSELECTFP_F_I64:
1034 case Mips::PseudoSELECTFP_F_S:
1035 case Mips::PseudoSELECTFP_F_D32:
1036 case Mips::PseudoSELECTFP_F_D64:
1037 return emitPseudoSELECT(MI, BB, true, Mips::BC1F);
1038 case Mips::PseudoSELECTFP_T_I:
1039 case Mips::PseudoSELECTFP_T_I64:
1040 case Mips::PseudoSELECTFP_T_S:
1041 case Mips::PseudoSELECTFP_T_D32:
1042 case Mips::PseudoSELECTFP_T_D64:
1043 return emitPseudoSELECT(MI, BB, true, Mips::BC1T);
1047 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1048 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1050 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1051 unsigned Size, unsigned BinOpcode,
1053 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1055 MachineFunction *MF = BB->getParent();
1056 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1057 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1058 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1059 DebugLoc DL = MI->getDebugLoc();
1060 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1067 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1068 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1075 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1076 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1079 ZERO = Mips::ZERO_64;
1083 unsigned OldVal = MI->getOperand(0).getReg();
1084 unsigned Ptr = MI->getOperand(1).getReg();
1085 unsigned Incr = MI->getOperand(2).getReg();
1087 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1088 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1089 unsigned Success = RegInfo.createVirtualRegister(RC);
1091 // insert new blocks after the current block
1092 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1093 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1094 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1095 MachineFunction::iterator It = ++BB->getIterator();
1096 MF->insert(It, loopMBB);
1097 MF->insert(It, exitMBB);
1099 // Transfer the remainder of BB and its successor edges to exitMBB.
1100 exitMBB->splice(exitMBB->begin(), BB,
1101 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1102 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1106 // fallthrough --> loopMBB
1107 BB->addSuccessor(loopMBB);
1108 loopMBB->addSuccessor(loopMBB);
1109 loopMBB->addSuccessor(exitMBB);
1112 // ll oldval, 0(ptr)
1113 // <binop> storeval, oldval, incr
1114 // sc success, storeval, 0(ptr)
1115 // beq success, $0, loopMBB
1117 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1119 // and andres, oldval, incr
1120 // nor storeval, $0, andres
1121 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1122 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1123 } else if (BinOpcode) {
1124 // <binop> storeval, oldval, incr
1125 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1129 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1130 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1132 MI->eraseFromParent(); // The instruction is gone now.
1137 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1138 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1139 unsigned SrcReg) const {
1140 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1141 DebugLoc DL = MI->getDebugLoc();
1143 if (Subtarget.hasMips32r2() && Size == 1) {
1144 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1148 if (Subtarget.hasMips32r2() && Size == 2) {
1149 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1153 MachineFunction *MF = BB->getParent();
1154 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1155 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1156 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1159 int64_t ShiftImm = 32 - (Size * 8);
1161 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1162 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1167 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1168 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1170 assert((Size == 1 || Size == 2) &&
1171 "Unsupported size for EmitAtomicBinaryPartial.");
1173 MachineFunction *MF = BB->getParent();
1174 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1175 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1176 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1177 DebugLoc DL = MI->getDebugLoc();
1179 unsigned Dest = MI->getOperand(0).getReg();
1180 unsigned Ptr = MI->getOperand(1).getReg();
1181 unsigned Incr = MI->getOperand(2).getReg();
1183 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1184 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1185 unsigned Mask = RegInfo.createVirtualRegister(RC);
1186 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1187 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1188 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1189 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1190 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1191 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1192 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1193 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1194 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1195 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1196 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1197 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1198 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1199 unsigned Success = RegInfo.createVirtualRegister(RC);
1201 // insert new blocks after the current block
1202 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1203 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1204 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1205 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1206 MachineFunction::iterator It = ++BB->getIterator();
1207 MF->insert(It, loopMBB);
1208 MF->insert(It, sinkMBB);
1209 MF->insert(It, exitMBB);
1211 // Transfer the remainder of BB and its successor edges to exitMBB.
1212 exitMBB->splice(exitMBB->begin(), BB,
1213 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1214 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1216 BB->addSuccessor(loopMBB);
1217 loopMBB->addSuccessor(loopMBB);
1218 loopMBB->addSuccessor(sinkMBB);
1219 sinkMBB->addSuccessor(exitMBB);
1222 // addiu masklsb2,$0,-4 # 0xfffffffc
1223 // and alignedaddr,ptr,masklsb2
1224 // andi ptrlsb2,ptr,3
1225 // sll shiftamt,ptrlsb2,3
1226 // ori maskupper,$0,255 # 0xff
1227 // sll mask,maskupper,shiftamt
1228 // nor mask2,$0,mask
1229 // sll incr2,incr,shiftamt
1231 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1232 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1233 .addReg(Mips::ZERO).addImm(-4);
1234 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1235 .addReg(Ptr).addReg(MaskLSB2);
1236 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1237 if (Subtarget.isLittle()) {
1238 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1240 unsigned Off = RegInfo.createVirtualRegister(RC);
1241 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1242 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1243 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1245 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1246 .addReg(Mips::ZERO).addImm(MaskImm);
1247 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1248 .addReg(MaskUpper).addReg(ShiftAmt);
1249 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1250 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1252 // atomic.load.binop
1254 // ll oldval,0(alignedaddr)
1255 // binop binopres,oldval,incr2
1256 // and newval,binopres,mask
1257 // and maskedoldval0,oldval,mask2
1258 // or storeval,maskedoldval0,newval
1259 // sc success,storeval,0(alignedaddr)
1260 // beq success,$0,loopMBB
1264 // ll oldval,0(alignedaddr)
1265 // and newval,incr2,mask
1266 // and maskedoldval0,oldval,mask2
1267 // or storeval,maskedoldval0,newval
1268 // sc success,storeval,0(alignedaddr)
1269 // beq success,$0,loopMBB
1272 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1273 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1275 // and andres, oldval, incr2
1276 // nor binopres, $0, andres
1277 // and newval, binopres, mask
1278 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1279 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1280 .addReg(Mips::ZERO).addReg(AndRes);
1281 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1282 } else if (BinOpcode) {
1283 // <binop> binopres, oldval, incr2
1284 // and newval, binopres, mask
1285 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1286 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1287 } else { // atomic.swap
1288 // and newval, incr2, mask
1289 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1292 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1293 .addReg(OldVal).addReg(Mask2);
1294 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1295 .addReg(MaskedOldVal0).addReg(NewVal);
1296 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1297 BuildMI(BB, DL, TII->get(SC), Success)
1298 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1299 BuildMI(BB, DL, TII->get(Mips::BEQ))
1300 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1303 // and maskedoldval1,oldval,mask
1304 // srl srlres,maskedoldval1,shiftamt
1305 // sign_extend dest,srlres
1308 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1309 .addReg(OldVal).addReg(Mask);
1310 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1311 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1312 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1314 MI->eraseFromParent(); // The instruction is gone now.
1319 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1320 MachineBasicBlock *BB,
1321 unsigned Size) const {
1322 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1324 MachineFunction *MF = BB->getParent();
1325 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1326 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1327 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1328 DebugLoc DL = MI->getDebugLoc();
1329 unsigned LL, SC, ZERO, BNE, BEQ;
1332 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1333 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1340 ZERO = Mips::ZERO_64;
1345 unsigned Dest = MI->getOperand(0).getReg();
1346 unsigned Ptr = MI->getOperand(1).getReg();
1347 unsigned OldVal = MI->getOperand(2).getReg();
1348 unsigned NewVal = MI->getOperand(3).getReg();
1350 unsigned Success = RegInfo.createVirtualRegister(RC);
1352 // insert new blocks after the current block
1353 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1354 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1355 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1356 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1357 MachineFunction::iterator It = ++BB->getIterator();
1358 MF->insert(It, loop1MBB);
1359 MF->insert(It, loop2MBB);
1360 MF->insert(It, exitMBB);
1362 // Transfer the remainder of BB and its successor edges to exitMBB.
1363 exitMBB->splice(exitMBB->begin(), BB,
1364 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1365 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1369 // fallthrough --> loop1MBB
1370 BB->addSuccessor(loop1MBB);
1371 loop1MBB->addSuccessor(exitMBB);
1372 loop1MBB->addSuccessor(loop2MBB);
1373 loop2MBB->addSuccessor(loop1MBB);
1374 loop2MBB->addSuccessor(exitMBB);
1378 // bne dest, oldval, exitMBB
1380 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1381 BuildMI(BB, DL, TII->get(BNE))
1382 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1385 // sc success, newval, 0(ptr)
1386 // beq success, $0, loop1MBB
1388 BuildMI(BB, DL, TII->get(SC), Success)
1389 .addReg(NewVal).addReg(Ptr).addImm(0);
1390 BuildMI(BB, DL, TII->get(BEQ))
1391 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1393 MI->eraseFromParent(); // The instruction is gone now.
1399 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1400 MachineBasicBlock *BB,
1401 unsigned Size) const {
1402 assert((Size == 1 || Size == 2) &&
1403 "Unsupported size for EmitAtomicCmpSwapPartial.");
1405 MachineFunction *MF = BB->getParent();
1406 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1407 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1408 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1409 DebugLoc DL = MI->getDebugLoc();
1411 unsigned Dest = MI->getOperand(0).getReg();
1412 unsigned Ptr = MI->getOperand(1).getReg();
1413 unsigned CmpVal = MI->getOperand(2).getReg();
1414 unsigned NewVal = MI->getOperand(3).getReg();
1416 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1417 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1418 unsigned Mask = RegInfo.createVirtualRegister(RC);
1419 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1420 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1421 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1422 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1423 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1424 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1425 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1426 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1427 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1428 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1429 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1430 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1431 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1432 unsigned Success = RegInfo.createVirtualRegister(RC);
1434 // insert new blocks after the current block
1435 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1436 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1437 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1438 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1439 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1440 MachineFunction::iterator It = ++BB->getIterator();
1441 MF->insert(It, loop1MBB);
1442 MF->insert(It, loop2MBB);
1443 MF->insert(It, sinkMBB);
1444 MF->insert(It, exitMBB);
1446 // Transfer the remainder of BB and its successor edges to exitMBB.
1447 exitMBB->splice(exitMBB->begin(), BB,
1448 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1449 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1451 BB->addSuccessor(loop1MBB);
1452 loop1MBB->addSuccessor(sinkMBB);
1453 loop1MBB->addSuccessor(loop2MBB);
1454 loop2MBB->addSuccessor(loop1MBB);
1455 loop2MBB->addSuccessor(sinkMBB);
1456 sinkMBB->addSuccessor(exitMBB);
1458 // FIXME: computation of newval2 can be moved to loop2MBB.
1460 // addiu masklsb2,$0,-4 # 0xfffffffc
1461 // and alignedaddr,ptr,masklsb2
1462 // andi ptrlsb2,ptr,3
1463 // sll shiftamt,ptrlsb2,3
1464 // ori maskupper,$0,255 # 0xff
1465 // sll mask,maskupper,shiftamt
1466 // nor mask2,$0,mask
1467 // andi maskedcmpval,cmpval,255
1468 // sll shiftedcmpval,maskedcmpval,shiftamt
1469 // andi maskednewval,newval,255
1470 // sll shiftednewval,maskednewval,shiftamt
1471 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1472 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1473 .addReg(Mips::ZERO).addImm(-4);
1474 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1475 .addReg(Ptr).addReg(MaskLSB2);
1476 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1477 if (Subtarget.isLittle()) {
1478 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1480 unsigned Off = RegInfo.createVirtualRegister(RC);
1481 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1482 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1483 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1485 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1486 .addReg(Mips::ZERO).addImm(MaskImm);
1487 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1488 .addReg(MaskUpper).addReg(ShiftAmt);
1489 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1490 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1491 .addReg(CmpVal).addImm(MaskImm);
1492 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1493 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1494 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1495 .addReg(NewVal).addImm(MaskImm);
1496 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1497 .addReg(MaskedNewVal).addReg(ShiftAmt);
1500 // ll oldval,0(alginedaddr)
1501 // and maskedoldval0,oldval,mask
1502 // bne maskedoldval0,shiftedcmpval,sinkMBB
1504 unsigned LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1505 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1506 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1507 .addReg(OldVal).addReg(Mask);
1508 BuildMI(BB, DL, TII->get(Mips::BNE))
1509 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1512 // and maskedoldval1,oldval,mask2
1513 // or storeval,maskedoldval1,shiftednewval
1514 // sc success,storeval,0(alignedaddr)
1515 // beq success,$0,loop1MBB
1517 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1518 .addReg(OldVal).addReg(Mask2);
1519 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1520 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1521 unsigned SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1522 BuildMI(BB, DL, TII->get(SC), Success)
1523 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1524 BuildMI(BB, DL, TII->get(Mips::BEQ))
1525 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1528 // srl srlres,maskedoldval0,shiftamt
1529 // sign_extend dest,srlres
1532 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1533 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1534 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1536 MI->eraseFromParent(); // The instruction is gone now.
1541 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1542 MachineBasicBlock *BB) const {
1543 MachineFunction *MF = BB->getParent();
1544 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
1545 const TargetInstrInfo *TII = Subtarget.getInstrInfo();
1546 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1547 DebugLoc DL = MI->getDebugLoc();
1548 MachineBasicBlock::iterator II(MI);
1550 unsigned Fc = MI->getOperand(1).getReg();
1551 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1553 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1555 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1558 .addImm(Mips::sub_lo);
1560 // We don't erase the original instruction, we just replace the condition
1561 // register with the 64-bit super-register.
1562 MI->getOperand(1).setReg(Fc2);
1567 //===----------------------------------------------------------------------===//
1568 // Misc Lower Operation implementation
1569 //===----------------------------------------------------------------------===//
1570 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1571 SDValue Chain = Op.getOperand(0);
1572 SDValue Table = Op.getOperand(1);
1573 SDValue Index = Op.getOperand(2);
1575 auto &TD = DAG.getDataLayout();
1576 EVT PTy = getPointerTy(TD);
1577 unsigned EntrySize =
1578 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(TD);
1580 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1581 DAG.getConstant(EntrySize, DL, PTy));
1582 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1584 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1586 DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1587 MachinePointerInfo::getJumpTable(DAG.getMachineFunction()),
1588 MemVT, false, false, false, 0);
1589 Chain = Addr.getValue(1);
1591 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || ABI.IsN64()) {
1592 // For PIC, the sequence is:
1593 // BRIND(load(Jumptable + index) + RelocBase)
1594 // RelocBase can be JumpTable, GOT or some sort of global base.
1595 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1596 getPICJumpTableRelocBase(Table, DAG));
1599 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1602 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1603 // The first operand is the chain, the second is the condition, the third is
1604 // the block to branch to if the condition is true.
1605 SDValue Chain = Op.getOperand(0);
1606 SDValue Dest = Op.getOperand(2);
1609 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1610 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1612 // Return if flag is not set by a floating point comparison.
1613 if (CondRes.getOpcode() != MipsISD::FPCmp)
1616 SDValue CCNode = CondRes.getOperand(2);
1618 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1619 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1620 SDValue BrCode = DAG.getConstant(Opc, DL, MVT::i32);
1621 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1622 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1623 FCC0, Dest, CondRes);
1626 SDValue MipsTargetLowering::
1627 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1629 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1630 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1632 // Return if flag is not set by a floating point comparison.
1633 if (Cond.getOpcode() != MipsISD::FPCmp)
1636 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1640 SDValue MipsTargetLowering::
1641 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1644 EVT Ty = Op.getOperand(0).getValueType();
1646 DAG.getNode(ISD::SETCC, DL, getSetCCResultType(DAG.getDataLayout(),
1647 *DAG.getContext(), Ty),
1648 Op.getOperand(0), Op.getOperand(1), Op.getOperand(4));
1650 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1654 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1655 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1656 SDValue Cond = createFPCmp(DAG, Op);
1658 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1659 "Floating point operand expected.");
1662 SDValue True = DAG.getConstant(1, DL, MVT::i32);
1663 SDValue False = DAG.getConstant(0, DL, MVT::i32);
1665 return createCMovFP(DAG, Cond, True, False, DL);
1668 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1669 SelectionDAG &DAG) const {
1670 EVT Ty = Op.getValueType();
1671 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1672 const GlobalValue *GV = N->getGlobal();
1674 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1675 const MipsTargetObjectFile *TLOF =
1676 static_cast<const MipsTargetObjectFile *>(
1677 getTargetMachine().getObjFileLowering());
1678 if (TLOF->IsGlobalInSmallSection(GV, getTargetMachine()))
1679 // %gp_rel relocation
1680 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1682 // %hi/%lo relocation
1683 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1686 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1687 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1690 return getAddrGlobalLargeGOT(
1691 N, SDLoc(N), Ty, DAG, MipsII::MO_GOT_HI16, MipsII::MO_GOT_LO16,
1693 MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1695 return getAddrGlobal(
1696 N, SDLoc(N), Ty, DAG,
1697 (ABI.IsN32() || ABI.IsN64()) ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16,
1698 DAG.getEntryNode(), MachinePointerInfo::getGOT(DAG.getMachineFunction()));
1701 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1702 SelectionDAG &DAG) const {
1703 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1704 EVT Ty = Op.getValueType();
1706 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1707 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1709 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1712 SDValue MipsTargetLowering::
1713 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1715 // If the relocation model is PIC, use the General Dynamic TLS Model or
1716 // Local Dynamic TLS model, otherwise use the Initial Exec or
1717 // Local Exec TLS Model.
1719 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1720 if (DAG.getTarget().Options.EmulatedTLS)
1721 return LowerToTLSEmulatedModel(GA, DAG);
1724 const GlobalValue *GV = GA->getGlobal();
1725 EVT PtrVT = getPointerTy(DAG.getDataLayout());
1727 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1729 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1730 // General Dynamic and Local Dynamic TLS Model.
1731 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1734 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1735 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1736 getGlobalReg(DAG, PtrVT), TGA);
1737 unsigned PtrSize = PtrVT.getSizeInBits();
1738 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1740 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1744 Entry.Node = Argument;
1746 Args.push_back(Entry);
1748 TargetLowering::CallLoweringInfo CLI(DAG);
1749 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1750 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1751 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1753 SDValue Ret = CallResult.first;
1755 if (model != TLSModel::LocalDynamic)
1758 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1759 MipsII::MO_DTPREL_HI);
1760 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1761 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1762 MipsII::MO_DTPREL_LO);
1763 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1764 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1765 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1769 if (model == TLSModel::InitialExec) {
1770 // Initial Exec TLS Model
1771 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1772 MipsII::MO_GOTTPREL);
1773 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1775 Offset = DAG.getLoad(PtrVT, DL,
1776 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1777 false, false, false, 0);
1779 // Local Exec TLS Model
1780 assert(model == TLSModel::LocalExec);
1781 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1782 MipsII::MO_TPREL_HI);
1783 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1784 MipsII::MO_TPREL_LO);
1785 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1786 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1787 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1790 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1791 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1794 SDValue MipsTargetLowering::
1795 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1797 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1798 EVT Ty = Op.getValueType();
1800 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64())
1801 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1803 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1806 SDValue MipsTargetLowering::
1807 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1809 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1810 EVT Ty = Op.getValueType();
1812 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !ABI.IsN64()) {
1813 const MipsTargetObjectFile *TLOF =
1814 static_cast<const MipsTargetObjectFile *>(
1815 getTargetMachine().getObjFileLowering());
1817 if (TLOF->IsConstantInSmallSection(DAG.getDataLayout(), N->getConstVal(),
1818 getTargetMachine()))
1819 // %gp_rel relocation
1820 return getAddrGPRel(N, SDLoc(N), Ty, DAG);
1822 return getAddrNonPIC(N, SDLoc(N), Ty, DAG);
1825 return getAddrLocal(N, SDLoc(N), Ty, DAG, ABI.IsN32() || ABI.IsN64());
1828 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1829 MachineFunction &MF = DAG.getMachineFunction();
1830 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1833 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1834 getPointerTy(MF.getDataLayout()));
1836 // vastart just stores the address of the VarArgsFrameIndex slot into the
1837 // memory location argument.
1838 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1839 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1840 MachinePointerInfo(SV), false, false, 0);
1843 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1844 SDNode *Node = Op.getNode();
1845 EVT VT = Node->getValueType(0);
1846 SDValue Chain = Node->getOperand(0);
1847 SDValue VAListPtr = Node->getOperand(1);
1848 unsigned Align = Node->getConstantOperandVal(3);
1849 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1851 unsigned ArgSlotSizeInBytes = (ABI.IsN32() || ABI.IsN64()) ? 8 : 4;
1853 SDValue VAListLoad =
1854 DAG.getLoad(getPointerTy(DAG.getDataLayout()), DL, Chain, VAListPtr,
1855 MachinePointerInfo(SV), false, false, false, 0);
1856 SDValue VAList = VAListLoad;
1858 // Re-align the pointer if necessary.
1859 // It should only ever be necessary for 64-bit types on O32 since the minimum
1860 // argument alignment is the same as the maximum type alignment for N32/N64.
1862 // FIXME: We currently align too often. The code generator doesn't notice
1863 // when the pointer is still aligned from the last va_arg (or pair of
1864 // va_args for the i64 on O32 case).
1865 if (Align > getMinStackArgumentAlignment()) {
1866 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1868 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1869 DAG.getConstant(Align - 1, DL, VAList.getValueType()));
1871 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1872 DAG.getConstant(-(int64_t)Align, DL,
1873 VAList.getValueType()));
1876 // Increment the pointer, VAList, to the next vaarg.
1877 auto &TD = DAG.getDataLayout();
1878 unsigned ArgSizeInBytes =
1879 TD.getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1880 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1881 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes,
1882 ArgSlotSizeInBytes),
1883 DL, VAList.getValueType()));
1884 // Store the incremented VAList to the legalized pointer
1885 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1886 MachinePointerInfo(SV), false, false, 0);
1888 // In big-endian mode we must adjust the pointer when the load size is smaller
1889 // than the argument slot size. We must also reduce the known alignment to
1890 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1891 // the correct half of the slot, and reduce the alignment from 8 (slot
1892 // alignment) down to 4 (type alignment).
1893 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1894 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1895 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1896 DAG.getIntPtrConstant(Adjustment, DL));
1898 // Load the actual argument out of the pointer VAList
1899 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1903 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1904 bool HasExtractInsert) {
1905 EVT TyX = Op.getOperand(0).getValueType();
1906 EVT TyY = Op.getOperand(1).getValueType();
1908 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1909 SDValue Const31 = DAG.getConstant(31, DL, MVT::i32);
1912 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1914 SDValue X = (TyX == MVT::f32) ?
1915 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1916 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1918 SDValue Y = (TyY == MVT::f32) ?
1919 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1920 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1923 if (HasExtractInsert) {
1924 // ext E, Y, 31, 1 ; extract bit31 of Y
1925 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1926 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1927 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1930 // srl SrlX, SllX, 1
1932 // sll SllY, SrlX, 31
1933 // or Or, SrlX, SllY
1934 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1935 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1936 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1937 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1938 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1941 if (TyX == MVT::f32)
1942 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1944 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1946 DAG.getConstant(0, DL, MVT::i32));
1947 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1950 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1951 bool HasExtractInsert) {
1952 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1953 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1954 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1956 SDValue Const1 = DAG.getConstant(1, DL, MVT::i32);
1958 // Bitcast to integer nodes.
1959 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1960 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1962 if (HasExtractInsert) {
1963 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1964 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1965 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1966 DAG.getConstant(WidthY - 1, DL, MVT::i32), Const1);
1968 if (WidthX > WidthY)
1969 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1970 else if (WidthY > WidthX)
1971 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1973 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1974 DAG.getConstant(WidthX - 1, DL, MVT::i32), Const1,
1976 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1979 // (d)sll SllX, X, 1
1980 // (d)srl SrlX, SllX, 1
1981 // (d)srl SrlY, Y, width(Y)-1
1982 // (d)sll SllY, SrlX, width(Y)-1
1983 // or Or, SrlX, SllY
1984 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1985 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1986 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1987 DAG.getConstant(WidthY - 1, DL, MVT::i32));
1989 if (WidthX > WidthY)
1990 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1991 else if (WidthY > WidthX)
1992 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1994 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1995 DAG.getConstant(WidthX - 1, DL, MVT::i32));
1996 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1997 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2001 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2002 if (Subtarget.isGP64bit())
2003 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2005 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2008 SDValue MipsTargetLowering::
2009 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2011 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2012 "Frame address can only be determined for current frame.");
2014 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2015 MFI->setFrameAddressIsTaken(true);
2016 EVT VT = Op.getValueType();
2018 SDValue FrameAddr = DAG.getCopyFromReg(
2019 DAG.getEntryNode(), DL, ABI.IsN64() ? Mips::FP_64 : Mips::FP, VT);
2023 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2024 SelectionDAG &DAG) const {
2025 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2029 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2030 "Return address can be determined only for current frame.");
2032 MachineFunction &MF = DAG.getMachineFunction();
2033 MachineFrameInfo *MFI = MF.getFrameInfo();
2034 MVT VT = Op.getSimpleValueType();
2035 unsigned RA = ABI.IsN64() ? Mips::RA_64 : Mips::RA;
2036 MFI->setReturnAddressIsTaken(true);
2038 // Return RA, which contains the return address. Mark it an implicit live-in.
2039 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2040 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2043 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2044 // generated from __builtin_eh_return (offset, handler)
2045 // The effect of this is to adjust the stack pointer by "offset"
2046 // and then branch to "handler".
2047 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2049 MachineFunction &MF = DAG.getMachineFunction();
2050 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2052 MipsFI->setCallsEhReturn();
2053 SDValue Chain = Op.getOperand(0);
2054 SDValue Offset = Op.getOperand(1);
2055 SDValue Handler = Op.getOperand(2);
2057 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2059 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2060 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2061 unsigned OffsetReg = ABI.IsN64() ? Mips::V1_64 : Mips::V1;
2062 unsigned AddrReg = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
2063 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2064 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2065 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2066 DAG.getRegister(OffsetReg, Ty),
2067 DAG.getRegister(AddrReg, getPointerTy(MF.getDataLayout())),
2071 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2072 SelectionDAG &DAG) const {
2073 // FIXME: Need pseudo-fence for 'singlethread' fences
2074 // FIXME: Set SType for weaker fences where supported/appropriate.
2077 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2078 DAG.getConstant(SType, DL, MVT::i32));
2081 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2082 SelectionDAG &DAG) const {
2084 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2086 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2087 SDValue Shamt = Op.getOperand(2);
2088 // if shamt < (VT.bits):
2089 // lo = (shl lo, shamt)
2090 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2093 // hi = (shl lo, shamt[4:0])
2094 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2095 DAG.getConstant(-1, DL, MVT::i32));
2096 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo,
2097 DAG.getConstant(1, DL, VT));
2098 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, Not);
2099 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
2100 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2101 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
2102 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2103 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2104 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2105 DAG.getConstant(0, DL, VT), ShiftLeftLo);
2106 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftLeftLo, Or);
2108 SDValue Ops[2] = {Lo, Hi};
2109 return DAG.getMergeValues(Ops, DL);
2112 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2115 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2116 SDValue Shamt = Op.getOperand(2);
2117 MVT VT = Subtarget.isGP64bit() ? MVT::i64 : MVT::i32;
2119 // if shamt < (VT.bits):
2120 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2122 // hi = (sra hi, shamt)
2124 // hi = (srl hi, shamt)
2127 // lo = (sra hi, shamt[4:0])
2128 // hi = (sra hi, 31)
2130 // lo = (srl hi, shamt[4:0])
2132 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2133 DAG.getConstant(-1, DL, MVT::i32));
2134 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, VT, Hi,
2135 DAG.getConstant(1, DL, VT));
2136 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, ShiftLeft1Hi, Not);
2137 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
2138 SDValue Or = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
2139 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL,
2141 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2142 DAG.getConstant(VT.getSizeInBits(), DL, MVT::i32));
2143 SDValue Ext = DAG.getNode(ISD::SRA, DL, VT, Hi,
2144 DAG.getConstant(VT.getSizeInBits() - 1, DL, VT));
2145 Lo = DAG.getNode(ISD::SELECT, DL, VT, Cond, ShiftRightHi, Or);
2146 Hi = DAG.getNode(ISD::SELECT, DL, VT, Cond,
2147 IsSRA ? Ext : DAG.getConstant(0, DL, VT), ShiftRightHi);
2149 SDValue Ops[2] = {Lo, Hi};
2150 return DAG.getMergeValues(Ops, DL);
2153 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2154 SDValue Chain, SDValue Src, unsigned Offset) {
2155 SDValue Ptr = LD->getBasePtr();
2156 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2157 EVT BasePtrVT = Ptr.getValueType();
2159 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2162 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2163 DAG.getConstant(Offset, DL, BasePtrVT));
2165 SDValue Ops[] = { Chain, Ptr, Src };
2166 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2167 LD->getMemOperand());
2170 // Expand an unaligned 32 or 64-bit integer load node.
2171 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2172 LoadSDNode *LD = cast<LoadSDNode>(Op);
2173 EVT MemVT = LD->getMemoryVT();
2175 if (Subtarget.systemSupportsUnalignedAccess())
2178 // Return if load is aligned or if MemVT is neither i32 nor i64.
2179 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2180 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2183 bool IsLittle = Subtarget.isLittle();
2184 EVT VT = Op.getValueType();
2185 ISD::LoadExtType ExtType = LD->getExtensionType();
2186 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2188 assert((VT == MVT::i32) || (VT == MVT::i64));
2191 // (set dst, (i64 (load baseptr)))
2193 // (set tmp, (ldl (add baseptr, 7), undef))
2194 // (set dst, (ldr baseptr, tmp))
2195 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2196 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2198 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2202 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2204 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2208 // (set dst, (i32 (load baseptr))) or
2209 // (set dst, (i64 (sextload baseptr))) or
2210 // (set dst, (i64 (extload baseptr)))
2212 // (set tmp, (lwl (add baseptr, 3), undef))
2213 // (set dst, (lwr baseptr, tmp))
2214 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2215 (ExtType == ISD::EXTLOAD))
2218 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2221 // (set dst, (i64 (zextload baseptr)))
2223 // (set tmp0, (lwl (add baseptr, 3), undef))
2224 // (set tmp1, (lwr baseptr, tmp0))
2225 // (set tmp2, (shl tmp1, 32))
2226 // (set dst, (srl tmp2, 32))
2228 SDValue Const32 = DAG.getConstant(32, DL, MVT::i32);
2229 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2230 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2231 SDValue Ops[] = { SRL, LWR.getValue(1) };
2232 return DAG.getMergeValues(Ops, DL);
2235 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2236 SDValue Chain, unsigned Offset) {
2237 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2238 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2240 SDVTList VTList = DAG.getVTList(MVT::Other);
2243 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2244 DAG.getConstant(Offset, DL, BasePtrVT));
2246 SDValue Ops[] = { Chain, Value, Ptr };
2247 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2248 SD->getMemOperand());
2251 // Expand an unaligned 32 or 64-bit integer store node.
2252 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2254 SDValue Value = SD->getValue(), Chain = SD->getChain();
2255 EVT VT = Value.getValueType();
2258 // (store val, baseptr) or
2259 // (truncstore val, baseptr)
2261 // (swl val, (add baseptr, 3))
2262 // (swr val, baseptr)
2263 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2264 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2266 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2269 assert(VT == MVT::i64);
2272 // (store val, baseptr)
2274 // (sdl val, (add baseptr, 7))
2275 // (sdr val, baseptr)
2276 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2277 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2280 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2281 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2282 SDValue Val = SD->getValue();
2284 if (Val.getOpcode() != ISD::FP_TO_SINT)
2287 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2288 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2291 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2292 SD->getPointerInfo(), SD->isVolatile(),
2293 SD->isNonTemporal(), SD->getAlignment());
2296 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2297 StoreSDNode *SD = cast<StoreSDNode>(Op);
2298 EVT MemVT = SD->getMemoryVT();
2300 // Lower unaligned integer stores.
2301 if (!Subtarget.systemSupportsUnalignedAccess() &&
2302 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2303 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2304 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2306 return lowerFP_TO_SINT_STORE(SD, DAG);
2309 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2310 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2311 || cast<ConstantSDNode>
2312 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2313 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2317 // (add (frameaddr 0), (frame_to_args_offset))
2318 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2319 // (add FrameObject, 0)
2320 // where FrameObject is a fixed StackObject with offset 0 which points to
2321 // the old stack pointer.
2322 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2323 EVT ValTy = Op->getValueType(0);
2324 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2325 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2327 return DAG.getNode(ISD::ADD, DL, ValTy, InArgsAddr,
2328 DAG.getConstant(0, DL, ValTy));
2331 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2332 SelectionDAG &DAG) const {
2333 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2334 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2336 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2339 //===----------------------------------------------------------------------===//
2340 // Calling Convention Implementation
2341 //===----------------------------------------------------------------------===//
2343 //===----------------------------------------------------------------------===//
2344 // TODO: Implement a generic logic using tblgen that can support this.
2345 // Mips O32 ABI rules:
2347 // i32 - Passed in A0, A1, A2, A3 and stack
2348 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2349 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2350 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2351 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2352 // not used, it must be shadowed. If only A3 is available, shadow it and
2355 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2356 //===----------------------------------------------------------------------===//
2358 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2359 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2360 CCState &State, ArrayRef<MCPhysReg> F64Regs) {
2361 const MipsSubtarget &Subtarget = static_cast<const MipsSubtarget &>(
2362 State.getMachineFunction().getSubtarget());
2364 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2365 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2367 // Do not process byval args here.
2368 if (ArgFlags.isByVal())
2371 // Promote i8 and i16
2372 if (ArgFlags.isInReg() && !Subtarget.isLittle()) {
2373 if (LocVT == MVT::i8 || LocVT == MVT::i16 || LocVT == MVT::i32) {
2375 if (ArgFlags.isSExt())
2376 LocInfo = CCValAssign::SExtUpper;
2377 else if (ArgFlags.isZExt())
2378 LocInfo = CCValAssign::ZExtUpper;
2380 LocInfo = CCValAssign::AExtUpper;
2384 // Promote i8 and i16
2385 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2387 if (ArgFlags.isSExt())
2388 LocInfo = CCValAssign::SExt;
2389 else if (ArgFlags.isZExt())
2390 LocInfo = CCValAssign::ZExt;
2392 LocInfo = CCValAssign::AExt;
2397 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2398 // is true: function is vararg, argument is 3rd or higher, there is previous
2399 // argument which is not f32 or f64.
2400 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1 ||
2401 State.getFirstUnallocated(F32Regs) != ValNo;
2402 unsigned OrigAlign = ArgFlags.getOrigAlign();
2403 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2405 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2406 Reg = State.AllocateReg(IntRegs);
2407 // If this is the first part of an i64 arg,
2408 // the allocated register must be either A0 or A2.
2409 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2410 Reg = State.AllocateReg(IntRegs);
2412 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2413 // Allocate int register and shadow next int register. If first
2414 // available register is Mips::A1 or Mips::A3, shadow it too.
2415 Reg = State.AllocateReg(IntRegs);
2416 if (Reg == Mips::A1 || Reg == Mips::A3)
2417 Reg = State.AllocateReg(IntRegs);
2418 State.AllocateReg(IntRegs);
2420 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2421 // we are guaranteed to find an available float register
2422 if (ValVT == MVT::f32) {
2423 Reg = State.AllocateReg(F32Regs);
2424 // Shadow int register
2425 State.AllocateReg(IntRegs);
2427 Reg = State.AllocateReg(F64Regs);
2428 // Shadow int registers
2429 unsigned Reg2 = State.AllocateReg(IntRegs);
2430 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2431 State.AllocateReg(IntRegs);
2432 State.AllocateReg(IntRegs);
2435 llvm_unreachable("Cannot handle this ValVT.");
2438 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2440 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2442 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2447 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2448 MVT LocVT, CCValAssign::LocInfo LocInfo,
2449 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2450 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2452 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2455 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2456 MVT LocVT, CCValAssign::LocInfo LocInfo,
2457 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2458 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2460 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2463 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2464 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2465 CCState &State) LLVM_ATTRIBUTE_UNUSED;
2467 #include "MipsGenCallingConv.inc"
2469 //===----------------------------------------------------------------------===//
2470 // Call Calling Convention Implementation
2471 //===----------------------------------------------------------------------===//
2473 // Return next O32 integer argument register.
2474 static unsigned getNextIntArgReg(unsigned Reg) {
2475 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2476 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2480 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2481 SDValue Chain, SDValue Arg, SDLoc DL,
2482 bool IsTailCall, SelectionDAG &DAG) const {
2485 DAG.getNode(ISD::ADD, DL, getPointerTy(DAG.getDataLayout()), StackPtr,
2486 DAG.getIntPtrConstant(Offset, DL));
2487 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2491 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2492 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2493 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
2494 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2495 /*isVolatile=*/ true, false, 0);
2498 void MipsTargetLowering::
2499 getOpndList(SmallVectorImpl<SDValue> &Ops,
2500 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2501 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2502 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2503 SDValue Chain) const {
2504 // Insert node "GP copy globalreg" before call to function.
2506 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2507 // in PIC mode) allow symbols to be resolved via lazy binding.
2508 // The lazy binding stub requires GP to point to the GOT.
2509 // Note that we don't need GP to point to the GOT for indirect calls
2510 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2511 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2512 // used for the function (that is, Mips linker doesn't generate lazy binding
2513 // stub for a function whose address is taken in the program).
2514 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2515 unsigned GPReg = ABI.IsN64() ? Mips::GP_64 : Mips::GP;
2516 EVT Ty = ABI.IsN64() ? MVT::i64 : MVT::i32;
2517 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2520 // Build a sequence of copy-to-reg nodes chained together with token
2521 // chain and flag operands which copy the outgoing args into registers.
2522 // The InFlag in necessary since all emitted instructions must be
2526 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2527 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2528 RegsToPass[i].second, InFlag);
2529 InFlag = Chain.getValue(1);
2532 // Add argument registers to the end of the list so that they are
2533 // known live into the call.
2534 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2535 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2536 RegsToPass[i].second.getValueType()));
2538 // Add a register mask operand representing the call-preserved registers.
2539 const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
2540 const uint32_t *Mask =
2541 TRI->getCallPreservedMask(CLI.DAG.getMachineFunction(), CLI.CallConv);
2542 assert(Mask && "Missing call preserved mask for calling convention");
2543 if (Subtarget.inMips16HardFloat()) {
2544 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2545 llvm::StringRef Sym = G->getGlobal()->getName();
2546 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2547 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2548 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2552 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2554 if (InFlag.getNode())
2555 Ops.push_back(InFlag);
2558 /// LowerCall - functions arguments are copied from virtual regs to
2559 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2561 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2562 SmallVectorImpl<SDValue> &InVals) const {
2563 SelectionDAG &DAG = CLI.DAG;
2565 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2566 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2567 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2568 SDValue Chain = CLI.Chain;
2569 SDValue Callee = CLI.Callee;
2570 bool &IsTailCall = CLI.IsTailCall;
2571 CallingConv::ID CallConv = CLI.CallConv;
2572 bool IsVarArg = CLI.IsVarArg;
2574 MachineFunction &MF = DAG.getMachineFunction();
2575 MachineFrameInfo *MFI = MF.getFrameInfo();
2576 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
2577 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2578 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2580 // Analyze operands of the call, assigning locations to each operand.
2581 SmallVector<CCValAssign, 16> ArgLocs;
2583 CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs, *DAG.getContext(),
2584 MipsCCState::getSpecialCallingConvForCallee(Callee.getNode(), Subtarget));
2586 // Allocate the reserved argument area. It seems strange to do this from the
2587 // caller side but removing it breaks the frame size calculation.
2588 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2590 CCInfo.AnalyzeCallOperands(Outs, CC_Mips, CLI.getArgs(), Callee.getNode());
2592 // Get a count of how many bytes are to be pushed on the stack.
2593 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2595 // Check if it's really possible to do a tail call.
2597 IsTailCall = isEligibleForTailCallOptimization(
2598 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2600 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2601 report_fatal_error("failed to perform tail call elimination on a call "
2602 "site marked musttail");
2607 // Chain is the output chain of the last Load/Store or CopyToReg node.
2608 // ByValChain is the output chain of the last Memcpy node created for copying
2609 // byval arguments to the stack.
2610 unsigned StackAlignment = TFL->getStackAlignment();
2611 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2612 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, DL, true);
2615 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2618 DAG.getCopyFromReg(Chain, DL, ABI.IsN64() ? Mips::SP_64 : Mips::SP,
2619 getPointerTy(DAG.getDataLayout()));
2621 // With EABI is it possible to have 16 args on registers.
2622 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2623 SmallVector<SDValue, 8> MemOpChains;
2625 CCInfo.rewindByValRegsInfo();
2627 // Walk the register/memloc assignments, inserting copies/loads.
2628 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2629 SDValue Arg = OutVals[i];
2630 CCValAssign &VA = ArgLocs[i];
2631 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2632 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2633 bool UseUpperBits = false;
2636 if (Flags.isByVal()) {
2637 unsigned FirstByValReg, LastByValReg;
2638 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2639 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2641 assert(Flags.getByValSize() &&
2642 "ByVal args of size 0 should have been ignored by front-end.");
2643 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2644 assert(!IsTailCall &&
2645 "Do not tail-call optimize if there is a byval argument.");
2646 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2647 FirstByValReg, LastByValReg, Flags, Subtarget.isLittle(),
2649 CCInfo.nextInRegsParam();
2653 // Promote the value if needed.
2654 switch (VA.getLocInfo()) {
2656 llvm_unreachable("Unknown loc info!");
2657 case CCValAssign::Full:
2658 if (VA.isRegLoc()) {
2659 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2660 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2661 (ValVT == MVT::i64 && LocVT == MVT::f64))
2662 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2663 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2664 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2665 Arg, DAG.getConstant(0, DL, MVT::i32));
2666 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2667 Arg, DAG.getConstant(1, DL, MVT::i32));
2668 if (!Subtarget.isLittle())
2670 unsigned LocRegLo = VA.getLocReg();
2671 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2672 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2673 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2678 case CCValAssign::BCvt:
2679 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2681 case CCValAssign::SExtUpper:
2682 UseUpperBits = true;
2684 case CCValAssign::SExt:
2685 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2687 case CCValAssign::ZExtUpper:
2688 UseUpperBits = true;
2690 case CCValAssign::ZExt:
2691 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2693 case CCValAssign::AExtUpper:
2694 UseUpperBits = true;
2696 case CCValAssign::AExt:
2697 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2702 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
2703 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2705 ISD::SHL, DL, VA.getLocVT(), Arg,
2706 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2709 // Arguments that can be passed on register must be kept at
2710 // RegsToPass vector
2711 if (VA.isRegLoc()) {
2712 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2716 // Register can't get to this point...
2717 assert(VA.isMemLoc());
2719 // emit ISD::STORE whichs stores the
2720 // parameter value to a stack Location
2721 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2722 Chain, Arg, DL, IsTailCall, DAG));
2725 // Transform all store nodes into one single node because all store
2726 // nodes are independent of each other.
2727 if (!MemOpChains.empty())
2728 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2730 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2731 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2732 // node so that legalize doesn't hack it.
2733 bool IsPICCall = (ABI.IsN64() || IsPIC); // true if calls are translated to
2735 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2737 EVT Ty = Callee.getValueType();
2739 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2741 const GlobalValue *Val = G->getGlobal();
2742 InternalLinkage = Val->hasInternalLinkage();
2744 if (InternalLinkage)
2745 Callee = getAddrLocal(G, DL, Ty, DAG, ABI.IsN32() || ABI.IsN64());
2746 else if (LargeGOT) {
2747 Callee = getAddrGlobalLargeGOT(G, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2748 MipsII::MO_CALL_LO16, Chain,
2749 FuncInfo->callPtrInfo(Val));
2752 Callee = getAddrGlobal(G, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2753 FuncInfo->callPtrInfo(Val));
2757 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL,
2758 getPointerTy(DAG.getDataLayout()), 0,
2759 MipsII::MO_NO_FLAG);
2760 GlobalOrExternal = true;
2762 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2763 const char *Sym = S->getSymbol();
2765 if (!ABI.IsN64() && !IsPIC) // !N64 && static
2766 Callee = DAG.getTargetExternalSymbol(
2767 Sym, getPointerTy(DAG.getDataLayout()), MipsII::MO_NO_FLAG);
2768 else if (LargeGOT) {
2769 Callee = getAddrGlobalLargeGOT(S, DL, Ty, DAG, MipsII::MO_CALL_HI16,
2770 MipsII::MO_CALL_LO16, Chain,
2771 FuncInfo->callPtrInfo(Sym));
2773 } else { // N64 || PIC
2774 Callee = getAddrGlobal(S, DL, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2775 FuncInfo->callPtrInfo(Sym));
2779 GlobalOrExternal = true;
2782 SmallVector<SDValue, 8> Ops(1, Chain);
2783 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2785 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2786 IsCallReloc, CLI, Callee, Chain);
2789 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2791 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2792 SDValue InFlag = Chain.getValue(1);
2794 // Create the CALLSEQ_END node.
2795 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2796 DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
2797 InFlag = Chain.getValue(1);
2799 // Handle result values, copying them out of physregs into vregs that we
2801 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2805 /// LowerCallResult - Lower the result values of a call into the
2806 /// appropriate copies out of appropriate physical registers.
2807 SDValue MipsTargetLowering::LowerCallResult(
2808 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2809 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2810 SmallVectorImpl<SDValue> &InVals,
2811 TargetLowering::CallLoweringInfo &CLI) const {
2812 // Assign locations to each value returned by this call.
2813 SmallVector<CCValAssign, 16> RVLocs;
2814 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2816 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2818 // Copy all of the result registers out of their specified physreg.
2819 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2820 CCValAssign &VA = RVLocs[i];
2821 assert(VA.isRegLoc() && "Can only return in registers!");
2823 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2824 RVLocs[i].getLocVT(), InFlag);
2825 Chain = Val.getValue(1);
2826 InFlag = Val.getValue(2);
2828 if (VA.isUpperBitsInLoc()) {
2829 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2830 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2832 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2834 Shift, DL, VA.getLocVT(), Val,
2835 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2838 switch (VA.getLocInfo()) {
2840 llvm_unreachable("Unknown loc info!");
2841 case CCValAssign::Full:
2843 case CCValAssign::BCvt:
2844 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2846 case CCValAssign::AExt:
2847 case CCValAssign::AExtUpper:
2848 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2850 case CCValAssign::ZExt:
2851 case CCValAssign::ZExtUpper:
2852 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2853 DAG.getValueType(VA.getValVT()));
2854 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2856 case CCValAssign::SExt:
2857 case CCValAssign::SExtUpper:
2858 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2859 DAG.getValueType(VA.getValVT()));
2860 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2864 InVals.push_back(Val);
2870 static SDValue UnpackFromArgumentSlot(SDValue Val, const CCValAssign &VA,
2871 EVT ArgVT, SDLoc DL, SelectionDAG &DAG) {
2872 MVT LocVT = VA.getLocVT();
2873 EVT ValVT = VA.getValVT();
2875 // Shift into the upper bits if necessary.
2876 switch (VA.getLocInfo()) {
2879 case CCValAssign::AExtUpper:
2880 case CCValAssign::SExtUpper:
2881 case CCValAssign::ZExtUpper: {
2882 unsigned ValSizeInBits = ArgVT.getSizeInBits();
2883 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2885 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2887 Opcode, DL, VA.getLocVT(), Val,
2888 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
2893 // If this is an value smaller than the argument slot size (32-bit for O32,
2894 // 64-bit for N32/N64), it has been promoted in some way to the argument slot
2895 // size. Extract the value and insert any appropriate assertions regarding
2896 // sign/zero extension.
2897 switch (VA.getLocInfo()) {
2899 llvm_unreachable("Unknown loc info!");
2900 case CCValAssign::Full:
2902 case CCValAssign::AExtUpper:
2903 case CCValAssign::AExt:
2904 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2906 case CCValAssign::SExtUpper:
2907 case CCValAssign::SExt:
2908 Val = DAG.getNode(ISD::AssertSext, DL, LocVT, Val, DAG.getValueType(ValVT));
2909 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2911 case CCValAssign::ZExtUpper:
2912 case CCValAssign::ZExt:
2913 Val = DAG.getNode(ISD::AssertZext, DL, LocVT, Val, DAG.getValueType(ValVT));
2914 Val = DAG.getNode(ISD::TRUNCATE, DL, ValVT, Val);
2916 case CCValAssign::BCvt:
2917 Val = DAG.getNode(ISD::BITCAST, DL, ValVT, Val);
2924 //===----------------------------------------------------------------------===//
2925 // Formal Arguments Calling Convention Implementation
2926 //===----------------------------------------------------------------------===//
2927 /// LowerFormalArguments - transform physical registers into virtual registers
2928 /// and generate load operations for arguments places on the stack.
2930 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2931 CallingConv::ID CallConv,
2933 const SmallVectorImpl<ISD::InputArg> &Ins,
2934 SDLoc DL, SelectionDAG &DAG,
2935 SmallVectorImpl<SDValue> &InVals)
2937 MachineFunction &MF = DAG.getMachineFunction();
2938 MachineFrameInfo *MFI = MF.getFrameInfo();
2939 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2941 MipsFI->setVarArgsFrameIndex(0);
2943 // Used with vargs to acumulate store chains.
2944 std::vector<SDValue> OutChains;
2946 // Assign locations to all of the incoming arguments.
2947 SmallVector<CCValAssign, 16> ArgLocs;
2948 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2950 CCInfo.AllocateStack(ABI.GetCalleeAllocdArgSizeInBytes(CallConv), 1);
2951 Function::const_arg_iterator FuncArg =
2952 DAG.getMachineFunction().getFunction()->arg_begin();
2954 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2955 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2956 CCInfo.getInRegsParamsCount() > 0);
2958 unsigned CurArgIdx = 0;
2959 CCInfo.rewindByValRegsInfo();
2961 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2962 CCValAssign &VA = ArgLocs[i];
2963 if (Ins[i].isOrigArg()) {
2964 std::advance(FuncArg, Ins[i].getOrigArgIndex() - CurArgIdx);
2965 CurArgIdx = Ins[i].getOrigArgIndex();
2967 EVT ValVT = VA.getValVT();
2968 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2969 bool IsRegLoc = VA.isRegLoc();
2971 if (Flags.isByVal()) {
2972 assert(Ins[i].isOrigArg() && "Byval arguments cannot be implicit");
2973 unsigned FirstByValReg, LastByValReg;
2974 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2975 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2977 assert(Flags.getByValSize() &&
2978 "ByVal args of size 0 should have been ignored by front-end.");
2979 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2980 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2981 FirstByValReg, LastByValReg, VA, CCInfo);
2982 CCInfo.nextInRegsParam();
2986 // Arguments stored on registers
2988 MVT RegVT = VA.getLocVT();
2989 unsigned ArgReg = VA.getLocReg();
2990 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2992 // Transform the arguments stored on
2993 // physical registers into virtual ones
2994 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2995 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2997 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
2999 // Handle floating point arguments passed in integer registers and
3000 // long double arguments passed in floating point registers.
3001 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3002 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3003 (RegVT == MVT::f64 && ValVT == MVT::i64))
3004 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3005 else if (ABI.IsO32() && RegVT == MVT::i32 &&
3006 ValVT == MVT::f64) {
3007 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3008 getNextIntArgReg(ArgReg), RC);
3009 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3010 if (!Subtarget.isLittle())
3011 std::swap(ArgValue, ArgValue2);
3012 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3013 ArgValue, ArgValue2);
3016 InVals.push_back(ArgValue);
3017 } else { // VA.isRegLoc()
3018 MVT LocVT = VA.getLocVT();
3021 // We ought to be able to use LocVT directly but O32 sets it to i32
3022 // when allocating floating point values to integer registers.
3023 // This shouldn't influence how we load the value into registers unless
3024 // we are targeting softfloat.
3025 if (VA.getValVT().isFloatingPoint() && !Subtarget.useSoftFloat())
3026 LocVT = VA.getValVT();
3030 assert(VA.isMemLoc());
3032 // The stack pointer offset is relative to the caller stack frame.
3033 int FI = MFI->CreateFixedObject(LocVT.getSizeInBits() / 8,
3034 VA.getLocMemOffset(), true);
3036 // Create load nodes to retrieve arguments from the stack
3037 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3038 SDValue ArgValue = DAG.getLoad(
3039 LocVT, DL, Chain, FIN,
3040 MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
3041 false, false, false, 0);
3042 OutChains.push_back(ArgValue.getValue(1));
3044 ArgValue = UnpackFromArgumentSlot(ArgValue, VA, Ins[i].ArgVT, DL, DAG);
3046 InVals.push_back(ArgValue);
3050 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3051 // The mips ABIs for returning structs by value requires that we copy
3052 // the sret argument into $v0 for the return. Save the argument into
3053 // a virtual register so that we can access it from the return points.
3054 if (Ins[i].Flags.isSRet()) {
3055 unsigned Reg = MipsFI->getSRetReturnReg();
3057 Reg = MF.getRegInfo().createVirtualRegister(
3058 getRegClassFor(ABI.IsN64() ? MVT::i64 : MVT::i32));
3059 MipsFI->setSRetReturnReg(Reg);
3061 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3062 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3068 writeVarArgRegs(OutChains, Chain, DL, DAG, CCInfo);
3070 // All stores are grouped in one node to allow the matching between
3071 // the size of Ins and InVals. This only happens when on varg functions
3072 if (!OutChains.empty()) {
3073 OutChains.push_back(Chain);
3074 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3080 //===----------------------------------------------------------------------===//
3081 // Return Value Calling Convention Implementation
3082 //===----------------------------------------------------------------------===//
3085 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3086 MachineFunction &MF, bool IsVarArg,
3087 const SmallVectorImpl<ISD::OutputArg> &Outs,
3088 LLVMContext &Context) const {
3089 SmallVector<CCValAssign, 16> RVLocs;
3090 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3091 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3095 MipsTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
3096 if (Subtarget.hasMips3() && Subtarget.useSoftFloat()) {
3097 if (Type == MVT::i32)
3104 MipsTargetLowering::LowerReturn(SDValue Chain,
3105 CallingConv::ID CallConv, bool IsVarArg,
3106 const SmallVectorImpl<ISD::OutputArg> &Outs,
3107 const SmallVectorImpl<SDValue> &OutVals,
3108 SDLoc DL, SelectionDAG &DAG) const {
3109 // CCValAssign - represent the assignment of
3110 // the return value to a location
3111 SmallVector<CCValAssign, 16> RVLocs;
3112 MachineFunction &MF = DAG.getMachineFunction();
3114 // CCState - Info about the registers and stack slot.
3115 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3117 // Analyze return values.
3118 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3121 SmallVector<SDValue, 4> RetOps(1, Chain);
3123 // Copy the result values into the output registers.
3124 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3125 SDValue Val = OutVals[i];
3126 CCValAssign &VA = RVLocs[i];
3127 assert(VA.isRegLoc() && "Can only return in registers!");
3128 bool UseUpperBits = false;
3130 switch (VA.getLocInfo()) {
3132 llvm_unreachable("Unknown loc info!");
3133 case CCValAssign::Full:
3135 case CCValAssign::BCvt:
3136 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3138 case CCValAssign::AExtUpper:
3139 UseUpperBits = true;
3141 case CCValAssign::AExt:
3142 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3144 case CCValAssign::ZExtUpper:
3145 UseUpperBits = true;
3147 case CCValAssign::ZExt:
3148 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3150 case CCValAssign::SExtUpper:
3151 UseUpperBits = true;
3153 case CCValAssign::SExt:
3154 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3159 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3160 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3162 ISD::SHL, DL, VA.getLocVT(), Val,
3163 DAG.getConstant(LocSizeInBits - ValSizeInBits, DL, VA.getLocVT()));
3166 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3168 // Guarantee that all emitted copies are stuck together with flags.
3169 Flag = Chain.getValue(1);
3170 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3173 // The mips ABIs for returning structs by value requires that we copy
3174 // the sret argument into $v0 for the return. We saved the argument into
3175 // a virtual register in the entry block, so now we copy the value out
3177 if (MF.getFunction()->hasStructRetAttr()) {
3178 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3179 unsigned Reg = MipsFI->getSRetReturnReg();
3182 llvm_unreachable("sret virtual register not created in the entry block");
3184 DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy(DAG.getDataLayout()));
3185 unsigned V0 = ABI.IsN64() ? Mips::V0_64 : Mips::V0;
3187 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3188 Flag = Chain.getValue(1);
3189 RetOps.push_back(DAG.getRegister(V0, getPointerTy(DAG.getDataLayout())));
3192 RetOps[0] = Chain; // Update chain.
3194 // Add the flag if we have it.
3196 RetOps.push_back(Flag);
3198 // Return on Mips is always a "jr $ra"
3199 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3202 //===----------------------------------------------------------------------===//
3203 // Mips Inline Assembly Support
3204 //===----------------------------------------------------------------------===//
3206 /// getConstraintType - Given a constraint letter, return the type of
3207 /// constraint it is for this target.
3208 MipsTargetLowering::ConstraintType
3209 MipsTargetLowering::getConstraintType(StringRef Constraint) const {
3210 // Mips specific constraints
3211 // GCC config/mips/constraints.md
3213 // 'd' : An address register. Equivalent to r
3214 // unless generating MIPS16 code.
3215 // 'y' : Equivalent to r; retained for
3216 // backwards compatibility.
3217 // 'c' : A register suitable for use in an indirect
3218 // jump. This will always be $25 for -mabicalls.
3219 // 'l' : The lo register. 1 word storage.
3220 // 'x' : The hilo register pair. Double word storage.
3221 if (Constraint.size() == 1) {
3222 switch (Constraint[0]) {
3230 return C_RegisterClass;
3236 if (Constraint == "ZC")
3239 return TargetLowering::getConstraintType(Constraint);
3242 /// Examine constraint type and operand type and determine a weight value.
3243 /// This object must already have been set up with the operand type
3244 /// and the current alternative constraint selected.
3245 TargetLowering::ConstraintWeight
3246 MipsTargetLowering::getSingleConstraintMatchWeight(
3247 AsmOperandInfo &info, const char *constraint) const {
3248 ConstraintWeight weight = CW_Invalid;
3249 Value *CallOperandVal = info.CallOperandVal;
3250 // If we don't have a value, we can't do a match,
3251 // but allow it at the lowest weight.
3252 if (!CallOperandVal)
3254 Type *type = CallOperandVal->getType();
3255 // Look at the constraint type.
3256 switch (*constraint) {
3258 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3262 if (type->isIntegerTy())
3263 weight = CW_Register;
3265 case 'f': // FPU or MSA register
3266 if (Subtarget.hasMSA() && type->isVectorTy() &&
3267 cast<VectorType>(type)->getBitWidth() == 128)
3268 weight = CW_Register;
3269 else if (type->isFloatTy())
3270 weight = CW_Register;
3272 case 'c': // $25 for indirect jumps
3273 case 'l': // lo register
3274 case 'x': // hilo register pair
3275 if (type->isIntegerTy())
3276 weight = CW_SpecificReg;
3278 case 'I': // signed 16 bit immediate
3279 case 'J': // integer zero
3280 case 'K': // unsigned 16 bit immediate
3281 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3282 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3283 case 'O': // signed 15 bit immediate (+- 16383)
3284 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3285 if (isa<ConstantInt>(CallOperandVal))
3286 weight = CW_Constant;
3295 /// This is a helper function to parse a physical register string and split it
3296 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3297 /// that is returned indicates whether parsing was successful. The second flag
3298 /// is true if the numeric part exists.
3299 static std::pair<bool, bool> parsePhysicalReg(StringRef C, StringRef &Prefix,
3300 unsigned long long &Reg) {
3301 if (C.front() != '{' || C.back() != '}')
3302 return std::make_pair(false, false);
3304 // Search for the first numeric character.
3305 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3306 I = std::find_if(B, E, std::ptr_fun(isdigit));
3308 Prefix = StringRef(B, I - B);
3310 // The second flag is set to false if no numeric characters were found.
3312 return std::make_pair(true, false);
3314 // Parse the numeric characters.
3315 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3319 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3320 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3321 const TargetRegisterInfo *TRI =
3322 Subtarget.getRegisterInfo();
3323 const TargetRegisterClass *RC;
3325 unsigned long long Reg;
3327 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3330 return std::make_pair(0U, nullptr);
3332 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3333 // No numeric characters follow "hi" or "lo".
3335 return std::make_pair(0U, nullptr);
3337 RC = TRI->getRegClass(Prefix == "hi" ?
3338 Mips::HI32RegClassID : Mips::LO32RegClassID);
3339 return std::make_pair(*(RC->begin()), RC);
3340 } else if (Prefix.startswith("$msa")) {
3341 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3343 // No numeric characters follow the name.
3345 return std::make_pair(0U, nullptr);
3347 Reg = StringSwitch<unsigned long long>(Prefix)
3348 .Case("$msair", Mips::MSAIR)
3349 .Case("$msacsr", Mips::MSACSR)
3350 .Case("$msaaccess", Mips::MSAAccess)
3351 .Case("$msasave", Mips::MSASave)
3352 .Case("$msamodify", Mips::MSAModify)
3353 .Case("$msarequest", Mips::MSARequest)
3354 .Case("$msamap", Mips::MSAMap)
3355 .Case("$msaunmap", Mips::MSAUnmap)
3359 return std::make_pair(0U, nullptr);
3361 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3362 return std::make_pair(Reg, RC);
3366 return std::make_pair(0U, nullptr);
3368 if (Prefix == "$f") { // Parse $f0-$f31.
3369 // If the size of FP registers is 64-bit or Reg is an even number, select
3370 // the 64-bit register class. Otherwise, select the 32-bit register class.
3371 if (VT == MVT::Other)
3372 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3374 RC = getRegClassFor(VT);
3376 if (RC == &Mips::AFGR64RegClass) {
3377 assert(Reg % 2 == 0);
3380 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3381 RC = TRI->getRegClass(Mips::FCCRegClassID);
3382 else if (Prefix == "$w") { // Parse $w0-$w31.
3383 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3384 } else { // Parse $0-$31.
3385 assert(Prefix == "$");
3386 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3389 assert(Reg < RC->getNumRegs());
3390 return std::make_pair(*(RC->begin() + Reg), RC);
3393 /// Given a register class constraint, like 'r', if this corresponds directly
3394 /// to an LLVM register class, return a register of 0 and the register class
3396 std::pair<unsigned, const TargetRegisterClass *>
3397 MipsTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
3398 StringRef Constraint,
3400 if (Constraint.size() == 1) {
3401 switch (Constraint[0]) {
3402 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3403 case 'y': // Same as 'r'. Exists for compatibility.
3405 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3406 if (Subtarget.inMips16Mode())
3407 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3408 return std::make_pair(0U, &Mips::GPR32RegClass);
3410 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3411 return std::make_pair(0U, &Mips::GPR32RegClass);
3412 if (VT == MVT::i64 && Subtarget.isGP64bit())
3413 return std::make_pair(0U, &Mips::GPR64RegClass);
3414 // This will generate an error message
3415 return std::make_pair(0U, nullptr);
3416 case 'f': // FPU or MSA register
3417 if (VT == MVT::v16i8)
3418 return std::make_pair(0U, &Mips::MSA128BRegClass);
3419 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3420 return std::make_pair(0U, &Mips::MSA128HRegClass);
3421 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3422 return std::make_pair(0U, &Mips::MSA128WRegClass);
3423 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3424 return std::make_pair(0U, &Mips::MSA128DRegClass);
3425 else if (VT == MVT::f32)
3426 return std::make_pair(0U, &Mips::FGR32RegClass);
3427 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3428 if (Subtarget.isFP64bit())
3429 return std::make_pair(0U, &Mips::FGR64RegClass);
3430 return std::make_pair(0U, &Mips::AFGR64RegClass);
3433 case 'c': // register suitable for indirect jump
3435 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3436 assert(VT == MVT::i64 && "Unexpected type.");
3437 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3438 case 'l': // register suitable for indirect jump
3440 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3441 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3442 case 'x': // register suitable for indirect jump
3443 // Fixme: Not triggering the use of both hi and low
3444 // This will generate an error message
3445 return std::make_pair(0U, nullptr);
3449 std::pair<unsigned, const TargetRegisterClass *> R;
3450 R = parseRegForInlineAsmConstraint(Constraint, VT);
3455 return TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
3458 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3459 /// vector. If it is invalid, don't add anything to Ops.
3460 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3461 std::string &Constraint,
3462 std::vector<SDValue>&Ops,
3463 SelectionDAG &DAG) const {
3467 // Only support length 1 constraints for now.
3468 if (Constraint.length() > 1) return;
3470 char ConstraintLetter = Constraint[0];
3471 switch (ConstraintLetter) {
3472 default: break; // This will fall through to the generic implementation
3473 case 'I': // Signed 16 bit constant
3474 // If this fails, the parent routine will give an error
3475 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3476 EVT Type = Op.getValueType();
3477 int64_t Val = C->getSExtValue();
3478 if (isInt<16>(Val)) {
3479 Result = DAG.getTargetConstant(Val, DL, Type);
3484 case 'J': // integer zero
3485 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3486 EVT Type = Op.getValueType();
3487 int64_t Val = C->getZExtValue();
3489 Result = DAG.getTargetConstant(0, DL, Type);
3494 case 'K': // unsigned 16 bit immediate
3495 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3496 EVT Type = Op.getValueType();
3497 uint64_t Val = (uint64_t)C->getZExtValue();
3498 if (isUInt<16>(Val)) {
3499 Result = DAG.getTargetConstant(Val, DL, Type);
3504 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3505 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3506 EVT Type = Op.getValueType();
3507 int64_t Val = C->getSExtValue();
3508 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3509 Result = DAG.getTargetConstant(Val, DL, Type);
3514 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3515 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3516 EVT Type = Op.getValueType();
3517 int64_t Val = C->getSExtValue();
3518 if ((Val >= -65535) && (Val <= -1)) {
3519 Result = DAG.getTargetConstant(Val, DL, Type);
3524 case 'O': // signed 15 bit immediate
3525 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3526 EVT Type = Op.getValueType();
3527 int64_t Val = C->getSExtValue();
3528 if ((isInt<15>(Val))) {
3529 Result = DAG.getTargetConstant(Val, DL, Type);
3534 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3535 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3536 EVT Type = Op.getValueType();
3537 int64_t Val = C->getSExtValue();
3538 if ((Val <= 65535) && (Val >= 1)) {
3539 Result = DAG.getTargetConstant(Val, DL, Type);
3546 if (Result.getNode()) {
3547 Ops.push_back(Result);
3551 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3554 bool MipsTargetLowering::isLegalAddressingMode(const DataLayout &DL,
3555 const AddrMode &AM, Type *Ty,
3556 unsigned AS) const {
3557 // No global is ever allowed as a base.
3562 case 0: // "r+i" or just "i", depending on HasBaseReg.
3565 if (!AM.HasBaseReg) // allow "r+i".
3567 return false; // disallow "r+r" or "r+r+i".
3576 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3577 // The Mips target isn't yet aware of offsets.
3581 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3583 bool IsMemset, bool ZeroMemset,
3585 MachineFunction &MF) const {
3586 if (Subtarget.hasMips64())
3592 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3593 if (VT != MVT::f32 && VT != MVT::f64)
3595 if (Imm.isNegZero())
3597 return Imm.isZero();
3600 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3602 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3604 return TargetLowering::getJumpTableEncoding();
3607 bool MipsTargetLowering::useSoftFloat() const {
3608 return Subtarget.useSoftFloat();
3611 void MipsTargetLowering::copyByValRegs(
3612 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3613 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3614 const Argument *FuncArg, unsigned FirstReg, unsigned LastReg,
3615 const CCValAssign &VA, MipsCCState &State) const {
3616 MachineFunction &MF = DAG.getMachineFunction();
3617 MachineFrameInfo *MFI = MF.getFrameInfo();
3618 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3619 unsigned NumRegs = LastReg - FirstReg;
3620 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3621 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3623 ArrayRef<MCPhysReg> ByValArgRegs = ABI.GetByValArgRegs();
3627 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3628 (int)((ByValArgRegs.size() - FirstReg) * GPRSizeInBytes);
3630 FrameObjOffset = VA.getLocMemOffset();
3632 // Create frame object.
3633 EVT PtrTy = getPointerTy(DAG.getDataLayout());
3634 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3635 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3636 InVals.push_back(FIN);
3641 // Copy arg registers.
3642 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3643 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3645 for (unsigned I = 0; I < NumRegs; ++I) {
3646 unsigned ArgReg = ByValArgRegs[FirstReg + I];
3647 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3648 unsigned Offset = I * GPRSizeInBytes;
3649 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3650 DAG.getConstant(Offset, DL, PtrTy));
3651 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3652 StorePtr, MachinePointerInfo(FuncArg, Offset),
3654 OutChains.push_back(Store);
3658 // Copy byVal arg to registers and stack.
3659 void MipsTargetLowering::passByValArg(
3660 SDValue Chain, SDLoc DL,
3661 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3662 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3663 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, unsigned FirstReg,
3664 unsigned LastReg, const ISD::ArgFlagsTy &Flags, bool isLittle,
3665 const CCValAssign &VA) const {
3666 unsigned ByValSizeInBytes = Flags.getByValSize();
3667 unsigned OffsetInBytes = 0; // From beginning of struct
3668 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3669 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3670 EVT PtrTy = getPointerTy(DAG.getDataLayout()),
3671 RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3672 unsigned NumRegs = LastReg - FirstReg;
3675 ArrayRef<MCPhysReg> ArgRegs = ABI.GetByValArgRegs();
3676 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3679 // Copy words to registers.
3680 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3681 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3682 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3683 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3684 MachinePointerInfo(), false, false, false,
3686 MemOpChains.push_back(LoadVal.getValue(1));
3687 unsigned ArgReg = ArgRegs[FirstReg + I];
3688 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3691 // Return if the struct has been fully copied.
3692 if (ByValSizeInBytes == OffsetInBytes)
3695 // Copy the remainder of the byval argument with sub-word loads and shifts.
3696 if (LeftoverBytes) {
3699 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3700 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3701 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3703 if (RemainingSizeInBytes < LoadSizeInBytes)
3707 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3708 DAG.getConstant(OffsetInBytes, DL,
3710 SDValue LoadVal = DAG.getExtLoad(
3711 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3712 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3714 MemOpChains.push_back(LoadVal.getValue(1));
3716 // Shift the loaded value.
3720 Shamt = TotalBytesLoaded * 8;
3722 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3724 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3725 DAG.getConstant(Shamt, DL, MVT::i32));
3728 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3732 OffsetInBytes += LoadSizeInBytes;
3733 TotalBytesLoaded += LoadSizeInBytes;
3734 Alignment = std::min(Alignment, LoadSizeInBytes);
3737 unsigned ArgReg = ArgRegs[FirstReg + I];
3738 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3743 // Copy remainder of byval arg to it with memcpy.
3744 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3745 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3746 DAG.getConstant(OffsetInBytes, DL, PtrTy));
3747 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3748 DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
3749 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3750 DAG.getConstant(MemCpySize, DL, PtrTy),
3751 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3752 /*isTailCall=*/false,
3753 MachinePointerInfo(), MachinePointerInfo());
3754 MemOpChains.push_back(Chain);
3757 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3758 SDValue Chain, SDLoc DL,
3760 CCState &State) const {
3761 ArrayRef<MCPhysReg> ArgRegs = ABI.GetVarArgRegs();
3762 unsigned Idx = State.getFirstUnallocated(ArgRegs);
3763 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3764 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3765 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3766 MachineFunction &MF = DAG.getMachineFunction();
3767 MachineFrameInfo *MFI = MF.getFrameInfo();
3768 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3770 // Offset of the first variable argument from stack pointer.
3773 if (ArgRegs.size() == Idx)
3775 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3778 (int)ABI.GetCalleeAllocdArgSizeInBytes(State.getCallingConv()) -
3779 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3782 // Record the frame index of the first variable argument
3783 // which is a value necessary to VASTART.
3784 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3785 MipsFI->setVarArgsFrameIndex(FI);
3787 // Copy the integer registers that have not been used for argument passing
3788 // to the argument register save area. For O32, the save area is allocated
3789 // in the caller's stack frame, while for N32/64, it is allocated in the
3790 // callee's stack frame.
3791 for (unsigned I = Idx; I < ArgRegs.size();
3792 ++I, VaArgOffset += RegSizeInBytes) {
3793 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3794 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3795 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3796 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
3797 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3798 MachinePointerInfo(), false, false, 0);
3799 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3801 OutChains.push_back(Store);
3805 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3806 unsigned Align) const {
3807 const TargetFrameLowering *TFL = Subtarget.getFrameLowering();
3809 assert(Size && "Byval argument's size shouldn't be 0.");
3811 Align = std::min(Align, TFL->getStackAlignment());
3813 unsigned FirstReg = 0;
3814 unsigned NumRegs = 0;
3816 if (State->getCallingConv() != CallingConv::Fast) {
3817 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3818 ArrayRef<MCPhysReg> IntArgRegs = ABI.GetByValArgRegs();
3819 // FIXME: The O32 case actually describes no shadow registers.
3820 const MCPhysReg *ShadowRegs =
3821 ABI.IsO32() ? IntArgRegs.data() : Mips64DPRegs;
3823 // We used to check the size as well but we can't do that anymore since
3824 // CCState::HandleByVal() rounds up the size after calling this function.
3825 assert(!(Align % RegSizeInBytes) &&
3826 "Byval argument's alignment should be a multiple of"
3829 FirstReg = State->getFirstUnallocated(IntArgRegs);
3831 // If Align > RegSizeInBytes, the first arg register must be even.
3832 // FIXME: This condition happens to do the right thing but it's not the
3833 // right way to test it. We want to check that the stack frame offset
3834 // of the register is aligned.
3835 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3836 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3840 // Mark the registers allocated.
3841 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3842 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3843 Size -= RegSizeInBytes, ++I, ++NumRegs)
3844 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3847 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);
3851 MipsTargetLowering::emitPseudoSELECT(MachineInstr *MI, MachineBasicBlock *BB,
3852 bool isFPCmp, unsigned Opc) const {
3853 assert(!(Subtarget.hasMips4() || Subtarget.hasMips32()) &&
3854 "Subtarget already supports SELECT nodes with the use of"
3855 "conditional-move instructions.");
3857 const TargetInstrInfo *TII =
3858 Subtarget.getInstrInfo();
3859 DebugLoc DL = MI->getDebugLoc();
3861 // To "insert" a SELECT instruction, we actually have to insert the
3862 // diamond control-flow pattern. The incoming instruction knows the
3863 // destination vreg to set, the condition code register to branch on, the
3864 // true/false values to select between, and a branch opcode to use.
3865 const BasicBlock *LLVM_BB = BB->getBasicBlock();
3866 MachineFunction::iterator It = ++BB->getIterator();
3872 // bNE r1, r0, copy1MBB
3873 // fallthrough --> copy0MBB
3874 MachineBasicBlock *thisMBB = BB;
3875 MachineFunction *F = BB->getParent();
3876 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
3877 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
3878 F->insert(It, copy0MBB);
3879 F->insert(It, sinkMBB);
3881 // Transfer the remainder of BB and its successor edges to sinkMBB.
3882 sinkMBB->splice(sinkMBB->begin(), BB,
3883 std::next(MachineBasicBlock::iterator(MI)), BB->end());
3884 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
3886 // Next, add the true and fallthrough blocks as its successors.
3887 BB->addSuccessor(copy0MBB);
3888 BB->addSuccessor(sinkMBB);
3891 // bc1[tf] cc, sinkMBB
3892 BuildMI(BB, DL, TII->get(Opc))
3893 .addReg(MI->getOperand(1).getReg())
3896 // bne rs, $0, sinkMBB
3897 BuildMI(BB, DL, TII->get(Opc))
3898 .addReg(MI->getOperand(1).getReg())
3904 // %FalseValue = ...
3905 // # fallthrough to sinkMBB
3908 // Update machine-CFG edges
3909 BB->addSuccessor(sinkMBB);
3912 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
3916 BuildMI(*BB, BB->begin(), DL,
3917 TII->get(Mips::PHI), MI->getOperand(0).getReg())
3918 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
3919 .addReg(MI->getOperand(3).getReg()).addMBB(copy0MBB);
3921 MI->eraseFromParent(); // The pseudo instruction is gone now.
3926 // FIXME? Maybe this could be a TableGen attribute on some registers and
3927 // this table could be generated automatically from RegInfo.
3928 unsigned MipsTargetLowering::getRegisterByName(const char* RegName, EVT VT,
3929 SelectionDAG &DAG) const {
3930 // Named registers is expected to be fairly rare. For now, just support $28
3931 // since the linux kernel uses it.
3932 if (Subtarget.isGP64bit()) {
3933 unsigned Reg = StringSwitch<unsigned>(RegName)
3934 .Case("$28", Mips::GP_64)
3939 unsigned Reg = StringSwitch<unsigned>(RegName)
3940 .Case("$28", Mips::GP)
3945 report_fatal_error("Invalid register name global variable");