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 "MipsMachineFunction.h"
18 #include "MipsSubtarget.h"
19 #include "MipsTargetMachine.h"
20 #include "MipsTargetObjectFile.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineJumpTableInfo.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
42 #define DEBUG_TYPE "mips-lower"
44 STATISTIC(NumTailCalls, "Number of tail calls");
47 LargeGOT("mxgot", cl::Hidden,
48 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
51 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
52 cl::desc("MIPS: Don't trap on integer division by zero."),
56 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
57 cl::desc("Allow mips-fast-isel to be used"),
60 static const MCPhysReg O32IntRegs[4] = {
61 Mips::A0, Mips::A1, Mips::A2, Mips::A3
64 static const MCPhysReg Mips64IntRegs[8] = {
65 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
66 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
69 static const MCPhysReg Mips64DPRegs[8] = {
70 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
71 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
74 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode);
77 class MipsCCState : public CCState {
79 /// Identify lowered values that originated from f128 arguments and record
80 /// this for use by RetCC_MipsN.
82 PreAnalyzeCallResultForF128(const SmallVectorImpl<ISD::InputArg> &Ins,
83 const TargetLowering::CallLoweringInfo &CLI) {
84 for (unsigned i = 0; i < Ins.size(); ++i)
85 OriginalArgWasF128.push_back(
86 originalTypeIsF128(CLI.RetTy, CLI.Callee.getNode()));
89 /// Identify lowered values that originated from f128 arguments and record
90 /// this for use by RetCC_MipsN.
91 void PreAnalyzeReturnForF128(const SmallVectorImpl<ISD::OutputArg> &Outs) {
92 const MachineFunction &MF = getMachineFunction();
93 for (unsigned i = 0; i < Outs.size(); ++i)
94 OriginalArgWasF128.push_back(
95 originalTypeIsF128(MF.getFunction()->getReturnType(), nullptr));
98 /// Identify lowered values that originated from f128 arguments and record
100 void PreAnalyzeCallOperandsForF128(
101 const SmallVectorImpl<ISD::OutputArg> &Outs,
102 std::vector<TargetLowering::ArgListEntry> &FuncArgs, SDNode *CallNode) {
103 for (unsigned i = 0; i < Outs.size(); ++i)
104 OriginalArgWasF128.push_back(
105 originalTypeIsF128(FuncArgs[Outs[i].OrigArgIndex].Ty, CallNode));
108 /// Identify lowered values that originated from f128 arguments and record
111 PreAnalyzeFormalArgumentsForF128(const SmallVectorImpl<ISD::InputArg> &Ins) {
112 const MachineFunction &MF = getMachineFunction();
113 for (unsigned i = 0; i < Ins.size(); ++i) {
114 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
116 // SRet arguments cannot originate from f128 or {f128} returns so we just
117 // push false. We have to handle this specially since SRet arguments
118 // aren't mapped to an original argument.
119 if (Ins[i].Flags.isSRet()) {
120 OriginalArgWasF128.push_back(false);
124 assert(Ins[i].OrigArgIndex < MF.getFunction()->arg_size());
125 std::advance(FuncArg, Ins[i].OrigArgIndex);
126 OriginalArgWasF128.push_back(
127 originalTypeIsF128(FuncArg->getType(), nullptr));
131 /// Records whether the value has been lowered from an f128.
132 SmallVector<bool, 4> OriginalArgWasF128;
135 // FIXME: Remove this from a public inteface ASAP. It's a temporary trap door
136 // to allow analyzeCallOperands to be removed incrementally.
137 void PreAnalyzeCallOperandsForF128_(
138 const SmallVectorImpl<ISD::OutputArg> &Outs,
139 std::vector<TargetLowering::ArgListEntry> &FuncArgs, SDNode *CallNode) {
140 PreAnalyzeCallOperandsForF128(Outs, FuncArgs, CallNode);
142 // FIXME: Remove this from a public inteface ASAP. It's a temporary trap door
143 // to clean up after the above functions.
144 void ClearOriginalArgWasF128() { OriginalArgWasF128.clear(); }
146 MipsCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
147 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C)
148 : CCState(CC, isVarArg, MF, locs, C) {}
150 void AnalyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Ins,
152 PreAnalyzeFormalArgumentsForF128(Ins);
153 CCState::AnalyzeFormalArguments(Ins, Fn);
154 OriginalArgWasF128.clear();
157 void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
159 const TargetLowering::CallLoweringInfo &CLI) {
160 PreAnalyzeCallResultForF128(Ins, CLI);
161 CCState::AnalyzeCallResult(Ins, Fn);
162 OriginalArgWasF128.clear();
165 void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
167 PreAnalyzeReturnForF128(Outs);
168 CCState::AnalyzeReturn(Outs, Fn);
169 OriginalArgWasF128.clear();
172 bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags,
174 PreAnalyzeReturnForF128(ArgsFlags);
175 bool Return = CCState::CheckReturn(ArgsFlags, Fn);
176 OriginalArgWasF128.clear();
180 bool WasOriginalArgF128(unsigned ValNo) { return OriginalArgWasF128[ValNo]; }
184 // If I is a shifted mask, set the size (Size) and the first bit of the
185 // mask (Pos), and return true.
186 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
187 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
188 if (!isShiftedMask_64(I))
191 Size = CountPopulation_64(I);
192 Pos = countTrailingZeros(I);
196 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
197 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
198 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
201 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
203 unsigned Flag) const {
204 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
207 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
209 unsigned Flag) const {
210 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
213 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
215 unsigned Flag) const {
216 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
219 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
221 unsigned Flag) const {
222 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
225 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
227 unsigned Flag) const {
228 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
229 N->getOffset(), Flag);
232 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
234 case MipsISD::JmpLink: return "MipsISD::JmpLink";
235 case MipsISD::TailCall: return "MipsISD::TailCall";
236 case MipsISD::Hi: return "MipsISD::Hi";
237 case MipsISD::Lo: return "MipsISD::Lo";
238 case MipsISD::GPRel: return "MipsISD::GPRel";
239 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
240 case MipsISD::Ret: return "MipsISD::Ret";
241 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
242 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
243 case MipsISD::FPCmp: return "MipsISD::FPCmp";
244 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
245 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
246 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
247 case MipsISD::MFHI: return "MipsISD::MFHI";
248 case MipsISD::MFLO: return "MipsISD::MFLO";
249 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
250 case MipsISD::Mult: return "MipsISD::Mult";
251 case MipsISD::Multu: return "MipsISD::Multu";
252 case MipsISD::MAdd: return "MipsISD::MAdd";
253 case MipsISD::MAddu: return "MipsISD::MAddu";
254 case MipsISD::MSub: return "MipsISD::MSub";
255 case MipsISD::MSubu: return "MipsISD::MSubu";
256 case MipsISD::DivRem: return "MipsISD::DivRem";
257 case MipsISD::DivRemU: return "MipsISD::DivRemU";
258 case MipsISD::DivRem16: return "MipsISD::DivRem16";
259 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
260 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
261 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
262 case MipsISD::Wrapper: return "MipsISD::Wrapper";
263 case MipsISD::Sync: return "MipsISD::Sync";
264 case MipsISD::Ext: return "MipsISD::Ext";
265 case MipsISD::Ins: return "MipsISD::Ins";
266 case MipsISD::LWL: return "MipsISD::LWL";
267 case MipsISD::LWR: return "MipsISD::LWR";
268 case MipsISD::SWL: return "MipsISD::SWL";
269 case MipsISD::SWR: return "MipsISD::SWR";
270 case MipsISD::LDL: return "MipsISD::LDL";
271 case MipsISD::LDR: return "MipsISD::LDR";
272 case MipsISD::SDL: return "MipsISD::SDL";
273 case MipsISD::SDR: return "MipsISD::SDR";
274 case MipsISD::EXTP: return "MipsISD::EXTP";
275 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
276 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
277 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
278 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
279 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
280 case MipsISD::SHILO: return "MipsISD::SHILO";
281 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
282 case MipsISD::MULT: return "MipsISD::MULT";
283 case MipsISD::MULTU: return "MipsISD::MULTU";
284 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
285 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
286 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
287 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
288 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
289 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
290 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
291 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
292 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
293 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
294 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
295 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
296 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
297 case MipsISD::VCEQ: return "MipsISD::VCEQ";
298 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
299 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
300 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
301 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
302 case MipsISD::VSMAX: return "MipsISD::VSMAX";
303 case MipsISD::VSMIN: return "MipsISD::VSMIN";
304 case MipsISD::VUMAX: return "MipsISD::VUMAX";
305 case MipsISD::VUMIN: return "MipsISD::VUMIN";
306 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
307 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
308 case MipsISD::VNOR: return "MipsISD::VNOR";
309 case MipsISD::VSHF: return "MipsISD::VSHF";
310 case MipsISD::SHF: return "MipsISD::SHF";
311 case MipsISD::ILVEV: return "MipsISD::ILVEV";
312 case MipsISD::ILVOD: return "MipsISD::ILVOD";
313 case MipsISD::ILVL: return "MipsISD::ILVL";
314 case MipsISD::ILVR: return "MipsISD::ILVR";
315 case MipsISD::PCKEV: return "MipsISD::PCKEV";
316 case MipsISD::PCKOD: return "MipsISD::PCKOD";
317 case MipsISD::INSVE: return "MipsISD::INSVE";
318 default: return nullptr;
322 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
323 const MipsSubtarget &STI)
324 : TargetLowering(TM, new MipsTargetObjectFile()), Subtarget(STI) {
325 // Mips does not have i1 type, so use i32 for
326 // setcc operations results (slt, sgt, ...).
327 setBooleanContents(ZeroOrOneBooleanContent);
328 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
329 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
330 // does. Integer booleans still use 0 and 1.
331 if (Subtarget.hasMips32r6())
332 setBooleanContents(ZeroOrOneBooleanContent,
333 ZeroOrNegativeOneBooleanContent);
335 // Load extented operations for i1 types must be promoted
336 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
337 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
338 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
340 // MIPS doesn't have extending float->double load/store
341 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
342 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
344 // Used by legalize types to correctly generate the setcc result.
345 // Without this, every float setcc comes with a AND/OR with the result,
346 // we don't want this, since the fpcmp result goes to a flag register,
347 // which is used implicitly by brcond and select operations.
348 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
350 // Mips Custom Operations
351 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
352 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
353 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
354 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
355 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
356 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
357 setOperationAction(ISD::SELECT, MVT::f32, Custom);
358 setOperationAction(ISD::SELECT, MVT::f64, Custom);
359 setOperationAction(ISD::SELECT, MVT::i32, Custom);
360 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
361 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
362 setOperationAction(ISD::SETCC, MVT::f32, Custom);
363 setOperationAction(ISD::SETCC, MVT::f64, Custom);
364 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
365 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
366 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
367 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
369 if (Subtarget.isGP64bit()) {
370 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
371 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
372 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
373 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
374 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
375 setOperationAction(ISD::SELECT, MVT::i64, Custom);
376 setOperationAction(ISD::LOAD, MVT::i64, Custom);
377 setOperationAction(ISD::STORE, MVT::i64, Custom);
378 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
381 if (!Subtarget.isGP64bit()) {
382 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
383 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
384 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
387 setOperationAction(ISD::ADD, MVT::i32, Custom);
388 if (Subtarget.isGP64bit())
389 setOperationAction(ISD::ADD, MVT::i64, Custom);
391 setOperationAction(ISD::SDIV, MVT::i32, Expand);
392 setOperationAction(ISD::SREM, MVT::i32, Expand);
393 setOperationAction(ISD::UDIV, MVT::i32, Expand);
394 setOperationAction(ISD::UREM, MVT::i32, Expand);
395 setOperationAction(ISD::SDIV, MVT::i64, Expand);
396 setOperationAction(ISD::SREM, MVT::i64, Expand);
397 setOperationAction(ISD::UDIV, MVT::i64, Expand);
398 setOperationAction(ISD::UREM, MVT::i64, Expand);
400 // Operations not directly supported by Mips.
401 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
402 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
403 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
404 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
405 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
406 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
407 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
408 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
409 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
410 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
411 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
412 if (Subtarget.hasCnMips()) {
413 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
414 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
416 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
417 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
419 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
420 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
421 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
422 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
423 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
424 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
425 setOperationAction(ISD::ROTL, MVT::i32, Expand);
426 setOperationAction(ISD::ROTL, MVT::i64, Expand);
427 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
428 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
430 if (!Subtarget.hasMips32r2())
431 setOperationAction(ISD::ROTR, MVT::i32, Expand);
433 if (!Subtarget.hasMips64r2())
434 setOperationAction(ISD::ROTR, MVT::i64, Expand);
436 setOperationAction(ISD::FSIN, MVT::f32, Expand);
437 setOperationAction(ISD::FSIN, MVT::f64, Expand);
438 setOperationAction(ISD::FCOS, MVT::f32, Expand);
439 setOperationAction(ISD::FCOS, MVT::f64, Expand);
440 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
441 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
442 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
443 setOperationAction(ISD::FPOW, MVT::f32, Expand);
444 setOperationAction(ISD::FPOW, MVT::f64, Expand);
445 setOperationAction(ISD::FLOG, MVT::f32, Expand);
446 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
447 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
448 setOperationAction(ISD::FEXP, MVT::f32, Expand);
449 setOperationAction(ISD::FMA, MVT::f32, Expand);
450 setOperationAction(ISD::FMA, MVT::f64, Expand);
451 setOperationAction(ISD::FREM, MVT::f32, Expand);
452 setOperationAction(ISD::FREM, MVT::f64, Expand);
454 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
456 setOperationAction(ISD::VASTART, MVT::Other, Custom);
457 setOperationAction(ISD::VAARG, MVT::Other, Custom);
458 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
459 setOperationAction(ISD::VAEND, MVT::Other, Expand);
461 // Use the default for now
462 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
463 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
465 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
466 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
467 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
468 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
470 setInsertFencesForAtomic(true);
472 if (!Subtarget.hasMips32r2()) {
473 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
474 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
477 // MIPS16 lacks MIPS32's clz and clo instructions.
478 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
479 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
480 if (!Subtarget.hasMips64())
481 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
483 if (!Subtarget.hasMips32r2())
484 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
485 if (!Subtarget.hasMips64r2())
486 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
488 if (Subtarget.isGP64bit()) {
489 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
490 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
491 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
492 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
495 setOperationAction(ISD::TRAP, MVT::Other, Legal);
497 setTargetDAGCombine(ISD::SDIVREM);
498 setTargetDAGCombine(ISD::UDIVREM);
499 setTargetDAGCombine(ISD::SELECT);
500 setTargetDAGCombine(ISD::AND);
501 setTargetDAGCombine(ISD::OR);
502 setTargetDAGCombine(ISD::ADD);
504 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
506 // The arguments on the stack are defined in terms of 4-byte slots on O32
507 // and 8-byte slots on N32/N64.
508 setMinStackArgumentAlignment(
509 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
511 setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
514 setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
515 setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
517 MaxStoresPerMemcpy = 16;
519 isMicroMips = Subtarget.inMicroMipsMode();
522 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
523 const MipsSubtarget &STI) {
524 if (STI.inMips16Mode())
525 return llvm::createMips16TargetLowering(TM, STI);
527 return llvm::createMipsSETargetLowering(TM, STI);
530 // Create a fast isel object.
532 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
533 const TargetLibraryInfo *libInfo) const {
534 if (!EnableMipsFastISel)
535 return TargetLowering::createFastISel(funcInfo, libInfo);
536 return Mips::createFastISel(funcInfo, libInfo);
539 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
542 return VT.changeVectorElementTypeToInteger();
545 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
546 TargetLowering::DAGCombinerInfo &DCI,
547 const MipsSubtarget &Subtarget) {
548 if (DCI.isBeforeLegalizeOps())
551 EVT Ty = N->getValueType(0);
552 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
553 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
554 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
558 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
559 N->getOperand(0), N->getOperand(1));
560 SDValue InChain = DAG.getEntryNode();
561 SDValue InGlue = DivRem;
564 if (N->hasAnyUseOfValue(0)) {
565 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
567 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
568 InChain = CopyFromLo.getValue(1);
569 InGlue = CopyFromLo.getValue(2);
573 if (N->hasAnyUseOfValue(1)) {
574 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
576 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
582 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
584 default: llvm_unreachable("Unknown fp condition code!");
586 case ISD::SETOEQ: return Mips::FCOND_OEQ;
587 case ISD::SETUNE: return Mips::FCOND_UNE;
589 case ISD::SETOLT: return Mips::FCOND_OLT;
591 case ISD::SETOGT: return Mips::FCOND_OGT;
593 case ISD::SETOLE: return Mips::FCOND_OLE;
595 case ISD::SETOGE: return Mips::FCOND_OGE;
596 case ISD::SETULT: return Mips::FCOND_ULT;
597 case ISD::SETULE: return Mips::FCOND_ULE;
598 case ISD::SETUGT: return Mips::FCOND_UGT;
599 case ISD::SETUGE: return Mips::FCOND_UGE;
600 case ISD::SETUO: return Mips::FCOND_UN;
601 case ISD::SETO: return Mips::FCOND_OR;
603 case ISD::SETONE: return Mips::FCOND_ONE;
604 case ISD::SETUEQ: return Mips::FCOND_UEQ;
609 /// This function returns true if the floating point conditional branches and
610 /// conditional moves which use condition code CC should be inverted.
611 static bool invertFPCondCodeUser(Mips::CondCode CC) {
612 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
615 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
616 "Illegal Condition Code");
621 // Creates and returns an FPCmp node from a setcc node.
622 // Returns Op if setcc is not a floating point comparison.
623 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
624 // must be a SETCC node
625 if (Op.getOpcode() != ISD::SETCC)
628 SDValue LHS = Op.getOperand(0);
630 if (!LHS.getValueType().isFloatingPoint())
633 SDValue RHS = Op.getOperand(1);
636 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
637 // node if necessary.
638 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
640 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
641 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
644 // Creates and returns a CMovFPT/F node.
645 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
646 SDValue False, SDLoc DL) {
647 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
648 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
649 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
651 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
652 True.getValueType(), True, FCC0, False, Cond);
655 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
656 TargetLowering::DAGCombinerInfo &DCI,
657 const MipsSubtarget &Subtarget) {
658 if (DCI.isBeforeLegalizeOps())
661 SDValue SetCC = N->getOperand(0);
663 if ((SetCC.getOpcode() != ISD::SETCC) ||
664 !SetCC.getOperand(0).getValueType().isInteger())
667 SDValue False = N->getOperand(2);
668 EVT FalseTy = False.getValueType();
670 if (!FalseTy.isInteger())
673 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
675 // If the RHS (False) is 0, we swap the order of the operands
676 // of ISD::SELECT (obviously also inverting the condition) so that we can
677 // take advantage of conditional moves using the $0 register.
679 // return (a != 0) ? x : 0;
687 if (!FalseC->getZExtValue()) {
688 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
689 SDValue True = N->getOperand(1);
691 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
692 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
694 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
697 // If both operands are integer constants there's a possibility that we
698 // can do some interesting optimizations.
699 SDValue True = N->getOperand(1);
700 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
702 if (!TrueC || !True.getValueType().isInteger())
705 // We'll also ignore MVT::i64 operands as this optimizations proves
706 // to be ineffective because of the required sign extensions as the result
707 // of a SETCC operator is always MVT::i32 for non-vector types.
708 if (True.getValueType() == MVT::i64)
711 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
713 // 1) (a < x) ? y : y-1
715 // addiu $reg2, $reg1, y-1
717 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
719 // 2) (a < x) ? y-1 : y
721 // xor $reg1, $reg1, 1
722 // addiu $reg2, $reg1, y-1
724 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
725 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
726 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
727 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
730 // Couldn't optimize.
734 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
735 TargetLowering::DAGCombinerInfo &DCI,
736 const MipsSubtarget &Subtarget) {
737 // Pattern match EXT.
738 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
739 // => ext $dst, $src, size, pos
740 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
743 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
744 unsigned ShiftRightOpc = ShiftRight.getOpcode();
746 // Op's first operand must be a shift right.
747 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
750 // The second operand of the shift must be an immediate.
752 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
755 uint64_t Pos = CN->getZExtValue();
756 uint64_t SMPos, SMSize;
758 // Op's second operand must be a shifted mask.
759 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
760 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
763 // Return if the shifted mask does not start at bit 0 or the sum of its size
764 // and Pos exceeds the word's size.
765 EVT ValTy = N->getValueType(0);
766 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
769 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
770 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
771 DAG.getConstant(SMSize, MVT::i32));
774 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
775 TargetLowering::DAGCombinerInfo &DCI,
776 const MipsSubtarget &Subtarget) {
777 // Pattern match INS.
778 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
779 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
780 // => ins $dst, $src, size, pos, $src1
781 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
784 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
785 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
788 // See if Op's first operand matches (and $src1 , mask0).
789 if (And0.getOpcode() != ISD::AND)
792 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
793 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
796 // See if Op's second operand matches (and (shl $src, pos), mask1).
797 if (And1.getOpcode() != ISD::AND)
800 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
801 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
804 // The shift masks must have the same position and size.
805 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
808 SDValue Shl = And1.getOperand(0);
809 if (Shl.getOpcode() != ISD::SHL)
812 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
815 unsigned Shamt = CN->getZExtValue();
817 // Return if the shift amount and the first bit position of mask are not the
819 EVT ValTy = N->getValueType(0);
820 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
823 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
824 DAG.getConstant(SMPos0, MVT::i32),
825 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
828 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
829 TargetLowering::DAGCombinerInfo &DCI,
830 const MipsSubtarget &Subtarget) {
831 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
833 if (DCI.isBeforeLegalizeOps())
836 SDValue Add = N->getOperand(1);
838 if (Add.getOpcode() != ISD::ADD)
841 SDValue Lo = Add.getOperand(1);
843 if ((Lo.getOpcode() != MipsISD::Lo) ||
844 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
847 EVT ValTy = N->getValueType(0);
850 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
852 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
855 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
857 SelectionDAG &DAG = DCI.DAG;
858 unsigned Opc = N->getOpcode();
864 return performDivRemCombine(N, DAG, DCI, Subtarget);
866 return performSELECTCombine(N, DAG, DCI, Subtarget);
868 return performANDCombine(N, DAG, DCI, Subtarget);
870 return performORCombine(N, DAG, DCI, Subtarget);
872 return performADDCombine(N, DAG, DCI, Subtarget);
879 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
880 SmallVectorImpl<SDValue> &Results,
881 SelectionDAG &DAG) const {
882 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
884 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
885 Results.push_back(Res.getValue(I));
889 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
890 SmallVectorImpl<SDValue> &Results,
891 SelectionDAG &DAG) const {
892 return LowerOperationWrapper(N, Results, DAG);
895 SDValue MipsTargetLowering::
896 LowerOperation(SDValue Op, SelectionDAG &DAG) const
898 switch (Op.getOpcode())
900 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
901 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
902 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
903 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
904 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
905 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
906 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
907 case ISD::SELECT: return lowerSELECT(Op, DAG);
908 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
909 case ISD::SETCC: return lowerSETCC(Op, DAG);
910 case ISD::VASTART: return lowerVASTART(Op, DAG);
911 case ISD::VAARG: return lowerVAARG(Op, DAG);
912 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
913 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
914 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
915 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
916 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
917 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
918 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
919 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
920 case ISD::LOAD: return lowerLOAD(Op, DAG);
921 case ISD::STORE: return lowerSTORE(Op, DAG);
922 case ISD::ADD: return lowerADD(Op, DAG);
923 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
928 //===----------------------------------------------------------------------===//
929 // Lower helper functions
930 //===----------------------------------------------------------------------===//
932 // addLiveIn - This helper function adds the specified physical register to the
933 // MachineFunction as a live in value. It also creates a corresponding
934 // virtual register for it.
936 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
938 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
939 MF.getRegInfo().addLiveIn(PReg, VReg);
943 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
944 MachineBasicBlock &MBB,
945 const TargetInstrInfo &TII,
950 // Insert instruction "teq $divisor_reg, $zero, 7".
951 MachineBasicBlock::iterator I(MI);
952 MachineInstrBuilder MIB;
953 MachineOperand &Divisor = MI->getOperand(2);
954 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
955 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
956 .addReg(Mips::ZERO).addImm(7);
958 // Use the 32-bit sub-register if this is a 64-bit division.
960 MIB->getOperand(0).setSubReg(Mips::sub_32);
962 // Clear Divisor's kill flag.
963 Divisor.setIsKill(false);
965 // We would normally delete the original instruction here but in this case
966 // we only needed to inject an additional instruction rather than replace it.
972 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
973 MachineBasicBlock *BB) const {
974 switch (MI->getOpcode()) {
976 llvm_unreachable("Unexpected instr type to insert");
977 case Mips::ATOMIC_LOAD_ADD_I8:
978 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
979 case Mips::ATOMIC_LOAD_ADD_I16:
980 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
981 case Mips::ATOMIC_LOAD_ADD_I32:
982 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
983 case Mips::ATOMIC_LOAD_ADD_I64:
984 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
986 case Mips::ATOMIC_LOAD_AND_I8:
987 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
988 case Mips::ATOMIC_LOAD_AND_I16:
989 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
990 case Mips::ATOMIC_LOAD_AND_I32:
991 return emitAtomicBinary(MI, BB, 4, Mips::AND);
992 case Mips::ATOMIC_LOAD_AND_I64:
993 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
995 case Mips::ATOMIC_LOAD_OR_I8:
996 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
997 case Mips::ATOMIC_LOAD_OR_I16:
998 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
999 case Mips::ATOMIC_LOAD_OR_I32:
1000 return emitAtomicBinary(MI, BB, 4, Mips::OR);
1001 case Mips::ATOMIC_LOAD_OR_I64:
1002 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
1004 case Mips::ATOMIC_LOAD_XOR_I8:
1005 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1006 case Mips::ATOMIC_LOAD_XOR_I16:
1007 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1008 case Mips::ATOMIC_LOAD_XOR_I32:
1009 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
1010 case Mips::ATOMIC_LOAD_XOR_I64:
1011 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
1013 case Mips::ATOMIC_LOAD_NAND_I8:
1014 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
1015 case Mips::ATOMIC_LOAD_NAND_I16:
1016 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
1017 case Mips::ATOMIC_LOAD_NAND_I32:
1018 return emitAtomicBinary(MI, BB, 4, 0, true);
1019 case Mips::ATOMIC_LOAD_NAND_I64:
1020 return emitAtomicBinary(MI, BB, 8, 0, true);
1022 case Mips::ATOMIC_LOAD_SUB_I8:
1023 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1024 case Mips::ATOMIC_LOAD_SUB_I16:
1025 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1026 case Mips::ATOMIC_LOAD_SUB_I32:
1027 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
1028 case Mips::ATOMIC_LOAD_SUB_I64:
1029 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1031 case Mips::ATOMIC_SWAP_I8:
1032 return emitAtomicBinaryPartword(MI, BB, 1, 0);
1033 case Mips::ATOMIC_SWAP_I16:
1034 return emitAtomicBinaryPartword(MI, BB, 2, 0);
1035 case Mips::ATOMIC_SWAP_I32:
1036 return emitAtomicBinary(MI, BB, 4, 0);
1037 case Mips::ATOMIC_SWAP_I64:
1038 return emitAtomicBinary(MI, BB, 8, 0);
1040 case Mips::ATOMIC_CMP_SWAP_I8:
1041 return emitAtomicCmpSwapPartword(MI, BB, 1);
1042 case Mips::ATOMIC_CMP_SWAP_I16:
1043 return emitAtomicCmpSwapPartword(MI, BB, 2);
1044 case Mips::ATOMIC_CMP_SWAP_I32:
1045 return emitAtomicCmpSwap(MI, BB, 4);
1046 case Mips::ATOMIC_CMP_SWAP_I64:
1047 return emitAtomicCmpSwap(MI, BB, 8);
1048 case Mips::PseudoSDIV:
1049 case Mips::PseudoUDIV:
1054 return insertDivByZeroTrap(
1055 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
1056 case Mips::PseudoDSDIV:
1057 case Mips::PseudoDUDIV:
1062 return insertDivByZeroTrap(
1063 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
1065 return emitSEL_D(MI, BB);
1069 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1070 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1072 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1073 unsigned Size, unsigned BinOpcode,
1075 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1077 MachineFunction *MF = BB->getParent();
1078 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1079 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1080 const TargetInstrInfo *TII =
1081 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1082 DebugLoc DL = MI->getDebugLoc();
1083 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1090 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1091 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1098 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1099 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1102 ZERO = Mips::ZERO_64;
1106 unsigned OldVal = MI->getOperand(0).getReg();
1107 unsigned Ptr = MI->getOperand(1).getReg();
1108 unsigned Incr = MI->getOperand(2).getReg();
1110 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1111 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1112 unsigned Success = RegInfo.createVirtualRegister(RC);
1114 // insert new blocks after the current block
1115 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1116 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1117 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1118 MachineFunction::iterator It = BB;
1120 MF->insert(It, loopMBB);
1121 MF->insert(It, exitMBB);
1123 // Transfer the remainder of BB and its successor edges to exitMBB.
1124 exitMBB->splice(exitMBB->begin(), BB,
1125 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1126 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1130 // fallthrough --> loopMBB
1131 BB->addSuccessor(loopMBB);
1132 loopMBB->addSuccessor(loopMBB);
1133 loopMBB->addSuccessor(exitMBB);
1136 // ll oldval, 0(ptr)
1137 // <binop> storeval, oldval, incr
1138 // sc success, storeval, 0(ptr)
1139 // beq success, $0, loopMBB
1141 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1143 // and andres, oldval, incr
1144 // nor storeval, $0, andres
1145 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1146 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1147 } else if (BinOpcode) {
1148 // <binop> storeval, oldval, incr
1149 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1153 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1154 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1156 MI->eraseFromParent(); // The instruction is gone now.
1161 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1162 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1163 unsigned SrcReg) const {
1164 const TargetInstrInfo *TII =
1165 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1166 DebugLoc DL = MI->getDebugLoc();
1168 if (Subtarget.hasMips32r2() && Size == 1) {
1169 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1173 if (Subtarget.hasMips32r2() && Size == 2) {
1174 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1178 MachineFunction *MF = BB->getParent();
1179 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1180 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1181 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1184 int64_t ShiftImm = 32 - (Size * 8);
1186 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1187 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1192 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1193 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1195 assert((Size == 1 || Size == 2) &&
1196 "Unsupported size for EmitAtomicBinaryPartial.");
1198 MachineFunction *MF = BB->getParent();
1199 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1200 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1201 const TargetInstrInfo *TII =
1202 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1203 DebugLoc DL = MI->getDebugLoc();
1205 unsigned Dest = MI->getOperand(0).getReg();
1206 unsigned Ptr = MI->getOperand(1).getReg();
1207 unsigned Incr = MI->getOperand(2).getReg();
1209 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1210 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1211 unsigned Mask = RegInfo.createVirtualRegister(RC);
1212 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1213 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1214 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1215 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1216 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1217 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1218 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1219 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1220 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1221 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1222 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1223 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1224 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1225 unsigned Success = RegInfo.createVirtualRegister(RC);
1227 // insert new blocks after the current block
1228 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1229 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1230 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1231 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1232 MachineFunction::iterator It = BB;
1234 MF->insert(It, loopMBB);
1235 MF->insert(It, sinkMBB);
1236 MF->insert(It, exitMBB);
1238 // Transfer the remainder of BB and its successor edges to exitMBB.
1239 exitMBB->splice(exitMBB->begin(), BB,
1240 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1241 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1243 BB->addSuccessor(loopMBB);
1244 loopMBB->addSuccessor(loopMBB);
1245 loopMBB->addSuccessor(sinkMBB);
1246 sinkMBB->addSuccessor(exitMBB);
1249 // addiu masklsb2,$0,-4 # 0xfffffffc
1250 // and alignedaddr,ptr,masklsb2
1251 // andi ptrlsb2,ptr,3
1252 // sll shiftamt,ptrlsb2,3
1253 // ori maskupper,$0,255 # 0xff
1254 // sll mask,maskupper,shiftamt
1255 // nor mask2,$0,mask
1256 // sll incr2,incr,shiftamt
1258 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1259 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1260 .addReg(Mips::ZERO).addImm(-4);
1261 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1262 .addReg(Ptr).addReg(MaskLSB2);
1263 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1264 if (Subtarget.isLittle()) {
1265 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1267 unsigned Off = RegInfo.createVirtualRegister(RC);
1268 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1269 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1270 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1272 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1273 .addReg(Mips::ZERO).addImm(MaskImm);
1274 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1275 .addReg(MaskUpper).addReg(ShiftAmt);
1276 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1277 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1279 // atomic.load.binop
1281 // ll oldval,0(alignedaddr)
1282 // binop binopres,oldval,incr2
1283 // and newval,binopres,mask
1284 // and maskedoldval0,oldval,mask2
1285 // or storeval,maskedoldval0,newval
1286 // sc success,storeval,0(alignedaddr)
1287 // beq success,$0,loopMBB
1291 // ll oldval,0(alignedaddr)
1292 // and newval,incr2,mask
1293 // and maskedoldval0,oldval,mask2
1294 // or storeval,maskedoldval0,newval
1295 // sc success,storeval,0(alignedaddr)
1296 // beq success,$0,loopMBB
1299 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1301 // and andres, oldval, incr2
1302 // nor binopres, $0, andres
1303 // and newval, binopres, mask
1304 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1305 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1306 .addReg(Mips::ZERO).addReg(AndRes);
1307 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1308 } else if (BinOpcode) {
1309 // <binop> binopres, oldval, incr2
1310 // and newval, binopres, mask
1311 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1312 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1313 } else { // atomic.swap
1314 // and newval, incr2, mask
1315 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1318 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1319 .addReg(OldVal).addReg(Mask2);
1320 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1321 .addReg(MaskedOldVal0).addReg(NewVal);
1322 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1323 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1324 BuildMI(BB, DL, TII->get(Mips::BEQ))
1325 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1328 // and maskedoldval1,oldval,mask
1329 // srl srlres,maskedoldval1,shiftamt
1330 // sign_extend dest,srlres
1333 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1334 .addReg(OldVal).addReg(Mask);
1335 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1336 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1337 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1339 MI->eraseFromParent(); // The instruction is gone now.
1344 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1345 MachineBasicBlock *BB,
1346 unsigned Size) const {
1347 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1349 MachineFunction *MF = BB->getParent();
1350 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1351 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1352 const TargetInstrInfo *TII =
1353 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1354 DebugLoc DL = MI->getDebugLoc();
1355 unsigned LL, SC, ZERO, BNE, BEQ;
1358 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1359 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1366 ZERO = Mips::ZERO_64;
1371 unsigned Dest = MI->getOperand(0).getReg();
1372 unsigned Ptr = MI->getOperand(1).getReg();
1373 unsigned OldVal = MI->getOperand(2).getReg();
1374 unsigned NewVal = MI->getOperand(3).getReg();
1376 unsigned Success = RegInfo.createVirtualRegister(RC);
1378 // insert new blocks after the current block
1379 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1380 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1381 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1382 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1383 MachineFunction::iterator It = BB;
1385 MF->insert(It, loop1MBB);
1386 MF->insert(It, loop2MBB);
1387 MF->insert(It, exitMBB);
1389 // Transfer the remainder of BB and its successor edges to exitMBB.
1390 exitMBB->splice(exitMBB->begin(), BB,
1391 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1392 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1396 // fallthrough --> loop1MBB
1397 BB->addSuccessor(loop1MBB);
1398 loop1MBB->addSuccessor(exitMBB);
1399 loop1MBB->addSuccessor(loop2MBB);
1400 loop2MBB->addSuccessor(loop1MBB);
1401 loop2MBB->addSuccessor(exitMBB);
1405 // bne dest, oldval, exitMBB
1407 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1408 BuildMI(BB, DL, TII->get(BNE))
1409 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1412 // sc success, newval, 0(ptr)
1413 // beq success, $0, loop1MBB
1415 BuildMI(BB, DL, TII->get(SC), Success)
1416 .addReg(NewVal).addReg(Ptr).addImm(0);
1417 BuildMI(BB, DL, TII->get(BEQ))
1418 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1420 MI->eraseFromParent(); // The instruction is gone now.
1426 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1427 MachineBasicBlock *BB,
1428 unsigned Size) const {
1429 assert((Size == 1 || Size == 2) &&
1430 "Unsupported size for EmitAtomicCmpSwapPartial.");
1432 MachineFunction *MF = BB->getParent();
1433 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1434 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1435 const TargetInstrInfo *TII =
1436 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1437 DebugLoc DL = MI->getDebugLoc();
1439 unsigned Dest = MI->getOperand(0).getReg();
1440 unsigned Ptr = MI->getOperand(1).getReg();
1441 unsigned CmpVal = MI->getOperand(2).getReg();
1442 unsigned NewVal = MI->getOperand(3).getReg();
1444 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1445 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1446 unsigned Mask = RegInfo.createVirtualRegister(RC);
1447 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1448 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1449 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1450 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1451 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1452 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1453 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1454 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1455 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1456 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1457 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1458 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1459 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1460 unsigned Success = RegInfo.createVirtualRegister(RC);
1462 // insert new blocks after the current block
1463 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1464 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1465 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1466 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1467 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1468 MachineFunction::iterator It = BB;
1470 MF->insert(It, loop1MBB);
1471 MF->insert(It, loop2MBB);
1472 MF->insert(It, sinkMBB);
1473 MF->insert(It, exitMBB);
1475 // Transfer the remainder of BB and its successor edges to exitMBB.
1476 exitMBB->splice(exitMBB->begin(), BB,
1477 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1478 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1480 BB->addSuccessor(loop1MBB);
1481 loop1MBB->addSuccessor(sinkMBB);
1482 loop1MBB->addSuccessor(loop2MBB);
1483 loop2MBB->addSuccessor(loop1MBB);
1484 loop2MBB->addSuccessor(sinkMBB);
1485 sinkMBB->addSuccessor(exitMBB);
1487 // FIXME: computation of newval2 can be moved to loop2MBB.
1489 // addiu masklsb2,$0,-4 # 0xfffffffc
1490 // and alignedaddr,ptr,masklsb2
1491 // andi ptrlsb2,ptr,3
1492 // sll shiftamt,ptrlsb2,3
1493 // ori maskupper,$0,255 # 0xff
1494 // sll mask,maskupper,shiftamt
1495 // nor mask2,$0,mask
1496 // andi maskedcmpval,cmpval,255
1497 // sll shiftedcmpval,maskedcmpval,shiftamt
1498 // andi maskednewval,newval,255
1499 // sll shiftednewval,maskednewval,shiftamt
1500 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1501 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1502 .addReg(Mips::ZERO).addImm(-4);
1503 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1504 .addReg(Ptr).addReg(MaskLSB2);
1505 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1506 if (Subtarget.isLittle()) {
1507 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1509 unsigned Off = RegInfo.createVirtualRegister(RC);
1510 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1511 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1512 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1514 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1515 .addReg(Mips::ZERO).addImm(MaskImm);
1516 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1517 .addReg(MaskUpper).addReg(ShiftAmt);
1518 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1519 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1520 .addReg(CmpVal).addImm(MaskImm);
1521 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1522 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1523 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1524 .addReg(NewVal).addImm(MaskImm);
1525 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1526 .addReg(MaskedNewVal).addReg(ShiftAmt);
1529 // ll oldval,0(alginedaddr)
1530 // and maskedoldval0,oldval,mask
1531 // bne maskedoldval0,shiftedcmpval,sinkMBB
1533 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1534 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1535 .addReg(OldVal).addReg(Mask);
1536 BuildMI(BB, DL, TII->get(Mips::BNE))
1537 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1540 // and maskedoldval1,oldval,mask2
1541 // or storeval,maskedoldval1,shiftednewval
1542 // sc success,storeval,0(alignedaddr)
1543 // beq success,$0,loop1MBB
1545 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1546 .addReg(OldVal).addReg(Mask2);
1547 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1548 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1549 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1550 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1551 BuildMI(BB, DL, TII->get(Mips::BEQ))
1552 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1555 // srl srlres,maskedoldval0,shiftamt
1556 // sign_extend dest,srlres
1559 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1560 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1561 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1563 MI->eraseFromParent(); // The instruction is gone now.
1568 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1569 MachineBasicBlock *BB) const {
1570 MachineFunction *MF = BB->getParent();
1571 const TargetRegisterInfo *TRI =
1572 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1573 const TargetInstrInfo *TII =
1574 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1575 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1576 DebugLoc DL = MI->getDebugLoc();
1577 MachineBasicBlock::iterator II(MI);
1579 unsigned Fc = MI->getOperand(1).getReg();
1580 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1582 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1584 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1587 .addImm(Mips::sub_lo);
1589 // We don't erase the original instruction, we just replace the condition
1590 // register with the 64-bit super-register.
1591 MI->getOperand(1).setReg(Fc2);
1596 //===----------------------------------------------------------------------===//
1597 // Misc Lower Operation implementation
1598 //===----------------------------------------------------------------------===//
1599 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1600 SDValue Chain = Op.getOperand(0);
1601 SDValue Table = Op.getOperand(1);
1602 SDValue Index = Op.getOperand(2);
1604 EVT PTy = getPointerTy();
1605 unsigned EntrySize =
1606 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1608 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1609 DAG.getConstant(EntrySize, PTy));
1610 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1612 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1613 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1614 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1616 Chain = Addr.getValue(1);
1618 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
1619 Subtarget.isABI_N64()) {
1620 // For PIC, the sequence is:
1621 // BRIND(load(Jumptable + index) + RelocBase)
1622 // RelocBase can be JumpTable, GOT or some sort of global base.
1623 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1624 getPICJumpTableRelocBase(Table, DAG));
1627 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1630 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1631 // The first operand is the chain, the second is the condition, the third is
1632 // the block to branch to if the condition is true.
1633 SDValue Chain = Op.getOperand(0);
1634 SDValue Dest = Op.getOperand(2);
1637 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1638 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1640 // Return if flag is not set by a floating point comparison.
1641 if (CondRes.getOpcode() != MipsISD::FPCmp)
1644 SDValue CCNode = CondRes.getOperand(2);
1646 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1647 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1648 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1649 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1650 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1651 FCC0, Dest, CondRes);
1654 SDValue MipsTargetLowering::
1655 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1657 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1658 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1660 // Return if flag is not set by a floating point comparison.
1661 if (Cond.getOpcode() != MipsISD::FPCmp)
1664 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1668 SDValue MipsTargetLowering::
1669 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1672 EVT Ty = Op.getOperand(0).getValueType();
1673 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1674 getSetCCResultType(*DAG.getContext(), Ty),
1675 Op.getOperand(0), Op.getOperand(1),
1678 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1682 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1683 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1684 SDValue Cond = createFPCmp(DAG, Op);
1686 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1687 "Floating point operand expected.");
1689 SDValue True = DAG.getConstant(1, MVT::i32);
1690 SDValue False = DAG.getConstant(0, MVT::i32);
1692 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1695 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1696 SelectionDAG &DAG) const {
1697 EVT Ty = Op.getValueType();
1698 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1699 const GlobalValue *GV = N->getGlobal();
1701 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1702 !Subtarget.isABI_N64()) {
1703 const MipsTargetObjectFile &TLOF =
1704 (const MipsTargetObjectFile&)getObjFileLowering();
1706 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine()))
1707 // %gp_rel relocation
1708 return getAddrGPRel(N, Ty, DAG);
1710 // %hi/%lo relocation
1711 return getAddrNonPIC(N, Ty, DAG);
1714 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1715 return getAddrLocal(N, Ty, DAG,
1716 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1719 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1720 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1721 MachinePointerInfo::getGOT());
1723 return getAddrGlobal(N, Ty, DAG,
1724 (Subtarget.isABI_N32() || Subtarget.isABI_N64())
1725 ? MipsII::MO_GOT_DISP
1727 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1730 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1731 SelectionDAG &DAG) const {
1732 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1733 EVT Ty = Op.getValueType();
1735 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1736 !Subtarget.isABI_N64())
1737 return getAddrNonPIC(N, Ty, DAG);
1739 return getAddrLocal(N, Ty, DAG,
1740 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1743 SDValue MipsTargetLowering::
1744 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1746 // If the relocation model is PIC, use the General Dynamic TLS Model or
1747 // Local Dynamic TLS model, otherwise use the Initial Exec or
1748 // Local Exec TLS Model.
1750 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1752 const GlobalValue *GV = GA->getGlobal();
1753 EVT PtrVT = getPointerTy();
1755 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1757 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1758 // General Dynamic and Local Dynamic TLS Model.
1759 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1762 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1763 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1764 getGlobalReg(DAG, PtrVT), TGA);
1765 unsigned PtrSize = PtrVT.getSizeInBits();
1766 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1768 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1772 Entry.Node = Argument;
1774 Args.push_back(Entry);
1776 TargetLowering::CallLoweringInfo CLI(DAG);
1777 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1778 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1779 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1781 SDValue Ret = CallResult.first;
1783 if (model != TLSModel::LocalDynamic)
1786 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1787 MipsII::MO_DTPREL_HI);
1788 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1789 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1790 MipsII::MO_DTPREL_LO);
1791 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1792 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1793 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1797 if (model == TLSModel::InitialExec) {
1798 // Initial Exec TLS Model
1799 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1800 MipsII::MO_GOTTPREL);
1801 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1803 Offset = DAG.getLoad(PtrVT, DL,
1804 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1805 false, false, false, 0);
1807 // Local Exec TLS Model
1808 assert(model == TLSModel::LocalExec);
1809 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1810 MipsII::MO_TPREL_HI);
1811 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1812 MipsII::MO_TPREL_LO);
1813 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1814 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1815 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1818 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1819 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1822 SDValue MipsTargetLowering::
1823 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1825 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1826 EVT Ty = Op.getValueType();
1828 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1829 !Subtarget.isABI_N64())
1830 return getAddrNonPIC(N, Ty, DAG);
1832 return getAddrLocal(N, Ty, DAG,
1833 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1836 SDValue MipsTargetLowering::
1837 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1839 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1840 EVT Ty = Op.getValueType();
1842 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1843 !Subtarget.isABI_N64()) {
1844 const MipsTargetObjectFile &TLOF =
1845 (const MipsTargetObjectFile&)getObjFileLowering();
1847 if (TLOF.IsConstantInSmallSection(N->getConstVal(), getTargetMachine()))
1848 // %gp_rel relocation
1849 return getAddrGPRel(N, Ty, DAG);
1851 return getAddrNonPIC(N, Ty, DAG);
1854 return getAddrLocal(N, Ty, DAG,
1855 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1858 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1859 MachineFunction &MF = DAG.getMachineFunction();
1860 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1863 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1866 // vastart just stores the address of the VarArgsFrameIndex slot into the
1867 // memory location argument.
1868 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1869 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1870 MachinePointerInfo(SV), false, false, 0);
1873 SDValue MipsTargetLowering::lowerVAARG(SDValue Op, SelectionDAG &DAG) const {
1874 SDNode *Node = Op.getNode();
1875 EVT VT = Node->getValueType(0);
1876 SDValue Chain = Node->getOperand(0);
1877 SDValue VAListPtr = Node->getOperand(1);
1878 unsigned Align = Node->getConstantOperandVal(3);
1879 const Value *SV = cast<SrcValueSDNode>(Node->getOperand(2))->getValue();
1881 unsigned ArgSlotSizeInBytes =
1882 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4;
1884 SDValue VAListLoad = DAG.getLoad(getPointerTy(), DL, Chain, VAListPtr,
1885 MachinePointerInfo(SV), false, false, false,
1887 SDValue VAList = VAListLoad;
1889 // Re-align the pointer if necessary.
1890 // It should only ever be necessary for 64-bit types on O32 since the minimum
1891 // argument alignment is the same as the maximum type alignment for N32/N64.
1893 // FIXME: We currently align too often. The code generator doesn't notice
1894 // when the pointer is still aligned from the last va_arg (or pair of
1895 // va_args for the i64 on O32 case).
1896 if (Align > getMinStackArgumentAlignment()) {
1897 assert(((Align & (Align-1)) == 0) && "Expected Align to be a power of 2");
1899 VAList = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1900 DAG.getConstant(Align - 1,
1901 VAList.getValueType()));
1903 VAList = DAG.getNode(ISD::AND, DL, VAList.getValueType(), VAList,
1904 DAG.getConstant(-(int64_t)Align,
1905 VAList.getValueType()));
1908 // Increment the pointer, VAList, to the next vaarg.
1909 unsigned ArgSizeInBytes = getDataLayout()->getTypeAllocSize(VT.getTypeForEVT(*DAG.getContext()));
1910 SDValue Tmp3 = DAG.getNode(ISD::ADD, DL, VAList.getValueType(), VAList,
1911 DAG.getConstant(RoundUpToAlignment(ArgSizeInBytes, ArgSlotSizeInBytes),
1912 VAList.getValueType()));
1913 // Store the incremented VAList to the legalized pointer
1914 Chain = DAG.getStore(VAListLoad.getValue(1), DL, Tmp3, VAListPtr,
1915 MachinePointerInfo(SV), false, false, 0);
1917 // In big-endian mode we must adjust the pointer when the load size is smaller
1918 // than the argument slot size. We must also reduce the known alignment to
1919 // match. For example in the N64 ABI, we must add 4 bytes to the offset to get
1920 // the correct half of the slot, and reduce the alignment from 8 (slot
1921 // alignment) down to 4 (type alignment).
1922 if (!Subtarget.isLittle() && ArgSizeInBytes < ArgSlotSizeInBytes) {
1923 unsigned Adjustment = ArgSlotSizeInBytes - ArgSizeInBytes;
1924 VAList = DAG.getNode(ISD::ADD, DL, VAListPtr.getValueType(), VAList,
1925 DAG.getIntPtrConstant(Adjustment));
1927 // Load the actual argument out of the pointer VAList
1928 return DAG.getLoad(VT, DL, Chain, VAList, MachinePointerInfo(), false, false,
1932 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1933 bool HasExtractInsert) {
1934 EVT TyX = Op.getOperand(0).getValueType();
1935 EVT TyY = Op.getOperand(1).getValueType();
1936 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1937 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1941 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1943 SDValue X = (TyX == MVT::f32) ?
1944 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1945 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1947 SDValue Y = (TyY == MVT::f32) ?
1948 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1949 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1952 if (HasExtractInsert) {
1953 // ext E, Y, 31, 1 ; extract bit31 of Y
1954 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1955 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1956 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1959 // srl SrlX, SllX, 1
1961 // sll SllY, SrlX, 31
1962 // or Or, SrlX, SllY
1963 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1964 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1965 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1966 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1967 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1970 if (TyX == MVT::f32)
1971 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1973 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1974 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1975 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1978 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1979 bool HasExtractInsert) {
1980 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1981 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1982 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1983 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1986 // Bitcast to integer nodes.
1987 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1988 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1990 if (HasExtractInsert) {
1991 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1992 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1993 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1994 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1996 if (WidthX > WidthY)
1997 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1998 else if (WidthY > WidthX)
1999 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2001 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2002 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2003 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2006 // (d)sll SllX, X, 1
2007 // (d)srl SrlX, SllX, 1
2008 // (d)srl SrlY, Y, width(Y)-1
2009 // (d)sll SllY, SrlX, width(Y)-1
2010 // or Or, SrlX, SllY
2011 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2012 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2013 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2014 DAG.getConstant(WidthY - 1, MVT::i32));
2016 if (WidthX > WidthY)
2017 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2018 else if (WidthY > WidthX)
2019 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2021 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2022 DAG.getConstant(WidthX - 1, MVT::i32));
2023 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2024 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2028 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2029 if (Subtarget.isGP64bit())
2030 return lowerFCOPYSIGN64(Op, DAG, Subtarget.hasExtractInsert());
2032 return lowerFCOPYSIGN32(Op, DAG, Subtarget.hasExtractInsert());
2035 SDValue MipsTargetLowering::
2036 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2038 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2039 "Frame address can only be determined for current frame.");
2041 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2042 MFI->setFrameAddressIsTaken(true);
2043 EVT VT = Op.getValueType();
2046 DAG.getCopyFromReg(DAG.getEntryNode(), DL,
2047 Subtarget.isABI_N64() ? Mips::FP_64 : Mips::FP, VT);
2051 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2052 SelectionDAG &DAG) const {
2053 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
2057 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2058 "Return address can be determined only for current frame.");
2060 MachineFunction &MF = DAG.getMachineFunction();
2061 MachineFrameInfo *MFI = MF.getFrameInfo();
2062 MVT VT = Op.getSimpleValueType();
2063 unsigned RA = Subtarget.isABI_N64() ? Mips::RA_64 : Mips::RA;
2064 MFI->setReturnAddressIsTaken(true);
2066 // Return RA, which contains the return address. Mark it an implicit live-in.
2067 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2068 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
2071 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2072 // generated from __builtin_eh_return (offset, handler)
2073 // The effect of this is to adjust the stack pointer by "offset"
2074 // and then branch to "handler".
2075 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2077 MachineFunction &MF = DAG.getMachineFunction();
2078 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2080 MipsFI->setCallsEhReturn();
2081 SDValue Chain = Op.getOperand(0);
2082 SDValue Offset = Op.getOperand(1);
2083 SDValue Handler = Op.getOperand(2);
2085 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2087 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2088 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2089 unsigned OffsetReg = Subtarget.isABI_N64() ? Mips::V1_64 : Mips::V1;
2090 unsigned AddrReg = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
2091 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2092 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2093 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2094 DAG.getRegister(OffsetReg, Ty),
2095 DAG.getRegister(AddrReg, getPointerTy()),
2099 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2100 SelectionDAG &DAG) const {
2101 // FIXME: Need pseudo-fence for 'singlethread' fences
2102 // FIXME: Set SType for weaker fences where supported/appropriate.
2105 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2106 DAG.getConstant(SType, MVT::i32));
2109 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2110 SelectionDAG &DAG) const {
2112 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2113 SDValue Shamt = Op.getOperand(2);
2116 // lo = (shl lo, shamt)
2117 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2120 // hi = (shl lo, shamt[4:0])
2121 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2122 DAG.getConstant(-1, MVT::i32));
2123 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2124 DAG.getConstant(1, MVT::i32));
2125 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2127 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2128 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2129 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2130 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2131 DAG.getConstant(0x20, MVT::i32));
2132 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2133 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2134 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2136 SDValue Ops[2] = {Lo, Hi};
2137 return DAG.getMergeValues(Ops, DL);
2140 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2143 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2144 SDValue Shamt = Op.getOperand(2);
2147 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2149 // hi = (sra hi, shamt)
2151 // hi = (srl hi, shamt)
2154 // lo = (sra hi, shamt[4:0])
2155 // hi = (sra hi, 31)
2157 // lo = (srl hi, shamt[4:0])
2159 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2160 DAG.getConstant(-1, MVT::i32));
2161 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2162 DAG.getConstant(1, MVT::i32));
2163 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2164 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2165 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2166 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2168 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2169 DAG.getConstant(0x20, MVT::i32));
2170 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2171 DAG.getConstant(31, MVT::i32));
2172 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2173 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2174 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2177 SDValue Ops[2] = {Lo, Hi};
2178 return DAG.getMergeValues(Ops, DL);
2181 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2182 SDValue Chain, SDValue Src, unsigned Offset) {
2183 SDValue Ptr = LD->getBasePtr();
2184 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2185 EVT BasePtrVT = Ptr.getValueType();
2187 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2190 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2191 DAG.getConstant(Offset, BasePtrVT));
2193 SDValue Ops[] = { Chain, Ptr, Src };
2194 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2195 LD->getMemOperand());
2198 // Expand an unaligned 32 or 64-bit integer load node.
2199 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2200 LoadSDNode *LD = cast<LoadSDNode>(Op);
2201 EVT MemVT = LD->getMemoryVT();
2203 if (Subtarget.systemSupportsUnalignedAccess())
2206 // Return if load is aligned or if MemVT is neither i32 nor i64.
2207 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2208 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2211 bool IsLittle = Subtarget.isLittle();
2212 EVT VT = Op.getValueType();
2213 ISD::LoadExtType ExtType = LD->getExtensionType();
2214 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2216 assert((VT == MVT::i32) || (VT == MVT::i64));
2219 // (set dst, (i64 (load baseptr)))
2221 // (set tmp, (ldl (add baseptr, 7), undef))
2222 // (set dst, (ldr baseptr, tmp))
2223 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2224 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2226 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2230 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2232 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2236 // (set dst, (i32 (load baseptr))) or
2237 // (set dst, (i64 (sextload baseptr))) or
2238 // (set dst, (i64 (extload baseptr)))
2240 // (set tmp, (lwl (add baseptr, 3), undef))
2241 // (set dst, (lwr baseptr, tmp))
2242 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2243 (ExtType == ISD::EXTLOAD))
2246 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2249 // (set dst, (i64 (zextload baseptr)))
2251 // (set tmp0, (lwl (add baseptr, 3), undef))
2252 // (set tmp1, (lwr baseptr, tmp0))
2253 // (set tmp2, (shl tmp1, 32))
2254 // (set dst, (srl tmp2, 32))
2256 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2257 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2258 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2259 SDValue Ops[] = { SRL, LWR.getValue(1) };
2260 return DAG.getMergeValues(Ops, DL);
2263 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2264 SDValue Chain, unsigned Offset) {
2265 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2266 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2268 SDVTList VTList = DAG.getVTList(MVT::Other);
2271 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2272 DAG.getConstant(Offset, BasePtrVT));
2274 SDValue Ops[] = { Chain, Value, Ptr };
2275 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2276 SD->getMemOperand());
2279 // Expand an unaligned 32 or 64-bit integer store node.
2280 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2282 SDValue Value = SD->getValue(), Chain = SD->getChain();
2283 EVT VT = Value.getValueType();
2286 // (store val, baseptr) or
2287 // (truncstore val, baseptr)
2289 // (swl val, (add baseptr, 3))
2290 // (swr val, baseptr)
2291 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2292 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2294 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2297 assert(VT == MVT::i64);
2300 // (store val, baseptr)
2302 // (sdl val, (add baseptr, 7))
2303 // (sdr val, baseptr)
2304 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2305 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2308 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2309 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2310 SDValue Val = SD->getValue();
2312 if (Val.getOpcode() != ISD::FP_TO_SINT)
2315 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2316 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2319 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2320 SD->getPointerInfo(), SD->isVolatile(),
2321 SD->isNonTemporal(), SD->getAlignment());
2324 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2325 StoreSDNode *SD = cast<StoreSDNode>(Op);
2326 EVT MemVT = SD->getMemoryVT();
2328 // Lower unaligned integer stores.
2329 if (!Subtarget.systemSupportsUnalignedAccess() &&
2330 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2331 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2332 return lowerUnalignedIntStore(SD, DAG, Subtarget.isLittle());
2334 return lowerFP_TO_SINT_STORE(SD, DAG);
2337 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2338 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2339 || cast<ConstantSDNode>
2340 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2341 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2345 // (add (frameaddr 0), (frame_to_args_offset))
2346 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2347 // (add FrameObject, 0)
2348 // where FrameObject is a fixed StackObject with offset 0 which points to
2349 // the old stack pointer.
2350 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2351 EVT ValTy = Op->getValueType(0);
2352 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2353 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2354 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2355 DAG.getConstant(0, ValTy));
2358 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2359 SelectionDAG &DAG) const {
2360 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2361 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2363 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2366 //===----------------------------------------------------------------------===//
2367 // Calling Convention Implementation
2368 //===----------------------------------------------------------------------===//
2370 //===----------------------------------------------------------------------===//
2371 // TODO: Implement a generic logic using tblgen that can support this.
2372 // Mips O32 ABI rules:
2374 // i32 - Passed in A0, A1, A2, A3 and stack
2375 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2376 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2377 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2378 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2379 // not used, it must be shadowed. If only A3 is available, shadow it and
2382 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2383 //===----------------------------------------------------------------------===//
2385 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2386 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2387 CCState &State, const MCPhysReg *F64Regs) {
2389 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2391 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2392 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2394 // Do not process byval args here.
2395 if (ArgFlags.isByVal())
2398 // Promote i8 and i16
2399 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2401 if (ArgFlags.isSExt())
2402 LocInfo = CCValAssign::SExt;
2403 else if (ArgFlags.isZExt())
2404 LocInfo = CCValAssign::ZExt;
2406 LocInfo = CCValAssign::AExt;
2411 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2412 // is true: function is vararg, argument is 3rd or higher, there is previous
2413 // argument which is not f32 or f64.
2414 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2415 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2416 unsigned OrigAlign = ArgFlags.getOrigAlign();
2417 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2419 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2420 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2421 // If this is the first part of an i64 arg,
2422 // the allocated register must be either A0 or A2.
2423 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2424 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2426 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2427 // Allocate int register and shadow next int register. If first
2428 // available register is Mips::A1 or Mips::A3, shadow it too.
2429 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2430 if (Reg == Mips::A1 || Reg == Mips::A3)
2431 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2432 State.AllocateReg(IntRegs, IntRegsSize);
2434 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2435 // we are guaranteed to find an available float register
2436 if (ValVT == MVT::f32) {
2437 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2438 // Shadow int register
2439 State.AllocateReg(IntRegs, IntRegsSize);
2441 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2442 // Shadow int registers
2443 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2444 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2445 State.AllocateReg(IntRegs, IntRegsSize);
2446 State.AllocateReg(IntRegs, IntRegsSize);
2449 llvm_unreachable("Cannot handle this ValVT.");
2452 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2454 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2456 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2461 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2462 MVT LocVT, CCValAssign::LocInfo LocInfo,
2463 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2464 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2466 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2469 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2470 MVT LocVT, CCValAssign::LocInfo LocInfo,
2471 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2472 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2474 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2477 #include "MipsGenCallingConv.inc"
2479 //===----------------------------------------------------------------------===//
2480 // Call Calling Convention Implementation
2481 //===----------------------------------------------------------------------===//
2483 // Return next O32 integer argument register.
2484 static unsigned getNextIntArgReg(unsigned Reg) {
2485 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2486 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2490 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2491 SDValue Chain, SDValue Arg, SDLoc DL,
2492 bool IsTailCall, SelectionDAG &DAG) const {
2494 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2495 DAG.getIntPtrConstant(Offset));
2496 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2500 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2501 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2502 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2503 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2504 /*isVolatile=*/ true, false, 0);
2507 void MipsTargetLowering::
2508 getOpndList(SmallVectorImpl<SDValue> &Ops,
2509 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2510 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2511 bool IsCallReloc, CallLoweringInfo &CLI, SDValue Callee,
2512 SDValue Chain) const {
2513 // Insert node "GP copy globalreg" before call to function.
2515 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2516 // in PIC mode) allow symbols to be resolved via lazy binding.
2517 // The lazy binding stub requires GP to point to the GOT.
2518 // Note that we don't need GP to point to the GOT for indirect calls
2519 // (when R_MIPS_CALL* is not used for the call) because Mips linker generates
2520 // lazy binding stub for a function only when R_MIPS_CALL* are the only relocs
2521 // used for the function (that is, Mips linker doesn't generate lazy binding
2522 // stub for a function whose address is taken in the program).
2523 if (IsPICCall && !InternalLinkage && IsCallReloc) {
2524 unsigned GPReg = Subtarget.isABI_N64() ? Mips::GP_64 : Mips::GP;
2525 EVT Ty = Subtarget.isABI_N64() ? MVT::i64 : MVT::i32;
2526 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2529 // Build a sequence of copy-to-reg nodes chained together with token
2530 // chain and flag operands which copy the outgoing args into registers.
2531 // The InFlag in necessary since all emitted instructions must be
2535 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2536 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2537 RegsToPass[i].second, InFlag);
2538 InFlag = Chain.getValue(1);
2541 // Add argument registers to the end of the list so that they are
2542 // known live into the call.
2543 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2544 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2545 RegsToPass[i].second.getValueType()));
2547 // Add a register mask operand representing the call-preserved registers.
2548 const TargetRegisterInfo *TRI =
2549 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
2550 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2551 assert(Mask && "Missing call preserved mask for calling convention");
2552 if (Subtarget.inMips16HardFloat()) {
2553 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2554 llvm::StringRef Sym = G->getGlobal()->getName();
2555 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2556 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2557 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2561 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2563 if (InFlag.getNode())
2564 Ops.push_back(InFlag);
2567 /// LowerCall - functions arguments are copied from virtual regs to
2568 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2570 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2571 SmallVectorImpl<SDValue> &InVals) const {
2572 SelectionDAG &DAG = CLI.DAG;
2574 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2575 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2576 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2577 SDValue Chain = CLI.Chain;
2578 SDValue Callee = CLI.Callee;
2579 bool &IsTailCall = CLI.IsTailCall;
2580 CallingConv::ID CallConv = CLI.CallConv;
2581 bool IsVarArg = CLI.IsVarArg;
2583 MachineFunction &MF = DAG.getMachineFunction();
2584 MachineFrameInfo *MFI = MF.getFrameInfo();
2585 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
2586 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2587 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2589 // Analyze operands of the call, assigning locations to each operand.
2590 SmallVector<CCValAssign, 16> ArgLocs;
2591 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2593 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
2595 CCInfo.PreAnalyzeCallOperandsForF128_(Outs, CLI.getArgs(), Callee.getNode());
2596 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg, Subtarget.abiUsesSoftFloat(),
2597 Callee.getNode(), CLI.getArgs(), CCInfo);
2598 CCInfo.ClearOriginalArgWasF128();
2600 // Get a count of how many bytes are to be pushed on the stack.
2601 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2603 // Check if it's really possible to do a tail call.
2605 IsTailCall = isEligibleForTailCallOptimization(
2606 CCInfo, NextStackOffset, *MF.getInfo<MipsFunctionInfo>());
2608 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2609 report_fatal_error("failed to perform tail call elimination on a call "
2610 "site marked musttail");
2615 // Chain is the output chain of the last Load/Store or CopyToReg node.
2616 // ByValChain is the output chain of the last Memcpy node created for copying
2617 // byval arguments to the stack.
2618 unsigned StackAlignment = TFL->getStackAlignment();
2619 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2620 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2623 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2625 SDValue StackPtr = DAG.getCopyFromReg(
2626 Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
2629 // With EABI is it possible to have 16 args on registers.
2630 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2631 SmallVector<SDValue, 8> MemOpChains;
2633 CCInfo.rewindByValRegsInfo();
2635 // Walk the register/memloc assignments, inserting copies/loads.
2636 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2637 SDValue Arg = OutVals[i];
2638 CCValAssign &VA = ArgLocs[i];
2639 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2640 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2643 if (Flags.isByVal()) {
2644 unsigned FirstByValReg, LastByValReg;
2645 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2646 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2648 assert(Flags.getByValSize() &&
2649 "ByVal args of size 0 should have been ignored by front-end.");
2650 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2651 assert(!IsTailCall &&
2652 "Do not tail-call optimize if there is a byval argument.");
2653 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2654 MipsCCInfo, FirstByValReg, LastByValReg, Flags,
2655 Subtarget.isLittle(), VA);
2656 CCInfo.nextInRegsParam();
2660 // Promote the value if needed.
2661 switch (VA.getLocInfo()) {
2662 default: llvm_unreachable("Unknown loc info!");
2663 case CCValAssign::Full:
2664 if (VA.isRegLoc()) {
2665 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2666 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2667 (ValVT == MVT::i64 && LocVT == MVT::f64))
2668 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2669 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2670 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2671 Arg, DAG.getConstant(0, MVT::i32));
2672 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2673 Arg, DAG.getConstant(1, MVT::i32));
2674 if (!Subtarget.isLittle())
2676 unsigned LocRegLo = VA.getLocReg();
2677 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2678 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2679 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2684 case CCValAssign::BCvt:
2685 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2687 case CCValAssign::SExt:
2688 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2690 case CCValAssign::ZExt:
2691 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2693 case CCValAssign::AExt:
2694 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2698 // Arguments that can be passed on register must be kept at
2699 // RegsToPass vector
2700 if (VA.isRegLoc()) {
2701 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2705 // Register can't get to this point...
2706 assert(VA.isMemLoc());
2708 // emit ISD::STORE whichs stores the
2709 // parameter value to a stack Location
2710 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2711 Chain, Arg, DL, IsTailCall, DAG));
2714 // Transform all store nodes into one single node because all store
2715 // nodes are independent of each other.
2716 if (!MemOpChains.empty())
2717 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2719 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2720 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2721 // node so that legalize doesn't hack it.
2723 (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
2725 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2727 EVT Ty = Callee.getValueType();
2729 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2731 const GlobalValue *Val = G->getGlobal();
2732 InternalLinkage = Val->hasInternalLinkage();
2734 if (InternalLinkage)
2735 Callee = getAddrLocal(G, Ty, DAG,
2736 Subtarget.isABI_N32() || Subtarget.isABI_N64());
2737 else if (LargeGOT) {
2738 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2739 MipsII::MO_CALL_LO16, Chain,
2740 FuncInfo->callPtrInfo(Val));
2743 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2744 FuncInfo->callPtrInfo(Val));
2748 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2749 MipsII::MO_NO_FLAG);
2750 GlobalOrExternal = true;
2752 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2753 const char *Sym = S->getSymbol();
2755 if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
2756 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2757 MipsII::MO_NO_FLAG);
2758 else if (LargeGOT) {
2759 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2760 MipsII::MO_CALL_LO16, Chain,
2761 FuncInfo->callPtrInfo(Sym));
2763 } else { // N64 || PIC
2764 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2765 FuncInfo->callPtrInfo(Sym));
2769 GlobalOrExternal = true;
2772 SmallVector<SDValue, 8> Ops(1, Chain);
2773 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2775 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2776 IsCallReloc, CLI, Callee, Chain);
2779 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2781 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2782 SDValue InFlag = Chain.getValue(1);
2784 // Create the CALLSEQ_END node.
2785 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2786 DAG.getIntPtrConstant(0, true), InFlag, DL);
2787 InFlag = Chain.getValue(1);
2789 // Handle result values, copying them out of physregs into vregs that we
2791 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2795 /// LowerCallResult - Lower the result values of a call into the
2796 /// appropriate copies out of appropriate physical registers.
2797 SDValue MipsTargetLowering::LowerCallResult(
2798 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2799 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2800 SmallVectorImpl<SDValue> &InVals,
2801 TargetLowering::CallLoweringInfo &CLI) const {
2802 // Assign locations to each value returned by this call.
2803 SmallVector<CCValAssign, 16> RVLocs;
2804 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2806 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2808 // Copy all of the result registers out of their specified physreg.
2809 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2810 CCValAssign &VA = RVLocs[i];
2811 assert(VA.isRegLoc() && "Can only return in registers!");
2813 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2814 RVLocs[i].getLocVT(), InFlag);
2815 Chain = Val.getValue(1);
2816 InFlag = Val.getValue(2);
2818 if (VA.isUpperBitsInLoc()) {
2819 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2820 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2822 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2824 Shift, DL, VA.getLocVT(), Val,
2825 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2828 switch (VA.getLocInfo()) {
2830 llvm_unreachable("Unknown loc info!");
2831 case CCValAssign::Full:
2833 case CCValAssign::BCvt:
2834 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2836 case CCValAssign::AExt:
2837 case CCValAssign::AExtUpper:
2838 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2840 case CCValAssign::ZExt:
2841 case CCValAssign::ZExtUpper:
2842 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2843 DAG.getValueType(VA.getValVT()));
2844 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2846 case CCValAssign::SExt:
2847 case CCValAssign::SExtUpper:
2848 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2849 DAG.getValueType(VA.getValVT()));
2850 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2854 InVals.push_back(Val);
2860 //===----------------------------------------------------------------------===//
2861 // Formal Arguments Calling Convention Implementation
2862 //===----------------------------------------------------------------------===//
2863 /// LowerFormalArguments - transform physical registers into virtual registers
2864 /// and generate load operations for arguments places on the stack.
2866 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2867 CallingConv::ID CallConv,
2869 const SmallVectorImpl<ISD::InputArg> &Ins,
2870 SDLoc DL, SelectionDAG &DAG,
2871 SmallVectorImpl<SDValue> &InVals)
2873 MachineFunction &MF = DAG.getMachineFunction();
2874 MachineFrameInfo *MFI = MF.getFrameInfo();
2875 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2877 MipsFI->setVarArgsFrameIndex(0);
2879 // Used with vargs to acumulate store chains.
2880 std::vector<SDValue> OutChains;
2882 // Assign locations to all of the incoming arguments.
2883 SmallVector<CCValAssign, 16> ArgLocs;
2884 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2886 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
2887 Function::const_arg_iterator FuncArg =
2888 DAG.getMachineFunction().getFunction()->arg_begin();
2890 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FixedArg);
2891 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2892 CCInfo.getInRegsParamsCount() > 0);
2894 unsigned CurArgIdx = 0;
2895 CCInfo.rewindByValRegsInfo();
2897 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2898 CCValAssign &VA = ArgLocs[i];
2899 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2900 CurArgIdx = Ins[i].OrigArgIndex;
2901 EVT ValVT = VA.getValVT();
2902 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2903 bool IsRegLoc = VA.isRegLoc();
2905 if (Flags.isByVal()) {
2906 unsigned FirstByValReg, LastByValReg;
2907 unsigned ByValIdx = CCInfo.getInRegsParamsProcessed();
2908 CCInfo.getInRegsParamInfo(ByValIdx, FirstByValReg, LastByValReg);
2910 assert(Flags.getByValSize() &&
2911 "ByVal args of size 0 should have been ignored by front-end.");
2912 assert(ByValIdx < CCInfo.getInRegsParamsCount());
2913 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2914 MipsCCInfo, FirstByValReg, LastByValReg, VA);
2915 CCInfo.nextInRegsParam();
2919 // Arguments stored on registers
2921 MVT RegVT = VA.getLocVT();
2922 unsigned ArgReg = VA.getLocReg();
2923 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2925 // Transform the arguments stored on
2926 // physical registers into virtual ones
2927 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2928 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2930 // If this is an 8 or 16-bit value, it has been passed promoted
2931 // to 32 bits. Insert an assert[sz]ext to capture this, then
2932 // truncate to the right size.
2933 switch (VA.getLocInfo()) {
2935 llvm_unreachable("Unknown loc info!");
2936 case CCValAssign::Full:
2938 case CCValAssign::SExt:
2939 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
2940 DAG.getValueType(ValVT));
2941 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2943 case CCValAssign::ZExt:
2944 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
2945 DAG.getValueType(ValVT));
2946 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2948 case CCValAssign::BCvt:
2949 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2953 // Handle floating point arguments passed in integer registers and
2954 // long double arguments passed in floating point registers.
2955 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2956 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2957 (RegVT == MVT::f64 && ValVT == MVT::i64))
2958 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2959 else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
2960 ValVT == MVT::f64) {
2961 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2962 getNextIntArgReg(ArgReg), RC);
2963 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2964 if (!Subtarget.isLittle())
2965 std::swap(ArgValue, ArgValue2);
2966 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2967 ArgValue, ArgValue2);
2970 InVals.push_back(ArgValue);
2971 } else { // VA.isRegLoc()
2974 assert(VA.isMemLoc());
2976 // The stack pointer offset is relative to the caller stack frame.
2977 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2978 VA.getLocMemOffset(), true);
2980 // Create load nodes to retrieve arguments from the stack
2981 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2982 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2983 MachinePointerInfo::getFixedStack(FI),
2984 false, false, false, 0);
2985 InVals.push_back(Load);
2986 OutChains.push_back(Load.getValue(1));
2990 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2991 // The mips ABIs for returning structs by value requires that we copy
2992 // the sret argument into $v0 for the return. Save the argument into
2993 // a virtual register so that we can access it from the return points.
2994 if (Ins[i].Flags.isSRet()) {
2995 unsigned Reg = MipsFI->getSRetReturnReg();
2997 Reg = MF.getRegInfo().createVirtualRegister(
2998 getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
2999 MipsFI->setSRetReturnReg(Reg);
3001 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
3002 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3008 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG, CCInfo);
3010 // All stores are grouped in one node to allow the matching between
3011 // the size of Ins and InVals. This only happens when on varg functions
3012 if (!OutChains.empty()) {
3013 OutChains.push_back(Chain);
3014 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3020 //===----------------------------------------------------------------------===//
3021 // Return Value Calling Convention Implementation
3022 //===----------------------------------------------------------------------===//
3025 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3026 MachineFunction &MF, bool IsVarArg,
3027 const SmallVectorImpl<ISD::OutputArg> &Outs,
3028 LLVMContext &Context) const {
3029 SmallVector<CCValAssign, 16> RVLocs;
3030 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3031 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3035 MipsTargetLowering::LowerReturn(SDValue Chain,
3036 CallingConv::ID CallConv, bool IsVarArg,
3037 const SmallVectorImpl<ISD::OutputArg> &Outs,
3038 const SmallVectorImpl<SDValue> &OutVals,
3039 SDLoc DL, SelectionDAG &DAG) const {
3040 // CCValAssign - represent the assignment of
3041 // the return value to a location
3042 SmallVector<CCValAssign, 16> RVLocs;
3043 MachineFunction &MF = DAG.getMachineFunction();
3045 // CCState - Info about the registers and stack slot.
3046 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3048 // Analyze return values.
3049 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3052 SmallVector<SDValue, 4> RetOps(1, Chain);
3054 // Copy the result values into the output registers.
3055 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3056 SDValue Val = OutVals[i];
3057 CCValAssign &VA = RVLocs[i];
3058 assert(VA.isRegLoc() && "Can only return in registers!");
3059 bool UseUpperBits = false;
3061 switch (VA.getLocInfo()) {
3063 llvm_unreachable("Unknown loc info!");
3064 case CCValAssign::Full:
3066 case CCValAssign::BCvt:
3067 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3069 case CCValAssign::AExtUpper:
3070 UseUpperBits = true;
3072 case CCValAssign::AExt:
3073 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3075 case CCValAssign::ZExtUpper:
3076 UseUpperBits = true;
3078 case CCValAssign::ZExt:
3079 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3081 case CCValAssign::SExtUpper:
3082 UseUpperBits = true;
3084 case CCValAssign::SExt:
3085 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3090 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3091 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3093 ISD::SHL, DL, VA.getLocVT(), Val,
3094 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3097 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3099 // Guarantee that all emitted copies are stuck together with flags.
3100 Flag = Chain.getValue(1);
3101 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3104 // The mips ABIs for returning structs by value requires that we copy
3105 // the sret argument into $v0 for the return. We saved the argument into
3106 // a virtual register in the entry block, so now we copy the value out
3108 if (MF.getFunction()->hasStructRetAttr()) {
3109 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3110 unsigned Reg = MipsFI->getSRetReturnReg();
3113 llvm_unreachable("sret virtual register not created in the entry block");
3114 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3115 unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
3117 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3118 Flag = Chain.getValue(1);
3119 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3122 RetOps[0] = Chain; // Update chain.
3124 // Add the flag if we have it.
3126 RetOps.push_back(Flag);
3128 // Return on Mips is always a "jr $ra"
3129 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3132 //===----------------------------------------------------------------------===//
3133 // Mips Inline Assembly Support
3134 //===----------------------------------------------------------------------===//
3136 /// getConstraintType - Given a constraint letter, return the type of
3137 /// constraint it is for this target.
3138 MipsTargetLowering::ConstraintType MipsTargetLowering::
3139 getConstraintType(const std::string &Constraint) const
3141 // Mips specific constraints
3142 // GCC config/mips/constraints.md
3144 // 'd' : An address register. Equivalent to r
3145 // unless generating MIPS16 code.
3146 // 'y' : Equivalent to r; retained for
3147 // backwards compatibility.
3148 // 'c' : A register suitable for use in an indirect
3149 // jump. This will always be $25 for -mabicalls.
3150 // 'l' : The lo register. 1 word storage.
3151 // 'x' : The hilo register pair. Double word storage.
3152 if (Constraint.size() == 1) {
3153 switch (Constraint[0]) {
3161 return C_RegisterClass;
3166 return TargetLowering::getConstraintType(Constraint);
3169 /// Examine constraint type and operand type and determine a weight value.
3170 /// This object must already have been set up with the operand type
3171 /// and the current alternative constraint selected.
3172 TargetLowering::ConstraintWeight
3173 MipsTargetLowering::getSingleConstraintMatchWeight(
3174 AsmOperandInfo &info, const char *constraint) const {
3175 ConstraintWeight weight = CW_Invalid;
3176 Value *CallOperandVal = info.CallOperandVal;
3177 // If we don't have a value, we can't do a match,
3178 // but allow it at the lowest weight.
3179 if (!CallOperandVal)
3181 Type *type = CallOperandVal->getType();
3182 // Look at the constraint type.
3183 switch (*constraint) {
3185 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3189 if (type->isIntegerTy())
3190 weight = CW_Register;
3192 case 'f': // FPU or MSA register
3193 if (Subtarget.hasMSA() && type->isVectorTy() &&
3194 cast<VectorType>(type)->getBitWidth() == 128)
3195 weight = CW_Register;
3196 else if (type->isFloatTy())
3197 weight = CW_Register;
3199 case 'c': // $25 for indirect jumps
3200 case 'l': // lo register
3201 case 'x': // hilo register pair
3202 if (type->isIntegerTy())
3203 weight = CW_SpecificReg;
3205 case 'I': // signed 16 bit immediate
3206 case 'J': // integer zero
3207 case 'K': // unsigned 16 bit immediate
3208 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3209 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3210 case 'O': // signed 15 bit immediate (+- 16383)
3211 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3212 if (isa<ConstantInt>(CallOperandVal))
3213 weight = CW_Constant;
3222 /// This is a helper function to parse a physical register string and split it
3223 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3224 /// that is returned indicates whether parsing was successful. The second flag
3225 /// is true if the numeric part exists.
3226 static std::pair<bool, bool>
3227 parsePhysicalReg(StringRef C, std::string &Prefix,
3228 unsigned long long &Reg) {
3229 if (C.front() != '{' || C.back() != '}')
3230 return std::make_pair(false, false);
3232 // Search for the first numeric character.
3233 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3234 I = std::find_if(B, E, std::ptr_fun(isdigit));
3236 Prefix.assign(B, I - B);
3238 // The second flag is set to false if no numeric characters were found.
3240 return std::make_pair(true, false);
3242 // Parse the numeric characters.
3243 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3247 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3248 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3249 const TargetRegisterInfo *TRI =
3250 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3251 const TargetRegisterClass *RC;
3253 unsigned long long Reg;
3255 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3258 return std::make_pair(0U, nullptr);
3260 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3261 // No numeric characters follow "hi" or "lo".
3263 return std::make_pair(0U, nullptr);
3265 RC = TRI->getRegClass(Prefix == "hi" ?
3266 Mips::HI32RegClassID : Mips::LO32RegClassID);
3267 return std::make_pair(*(RC->begin()), RC);
3268 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3269 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3271 // No numeric characters follow the name.
3273 return std::make_pair(0U, nullptr);
3275 Reg = StringSwitch<unsigned long long>(Prefix)
3276 .Case("$msair", Mips::MSAIR)
3277 .Case("$msacsr", Mips::MSACSR)
3278 .Case("$msaaccess", Mips::MSAAccess)
3279 .Case("$msasave", Mips::MSASave)
3280 .Case("$msamodify", Mips::MSAModify)
3281 .Case("$msarequest", Mips::MSARequest)
3282 .Case("$msamap", Mips::MSAMap)
3283 .Case("$msaunmap", Mips::MSAUnmap)
3287 return std::make_pair(0U, nullptr);
3289 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3290 return std::make_pair(Reg, RC);
3294 return std::make_pair(0U, nullptr);
3296 if (Prefix == "$f") { // Parse $f0-$f31.
3297 // If the size of FP registers is 64-bit or Reg is an even number, select
3298 // the 64-bit register class. Otherwise, select the 32-bit register class.
3299 if (VT == MVT::Other)
3300 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3302 RC = getRegClassFor(VT);
3304 if (RC == &Mips::AFGR64RegClass) {
3305 assert(Reg % 2 == 0);
3308 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3309 RC = TRI->getRegClass(Mips::FCCRegClassID);
3310 else if (Prefix == "$w") { // Parse $w0-$w31.
3311 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3312 } else { // Parse $0-$31.
3313 assert(Prefix == "$");
3314 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3317 assert(Reg < RC->getNumRegs());
3318 return std::make_pair(*(RC->begin() + Reg), RC);
3321 /// Given a register class constraint, like 'r', if this corresponds directly
3322 /// to an LLVM register class, return a register of 0 and the register class
3324 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3325 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3327 if (Constraint.size() == 1) {
3328 switch (Constraint[0]) {
3329 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3330 case 'y': // Same as 'r'. Exists for compatibility.
3332 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3333 if (Subtarget.inMips16Mode())
3334 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3335 return std::make_pair(0U, &Mips::GPR32RegClass);
3337 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3338 return std::make_pair(0U, &Mips::GPR32RegClass);
3339 if (VT == MVT::i64 && Subtarget.isGP64bit())
3340 return std::make_pair(0U, &Mips::GPR64RegClass);
3341 // This will generate an error message
3342 return std::make_pair(0U, nullptr);
3343 case 'f': // FPU or MSA register
3344 if (VT == MVT::v16i8)
3345 return std::make_pair(0U, &Mips::MSA128BRegClass);
3346 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3347 return std::make_pair(0U, &Mips::MSA128HRegClass);
3348 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3349 return std::make_pair(0U, &Mips::MSA128WRegClass);
3350 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3351 return std::make_pair(0U, &Mips::MSA128DRegClass);
3352 else if (VT == MVT::f32)
3353 return std::make_pair(0U, &Mips::FGR32RegClass);
3354 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3355 if (Subtarget.isFP64bit())
3356 return std::make_pair(0U, &Mips::FGR64RegClass);
3357 return std::make_pair(0U, &Mips::AFGR64RegClass);
3360 case 'c': // register suitable for indirect jump
3362 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3363 assert(VT == MVT::i64 && "Unexpected type.");
3364 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3365 case 'l': // register suitable for indirect jump
3367 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3368 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3369 case 'x': // register suitable for indirect jump
3370 // Fixme: Not triggering the use of both hi and low
3371 // This will generate an error message
3372 return std::make_pair(0U, nullptr);
3376 std::pair<unsigned, const TargetRegisterClass *> R;
3377 R = parseRegForInlineAsmConstraint(Constraint, VT);
3382 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3385 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3386 /// vector. If it is invalid, don't add anything to Ops.
3387 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3388 std::string &Constraint,
3389 std::vector<SDValue>&Ops,
3390 SelectionDAG &DAG) const {
3393 // Only support length 1 constraints for now.
3394 if (Constraint.length() > 1) return;
3396 char ConstraintLetter = Constraint[0];
3397 switch (ConstraintLetter) {
3398 default: break; // This will fall through to the generic implementation
3399 case 'I': // Signed 16 bit constant
3400 // If this fails, the parent routine will give an error
3401 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3402 EVT Type = Op.getValueType();
3403 int64_t Val = C->getSExtValue();
3404 if (isInt<16>(Val)) {
3405 Result = DAG.getTargetConstant(Val, Type);
3410 case 'J': // integer zero
3411 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3412 EVT Type = Op.getValueType();
3413 int64_t Val = C->getZExtValue();
3415 Result = DAG.getTargetConstant(0, Type);
3420 case 'K': // unsigned 16 bit immediate
3421 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3422 EVT Type = Op.getValueType();
3423 uint64_t Val = (uint64_t)C->getZExtValue();
3424 if (isUInt<16>(Val)) {
3425 Result = DAG.getTargetConstant(Val, Type);
3430 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3431 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3432 EVT Type = Op.getValueType();
3433 int64_t Val = C->getSExtValue();
3434 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3435 Result = DAG.getTargetConstant(Val, Type);
3440 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3441 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3442 EVT Type = Op.getValueType();
3443 int64_t Val = C->getSExtValue();
3444 if ((Val >= -65535) && (Val <= -1)) {
3445 Result = DAG.getTargetConstant(Val, Type);
3450 case 'O': // signed 15 bit immediate
3451 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3452 EVT Type = Op.getValueType();
3453 int64_t Val = C->getSExtValue();
3454 if ((isInt<15>(Val))) {
3455 Result = DAG.getTargetConstant(Val, Type);
3460 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3461 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3462 EVT Type = Op.getValueType();
3463 int64_t Val = C->getSExtValue();
3464 if ((Val <= 65535) && (Val >= 1)) {
3465 Result = DAG.getTargetConstant(Val, Type);
3472 if (Result.getNode()) {
3473 Ops.push_back(Result);
3477 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3480 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3482 // No global is ever allowed as a base.
3487 case 0: // "r+i" or just "i", depending on HasBaseReg.
3490 if (!AM.HasBaseReg) // allow "r+i".
3492 return false; // disallow "r+r" or "r+r+i".
3501 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3502 // The Mips target isn't yet aware of offsets.
3506 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3508 bool IsMemset, bool ZeroMemset,
3510 MachineFunction &MF) const {
3511 if (Subtarget.hasMips64())
3517 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3518 if (VT != MVT::f32 && VT != MVT::f64)
3520 if (Imm.isNegZero())
3522 return Imm.isZero();
3525 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3526 if (Subtarget.isABI_N64())
3527 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3529 return TargetLowering::getJumpTableEncoding();
3532 /// This function returns true if CallSym is a long double emulation routine.
3533 static bool isF128SoftLibCall(const char *CallSym) {
3534 const char *const LibCalls[] =
3535 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3536 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3537 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3538 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3539 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3540 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3541 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3542 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3545 const char *const *End = LibCalls + array_lengthof(LibCalls);
3547 // Check that LibCalls is sorted alphabetically.
3548 MipsTargetLowering::LTStr Comp;
3551 for (const char *const *I = LibCalls; I < End - 1; ++I)
3552 assert(Comp(*I, *(I + 1)));
3555 return std::binary_search(LibCalls, End, CallSym, Comp);
3558 /// This function returns true if Ty is fp128, {f128} or i128 which was
3559 /// originally a fp128.
3560 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3561 if (Ty->isFP128Ty())
3564 if (Ty->isStructTy() && Ty->getStructNumElements() == 1 &&
3565 Ty->getStructElementType(0)->isFP128Ty())
3568 const ExternalSymbolSDNode *ES =
3569 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3571 // If the Ty is i128 and the function being called is a long double emulation
3572 // routine, then the original type is f128.
3573 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3576 MipsTargetLowering::MipsCC::SpecialCallingConvType
3577 MipsTargetLowering::MipsCC::getSpecialCallingConv(const SDNode *Callee) const {
3578 MipsCC::SpecialCallingConvType SpecialCallingConv =
3579 MipsCC::NoSpecialCallingConv;
3580 if (Subtarget.inMips16HardFloat()) {
3581 if (const GlobalAddressSDNode *G =
3582 dyn_cast<const GlobalAddressSDNode>(Callee)) {
3583 llvm::StringRef Sym = G->getGlobal()->getName();
3584 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3585 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3586 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3590 return SpecialCallingConv;
3593 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CC,
3594 const MipsSubtarget &Subtarget_,
3596 : CallConv(CC), Subtarget(Subtarget_) {
3597 // Pre-allocate reserved argument area.
3598 Info.AllocateStack(reservedArgArea(), 1);
3601 void MipsTargetLowering::MipsCC::analyzeCallOperands(
3602 const SmallVectorImpl<ISD::OutputArg> &Args, bool IsVarArg,
3603 bool IsSoftFloat, const SDNode *CallNode,
3604 std::vector<ArgListEntry> &FuncArgs, CCState &State) {
3605 MipsCC::SpecialCallingConvType SpecialCallingConv =
3606 getSpecialCallingConv(CallNode);
3607 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3608 "CallingConv::Fast shouldn't be used for vararg functions.");
3610 unsigned NumOpnds = Args.size();
3611 llvm::CCAssignFn *FixedFn = CC_Mips_FixedArg;
3612 if (CallConv != CallingConv::Fast &&
3613 SpecialCallingConv == Mips16RetHelperConv)
3614 FixedFn = CC_Mips16RetHelper;
3616 for (unsigned I = 0; I != NumOpnds; ++I) {
3617 MVT ArgVT = Args[I].VT;
3618 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3621 if (IsVarArg && !Args[I].IsFixed)
3622 R = CC_Mips_VarArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, State);
3624 R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, State);
3628 dbgs() << "Call operand #" << I << " has unhandled type "
3629 << EVT(ArgVT).getEVTString();
3631 llvm_unreachable(nullptr);
3636 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3637 return (Subtarget.isABI_O32() && (CallConv != CallingConv::Fast)) ? 16 : 0;
3640 const ArrayRef<MCPhysReg> MipsTargetLowering::MipsCC::intArgRegs() const {
3641 if (Subtarget.isABI_O32())
3642 return makeArrayRef(O32IntRegs);
3643 return makeArrayRef(Mips64IntRegs);
3646 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3647 const SDNode *CallNode,
3648 bool IsSoftFloat) const {
3649 if (IsSoftFloat || Subtarget.isABI_O32())
3652 // Check if the original type was fp128.
3653 if (originalTypeIsF128(OrigTy, CallNode)) {
3654 assert(VT == MVT::i64);
3661 void MipsTargetLowering::copyByValRegs(
3662 SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains, SelectionDAG &DAG,
3663 const ISD::ArgFlagsTy &Flags, SmallVectorImpl<SDValue> &InVals,
3664 const Argument *FuncArg, const MipsCC &CC, unsigned FirstReg,
3665 unsigned LastReg, const CCValAssign &VA) const {
3666 MachineFunction &MF = DAG.getMachineFunction();
3667 MachineFrameInfo *MFI = MF.getFrameInfo();
3668 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3669 unsigned NumRegs = LastReg - FirstReg;
3670 unsigned RegAreaSize = NumRegs * GPRSizeInBytes;
3671 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3676 (int)CC.reservedArgArea() -
3677 (int)((CC.intArgRegs().size() - FirstReg) * GPRSizeInBytes);
3679 FrameObjOffset = VA.getLocMemOffset();
3681 // Create frame object.
3682 EVT PtrTy = getPointerTy();
3683 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3684 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3685 InVals.push_back(FIN);
3690 // Copy arg registers.
3691 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3692 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3694 for (unsigned I = 0; I < NumRegs; ++I) {
3695 unsigned ArgReg = CC.intArgRegs()[FirstReg + I];
3696 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3697 unsigned Offset = I * GPRSizeInBytes;
3698 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3699 DAG.getConstant(Offset, PtrTy));
3700 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3701 StorePtr, MachinePointerInfo(FuncArg, Offset),
3703 OutChains.push_back(Store);
3707 // Copy byVal arg to registers and stack.
3708 void MipsTargetLowering::passByValArg(
3709 SDValue Chain, SDLoc DL,
3710 std::deque<std::pair<unsigned, SDValue>> &RegsToPass,
3711 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3712 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg, const MipsCC &CC,
3713 unsigned FirstReg, unsigned LastReg, const ISD::ArgFlagsTy &Flags,
3714 bool isLittle, const CCValAssign &VA) const {
3715 unsigned ByValSizeInBytes = Flags.getByValSize();
3716 unsigned OffsetInBytes = 0; // From beginning of struct
3717 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3718 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3719 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3720 unsigned NumRegs = LastReg - FirstReg;
3723 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3724 bool LeftoverBytes = (NumRegs * RegSizeInBytes > ByValSizeInBytes);
3727 // Copy words to registers.
3728 for (; I < NumRegs - LeftoverBytes; ++I, OffsetInBytes += RegSizeInBytes) {
3729 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3730 DAG.getConstant(OffsetInBytes, PtrTy));
3731 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3732 MachinePointerInfo(), false, false, false,
3734 MemOpChains.push_back(LoadVal.getValue(1));
3735 unsigned ArgReg = ArgRegs[FirstReg + I];
3736 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3739 // Return if the struct has been fully copied.
3740 if (ByValSizeInBytes == OffsetInBytes)
3743 // Copy the remainder of the byval argument with sub-word loads and shifts.
3744 if (LeftoverBytes) {
3747 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3748 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3749 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3751 if (RemainingSizeInBytes < LoadSizeInBytes)
3755 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3756 DAG.getConstant(OffsetInBytes, PtrTy));
3757 SDValue LoadVal = DAG.getExtLoad(
3758 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3759 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3761 MemOpChains.push_back(LoadVal.getValue(1));
3763 // Shift the loaded value.
3767 Shamt = TotalBytesLoaded * 8;
3769 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3771 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3772 DAG.getConstant(Shamt, MVT::i32));
3775 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3779 OffsetInBytes += LoadSizeInBytes;
3780 TotalBytesLoaded += LoadSizeInBytes;
3781 Alignment = std::min(Alignment, LoadSizeInBytes);
3784 unsigned ArgReg = ArgRegs[FirstReg + I];
3785 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3790 // Copy remainder of byval arg to it with memcpy.
3791 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3792 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3793 DAG.getConstant(OffsetInBytes, PtrTy));
3794 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3795 DAG.getIntPtrConstant(VA.getLocMemOffset()));
3796 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3797 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3798 MachinePointerInfo(), MachinePointerInfo());
3799 MemOpChains.push_back(Chain);
3802 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3803 const MipsCC &CC, SDValue Chain,
3804 SDLoc DL, SelectionDAG &DAG,
3805 CCState &State) const {
3806 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3807 unsigned Idx = State.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3808 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3809 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3810 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3811 MachineFunction &MF = DAG.getMachineFunction();
3812 MachineFrameInfo *MFI = MF.getFrameInfo();
3813 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3815 // Offset of the first variable argument from stack pointer.
3818 if (ArgRegs.size() == Idx)
3820 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3822 VaArgOffset = (int)CC.reservedArgArea() -
3823 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3825 // Record the frame index of the first variable argument
3826 // which is a value necessary to VASTART.
3827 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3828 MipsFI->setVarArgsFrameIndex(FI);
3830 // Copy the integer registers that have not been used for argument passing
3831 // to the argument register save area. For O32, the save area is allocated
3832 // in the caller's stack frame, while for N32/64, it is allocated in the
3833 // callee's stack frame.
3834 for (unsigned I = Idx; I < ArgRegs.size();
3835 ++I, VaArgOffset += RegSizeInBytes) {
3836 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3837 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3838 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3839 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3840 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3841 MachinePointerInfo(), false, false, 0);
3842 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3844 OutChains.push_back(Store);
3848 void MipsTargetLowering::HandleByVal(CCState *State, unsigned &Size,
3849 unsigned Align) const {
3850 MachineFunction &MF = State->getMachineFunction();
3851 const TargetFrameLowering *TFL = MF.getSubtarget().getFrameLowering();
3853 assert(Size && "Byval argument's size shouldn't be 0.");
3855 Align = std::min(Align, TFL->getStackAlignment());
3857 unsigned FirstReg = 0;
3858 unsigned NumRegs = 0;
3860 if (State->getCallingConv() != CallingConv::Fast) {
3861 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3862 const ArrayRef<MCPhysReg> IntArgRegs = Subtarget.getABI().GetByValArgRegs();
3863 // FIXME: The O32 case actually describes no shadow registers.
3864 const MCPhysReg *ShadowRegs =
3865 Subtarget.isABI_O32() ? IntArgRegs.data() : Mips64DPRegs;
3867 // We used to check the size as well but we can't do that anymore since
3868 // CCState::HandleByVal() rounds up the size after calling this function.
3869 assert(!(Align % RegSizeInBytes) &&
3870 "Byval argument's alignment should be a multiple of"
3873 FirstReg = State->getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3875 // If Align > RegSizeInBytes, the first arg register must be even.
3876 // FIXME: This condition happens to do the right thing but it's not the
3877 // right way to test it. We want to check that the stack frame offset
3878 // of the register is aligned.
3879 if ((Align > RegSizeInBytes) && (FirstReg % 2)) {
3880 State->AllocateReg(IntArgRegs[FirstReg], ShadowRegs[FirstReg]);
3884 // Mark the registers allocated.
3885 Size = RoundUpToAlignment(Size, RegSizeInBytes);
3886 for (unsigned I = FirstReg; Size > 0 && (I < IntArgRegs.size());
3887 Size -= RegSizeInBytes, ++I, ++NumRegs)
3888 State->AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3891 State->addInRegsParamInfo(FirstReg, FirstReg + NumRegs);