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 const MachineFunction &MF = getMachineFunction();
104 for (unsigned i = 0; i < Outs.size(); ++i)
105 OriginalArgWasF128.push_back(
106 originalTypeIsF128(FuncArgs[Outs[i].OrigArgIndex].Ty, CallNode));
109 /// Identify lowered values that originated from f128 arguments and record
112 PreAnalyzeFormalArgumentsForF128(const SmallVectorImpl<ISD::InputArg> &Ins) {
113 const MachineFunction &MF = getMachineFunction();
114 for (unsigned i = 0; i < Ins.size(); ++i) {
115 Function::const_arg_iterator FuncArg = MF.getFunction()->arg_begin();
116 std::advance(FuncArg, Ins[i].OrigArgIndex);
118 OriginalArgWasF128.push_back(
119 originalTypeIsF128(FuncArg->getType(), nullptr));
123 /// Records whether the value has been lowered from an f128.
124 SmallVector<bool, 4> OriginalArgWasF128;
127 // FIXME: Remove this from a public inteface ASAP. It's a temporary trap door
128 // to allow analyzeCallOperands to be removed incrementally.
129 void PreAnalyzeCallOperandsForF128_(
130 const SmallVectorImpl<ISD::OutputArg> &Outs,
131 std::vector<TargetLowering::ArgListEntry> &FuncArgs, SDNode *CallNode) {
132 PreAnalyzeCallOperandsForF128(Outs, FuncArgs, CallNode);
134 // FIXME: Remove this from a public inteface ASAP. It's a temporary trap door
135 // to allow analyzeFormalArguments to be removed incrementally.
137 PreAnalyzeFormalArgumentsForF128_(const SmallVectorImpl<ISD::InputArg> &Ins) {
138 PreAnalyzeFormalArgumentsForF128(Ins);
140 // FIXME: Remove this from a public inteface ASAP. It's a temporary trap door
141 // to clean up after the above functions.
142 void ClearOriginalArgWasF128() { OriginalArgWasF128.clear(); }
144 MipsCCState(CallingConv::ID CC, bool isVarArg, MachineFunction &MF,
145 SmallVectorImpl<CCValAssign> &locs, LLVMContext &C)
146 : CCState(CC, isVarArg, MF, locs, C) {}
148 void AnalyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins,
150 const TargetLowering::CallLoweringInfo &CLI) {
151 PreAnalyzeCallResultForF128(Ins, CLI);
152 CCState::AnalyzeCallResult(Ins, Fn);
153 OriginalArgWasF128.clear();
156 void AnalyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs,
158 PreAnalyzeReturnForF128(Outs);
159 CCState::AnalyzeReturn(Outs, Fn);
160 OriginalArgWasF128.clear();
163 bool CheckReturn(const SmallVectorImpl<ISD::OutputArg> &ArgsFlags,
165 PreAnalyzeReturnForF128(ArgsFlags);
166 bool Return = CCState::CheckReturn(ArgsFlags, Fn);
167 OriginalArgWasF128.clear();
171 bool WasOriginalArgF128(unsigned ValNo) { return OriginalArgWasF128[ValNo]; }
175 // If I is a shifted mask, set the size (Size) and the first bit of the
176 // mask (Pos), and return true.
177 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
178 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
179 if (!isShiftedMask_64(I))
182 Size = CountPopulation_64(I);
183 Pos = countTrailingZeros(I);
187 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
188 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
189 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
192 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
194 unsigned Flag) const {
195 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
198 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
200 unsigned Flag) const {
201 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
204 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
206 unsigned Flag) const {
207 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
210 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
212 unsigned Flag) const {
213 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
216 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
218 unsigned Flag) const {
219 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
220 N->getOffset(), Flag);
223 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
225 case MipsISD::JmpLink: return "MipsISD::JmpLink";
226 case MipsISD::TailCall: return "MipsISD::TailCall";
227 case MipsISD::Hi: return "MipsISD::Hi";
228 case MipsISD::Lo: return "MipsISD::Lo";
229 case MipsISD::GPRel: return "MipsISD::GPRel";
230 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
231 case MipsISD::Ret: return "MipsISD::Ret";
232 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
233 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
234 case MipsISD::FPCmp: return "MipsISD::FPCmp";
235 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
236 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
237 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
238 case MipsISD::MFHI: return "MipsISD::MFHI";
239 case MipsISD::MFLO: return "MipsISD::MFLO";
240 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
241 case MipsISD::Mult: return "MipsISD::Mult";
242 case MipsISD::Multu: return "MipsISD::Multu";
243 case MipsISD::MAdd: return "MipsISD::MAdd";
244 case MipsISD::MAddu: return "MipsISD::MAddu";
245 case MipsISD::MSub: return "MipsISD::MSub";
246 case MipsISD::MSubu: return "MipsISD::MSubu";
247 case MipsISD::DivRem: return "MipsISD::DivRem";
248 case MipsISD::DivRemU: return "MipsISD::DivRemU";
249 case MipsISD::DivRem16: return "MipsISD::DivRem16";
250 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
251 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
252 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
253 case MipsISD::Wrapper: return "MipsISD::Wrapper";
254 case MipsISD::Sync: return "MipsISD::Sync";
255 case MipsISD::Ext: return "MipsISD::Ext";
256 case MipsISD::Ins: return "MipsISD::Ins";
257 case MipsISD::LWL: return "MipsISD::LWL";
258 case MipsISD::LWR: return "MipsISD::LWR";
259 case MipsISD::SWL: return "MipsISD::SWL";
260 case MipsISD::SWR: return "MipsISD::SWR";
261 case MipsISD::LDL: return "MipsISD::LDL";
262 case MipsISD::LDR: return "MipsISD::LDR";
263 case MipsISD::SDL: return "MipsISD::SDL";
264 case MipsISD::SDR: return "MipsISD::SDR";
265 case MipsISD::EXTP: return "MipsISD::EXTP";
266 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
267 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
268 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
269 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
270 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
271 case MipsISD::SHILO: return "MipsISD::SHILO";
272 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
273 case MipsISD::MULT: return "MipsISD::MULT";
274 case MipsISD::MULTU: return "MipsISD::MULTU";
275 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
276 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
277 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
278 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
279 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
280 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
281 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
282 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
283 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
284 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
285 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
286 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
287 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
288 case MipsISD::VCEQ: return "MipsISD::VCEQ";
289 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
290 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
291 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
292 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
293 case MipsISD::VSMAX: return "MipsISD::VSMAX";
294 case MipsISD::VSMIN: return "MipsISD::VSMIN";
295 case MipsISD::VUMAX: return "MipsISD::VUMAX";
296 case MipsISD::VUMIN: return "MipsISD::VUMIN";
297 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
298 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
299 case MipsISD::VNOR: return "MipsISD::VNOR";
300 case MipsISD::VSHF: return "MipsISD::VSHF";
301 case MipsISD::SHF: return "MipsISD::SHF";
302 case MipsISD::ILVEV: return "MipsISD::ILVEV";
303 case MipsISD::ILVOD: return "MipsISD::ILVOD";
304 case MipsISD::ILVL: return "MipsISD::ILVL";
305 case MipsISD::ILVR: return "MipsISD::ILVR";
306 case MipsISD::PCKEV: return "MipsISD::PCKEV";
307 case MipsISD::PCKOD: return "MipsISD::PCKOD";
308 case MipsISD::INSVE: return "MipsISD::INSVE";
309 default: return nullptr;
313 MipsTargetLowering::MipsTargetLowering(const MipsTargetMachine &TM,
314 const MipsSubtarget &STI)
315 : TargetLowering(TM, new MipsTargetObjectFile()), Subtarget(STI) {
316 // Mips does not have i1 type, so use i32 for
317 // setcc operations results (slt, sgt, ...).
318 setBooleanContents(ZeroOrOneBooleanContent);
319 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
320 // The cmp.cond.fmt instruction in MIPS32r6/MIPS64r6 uses 0 and -1 like MSA
321 // does. Integer booleans still use 0 and 1.
322 if (Subtarget.hasMips32r6())
323 setBooleanContents(ZeroOrOneBooleanContent,
324 ZeroOrNegativeOneBooleanContent);
326 // Load extented operations for i1 types must be promoted
327 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
328 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
329 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
331 // MIPS doesn't have extending float->double load/store
332 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
333 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
335 // Used by legalize types to correctly generate the setcc result.
336 // Without this, every float setcc comes with a AND/OR with the result,
337 // we don't want this, since the fpcmp result goes to a flag register,
338 // which is used implicitly by brcond and select operations.
339 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
341 // Mips Custom Operations
342 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
343 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
344 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
345 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
346 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
347 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
348 setOperationAction(ISD::SELECT, MVT::f32, Custom);
349 setOperationAction(ISD::SELECT, MVT::f64, Custom);
350 setOperationAction(ISD::SELECT, MVT::i32, Custom);
351 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
352 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
353 setOperationAction(ISD::SETCC, MVT::f32, Custom);
354 setOperationAction(ISD::SETCC, MVT::f64, Custom);
355 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
356 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
357 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
358 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
360 if (Subtarget.isGP64bit()) {
361 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
362 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
363 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
364 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
365 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
366 setOperationAction(ISD::SELECT, MVT::i64, Custom);
367 setOperationAction(ISD::LOAD, MVT::i64, Custom);
368 setOperationAction(ISD::STORE, MVT::i64, Custom);
369 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
372 if (!Subtarget.isGP64bit()) {
373 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
374 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
375 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
378 setOperationAction(ISD::ADD, MVT::i32, Custom);
379 if (Subtarget.isGP64bit())
380 setOperationAction(ISD::ADD, MVT::i64, Custom);
382 setOperationAction(ISD::SDIV, MVT::i32, Expand);
383 setOperationAction(ISD::SREM, MVT::i32, Expand);
384 setOperationAction(ISD::UDIV, MVT::i32, Expand);
385 setOperationAction(ISD::UREM, MVT::i32, Expand);
386 setOperationAction(ISD::SDIV, MVT::i64, Expand);
387 setOperationAction(ISD::SREM, MVT::i64, Expand);
388 setOperationAction(ISD::UDIV, MVT::i64, Expand);
389 setOperationAction(ISD::UREM, MVT::i64, Expand);
391 // Operations not directly supported by Mips.
392 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
393 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
394 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
395 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
396 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
397 setOperationAction(ISD::SELECT_CC, MVT::i64, Expand);
398 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
399 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
400 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
401 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
402 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
403 if (Subtarget.hasCnMips()) {
404 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
405 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
407 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
408 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
410 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
411 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
412 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
413 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
414 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
415 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
416 setOperationAction(ISD::ROTL, MVT::i32, Expand);
417 setOperationAction(ISD::ROTL, MVT::i64, Expand);
418 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
419 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
421 if (!Subtarget.hasMips32r2())
422 setOperationAction(ISD::ROTR, MVT::i32, Expand);
424 if (!Subtarget.hasMips64r2())
425 setOperationAction(ISD::ROTR, MVT::i64, Expand);
427 setOperationAction(ISD::FSIN, MVT::f32, Expand);
428 setOperationAction(ISD::FSIN, MVT::f64, Expand);
429 setOperationAction(ISD::FCOS, MVT::f32, Expand);
430 setOperationAction(ISD::FCOS, MVT::f64, Expand);
431 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
432 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
433 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
434 setOperationAction(ISD::FPOW, MVT::f32, Expand);
435 setOperationAction(ISD::FPOW, MVT::f64, Expand);
436 setOperationAction(ISD::FLOG, MVT::f32, Expand);
437 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
438 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
439 setOperationAction(ISD::FEXP, MVT::f32, Expand);
440 setOperationAction(ISD::FMA, MVT::f32, Expand);
441 setOperationAction(ISD::FMA, MVT::f64, Expand);
442 setOperationAction(ISD::FREM, MVT::f32, Expand);
443 setOperationAction(ISD::FREM, MVT::f64, Expand);
445 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
447 setOperationAction(ISD::VASTART, MVT::Other, Custom);
448 setOperationAction(ISD::VAARG, MVT::Other, Custom);
449 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
450 setOperationAction(ISD::VAEND, MVT::Other, Expand);
452 // Use the default for now
453 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
454 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
456 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
457 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
458 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
459 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
461 setInsertFencesForAtomic(true);
463 if (!Subtarget.hasMips32r2()) {
464 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
465 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
468 // MIPS16 lacks MIPS32's clz and clo instructions.
469 if (!Subtarget.hasMips32() || Subtarget.inMips16Mode())
470 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
471 if (!Subtarget.hasMips64())
472 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
474 if (!Subtarget.hasMips32r2())
475 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
476 if (!Subtarget.hasMips64r2())
477 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
479 if (Subtarget.isGP64bit()) {
480 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
481 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
482 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
483 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
486 setOperationAction(ISD::TRAP, MVT::Other, Legal);
488 setTargetDAGCombine(ISD::SDIVREM);
489 setTargetDAGCombine(ISD::UDIVREM);
490 setTargetDAGCombine(ISD::SELECT);
491 setTargetDAGCombine(ISD::AND);
492 setTargetDAGCombine(ISD::OR);
493 setTargetDAGCombine(ISD::ADD);
495 setMinFunctionAlignment(Subtarget.isGP64bit() ? 3 : 2);
497 // The arguments on the stack are defined in terms of 4-byte slots on O32
498 // and 8-byte slots on N32/N64.
499 setMinStackArgumentAlignment(
500 (Subtarget.isABI_N32() || Subtarget.isABI_N64()) ? 8 : 4);
502 setStackPointerRegisterToSaveRestore(Subtarget.isABI_N64() ? Mips::SP_64
505 setExceptionPointerRegister(Subtarget.isABI_N64() ? Mips::A0_64 : Mips::A0);
506 setExceptionSelectorRegister(Subtarget.isABI_N64() ? Mips::A1_64 : Mips::A1);
508 MaxStoresPerMemcpy = 16;
510 isMicroMips = Subtarget.inMicroMipsMode();
513 const MipsTargetLowering *MipsTargetLowering::create(const MipsTargetMachine &TM,
514 const MipsSubtarget &STI) {
515 if (STI.inMips16Mode())
516 return llvm::createMips16TargetLowering(TM, STI);
518 return llvm::createMipsSETargetLowering(TM, STI);
521 // Create a fast isel object.
523 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
524 const TargetLibraryInfo *libInfo) const {
525 if (!EnableMipsFastISel)
526 return TargetLowering::createFastISel(funcInfo, libInfo);
527 return Mips::createFastISel(funcInfo, libInfo);
530 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
533 return VT.changeVectorElementTypeToInteger();
536 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
537 TargetLowering::DAGCombinerInfo &DCI,
538 const MipsSubtarget &Subtarget) {
539 if (DCI.isBeforeLegalizeOps())
542 EVT Ty = N->getValueType(0);
543 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
544 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
545 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
549 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
550 N->getOperand(0), N->getOperand(1));
551 SDValue InChain = DAG.getEntryNode();
552 SDValue InGlue = DivRem;
555 if (N->hasAnyUseOfValue(0)) {
556 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
558 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
559 InChain = CopyFromLo.getValue(1);
560 InGlue = CopyFromLo.getValue(2);
564 if (N->hasAnyUseOfValue(1)) {
565 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
567 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
573 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
575 default: llvm_unreachable("Unknown fp condition code!");
577 case ISD::SETOEQ: return Mips::FCOND_OEQ;
578 case ISD::SETUNE: return Mips::FCOND_UNE;
580 case ISD::SETOLT: return Mips::FCOND_OLT;
582 case ISD::SETOGT: return Mips::FCOND_OGT;
584 case ISD::SETOLE: return Mips::FCOND_OLE;
586 case ISD::SETOGE: return Mips::FCOND_OGE;
587 case ISD::SETULT: return Mips::FCOND_ULT;
588 case ISD::SETULE: return Mips::FCOND_ULE;
589 case ISD::SETUGT: return Mips::FCOND_UGT;
590 case ISD::SETUGE: return Mips::FCOND_UGE;
591 case ISD::SETUO: return Mips::FCOND_UN;
592 case ISD::SETO: return Mips::FCOND_OR;
594 case ISD::SETONE: return Mips::FCOND_ONE;
595 case ISD::SETUEQ: return Mips::FCOND_UEQ;
600 /// This function returns true if the floating point conditional branches and
601 /// conditional moves which use condition code CC should be inverted.
602 static bool invertFPCondCodeUser(Mips::CondCode CC) {
603 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
606 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
607 "Illegal Condition Code");
612 // Creates and returns an FPCmp node from a setcc node.
613 // Returns Op if setcc is not a floating point comparison.
614 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
615 // must be a SETCC node
616 if (Op.getOpcode() != ISD::SETCC)
619 SDValue LHS = Op.getOperand(0);
621 if (!LHS.getValueType().isFloatingPoint())
624 SDValue RHS = Op.getOperand(1);
627 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
628 // node if necessary.
629 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
631 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
632 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
635 // Creates and returns a CMovFPT/F node.
636 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
637 SDValue False, SDLoc DL) {
638 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
639 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
640 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
642 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
643 True.getValueType(), True, FCC0, False, Cond);
646 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
647 TargetLowering::DAGCombinerInfo &DCI,
648 const MipsSubtarget &Subtarget) {
649 if (DCI.isBeforeLegalizeOps())
652 SDValue SetCC = N->getOperand(0);
654 if ((SetCC.getOpcode() != ISD::SETCC) ||
655 !SetCC.getOperand(0).getValueType().isInteger())
658 SDValue False = N->getOperand(2);
659 EVT FalseTy = False.getValueType();
661 if (!FalseTy.isInteger())
664 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
666 // If the RHS (False) is 0, we swap the order of the operands
667 // of ISD::SELECT (obviously also inverting the condition) so that we can
668 // take advantage of conditional moves using the $0 register.
670 // return (a != 0) ? x : 0;
678 if (!FalseC->getZExtValue()) {
679 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
680 SDValue True = N->getOperand(1);
682 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
683 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
685 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
688 // If both operands are integer constants there's a possibility that we
689 // can do some interesting optimizations.
690 SDValue True = N->getOperand(1);
691 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
693 if (!TrueC || !True.getValueType().isInteger())
696 // We'll also ignore MVT::i64 operands as this optimizations proves
697 // to be ineffective because of the required sign extensions as the result
698 // of a SETCC operator is always MVT::i32 for non-vector types.
699 if (True.getValueType() == MVT::i64)
702 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
704 // 1) (a < x) ? y : y-1
706 // addiu $reg2, $reg1, y-1
708 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
710 // 2) (a < x) ? y-1 : y
712 // xor $reg1, $reg1, 1
713 // addiu $reg2, $reg1, y-1
715 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
716 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
717 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
718 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
721 // Couldn't optimize.
725 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
726 TargetLowering::DAGCombinerInfo &DCI,
727 const MipsSubtarget &Subtarget) {
728 // Pattern match EXT.
729 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
730 // => ext $dst, $src, size, pos
731 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
734 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
735 unsigned ShiftRightOpc = ShiftRight.getOpcode();
737 // Op's first operand must be a shift right.
738 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
741 // The second operand of the shift must be an immediate.
743 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
746 uint64_t Pos = CN->getZExtValue();
747 uint64_t SMPos, SMSize;
749 // Op's second operand must be a shifted mask.
750 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
751 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
754 // Return if the shifted mask does not start at bit 0 or the sum of its size
755 // and Pos exceeds the word's size.
756 EVT ValTy = N->getValueType(0);
757 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
760 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
761 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
762 DAG.getConstant(SMSize, MVT::i32));
765 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
766 TargetLowering::DAGCombinerInfo &DCI,
767 const MipsSubtarget &Subtarget) {
768 // Pattern match INS.
769 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
770 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
771 // => ins $dst, $src, size, pos, $src1
772 if (DCI.isBeforeLegalizeOps() || !Subtarget.hasExtractInsert())
775 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
776 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
779 // See if Op's first operand matches (and $src1 , mask0).
780 if (And0.getOpcode() != ISD::AND)
783 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
784 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
787 // See if Op's second operand matches (and (shl $src, pos), mask1).
788 if (And1.getOpcode() != ISD::AND)
791 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
792 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
795 // The shift masks must have the same position and size.
796 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
799 SDValue Shl = And1.getOperand(0);
800 if (Shl.getOpcode() != ISD::SHL)
803 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
806 unsigned Shamt = CN->getZExtValue();
808 // Return if the shift amount and the first bit position of mask are not the
810 EVT ValTy = N->getValueType(0);
811 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
814 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
815 DAG.getConstant(SMPos0, MVT::i32),
816 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
819 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
820 TargetLowering::DAGCombinerInfo &DCI,
821 const MipsSubtarget &Subtarget) {
822 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
824 if (DCI.isBeforeLegalizeOps())
827 SDValue Add = N->getOperand(1);
829 if (Add.getOpcode() != ISD::ADD)
832 SDValue Lo = Add.getOperand(1);
834 if ((Lo.getOpcode() != MipsISD::Lo) ||
835 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
838 EVT ValTy = N->getValueType(0);
841 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
843 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
846 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
848 SelectionDAG &DAG = DCI.DAG;
849 unsigned Opc = N->getOpcode();
855 return performDivRemCombine(N, DAG, DCI, Subtarget);
857 return performSELECTCombine(N, DAG, DCI, Subtarget);
859 return performANDCombine(N, DAG, DCI, Subtarget);
861 return performORCombine(N, DAG, DCI, Subtarget);
863 return performADDCombine(N, DAG, DCI, Subtarget);
870 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
871 SmallVectorImpl<SDValue> &Results,
872 SelectionDAG &DAG) const {
873 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
875 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
876 Results.push_back(Res.getValue(I));
880 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
881 SmallVectorImpl<SDValue> &Results,
882 SelectionDAG &DAG) const {
883 return LowerOperationWrapper(N, Results, DAG);
886 SDValue MipsTargetLowering::
887 LowerOperation(SDValue Op, SelectionDAG &DAG) const
889 switch (Op.getOpcode())
891 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
892 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
893 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
894 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
895 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
896 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
897 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
898 case ISD::SELECT: return lowerSELECT(Op, DAG);
899 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
900 case ISD::SETCC: return lowerSETCC(Op, DAG);
901 case ISD::VASTART: return lowerVASTART(Op, DAG);
902 case ISD::VAARG: return lowerVAARG(Op, DAG);
903 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
904 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
905 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
906 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
907 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
908 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
909 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
910 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
911 case ISD::LOAD: return lowerLOAD(Op, DAG);
912 case ISD::STORE: return lowerSTORE(Op, DAG);
913 case ISD::ADD: return lowerADD(Op, DAG);
914 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
919 //===----------------------------------------------------------------------===//
920 // Lower helper functions
921 //===----------------------------------------------------------------------===//
923 // addLiveIn - This helper function adds the specified physical register to the
924 // MachineFunction as a live in value. It also creates a corresponding
925 // virtual register for it.
927 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
929 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
930 MF.getRegInfo().addLiveIn(PReg, VReg);
934 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
935 MachineBasicBlock &MBB,
936 const TargetInstrInfo &TII,
941 // Insert instruction "teq $divisor_reg, $zero, 7".
942 MachineBasicBlock::iterator I(MI);
943 MachineInstrBuilder MIB;
944 MachineOperand &Divisor = MI->getOperand(2);
945 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
946 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
947 .addReg(Mips::ZERO).addImm(7);
949 // Use the 32-bit sub-register if this is a 64-bit division.
951 MIB->getOperand(0).setSubReg(Mips::sub_32);
953 // Clear Divisor's kill flag.
954 Divisor.setIsKill(false);
956 // We would normally delete the original instruction here but in this case
957 // we only needed to inject an additional instruction rather than replace it.
963 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
964 MachineBasicBlock *BB) const {
965 switch (MI->getOpcode()) {
967 llvm_unreachable("Unexpected instr type to insert");
968 case Mips::ATOMIC_LOAD_ADD_I8:
969 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
970 case Mips::ATOMIC_LOAD_ADD_I16:
971 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
972 case Mips::ATOMIC_LOAD_ADD_I32:
973 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
974 case Mips::ATOMIC_LOAD_ADD_I64:
975 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
977 case Mips::ATOMIC_LOAD_AND_I8:
978 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
979 case Mips::ATOMIC_LOAD_AND_I16:
980 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
981 case Mips::ATOMIC_LOAD_AND_I32:
982 return emitAtomicBinary(MI, BB, 4, Mips::AND);
983 case Mips::ATOMIC_LOAD_AND_I64:
984 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
986 case Mips::ATOMIC_LOAD_OR_I8:
987 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
988 case Mips::ATOMIC_LOAD_OR_I16:
989 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
990 case Mips::ATOMIC_LOAD_OR_I32:
991 return emitAtomicBinary(MI, BB, 4, Mips::OR);
992 case Mips::ATOMIC_LOAD_OR_I64:
993 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
995 case Mips::ATOMIC_LOAD_XOR_I8:
996 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
997 case Mips::ATOMIC_LOAD_XOR_I16:
998 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
999 case Mips::ATOMIC_LOAD_XOR_I32:
1000 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
1001 case Mips::ATOMIC_LOAD_XOR_I64:
1002 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
1004 case Mips::ATOMIC_LOAD_NAND_I8:
1005 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
1006 case Mips::ATOMIC_LOAD_NAND_I16:
1007 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
1008 case Mips::ATOMIC_LOAD_NAND_I32:
1009 return emitAtomicBinary(MI, BB, 4, 0, true);
1010 case Mips::ATOMIC_LOAD_NAND_I64:
1011 return emitAtomicBinary(MI, BB, 8, 0, true);
1013 case Mips::ATOMIC_LOAD_SUB_I8:
1014 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1015 case Mips::ATOMIC_LOAD_SUB_I16:
1016 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1017 case Mips::ATOMIC_LOAD_SUB_I32:
1018 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
1019 case Mips::ATOMIC_LOAD_SUB_I64:
1020 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1022 case Mips::ATOMIC_SWAP_I8:
1023 return emitAtomicBinaryPartword(MI, BB, 1, 0);
1024 case Mips::ATOMIC_SWAP_I16:
1025 return emitAtomicBinaryPartword(MI, BB, 2, 0);
1026 case Mips::ATOMIC_SWAP_I32:
1027 return emitAtomicBinary(MI, BB, 4, 0);
1028 case Mips::ATOMIC_SWAP_I64:
1029 return emitAtomicBinary(MI, BB, 8, 0);
1031 case Mips::ATOMIC_CMP_SWAP_I8:
1032 return emitAtomicCmpSwapPartword(MI, BB, 1);
1033 case Mips::ATOMIC_CMP_SWAP_I16:
1034 return emitAtomicCmpSwapPartword(MI, BB, 2);
1035 case Mips::ATOMIC_CMP_SWAP_I32:
1036 return emitAtomicCmpSwap(MI, BB, 4);
1037 case Mips::ATOMIC_CMP_SWAP_I64:
1038 return emitAtomicCmpSwap(MI, BB, 8);
1039 case Mips::PseudoSDIV:
1040 case Mips::PseudoUDIV:
1045 return insertDivByZeroTrap(
1046 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), false);
1047 case Mips::PseudoDSDIV:
1048 case Mips::PseudoDUDIV:
1053 return insertDivByZeroTrap(
1054 MI, *BB, *getTargetMachine().getSubtargetImpl()->getInstrInfo(), true);
1056 return emitSEL_D(MI, BB);
1060 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1061 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1063 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1064 unsigned Size, unsigned BinOpcode,
1066 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1068 MachineFunction *MF = BB->getParent();
1069 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1070 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1071 const TargetInstrInfo *TII =
1072 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1073 DebugLoc DL = MI->getDebugLoc();
1074 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1081 LL = Subtarget.hasMips32r6() ? Mips::LL_R6 : Mips::LL;
1082 SC = Subtarget.hasMips32r6() ? Mips::SC_R6 : Mips::SC;
1089 LL = Subtarget.hasMips64r6() ? Mips::LLD_R6 : Mips::LLD;
1090 SC = Subtarget.hasMips64r6() ? Mips::SCD_R6 : Mips::SCD;
1093 ZERO = Mips::ZERO_64;
1097 unsigned OldVal = MI->getOperand(0).getReg();
1098 unsigned Ptr = MI->getOperand(1).getReg();
1099 unsigned Incr = MI->getOperand(2).getReg();
1101 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1102 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1103 unsigned Success = RegInfo.createVirtualRegister(RC);
1105 // insert new blocks after the current block
1106 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1107 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1108 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1109 MachineFunction::iterator It = BB;
1111 MF->insert(It, loopMBB);
1112 MF->insert(It, exitMBB);
1114 // Transfer the remainder of BB and its successor edges to exitMBB.
1115 exitMBB->splice(exitMBB->begin(), BB,
1116 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1117 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1121 // fallthrough --> loopMBB
1122 BB->addSuccessor(loopMBB);
1123 loopMBB->addSuccessor(loopMBB);
1124 loopMBB->addSuccessor(exitMBB);
1127 // ll oldval, 0(ptr)
1128 // <binop> storeval, oldval, incr
1129 // sc success, storeval, 0(ptr)
1130 // beq success, $0, loopMBB
1132 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1134 // and andres, oldval, incr
1135 // nor storeval, $0, andres
1136 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1137 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1138 } else if (BinOpcode) {
1139 // <binop> storeval, oldval, incr
1140 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1144 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1145 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1147 MI->eraseFromParent(); // The instruction is gone now.
1152 MachineBasicBlock *MipsTargetLowering::emitSignExtendToI32InReg(
1153 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned DstReg,
1154 unsigned SrcReg) const {
1155 const TargetInstrInfo *TII =
1156 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1157 DebugLoc DL = MI->getDebugLoc();
1159 if (Subtarget.hasMips32r2() && Size == 1) {
1160 BuildMI(BB, DL, TII->get(Mips::SEB), DstReg).addReg(SrcReg);
1164 if (Subtarget.hasMips32r2() && Size == 2) {
1165 BuildMI(BB, DL, TII->get(Mips::SEH), DstReg).addReg(SrcReg);
1169 MachineFunction *MF = BB->getParent();
1170 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1171 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1172 unsigned ScrReg = RegInfo.createVirtualRegister(RC);
1175 int64_t ShiftImm = 32 - (Size * 8);
1177 BuildMI(BB, DL, TII->get(Mips::SLL), ScrReg).addReg(SrcReg).addImm(ShiftImm);
1178 BuildMI(BB, DL, TII->get(Mips::SRA), DstReg).addReg(ScrReg).addImm(ShiftImm);
1183 MachineBasicBlock *MipsTargetLowering::emitAtomicBinaryPartword(
1184 MachineInstr *MI, MachineBasicBlock *BB, unsigned Size, unsigned BinOpcode,
1186 assert((Size == 1 || Size == 2) &&
1187 "Unsupported size for EmitAtomicBinaryPartial.");
1189 MachineFunction *MF = BB->getParent();
1190 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1191 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1192 const TargetInstrInfo *TII =
1193 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1194 DebugLoc DL = MI->getDebugLoc();
1196 unsigned Dest = MI->getOperand(0).getReg();
1197 unsigned Ptr = MI->getOperand(1).getReg();
1198 unsigned Incr = MI->getOperand(2).getReg();
1200 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1201 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1202 unsigned Mask = RegInfo.createVirtualRegister(RC);
1203 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1204 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1205 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1206 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1207 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1208 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1209 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1210 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1211 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1212 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1213 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1214 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1215 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1216 unsigned Success = RegInfo.createVirtualRegister(RC);
1218 // insert new blocks after the current block
1219 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1220 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1221 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1222 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1223 MachineFunction::iterator It = BB;
1225 MF->insert(It, loopMBB);
1226 MF->insert(It, sinkMBB);
1227 MF->insert(It, exitMBB);
1229 // Transfer the remainder of BB and its successor edges to exitMBB.
1230 exitMBB->splice(exitMBB->begin(), BB,
1231 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1232 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1234 BB->addSuccessor(loopMBB);
1235 loopMBB->addSuccessor(loopMBB);
1236 loopMBB->addSuccessor(sinkMBB);
1237 sinkMBB->addSuccessor(exitMBB);
1240 // addiu masklsb2,$0,-4 # 0xfffffffc
1241 // and alignedaddr,ptr,masklsb2
1242 // andi ptrlsb2,ptr,3
1243 // sll shiftamt,ptrlsb2,3
1244 // ori maskupper,$0,255 # 0xff
1245 // sll mask,maskupper,shiftamt
1246 // nor mask2,$0,mask
1247 // sll incr2,incr,shiftamt
1249 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1250 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1251 .addReg(Mips::ZERO).addImm(-4);
1252 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1253 .addReg(Ptr).addReg(MaskLSB2);
1254 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1255 if (Subtarget.isLittle()) {
1256 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1258 unsigned Off = RegInfo.createVirtualRegister(RC);
1259 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1260 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1261 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1263 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1264 .addReg(Mips::ZERO).addImm(MaskImm);
1265 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1266 .addReg(MaskUpper).addReg(ShiftAmt);
1267 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1268 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1270 // atomic.load.binop
1272 // ll oldval,0(alignedaddr)
1273 // binop binopres,oldval,incr2
1274 // and newval,binopres,mask
1275 // and maskedoldval0,oldval,mask2
1276 // or storeval,maskedoldval0,newval
1277 // sc success,storeval,0(alignedaddr)
1278 // beq success,$0,loopMBB
1282 // ll oldval,0(alignedaddr)
1283 // and newval,incr2,mask
1284 // and maskedoldval0,oldval,mask2
1285 // or storeval,maskedoldval0,newval
1286 // sc success,storeval,0(alignedaddr)
1287 // beq success,$0,loopMBB
1290 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1292 // and andres, oldval, incr2
1293 // nor binopres, $0, andres
1294 // and newval, binopres, mask
1295 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1296 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1297 .addReg(Mips::ZERO).addReg(AndRes);
1298 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1299 } else if (BinOpcode) {
1300 // <binop> binopres, oldval, incr2
1301 // and newval, binopres, mask
1302 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1303 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1304 } else { // atomic.swap
1305 // and newval, incr2, mask
1306 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1309 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1310 .addReg(OldVal).addReg(Mask2);
1311 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1312 .addReg(MaskedOldVal0).addReg(NewVal);
1313 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1314 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1315 BuildMI(BB, DL, TII->get(Mips::BEQ))
1316 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1319 // and maskedoldval1,oldval,mask
1320 // srl srlres,maskedoldval1,shiftamt
1321 // sign_extend dest,srlres
1324 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1325 .addReg(OldVal).addReg(Mask);
1326 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1327 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1328 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1330 MI->eraseFromParent(); // The instruction is gone now.
1335 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1336 MachineBasicBlock *BB,
1337 unsigned Size) const {
1338 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1340 MachineFunction *MF = BB->getParent();
1341 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1342 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1343 const TargetInstrInfo *TII =
1344 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1345 DebugLoc DL = MI->getDebugLoc();
1346 unsigned LL, SC, ZERO, BNE, BEQ;
1349 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1350 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1357 ZERO = Mips::ZERO_64;
1362 unsigned Dest = MI->getOperand(0).getReg();
1363 unsigned Ptr = MI->getOperand(1).getReg();
1364 unsigned OldVal = MI->getOperand(2).getReg();
1365 unsigned NewVal = MI->getOperand(3).getReg();
1367 unsigned Success = RegInfo.createVirtualRegister(RC);
1369 // insert new blocks after the current block
1370 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1371 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1372 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1373 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1374 MachineFunction::iterator It = BB;
1376 MF->insert(It, loop1MBB);
1377 MF->insert(It, loop2MBB);
1378 MF->insert(It, exitMBB);
1380 // Transfer the remainder of BB and its successor edges to exitMBB.
1381 exitMBB->splice(exitMBB->begin(), BB,
1382 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1383 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1387 // fallthrough --> loop1MBB
1388 BB->addSuccessor(loop1MBB);
1389 loop1MBB->addSuccessor(exitMBB);
1390 loop1MBB->addSuccessor(loop2MBB);
1391 loop2MBB->addSuccessor(loop1MBB);
1392 loop2MBB->addSuccessor(exitMBB);
1396 // bne dest, oldval, exitMBB
1398 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1399 BuildMI(BB, DL, TII->get(BNE))
1400 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1403 // sc success, newval, 0(ptr)
1404 // beq success, $0, loop1MBB
1406 BuildMI(BB, DL, TII->get(SC), Success)
1407 .addReg(NewVal).addReg(Ptr).addImm(0);
1408 BuildMI(BB, DL, TII->get(BEQ))
1409 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1411 MI->eraseFromParent(); // The instruction is gone now.
1417 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1418 MachineBasicBlock *BB,
1419 unsigned Size) const {
1420 assert((Size == 1 || Size == 2) &&
1421 "Unsupported size for EmitAtomicCmpSwapPartial.");
1423 MachineFunction *MF = BB->getParent();
1424 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1425 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1426 const TargetInstrInfo *TII =
1427 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1428 DebugLoc DL = MI->getDebugLoc();
1430 unsigned Dest = MI->getOperand(0).getReg();
1431 unsigned Ptr = MI->getOperand(1).getReg();
1432 unsigned CmpVal = MI->getOperand(2).getReg();
1433 unsigned NewVal = MI->getOperand(3).getReg();
1435 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1436 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1437 unsigned Mask = RegInfo.createVirtualRegister(RC);
1438 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1439 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1440 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1441 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1442 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1443 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1444 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1445 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1446 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1447 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1448 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1449 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1450 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1451 unsigned Success = RegInfo.createVirtualRegister(RC);
1453 // insert new blocks after the current block
1454 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1455 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1456 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1457 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1458 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1459 MachineFunction::iterator It = BB;
1461 MF->insert(It, loop1MBB);
1462 MF->insert(It, loop2MBB);
1463 MF->insert(It, sinkMBB);
1464 MF->insert(It, exitMBB);
1466 // Transfer the remainder of BB and its successor edges to exitMBB.
1467 exitMBB->splice(exitMBB->begin(), BB,
1468 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1469 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1471 BB->addSuccessor(loop1MBB);
1472 loop1MBB->addSuccessor(sinkMBB);
1473 loop1MBB->addSuccessor(loop2MBB);
1474 loop2MBB->addSuccessor(loop1MBB);
1475 loop2MBB->addSuccessor(sinkMBB);
1476 sinkMBB->addSuccessor(exitMBB);
1478 // FIXME: computation of newval2 can be moved to loop2MBB.
1480 // addiu masklsb2,$0,-4 # 0xfffffffc
1481 // and alignedaddr,ptr,masklsb2
1482 // andi ptrlsb2,ptr,3
1483 // sll shiftamt,ptrlsb2,3
1484 // ori maskupper,$0,255 # 0xff
1485 // sll mask,maskupper,shiftamt
1486 // nor mask2,$0,mask
1487 // andi maskedcmpval,cmpval,255
1488 // sll shiftedcmpval,maskedcmpval,shiftamt
1489 // andi maskednewval,newval,255
1490 // sll shiftednewval,maskednewval,shiftamt
1491 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1492 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1493 .addReg(Mips::ZERO).addImm(-4);
1494 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1495 .addReg(Ptr).addReg(MaskLSB2);
1496 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1497 if (Subtarget.isLittle()) {
1498 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1500 unsigned Off = RegInfo.createVirtualRegister(RC);
1501 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1502 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1503 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1505 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1506 .addReg(Mips::ZERO).addImm(MaskImm);
1507 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1508 .addReg(MaskUpper).addReg(ShiftAmt);
1509 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1510 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1511 .addReg(CmpVal).addImm(MaskImm);
1512 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1513 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1514 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1515 .addReg(NewVal).addImm(MaskImm);
1516 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1517 .addReg(MaskedNewVal).addReg(ShiftAmt);
1520 // ll oldval,0(alginedaddr)
1521 // and maskedoldval0,oldval,mask
1522 // bne maskedoldval0,shiftedcmpval,sinkMBB
1524 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1525 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1526 .addReg(OldVal).addReg(Mask);
1527 BuildMI(BB, DL, TII->get(Mips::BNE))
1528 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1531 // and maskedoldval1,oldval,mask2
1532 // or storeval,maskedoldval1,shiftednewval
1533 // sc success,storeval,0(alignedaddr)
1534 // beq success,$0,loop1MBB
1536 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1537 .addReg(OldVal).addReg(Mask2);
1538 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1539 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1540 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1541 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1542 BuildMI(BB, DL, TII->get(Mips::BEQ))
1543 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1546 // srl srlres,maskedoldval0,shiftamt
1547 // sign_extend dest,srlres
1550 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1551 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1552 BB = emitSignExtendToI32InReg(MI, BB, Size, Dest, SrlRes);
1554 MI->eraseFromParent(); // The instruction is gone now.
1559 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1560 MachineBasicBlock *BB) const {
1561 MachineFunction *MF = BB->getParent();
1562 const TargetRegisterInfo *TRI =
1563 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
1564 const TargetInstrInfo *TII =
1565 getTargetMachine().getSubtargetImpl()->getInstrInfo();
1566 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1567 DebugLoc DL = MI->getDebugLoc();
1568 MachineBasicBlock::iterator II(MI);
1570 unsigned Fc = MI->getOperand(1).getReg();
1571 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1573 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1575 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1578 .addImm(Mips::sub_lo);
1580 // We don't erase the original instruction, we just replace the condition
1581 // register with the 64-bit super-register.
1582 MI->getOperand(1).setReg(Fc2);
1587 //===----------------------------------------------------------------------===//
1588 // Misc Lower Operation implementation
1589 //===----------------------------------------------------------------------===//
1590 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1591 SDValue Chain = Op.getOperand(0);
1592 SDValue Table = Op.getOperand(1);
1593 SDValue Index = Op.getOperand(2);
1595 EVT PTy = getPointerTy();
1596 unsigned EntrySize =
1597 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1599 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1600 DAG.getConstant(EntrySize, PTy));
1601 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1603 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1604 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1605 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1607 Chain = Addr.getValue(1);
1609 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) ||
1610 Subtarget.isABI_N64()) {
1611 // For PIC, the sequence is:
1612 // BRIND(load(Jumptable + index) + RelocBase)
1613 // RelocBase can be JumpTable, GOT or some sort of global base.
1614 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1615 getPICJumpTableRelocBase(Table, DAG));
1618 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1621 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1622 // The first operand is the chain, the second is the condition, the third is
1623 // the block to branch to if the condition is true.
1624 SDValue Chain = Op.getOperand(0);
1625 SDValue Dest = Op.getOperand(2);
1628 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1629 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1631 // Return if flag is not set by a floating point comparison.
1632 if (CondRes.getOpcode() != MipsISD::FPCmp)
1635 SDValue CCNode = CondRes.getOperand(2);
1637 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1638 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1639 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1640 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1641 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1642 FCC0, Dest, CondRes);
1645 SDValue MipsTargetLowering::
1646 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1648 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1649 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1651 // Return if flag is not set by a floating point comparison.
1652 if (Cond.getOpcode() != MipsISD::FPCmp)
1655 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1659 SDValue MipsTargetLowering::
1660 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1663 EVT Ty = Op.getOperand(0).getValueType();
1664 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1665 getSetCCResultType(*DAG.getContext(), Ty),
1666 Op.getOperand(0), Op.getOperand(1),
1669 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1673 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1674 assert(!Subtarget.hasMips32r6() && !Subtarget.hasMips64r6());
1675 SDValue Cond = createFPCmp(DAG, Op);
1677 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1678 "Floating point operand expected.");
1680 SDValue True = DAG.getConstant(1, MVT::i32);
1681 SDValue False = DAG.getConstant(0, MVT::i32);
1683 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1686 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1687 SelectionDAG &DAG) const {
1688 // FIXME there isn't actually debug info here
1690 EVT Ty = Op.getValueType();
1691 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1692 const GlobalValue *GV = N->getGlobal();
1694 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1695 !Subtarget.isABI_N64()) {
1696 const MipsTargetObjectFile &TLOF =
1697 (const MipsTargetObjectFile&)getObjFileLowering();
1699 // %gp_rel relocation
1700 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1701 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1703 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1704 DAG.getVTList(MVT::i32), GA);
1705 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1706 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1709 // %hi/%lo relocation
1710 return getAddrNonPIC(N, Ty, DAG);
1713 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1714 return getAddrLocal(N, Ty, DAG,
1715 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1718 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1719 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1720 MachinePointerInfo::getGOT());
1722 return getAddrGlobal(N, Ty, DAG,
1723 (Subtarget.isABI_N32() || Subtarget.isABI_N64())
1724 ? MipsII::MO_GOT_DISP
1726 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1729 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1730 SelectionDAG &DAG) const {
1731 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1732 EVT Ty = Op.getValueType();
1734 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1735 !Subtarget.isABI_N64())
1736 return getAddrNonPIC(N, Ty, DAG);
1738 return getAddrLocal(N, Ty, DAG,
1739 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1742 SDValue MipsTargetLowering::
1743 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1745 // If the relocation model is PIC, use the General Dynamic TLS Model or
1746 // Local Dynamic TLS model, otherwise use the Initial Exec or
1747 // Local Exec TLS Model.
1749 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1751 const GlobalValue *GV = GA->getGlobal();
1752 EVT PtrVT = getPointerTy();
1754 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1756 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1757 // General Dynamic and Local Dynamic TLS Model.
1758 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1761 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1762 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1763 getGlobalReg(DAG, PtrVT), TGA);
1764 unsigned PtrSize = PtrVT.getSizeInBits();
1765 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1767 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1771 Entry.Node = Argument;
1773 Args.push_back(Entry);
1775 TargetLowering::CallLoweringInfo CLI(DAG);
1776 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1777 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, std::move(Args), 0);
1778 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1780 SDValue Ret = CallResult.first;
1782 if (model != TLSModel::LocalDynamic)
1785 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1786 MipsII::MO_DTPREL_HI);
1787 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1788 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1789 MipsII::MO_DTPREL_LO);
1790 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1791 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1792 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1796 if (model == TLSModel::InitialExec) {
1797 // Initial Exec TLS Model
1798 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1799 MipsII::MO_GOTTPREL);
1800 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1802 Offset = DAG.getLoad(PtrVT, DL,
1803 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1804 false, false, false, 0);
1806 // Local Exec TLS Model
1807 assert(model == TLSModel::LocalExec);
1808 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1809 MipsII::MO_TPREL_HI);
1810 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1811 MipsII::MO_TPREL_LO);
1812 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1813 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1814 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1817 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1818 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1821 SDValue MipsTargetLowering::
1822 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1824 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1825 EVT Ty = Op.getValueType();
1827 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1828 !Subtarget.isABI_N64())
1829 return getAddrNonPIC(N, Ty, DAG);
1831 return getAddrLocal(N, Ty, DAG,
1832 Subtarget.isABI_N32() || Subtarget.isABI_N64());
1835 SDValue MipsTargetLowering::
1836 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1838 // gp_rel relocation
1839 // FIXME: we should reference the constant pool using small data sections,
1840 // but the asm printer currently doesn't support this feature without
1841 // hacking it. This feature should come soon so we can uncomment the
1843 //if (IsInSmallSection(C->getType())) {
1844 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1845 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1846 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1847 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1848 EVT Ty = Op.getValueType();
1850 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ &&
1851 !Subtarget.isABI_N64())
1852 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.
2606 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2607 *MF.getInfo<MipsFunctionInfo>());
2609 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2610 report_fatal_error("failed to perform tail call elimination on a call "
2611 "site marked musttail");
2616 // Chain is the output chain of the last Load/Store or CopyToReg node.
2617 // ByValChain is the output chain of the last Memcpy node created for copying
2618 // byval arguments to the stack.
2619 unsigned StackAlignment = TFL->getStackAlignment();
2620 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2621 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2624 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2626 SDValue StackPtr = DAG.getCopyFromReg(
2627 Chain, DL, Subtarget.isABI_N64() ? Mips::SP_64 : Mips::SP,
2630 // With EABI is it possible to have 16 args on registers.
2631 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2632 SmallVector<SDValue, 8> MemOpChains;
2633 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
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 assert(Flags.getByValSize() &&
2645 "ByVal args of size 0 should have been ignored by front-end.");
2646 assert(ByValArg != MipsCCInfo.byval_end());
2647 assert(!IsTailCall &&
2648 "Do not tail-call optimize if there is a byval argument.");
2649 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2650 MipsCCInfo, *ByValArg, Flags, Subtarget.isLittle());
2655 // Promote the value if needed.
2656 switch (VA.getLocInfo()) {
2657 default: llvm_unreachable("Unknown loc info!");
2658 case CCValAssign::Full:
2659 if (VA.isRegLoc()) {
2660 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2661 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2662 (ValVT == MVT::i64 && LocVT == MVT::f64))
2663 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2664 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2665 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2666 Arg, DAG.getConstant(0, MVT::i32));
2667 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2668 Arg, DAG.getConstant(1, MVT::i32));
2669 if (!Subtarget.isLittle())
2671 unsigned LocRegLo = VA.getLocReg();
2672 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2673 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2674 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2679 case CCValAssign::BCvt:
2680 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2682 case CCValAssign::SExt:
2683 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2685 case CCValAssign::ZExt:
2686 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2688 case CCValAssign::AExt:
2689 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2693 // Arguments that can be passed on register must be kept at
2694 // RegsToPass vector
2695 if (VA.isRegLoc()) {
2696 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2700 // Register can't get to this point...
2701 assert(VA.isMemLoc());
2703 // emit ISD::STORE whichs stores the
2704 // parameter value to a stack Location
2705 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2706 Chain, Arg, DL, IsTailCall, DAG));
2709 // Transform all store nodes into one single node because all store
2710 // nodes are independent of each other.
2711 if (!MemOpChains.empty())
2712 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2714 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2715 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2716 // node so that legalize doesn't hack it.
2718 (Subtarget.isABI_N64() || IsPIC); // true if calls are translated to
2720 bool GlobalOrExternal = false, InternalLinkage = false, IsCallReloc = false;
2722 EVT Ty = Callee.getValueType();
2724 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2726 const GlobalValue *Val = G->getGlobal();
2727 InternalLinkage = Val->hasInternalLinkage();
2729 if (InternalLinkage)
2730 Callee = getAddrLocal(G, Ty, DAG,
2731 Subtarget.isABI_N32() || Subtarget.isABI_N64());
2732 else if (LargeGOT) {
2733 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2734 MipsII::MO_CALL_LO16, Chain,
2735 FuncInfo->callPtrInfo(Val));
2738 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2739 FuncInfo->callPtrInfo(Val));
2743 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2744 MipsII::MO_NO_FLAG);
2745 GlobalOrExternal = true;
2747 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2748 const char *Sym = S->getSymbol();
2750 if (!Subtarget.isABI_N64() && !IsPIC) // !N64 && static
2751 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2752 MipsII::MO_NO_FLAG);
2753 else if (LargeGOT) {
2754 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2755 MipsII::MO_CALL_LO16, Chain,
2756 FuncInfo->callPtrInfo(Sym));
2758 } else { // N64 || PIC
2759 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2760 FuncInfo->callPtrInfo(Sym));
2764 GlobalOrExternal = true;
2767 SmallVector<SDValue, 8> Ops(1, Chain);
2768 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2770 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2771 IsCallReloc, CLI, Callee, Chain);
2774 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2776 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2777 SDValue InFlag = Chain.getValue(1);
2779 // Create the CALLSEQ_END node.
2780 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2781 DAG.getIntPtrConstant(0, true), InFlag, DL);
2782 InFlag = Chain.getValue(1);
2784 // Handle result values, copying them out of physregs into vregs that we
2786 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
2790 /// LowerCallResult - Lower the result values of a call into the
2791 /// appropriate copies out of appropriate physical registers.
2792 SDValue MipsTargetLowering::LowerCallResult(
2793 SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool IsVarArg,
2794 const SmallVectorImpl<ISD::InputArg> &Ins, SDLoc DL, SelectionDAG &DAG,
2795 SmallVectorImpl<SDValue> &InVals,
2796 TargetLowering::CallLoweringInfo &CLI) const {
2797 // Assign locations to each value returned by this call.
2798 SmallVector<CCValAssign, 16> RVLocs;
2799 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
2801 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips, CLI);
2803 // Copy all of the result registers out of their specified physreg.
2804 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2805 CCValAssign &VA = RVLocs[i];
2806 assert(VA.isRegLoc() && "Can only return in registers!");
2808 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2809 RVLocs[i].getLocVT(), InFlag);
2810 Chain = Val.getValue(1);
2811 InFlag = Val.getValue(2);
2813 if (VA.isUpperBitsInLoc()) {
2814 unsigned ValSizeInBits = Ins[i].ArgVT.getSizeInBits();
2815 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
2817 VA.getLocInfo() == CCValAssign::ZExtUpper ? ISD::SRL : ISD::SRA;
2819 Shift, DL, VA.getLocVT(), Val,
2820 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
2823 switch (VA.getLocInfo()) {
2825 llvm_unreachable("Unknown loc info!");
2826 case CCValAssign::Full:
2828 case CCValAssign::BCvt:
2829 Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
2831 case CCValAssign::AExt:
2832 case CCValAssign::AExtUpper:
2833 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2835 case CCValAssign::ZExt:
2836 case CCValAssign::ZExtUpper:
2837 Val = DAG.getNode(ISD::AssertZext, DL, VA.getLocVT(), Val,
2838 DAG.getValueType(VA.getValVT()));
2839 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2841 case CCValAssign::SExt:
2842 case CCValAssign::SExtUpper:
2843 Val = DAG.getNode(ISD::AssertSext, DL, VA.getLocVT(), Val,
2844 DAG.getValueType(VA.getValVT()));
2845 Val = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Val);
2849 InVals.push_back(Val);
2855 //===----------------------------------------------------------------------===//
2856 // Formal Arguments Calling Convention Implementation
2857 //===----------------------------------------------------------------------===//
2858 /// LowerFormalArguments - transform physical registers into virtual registers
2859 /// and generate load operations for arguments places on the stack.
2861 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2862 CallingConv::ID CallConv,
2864 const SmallVectorImpl<ISD::InputArg> &Ins,
2865 SDLoc DL, SelectionDAG &DAG,
2866 SmallVectorImpl<SDValue> &InVals)
2868 MachineFunction &MF = DAG.getMachineFunction();
2869 MachineFrameInfo *MFI = MF.getFrameInfo();
2870 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2872 MipsFI->setVarArgsFrameIndex(0);
2874 // Used with vargs to acumulate store chains.
2875 std::vector<SDValue> OutChains;
2877 // Assign locations to all of the incoming arguments.
2878 SmallVector<CCValAssign, 16> ArgLocs;
2879 MipsCCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
2881 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
2882 Function::const_arg_iterator FuncArg =
2883 DAG.getMachineFunction().getFunction()->arg_begin();
2884 bool UseSoftFloat = Subtarget.abiUsesSoftFloat();
2886 CCInfo.PreAnalyzeFormalArgumentsForF128_(Ins);
2887 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, CCInfo);
2888 CCInfo.ClearOriginalArgWasF128();
2889 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2890 MipsCCInfo.hasByValArg());
2892 unsigned CurArgIdx = 0;
2893 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2895 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2896 CCValAssign &VA = ArgLocs[i];
2897 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2898 CurArgIdx = Ins[i].OrigArgIndex;
2899 EVT ValVT = VA.getValVT();
2900 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2901 bool IsRegLoc = VA.isRegLoc();
2903 if (Flags.isByVal()) {
2904 assert(Flags.getByValSize() &&
2905 "ByVal args of size 0 should have been ignored by front-end.");
2906 assert(ByValArg != MipsCCInfo.byval_end());
2907 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2908 MipsCCInfo, *ByValArg);
2913 // Arguments stored on registers
2915 MVT RegVT = VA.getLocVT();
2916 unsigned ArgReg = VA.getLocReg();
2917 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2919 // Transform the arguments stored on
2920 // physical registers into virtual ones
2921 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2922 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2924 // If this is an 8 or 16-bit value, it has been passed promoted
2925 // to 32 bits. Insert an assert[sz]ext to capture this, then
2926 // truncate to the right size.
2927 switch (VA.getLocInfo()) {
2929 llvm_unreachable("Unknown loc info!");
2930 case CCValAssign::Full:
2932 case CCValAssign::SExt:
2933 ArgValue = DAG.getNode(ISD::AssertSext, DL, RegVT, ArgValue,
2934 DAG.getValueType(ValVT));
2935 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2937 case CCValAssign::ZExt:
2938 ArgValue = DAG.getNode(ISD::AssertZext, DL, RegVT, ArgValue,
2939 DAG.getValueType(ValVT));
2940 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2942 case CCValAssign::BCvt:
2943 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2947 // Handle floating point arguments passed in integer registers and
2948 // long double arguments passed in floating point registers.
2949 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2950 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2951 (RegVT == MVT::f64 && ValVT == MVT::i64))
2952 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2953 else if (Subtarget.isABI_O32() && RegVT == MVT::i32 &&
2954 ValVT == MVT::f64) {
2955 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2956 getNextIntArgReg(ArgReg), RC);
2957 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2958 if (!Subtarget.isLittle())
2959 std::swap(ArgValue, ArgValue2);
2960 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2961 ArgValue, ArgValue2);
2964 InVals.push_back(ArgValue);
2965 } else { // VA.isRegLoc()
2968 assert(VA.isMemLoc());
2970 // The stack pointer offset is relative to the caller stack frame.
2971 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2972 VA.getLocMemOffset(), true);
2974 // Create load nodes to retrieve arguments from the stack
2975 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2976 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2977 MachinePointerInfo::getFixedStack(FI),
2978 false, false, false, 0);
2979 InVals.push_back(Load);
2980 OutChains.push_back(Load.getValue(1));
2984 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2985 // The mips ABIs for returning structs by value requires that we copy
2986 // the sret argument into $v0 for the return. Save the argument into
2987 // a virtual register so that we can access it from the return points.
2988 if (Ins[i].Flags.isSRet()) {
2989 unsigned Reg = MipsFI->getSRetReturnReg();
2991 Reg = MF.getRegInfo().createVirtualRegister(
2992 getRegClassFor(Subtarget.isABI_N64() ? MVT::i64 : MVT::i32));
2993 MipsFI->setSRetReturnReg(Reg);
2995 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
2996 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3002 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG, CCInfo);
3004 // All stores are grouped in one node to allow the matching between
3005 // the size of Ins and InVals. This only happens when on varg functions
3006 if (!OutChains.empty()) {
3007 OutChains.push_back(Chain);
3008 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
3014 //===----------------------------------------------------------------------===//
3015 // Return Value Calling Convention Implementation
3016 //===----------------------------------------------------------------------===//
3019 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3020 MachineFunction &MF, bool IsVarArg,
3021 const SmallVectorImpl<ISD::OutputArg> &Outs,
3022 LLVMContext &Context) const {
3023 SmallVector<CCValAssign, 16> RVLocs;
3024 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
3025 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3029 MipsTargetLowering::LowerReturn(SDValue Chain,
3030 CallingConv::ID CallConv, bool IsVarArg,
3031 const SmallVectorImpl<ISD::OutputArg> &Outs,
3032 const SmallVectorImpl<SDValue> &OutVals,
3033 SDLoc DL, SelectionDAG &DAG) const {
3034 // CCValAssign - represent the assignment of
3035 // the return value to a location
3036 SmallVector<CCValAssign, 16> RVLocs;
3037 MachineFunction &MF = DAG.getMachineFunction();
3039 // CCState - Info about the registers and stack slot.
3040 MipsCCState CCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
3041 MipsCC MipsCCInfo(CallConv, Subtarget, CCInfo);
3043 // Analyze return values.
3044 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3047 SmallVector<SDValue, 4> RetOps(1, Chain);
3049 // Copy the result values into the output registers.
3050 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3051 SDValue Val = OutVals[i];
3052 CCValAssign &VA = RVLocs[i];
3053 assert(VA.isRegLoc() && "Can only return in registers!");
3054 bool UseUpperBits = false;
3056 switch (VA.getLocInfo()) {
3058 llvm_unreachable("Unknown loc info!");
3059 case CCValAssign::Full:
3061 case CCValAssign::BCvt:
3062 Val = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Val);
3064 case CCValAssign::AExtUpper:
3065 UseUpperBits = true;
3067 case CCValAssign::AExt:
3068 Val = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Val);
3070 case CCValAssign::ZExtUpper:
3071 UseUpperBits = true;
3073 case CCValAssign::ZExt:
3074 Val = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Val);
3076 case CCValAssign::SExtUpper:
3077 UseUpperBits = true;
3079 case CCValAssign::SExt:
3080 Val = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Val);
3085 unsigned ValSizeInBits = Outs[i].ArgVT.getSizeInBits();
3086 unsigned LocSizeInBits = VA.getLocVT().getSizeInBits();
3088 ISD::SHL, DL, VA.getLocVT(), Val,
3089 DAG.getConstant(LocSizeInBits - ValSizeInBits, VA.getLocVT()));
3092 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3094 // Guarantee that all emitted copies are stuck together with flags.
3095 Flag = Chain.getValue(1);
3096 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3099 // The mips ABIs for returning structs by value requires that we copy
3100 // the sret argument into $v0 for the return. We saved the argument into
3101 // a virtual register in the entry block, so now we copy the value out
3103 if (MF.getFunction()->hasStructRetAttr()) {
3104 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3105 unsigned Reg = MipsFI->getSRetReturnReg();
3108 llvm_unreachable("sret virtual register not created in the entry block");
3109 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3110 unsigned V0 = Subtarget.isABI_N64() ? Mips::V0_64 : Mips::V0;
3112 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3113 Flag = Chain.getValue(1);
3114 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3117 RetOps[0] = Chain; // Update chain.
3119 // Add the flag if we have it.
3121 RetOps.push_back(Flag);
3123 // Return on Mips is always a "jr $ra"
3124 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
3127 //===----------------------------------------------------------------------===//
3128 // Mips Inline Assembly Support
3129 //===----------------------------------------------------------------------===//
3131 /// getConstraintType - Given a constraint letter, return the type of
3132 /// constraint it is for this target.
3133 MipsTargetLowering::ConstraintType MipsTargetLowering::
3134 getConstraintType(const std::string &Constraint) const
3136 // Mips specific constraints
3137 // GCC config/mips/constraints.md
3139 // 'd' : An address register. Equivalent to r
3140 // unless generating MIPS16 code.
3141 // 'y' : Equivalent to r; retained for
3142 // backwards compatibility.
3143 // 'c' : A register suitable for use in an indirect
3144 // jump. This will always be $25 for -mabicalls.
3145 // 'l' : The lo register. 1 word storage.
3146 // 'x' : The hilo register pair. Double word storage.
3147 if (Constraint.size() == 1) {
3148 switch (Constraint[0]) {
3156 return C_RegisterClass;
3161 return TargetLowering::getConstraintType(Constraint);
3164 /// Examine constraint type and operand type and determine a weight value.
3165 /// This object must already have been set up with the operand type
3166 /// and the current alternative constraint selected.
3167 TargetLowering::ConstraintWeight
3168 MipsTargetLowering::getSingleConstraintMatchWeight(
3169 AsmOperandInfo &info, const char *constraint) const {
3170 ConstraintWeight weight = CW_Invalid;
3171 Value *CallOperandVal = info.CallOperandVal;
3172 // If we don't have a value, we can't do a match,
3173 // but allow it at the lowest weight.
3174 if (!CallOperandVal)
3176 Type *type = CallOperandVal->getType();
3177 // Look at the constraint type.
3178 switch (*constraint) {
3180 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3184 if (type->isIntegerTy())
3185 weight = CW_Register;
3187 case 'f': // FPU or MSA register
3188 if (Subtarget.hasMSA() && type->isVectorTy() &&
3189 cast<VectorType>(type)->getBitWidth() == 128)
3190 weight = CW_Register;
3191 else if (type->isFloatTy())
3192 weight = CW_Register;
3194 case 'c': // $25 for indirect jumps
3195 case 'l': // lo register
3196 case 'x': // hilo register pair
3197 if (type->isIntegerTy())
3198 weight = CW_SpecificReg;
3200 case 'I': // signed 16 bit immediate
3201 case 'J': // integer zero
3202 case 'K': // unsigned 16 bit immediate
3203 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3204 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3205 case 'O': // signed 15 bit immediate (+- 16383)
3206 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3207 if (isa<ConstantInt>(CallOperandVal))
3208 weight = CW_Constant;
3217 /// This is a helper function to parse a physical register string and split it
3218 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
3219 /// that is returned indicates whether parsing was successful. The second flag
3220 /// is true if the numeric part exists.
3221 static std::pair<bool, bool>
3222 parsePhysicalReg(StringRef C, std::string &Prefix,
3223 unsigned long long &Reg) {
3224 if (C.front() != '{' || C.back() != '}')
3225 return std::make_pair(false, false);
3227 // Search for the first numeric character.
3228 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
3229 I = std::find_if(B, E, std::ptr_fun(isdigit));
3231 Prefix.assign(B, I - B);
3233 // The second flag is set to false if no numeric characters were found.
3235 return std::make_pair(true, false);
3237 // Parse the numeric characters.
3238 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
3242 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
3243 parseRegForInlineAsmConstraint(StringRef C, MVT VT) const {
3244 const TargetRegisterInfo *TRI =
3245 getTargetMachine().getSubtargetImpl()->getRegisterInfo();
3246 const TargetRegisterClass *RC;
3248 unsigned long long Reg;
3250 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
3253 return std::make_pair(0U, nullptr);
3255 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
3256 // No numeric characters follow "hi" or "lo".
3258 return std::make_pair(0U, nullptr);
3260 RC = TRI->getRegClass(Prefix == "hi" ?
3261 Mips::HI32RegClassID : Mips::LO32RegClassID);
3262 return std::make_pair(*(RC->begin()), RC);
3263 } else if (Prefix.compare(0, 4, "$msa") == 0) {
3264 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
3266 // No numeric characters follow the name.
3268 return std::make_pair(0U, nullptr);
3270 Reg = StringSwitch<unsigned long long>(Prefix)
3271 .Case("$msair", Mips::MSAIR)
3272 .Case("$msacsr", Mips::MSACSR)
3273 .Case("$msaaccess", Mips::MSAAccess)
3274 .Case("$msasave", Mips::MSASave)
3275 .Case("$msamodify", Mips::MSAModify)
3276 .Case("$msarequest", Mips::MSARequest)
3277 .Case("$msamap", Mips::MSAMap)
3278 .Case("$msaunmap", Mips::MSAUnmap)
3282 return std::make_pair(0U, nullptr);
3284 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
3285 return std::make_pair(Reg, RC);
3289 return std::make_pair(0U, nullptr);
3291 if (Prefix == "$f") { // Parse $f0-$f31.
3292 // If the size of FP registers is 64-bit or Reg is an even number, select
3293 // the 64-bit register class. Otherwise, select the 32-bit register class.
3294 if (VT == MVT::Other)
3295 VT = (Subtarget.isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
3297 RC = getRegClassFor(VT);
3299 if (RC == &Mips::AFGR64RegClass) {
3300 assert(Reg % 2 == 0);
3303 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3304 RC = TRI->getRegClass(Mips::FCCRegClassID);
3305 else if (Prefix == "$w") { // Parse $w0-$w31.
3306 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3307 } else { // Parse $0-$31.
3308 assert(Prefix == "$");
3309 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3312 assert(Reg < RC->getNumRegs());
3313 return std::make_pair(*(RC->begin() + Reg), RC);
3316 /// Given a register class constraint, like 'r', if this corresponds directly
3317 /// to an LLVM register class, return a register of 0 and the register class
3319 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3320 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3322 if (Constraint.size() == 1) {
3323 switch (Constraint[0]) {
3324 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3325 case 'y': // Same as 'r'. Exists for compatibility.
3327 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3328 if (Subtarget.inMips16Mode())
3329 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3330 return std::make_pair(0U, &Mips::GPR32RegClass);
3332 if (VT == MVT::i64 && !Subtarget.isGP64bit())
3333 return std::make_pair(0U, &Mips::GPR32RegClass);
3334 if (VT == MVT::i64 && Subtarget.isGP64bit())
3335 return std::make_pair(0U, &Mips::GPR64RegClass);
3336 // This will generate an error message
3337 return std::make_pair(0U, nullptr);
3338 case 'f': // FPU or MSA register
3339 if (VT == MVT::v16i8)
3340 return std::make_pair(0U, &Mips::MSA128BRegClass);
3341 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3342 return std::make_pair(0U, &Mips::MSA128HRegClass);
3343 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3344 return std::make_pair(0U, &Mips::MSA128WRegClass);
3345 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3346 return std::make_pair(0U, &Mips::MSA128DRegClass);
3347 else if (VT == MVT::f32)
3348 return std::make_pair(0U, &Mips::FGR32RegClass);
3349 else if ((VT == MVT::f64) && (!Subtarget.isSingleFloat())) {
3350 if (Subtarget.isFP64bit())
3351 return std::make_pair(0U, &Mips::FGR64RegClass);
3352 return std::make_pair(0U, &Mips::AFGR64RegClass);
3355 case 'c': // register suitable for indirect jump
3357 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3358 assert(VT == MVT::i64 && "Unexpected type.");
3359 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3360 case 'l': // register suitable for indirect jump
3362 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3363 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3364 case 'x': // register suitable for indirect jump
3365 // Fixme: Not triggering the use of both hi and low
3366 // This will generate an error message
3367 return std::make_pair(0U, nullptr);
3371 std::pair<unsigned, const TargetRegisterClass *> R;
3372 R = parseRegForInlineAsmConstraint(Constraint, VT);
3377 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3380 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3381 /// vector. If it is invalid, don't add anything to Ops.
3382 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3383 std::string &Constraint,
3384 std::vector<SDValue>&Ops,
3385 SelectionDAG &DAG) const {
3388 // Only support length 1 constraints for now.
3389 if (Constraint.length() > 1) return;
3391 char ConstraintLetter = Constraint[0];
3392 switch (ConstraintLetter) {
3393 default: break; // This will fall through to the generic implementation
3394 case 'I': // Signed 16 bit constant
3395 // If this fails, the parent routine will give an error
3396 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3397 EVT Type = Op.getValueType();
3398 int64_t Val = C->getSExtValue();
3399 if (isInt<16>(Val)) {
3400 Result = DAG.getTargetConstant(Val, Type);
3405 case 'J': // integer zero
3406 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3407 EVT Type = Op.getValueType();
3408 int64_t Val = C->getZExtValue();
3410 Result = DAG.getTargetConstant(0, Type);
3415 case 'K': // unsigned 16 bit immediate
3416 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3417 EVT Type = Op.getValueType();
3418 uint64_t Val = (uint64_t)C->getZExtValue();
3419 if (isUInt<16>(Val)) {
3420 Result = DAG.getTargetConstant(Val, Type);
3425 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3426 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3427 EVT Type = Op.getValueType();
3428 int64_t Val = C->getSExtValue();
3429 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3430 Result = DAG.getTargetConstant(Val, Type);
3435 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3436 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3437 EVT Type = Op.getValueType();
3438 int64_t Val = C->getSExtValue();
3439 if ((Val >= -65535) && (Val <= -1)) {
3440 Result = DAG.getTargetConstant(Val, Type);
3445 case 'O': // signed 15 bit immediate
3446 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3447 EVT Type = Op.getValueType();
3448 int64_t Val = C->getSExtValue();
3449 if ((isInt<15>(Val))) {
3450 Result = DAG.getTargetConstant(Val, Type);
3455 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3456 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3457 EVT Type = Op.getValueType();
3458 int64_t Val = C->getSExtValue();
3459 if ((Val <= 65535) && (Val >= 1)) {
3460 Result = DAG.getTargetConstant(Val, Type);
3467 if (Result.getNode()) {
3468 Ops.push_back(Result);
3472 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3475 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3477 // No global is ever allowed as a base.
3482 case 0: // "r+i" or just "i", depending on HasBaseReg.
3485 if (!AM.HasBaseReg) // allow "r+i".
3487 return false; // disallow "r+r" or "r+r+i".
3496 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3497 // The Mips target isn't yet aware of offsets.
3501 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3503 bool IsMemset, bool ZeroMemset,
3505 MachineFunction &MF) const {
3506 if (Subtarget.hasMips64())
3512 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3513 if (VT != MVT::f32 && VT != MVT::f64)
3515 if (Imm.isNegZero())
3517 return Imm.isZero();
3520 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3521 if (Subtarget.isABI_N64())
3522 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3524 return TargetLowering::getJumpTableEncoding();
3527 /// This function returns true if CallSym is a long double emulation routine.
3528 static bool isF128SoftLibCall(const char *CallSym) {
3529 const char *const LibCalls[] =
3530 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3531 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3532 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3533 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3534 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3535 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3536 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3537 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3540 const char *const *End = LibCalls + array_lengthof(LibCalls);
3542 // Check that LibCalls is sorted alphabetically.
3543 MipsTargetLowering::LTStr Comp;
3546 for (const char *const *I = LibCalls; I < End - 1; ++I)
3547 assert(Comp(*I, *(I + 1)));
3550 return std::binary_search(LibCalls, End, CallSym, Comp);
3553 /// This function returns true if Ty is fp128, {f128} or i128 which was
3554 /// originally a fp128.
3555 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3556 if (Ty->isFP128Ty())
3559 if (Ty->isStructTy() && Ty->getStructNumElements() == 1 &&
3560 Ty->getStructElementType(0)->isFP128Ty())
3563 const ExternalSymbolSDNode *ES =
3564 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3566 // If the Ty is i128 and the function being called is a long double emulation
3567 // routine, then the original type is f128.
3568 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3571 MipsTargetLowering::MipsCC::SpecialCallingConvType
3572 MipsTargetLowering::MipsCC::getSpecialCallingConv(const SDNode *Callee) const {
3573 MipsCC::SpecialCallingConvType SpecialCallingConv =
3574 MipsCC::NoSpecialCallingConv;
3575 if (Subtarget.inMips16HardFloat()) {
3576 if (const GlobalAddressSDNode *G =
3577 dyn_cast<const GlobalAddressSDNode>(Callee)) {
3578 llvm::StringRef Sym = G->getGlobal()->getName();
3579 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3580 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3581 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3585 return SpecialCallingConv;
3588 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CC,
3589 const MipsSubtarget &Subtarget_,
3591 : CallConv(CC), Subtarget(Subtarget_) {
3592 // Pre-allocate reserved argument area.
3593 Info.AllocateStack(reservedArgArea(), 1);
3596 void MipsTargetLowering::MipsCC::analyzeCallOperands(
3597 const SmallVectorImpl<ISD::OutputArg> &Args, bool IsVarArg,
3598 bool IsSoftFloat, const SDNode *CallNode,
3599 std::vector<ArgListEntry> &FuncArgs, CCState &State) {
3600 MipsCC::SpecialCallingConvType SpecialCallingConv =
3601 getSpecialCallingConv(CallNode);
3602 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3603 "CallingConv::Fast shouldn't be used for vararg functions.");
3605 unsigned NumOpnds = Args.size();
3606 llvm::CCAssignFn *FixedFn = CC_Mips_FixedArg;
3607 if (CallConv != CallingConv::Fast &&
3608 SpecialCallingConv == Mips16RetHelperConv)
3609 FixedFn = CC_Mips16RetHelper;
3611 for (unsigned I = 0; I != NumOpnds; ++I) {
3612 MVT ArgVT = Args[I].VT;
3613 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3616 if (ArgFlags.isByVal()) {
3617 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, State);
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 void MipsTargetLowering::MipsCC::analyzeFormalArguments(
3637 const SmallVectorImpl<ISD::InputArg> &Args, bool IsSoftFloat,
3639 unsigned NumArgs = Args.size();
3641 for (unsigned I = 0; I != NumArgs; ++I) {
3642 MVT ArgVT = Args[I].VT;
3643 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3645 if (ArgFlags.isByVal()) {
3646 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, State);
3650 if (!CC_Mips_FixedArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, State))
3654 dbgs() << "Formal Arg #" << I << " has unhandled type "
3655 << EVT(ArgVT).getEVTString();
3657 llvm_unreachable(nullptr);
3661 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3663 CCValAssign::LocInfo LocInfo,
3664 ISD::ArgFlagsTy ArgFlags,
3666 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3668 struct ByValArgInfo ByVal;
3669 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3670 unsigned ByValSize =
3671 RoundUpToAlignment(ArgFlags.getByValSize(), RegSizeInBytes);
3672 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSizeInBytes),
3673 RegSizeInBytes * 2);
3675 if (useRegsForByval())
3676 allocateRegs(ByVal, ByValSize, Align, State);
3678 // Allocate space on caller's stack.
3680 State.AllocateStack(ByValSize - RegSizeInBytes * ByVal.NumRegs, Align);
3682 CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT, LocInfo));
3683 ByValArgs.push_back(ByVal);
3686 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3687 return (Subtarget.isABI_O32() && (CallConv != CallingConv::Fast)) ? 16 : 0;
3690 const ArrayRef<MCPhysReg> MipsTargetLowering::MipsCC::intArgRegs() const {
3691 if (Subtarget.isABI_O32())
3692 return makeArrayRef(O32IntRegs);
3693 return makeArrayRef(Mips64IntRegs);
3696 const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
3697 return Subtarget.isABI_O32() ? O32IntRegs : Mips64DPRegs;
3700 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3702 unsigned Align, CCState &State) {
3703 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3704 const ArrayRef<MCPhysReg> IntArgRegs = intArgRegs();
3705 const MCPhysReg *ShadowRegs = shadowRegs();
3706 assert(!(ByValSize % RegSizeInBytes) && !(Align % RegSizeInBytes) &&
3707 "Byval argument's size and alignment should be a multiple of"
3711 State.getFirstUnallocated(IntArgRegs.data(), IntArgRegs.size());
3713 // If Align > RegSizeInBytes, the first arg register must be even.
3714 if ((Align > RegSizeInBytes) && (ByVal.FirstIdx % 2)) {
3715 State.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3719 // Mark the registers allocated.
3720 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < IntArgRegs.size());
3721 ByValSize -= RegSizeInBytes, ++I, ++ByVal.NumRegs)
3722 State.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3725 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3726 const SDNode *CallNode,
3727 bool IsSoftFloat) const {
3728 if (IsSoftFloat || Subtarget.isABI_O32())
3731 // Check if the original type was fp128.
3732 if (originalTypeIsF128(OrigTy, CallNode)) {
3733 assert(VT == MVT::i64);
3740 void MipsTargetLowering::
3741 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3742 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3743 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3744 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3745 MachineFunction &MF = DAG.getMachineFunction();
3746 MachineFrameInfo *MFI = MF.getFrameInfo();
3747 unsigned GPRSizeInBytes = Subtarget.getGPRSizeInBytes();
3748 unsigned RegAreaSize = ByVal.NumRegs * GPRSizeInBytes;
3749 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3754 (int)CC.reservedArgArea() -
3755 (int)((CC.intArgRegs().size() - ByVal.FirstIdx) * GPRSizeInBytes);
3757 FrameObjOffset = ByVal.Address;
3759 // Create frame object.
3760 EVT PtrTy = getPointerTy();
3761 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3762 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3763 InVals.push_back(FIN);
3768 // Copy arg registers.
3769 MVT RegTy = MVT::getIntegerVT(GPRSizeInBytes * 8);
3770 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3772 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3773 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3774 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3775 unsigned Offset = I * GPRSizeInBytes;
3776 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3777 DAG.getConstant(Offset, PtrTy));
3778 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3779 StorePtr, MachinePointerInfo(FuncArg, Offset),
3781 OutChains.push_back(Store);
3785 // Copy byVal arg to registers and stack.
3786 void MipsTargetLowering::
3787 passByValArg(SDValue Chain, SDLoc DL,
3788 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3789 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3790 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3791 const MipsCC &CC, const ByValArgInfo &ByVal,
3792 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3793 unsigned ByValSizeInBytes = Flags.getByValSize();
3794 unsigned OffsetInBytes = 0; // From beginning of struct
3795 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3796 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3797 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3799 if (ByVal.NumRegs) {
3800 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3801 bool LeftoverBytes = (ByVal.NumRegs * RegSizeInBytes > ByValSizeInBytes);
3804 // Copy words to registers.
3805 for (; I < ByVal.NumRegs - LeftoverBytes;
3806 ++I, OffsetInBytes += RegSizeInBytes) {
3807 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3808 DAG.getConstant(OffsetInBytes, PtrTy));
3809 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3810 MachinePointerInfo(), false, false, false,
3812 MemOpChains.push_back(LoadVal.getValue(1));
3813 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3814 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3817 // Return if the struct has been fully copied.
3818 if (ByValSizeInBytes == OffsetInBytes)
3821 // Copy the remainder of the byval argument with sub-word loads and shifts.
3822 if (LeftoverBytes) {
3823 assert((ByValSizeInBytes > OffsetInBytes) &&
3824 (ByValSizeInBytes < OffsetInBytes + RegSizeInBytes) &&
3825 "Size of the remainder should be smaller than RegSizeInBytes.");
3828 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3829 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3830 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3832 if (RemainingSizeInBytes < LoadSizeInBytes)
3836 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3837 DAG.getConstant(OffsetInBytes, PtrTy));
3838 SDValue LoadVal = DAG.getExtLoad(
3839 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3840 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, false,
3842 MemOpChains.push_back(LoadVal.getValue(1));
3844 // Shift the loaded value.
3848 Shamt = TotalBytesLoaded * 8;
3850 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3852 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3853 DAG.getConstant(Shamt, MVT::i32));
3856 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3860 OffsetInBytes += LoadSizeInBytes;
3861 TotalBytesLoaded += LoadSizeInBytes;
3862 Alignment = std::min(Alignment, LoadSizeInBytes);
3865 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3866 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3871 // Copy remainder of byval arg to it with memcpy.
3872 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3873 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3874 DAG.getConstant(OffsetInBytes, PtrTy));
3875 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3876 DAG.getIntPtrConstant(ByVal.Address));
3877 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3878 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3879 MachinePointerInfo(), MachinePointerInfo());
3880 MemOpChains.push_back(Chain);
3883 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3884 const MipsCC &CC, SDValue Chain,
3885 SDLoc DL, SelectionDAG &DAG,
3886 CCState &State) const {
3887 const ArrayRef<MCPhysReg> ArgRegs = CC.intArgRegs();
3888 unsigned Idx = State.getFirstUnallocated(ArgRegs.data(), ArgRegs.size());
3889 unsigned RegSizeInBytes = Subtarget.getGPRSizeInBytes();
3890 MVT RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3891 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3892 MachineFunction &MF = DAG.getMachineFunction();
3893 MachineFrameInfo *MFI = MF.getFrameInfo();
3894 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3896 // Offset of the first variable argument from stack pointer.
3899 if (ArgRegs.size() == Idx)
3901 RoundUpToAlignment(State.getNextStackOffset(), RegSizeInBytes);
3903 VaArgOffset = (int)CC.reservedArgArea() -
3904 (int)(RegSizeInBytes * (ArgRegs.size() - Idx));
3906 // Record the frame index of the first variable argument
3907 // which is a value necessary to VASTART.
3908 int FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3909 MipsFI->setVarArgsFrameIndex(FI);
3911 // Copy the integer registers that have not been used for argument passing
3912 // to the argument register save area. For O32, the save area is allocated
3913 // in the caller's stack frame, while for N32/64, it is allocated in the
3914 // callee's stack frame.
3915 for (unsigned I = Idx; I < ArgRegs.size();
3916 ++I, VaArgOffset += RegSizeInBytes) {
3917 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3918 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3919 FI = MFI->CreateFixedObject(RegSizeInBytes, VaArgOffset, true);
3920 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3921 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3922 MachinePointerInfo(), false, false, 0);
3923 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(
3925 OutChains.push_back(Store);