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 #define DEBUG_TYPE "mips-lower"
16 #include "MipsISelLowering.h"
17 #include "InstPrinter/MipsInstPrinter.h"
18 #include "MCTargetDesc/MipsBaseInfo.h"
19 #include "MipsMachineFunction.h"
20 #include "MipsSubtarget.h"
21 #include "MipsTargetMachine.h"
22 #include "MipsTargetObjectFile.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/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/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
43 STATISTIC(NumTailCalls, "Number of tail calls");
46 EnableMipsTailCalls("enable-mips-tail-calls", cl::Hidden,
47 cl::desc("MIPS: Enable tail calls."), cl::init(false));
50 LargeGOT("mxgot", cl::Hidden,
51 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
54 Mips16HardFloat("mips16-hard-float", cl::NotHidden,
55 cl::desc("MIPS: mips16 hard float enable."),
60 static const uint16_t O32IntRegs[4] = {
61 Mips::A0, Mips::A1, Mips::A2, Mips::A3
64 static const uint16_t 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 uint16_t 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 // If I is a shifted mask, set the size (Size) and the first bit of the
75 // mask (Pos), and return true.
76 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
77 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
78 if (!isShiftedMask_64(I))
81 Size = CountPopulation_64(I);
82 Pos = CountTrailingZeros_64(I);
86 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
87 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
88 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
91 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
92 EVT Ty = Op.getValueType();
94 if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
95 return DAG.getTargetGlobalAddress(N->getGlobal(), Op.getDebugLoc(), Ty, 0,
97 if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
98 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
99 if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
100 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
101 if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
102 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
103 if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
104 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
105 N->getOffset(), Flag);
107 llvm_unreachable("Unexpected node type.");
111 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
112 DebugLoc DL = Op.getDebugLoc();
113 EVT Ty = Op.getValueType();
114 SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
115 SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
116 return DAG.getNode(ISD::ADD, DL, Ty,
117 DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
118 DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
121 static SDValue getAddrLocal(SDValue Op, SelectionDAG &DAG, bool HasMips64) {
122 DebugLoc DL = Op.getDebugLoc();
123 EVT Ty = Op.getValueType();
124 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
125 SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
126 getTargetNode(Op, DAG, GOTFlag));
127 SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
128 MachinePointerInfo::getGOT(), false, false, false,
130 unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
131 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
132 return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
135 static SDValue getAddrGlobal(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
136 DebugLoc DL = Op.getDebugLoc();
137 EVT Ty = Op.getValueType();
138 SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
139 getTargetNode(Op, DAG, Flag));
140 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
141 MachinePointerInfo::getGOT(), false, false, false, 0);
144 static SDValue getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
145 unsigned HiFlag, unsigned LoFlag) {
146 DebugLoc DL = Op.getDebugLoc();
147 EVT Ty = Op.getValueType();
148 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
149 Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, GetGlobalReg(DAG, Ty));
150 SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
151 getTargetNode(Op, DAG, LoFlag));
152 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
153 MachinePointerInfo::getGOT(), false, false, false, 0);
156 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
158 case MipsISD::JmpLink: return "MipsISD::JmpLink";
159 case MipsISD::TailCall: return "MipsISD::TailCall";
160 case MipsISD::Hi: return "MipsISD::Hi";
161 case MipsISD::Lo: return "MipsISD::Lo";
162 case MipsISD::GPRel: return "MipsISD::GPRel";
163 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
164 case MipsISD::Ret: return "MipsISD::Ret";
165 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
166 case MipsISD::FPCmp: return "MipsISD::FPCmp";
167 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
168 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
169 case MipsISD::FPRound: return "MipsISD::FPRound";
170 case MipsISD::MAdd: return "MipsISD::MAdd";
171 case MipsISD::MAddu: return "MipsISD::MAddu";
172 case MipsISD::MSub: return "MipsISD::MSub";
173 case MipsISD::MSubu: return "MipsISD::MSubu";
174 case MipsISD::DivRem: return "MipsISD::DivRem";
175 case MipsISD::DivRemU: return "MipsISD::DivRemU";
176 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
177 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
178 case MipsISD::Wrapper: return "MipsISD::Wrapper";
179 case MipsISD::Sync: return "MipsISD::Sync";
180 case MipsISD::Ext: return "MipsISD::Ext";
181 case MipsISD::Ins: return "MipsISD::Ins";
182 case MipsISD::LWL: return "MipsISD::LWL";
183 case MipsISD::LWR: return "MipsISD::LWR";
184 case MipsISD::SWL: return "MipsISD::SWL";
185 case MipsISD::SWR: return "MipsISD::SWR";
186 case MipsISD::LDL: return "MipsISD::LDL";
187 case MipsISD::LDR: return "MipsISD::LDR";
188 case MipsISD::SDL: return "MipsISD::SDL";
189 case MipsISD::SDR: return "MipsISD::SDR";
190 case MipsISD::EXTP: return "MipsISD::EXTP";
191 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
192 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
193 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
194 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
195 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
196 case MipsISD::SHILO: return "MipsISD::SHILO";
197 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
198 case MipsISD::MULT: return "MipsISD::MULT";
199 case MipsISD::MULTU: return "MipsISD::MULTU";
200 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSPDSP";
201 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
202 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
203 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
204 default: return NULL;
210 bool operator()(const char *s1, const char *s2) const
212 return strcmp(s1, s2) < 0;
216 std::set<const char*, ltstr> noHelperNeeded;
219 void MipsTargetLowering::SetMips16LibcallName
220 (RTLIB::Libcall l, const char *Name) {
221 setLibcallName(l, Name);
222 noHelperNeeded.insert(Name);
225 void MipsTargetLowering::setMips16HardFloatLibCalls() {
226 SetMips16LibcallName(RTLIB::ADD_F32, "__mips16_addsf3");
227 SetMips16LibcallName(RTLIB::ADD_F64, "__mips16_adddf3");
228 SetMips16LibcallName(RTLIB::SUB_F32, "__mips16_subsf3");
229 SetMips16LibcallName(RTLIB::SUB_F64, "__mips16_subdf3");
230 SetMips16LibcallName(RTLIB::MUL_F32, "__mips16_mulsf3");
231 SetMips16LibcallName(RTLIB::MUL_F64, "__mips16_muldf3");
232 SetMips16LibcallName(RTLIB::DIV_F32, "__mips16_divsf3");
233 SetMips16LibcallName(RTLIB::DIV_F64, "__mips16_divdf3");
234 SetMips16LibcallName(RTLIB::FPEXT_F32_F64, "__mips16_extendsfdf2");
235 SetMips16LibcallName(RTLIB::FPROUND_F64_F32, "__mips16_truncdfsf2");
236 SetMips16LibcallName(RTLIB::FPTOSINT_F32_I32, "__mips16_fix_truncsfsi");
237 SetMips16LibcallName(RTLIB::FPTOSINT_F64_I32, "__mips16_fix_truncdfsi");
238 SetMips16LibcallName(RTLIB::SINTTOFP_I32_F32, "__mips16_floatsisf");
239 SetMips16LibcallName(RTLIB::SINTTOFP_I32_F64, "__mips16_floatsidf");
240 SetMips16LibcallName(RTLIB::UINTTOFP_I32_F32, "__mips16_floatunsisf");
241 SetMips16LibcallName(RTLIB::UINTTOFP_I32_F64, "__mips16_floatunsidf");
242 SetMips16LibcallName(RTLIB::OEQ_F32, "__mips16_eqsf2");
243 SetMips16LibcallName(RTLIB::OEQ_F64, "__mips16_eqdf2");
244 SetMips16LibcallName(RTLIB::UNE_F32, "__mips16_nesf2");
245 SetMips16LibcallName(RTLIB::UNE_F64, "__mips16_nedf2");
246 SetMips16LibcallName(RTLIB::OGE_F32, "__mips16_gesf2");
247 SetMips16LibcallName(RTLIB::OGE_F64, "__mips16_gedf2");
248 SetMips16LibcallName(RTLIB::OLT_F32, "__mips16_ltsf2");
249 SetMips16LibcallName(RTLIB::OLT_F64, "__mips16_ltdf2");
250 SetMips16LibcallName(RTLIB::OLE_F32, "__mips16_lesf2");
251 SetMips16LibcallName(RTLIB::OLE_F64, "__mips16_ledf2");
252 SetMips16LibcallName(RTLIB::OGT_F32, "__mips16_gtsf2");
253 SetMips16LibcallName(RTLIB::OGT_F64, "__mips16_gtdf2");
254 SetMips16LibcallName(RTLIB::UO_F32, "__mips16_unordsf2");
255 SetMips16LibcallName(RTLIB::UO_F64, "__mips16_unorddf2");
256 SetMips16LibcallName(RTLIB::O_F32, "__mips16_unordsf2");
257 SetMips16LibcallName(RTLIB::O_F64, "__mips16_unorddf2");
261 MipsTargetLowering(MipsTargetMachine &TM)
262 : TargetLowering(TM, new MipsTargetObjectFile()),
263 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
264 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
265 IsO32(Subtarget->isABI_O32()) {
267 // Mips does not have i1 type, so use i32 for
268 // setcc operations results (slt, sgt, ...).
269 setBooleanContents(ZeroOrOneBooleanContent);
270 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
272 // Set up the register classes
273 addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
276 addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
278 if (Subtarget->inMips16Mode()) {
279 addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
281 setMips16HardFloatLibCalls();
284 if (Subtarget->hasDSP()) {
285 MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
287 for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
288 addRegisterClass(VecTys[i], &Mips::DSPRegsRegClass);
290 // Expand all builtin opcodes.
291 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
292 setOperationAction(Opc, VecTys[i], Expand);
294 setOperationAction(ISD::LOAD, VecTys[i], Legal);
295 setOperationAction(ISD::STORE, VecTys[i], Legal);
296 setOperationAction(ISD::BITCAST, VecTys[i], Legal);
300 if (!TM.Options.UseSoftFloat) {
301 addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
303 // When dealing with single precision only, use libcalls
304 if (!Subtarget->isSingleFloat()) {
306 addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
308 addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
312 // Load extented operations for i1 types must be promoted
313 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
314 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
315 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
317 // MIPS doesn't have extending float->double load/store
318 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
319 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
321 // Used by legalize types to correctly generate the setcc result.
322 // Without this, every float setcc comes with a AND/OR with the result,
323 // we don't want this, since the fpcmp result goes to a flag register,
324 // which is used implicitly by brcond and select operations.
325 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
327 // Mips Custom Operations
328 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
329 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
330 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
331 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
332 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
333 setOperationAction(ISD::SELECT, MVT::f32, Custom);
334 setOperationAction(ISD::SELECT, MVT::f64, Custom);
335 setOperationAction(ISD::SELECT, MVT::i32, Custom);
336 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
337 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
338 setOperationAction(ISD::SETCC, MVT::f32, Custom);
339 setOperationAction(ISD::SETCC, MVT::f64, Custom);
340 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
341 setOperationAction(ISD::VASTART, MVT::Other, Custom);
342 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
343 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
344 if (Subtarget->inMips16Mode()) {
345 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
346 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
349 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
350 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
352 if (!Subtarget->inMips16Mode()) {
353 setOperationAction(ISD::LOAD, MVT::i32, Custom);
354 setOperationAction(ISD::STORE, MVT::i32, Custom);
357 if (!TM.Options.NoNaNsFPMath) {
358 setOperationAction(ISD::FABS, MVT::f32, Custom);
359 setOperationAction(ISD::FABS, MVT::f64, Custom);
363 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
364 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
365 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
366 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
367 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
368 setOperationAction(ISD::SELECT, MVT::i64, Custom);
369 setOperationAction(ISD::LOAD, MVT::i64, Custom);
370 setOperationAction(ISD::STORE, MVT::i64, Custom);
374 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
375 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
376 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
379 setOperationAction(ISD::ADD, MVT::i32, Custom);
381 setOperationAction(ISD::ADD, MVT::i64, Custom);
383 setOperationAction(ISD::SDIV, MVT::i32, Expand);
384 setOperationAction(ISD::SREM, MVT::i32, Expand);
385 setOperationAction(ISD::UDIV, MVT::i32, Expand);
386 setOperationAction(ISD::UREM, MVT::i32, Expand);
387 setOperationAction(ISD::SDIV, MVT::i64, Expand);
388 setOperationAction(ISD::SREM, MVT::i64, Expand);
389 setOperationAction(ISD::UDIV, MVT::i64, Expand);
390 setOperationAction(ISD::UREM, MVT::i64, Expand);
392 // Operations not directly supported by Mips.
393 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
394 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
395 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
396 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
397 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
398 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
399 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
400 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
401 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
402 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
403 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
404 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
405 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
406 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
407 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
408 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
409 setOperationAction(ISD::ROTL, MVT::i32, Expand);
410 setOperationAction(ISD::ROTL, MVT::i64, Expand);
411 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
412 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
414 if (!Subtarget->hasMips32r2())
415 setOperationAction(ISD::ROTR, MVT::i32, Expand);
417 if (!Subtarget->hasMips64r2())
418 setOperationAction(ISD::ROTR, MVT::i64, Expand);
420 setOperationAction(ISD::FSIN, MVT::f32, Expand);
421 setOperationAction(ISD::FSIN, MVT::f64, Expand);
422 setOperationAction(ISD::FCOS, MVT::f32, Expand);
423 setOperationAction(ISD::FCOS, MVT::f64, Expand);
424 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
425 setOperationAction(ISD::FPOW, MVT::f32, Expand);
426 setOperationAction(ISD::FPOW, MVT::f64, Expand);
427 setOperationAction(ISD::FLOG, MVT::f32, Expand);
428 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
429 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
430 setOperationAction(ISD::FEXP, MVT::f32, Expand);
431 setOperationAction(ISD::FMA, MVT::f32, Expand);
432 setOperationAction(ISD::FMA, MVT::f64, Expand);
433 setOperationAction(ISD::FREM, MVT::f32, Expand);
434 setOperationAction(ISD::FREM, MVT::f64, Expand);
436 if (!TM.Options.NoNaNsFPMath) {
437 setOperationAction(ISD::FNEG, MVT::f32, Expand);
438 setOperationAction(ISD::FNEG, MVT::f64, Expand);
441 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
442 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
443 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
444 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
446 setOperationAction(ISD::VAARG, MVT::Other, Expand);
447 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
448 setOperationAction(ISD::VAEND, MVT::Other, Expand);
450 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
451 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
453 // Use the default for now
454 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
455 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
457 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
458 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
459 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
460 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
462 if (Subtarget->inMips16Mode()) {
463 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
464 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
465 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
466 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
467 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
468 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
469 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
470 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
471 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
472 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
473 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
474 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
477 setInsertFencesForAtomic(true);
479 if (!Subtarget->hasSEInReg()) {
480 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
481 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
484 if (!Subtarget->hasBitCount()) {
485 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
486 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
489 if (!Subtarget->hasSwap()) {
490 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
491 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
495 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
496 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
497 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
498 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
501 setTargetDAGCombine(ISD::ADDE);
502 setTargetDAGCombine(ISD::SUBE);
503 setTargetDAGCombine(ISD::SDIVREM);
504 setTargetDAGCombine(ISD::UDIVREM);
505 setTargetDAGCombine(ISD::SELECT);
506 setTargetDAGCombine(ISD::AND);
507 setTargetDAGCombine(ISD::OR);
508 setTargetDAGCombine(ISD::ADD);
510 setMinFunctionAlignment(HasMips64 ? 3 : 2);
512 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
513 computeRegisterProperties();
515 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
516 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
518 maxStoresPerMemcpy = 16;
522 MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
523 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
525 if (Subtarget->inMips16Mode())
539 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
542 return VT.changeVectorElementTypeToInteger();
546 // Transforms a subgraph in CurDAG if the following pattern is found:
547 // (addc multLo, Lo0), (adde multHi, Hi0),
549 // multHi/Lo: product of multiplication
550 // Lo0: initial value of Lo register
551 // Hi0: initial value of Hi register
552 // Return true if pattern matching was successful.
553 static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
554 // ADDENode's second operand must be a flag output of an ADDC node in order
555 // for the matching to be successful.
556 SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
558 if (ADDCNode->getOpcode() != ISD::ADDC)
561 SDValue MultHi = ADDENode->getOperand(0);
562 SDValue MultLo = ADDCNode->getOperand(0);
563 SDNode *MultNode = MultHi.getNode();
564 unsigned MultOpc = MultHi.getOpcode();
566 // MultHi and MultLo must be generated by the same node,
567 if (MultLo.getNode() != MultNode)
570 // and it must be a multiplication.
571 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
574 // MultLo amd MultHi must be the first and second output of MultNode
576 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
579 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
580 // of the values of MultNode, in which case MultNode will be removed in later
582 // If there exist users other than ADDENode or ADDCNode, this function returns
583 // here, which will result in MultNode being mapped to a single MULT
584 // instruction node rather than a pair of MULT and MADD instructions being
586 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
589 SDValue Chain = CurDAG->getEntryNode();
590 DebugLoc dl = ADDENode->getDebugLoc();
592 // create MipsMAdd(u) node
593 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
595 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
596 MultNode->getOperand(0),// Factor 0
597 MultNode->getOperand(1),// Factor 1
598 ADDCNode->getOperand(1),// Lo0
599 ADDENode->getOperand(1));// Hi0
601 // create CopyFromReg nodes
602 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
604 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
606 CopyFromLo.getValue(2));
608 // replace uses of adde and addc here
609 if (!SDValue(ADDCNode, 0).use_empty())
610 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
612 if (!SDValue(ADDENode, 0).use_empty())
613 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
619 // Transforms a subgraph in CurDAG if the following pattern is found:
620 // (addc Lo0, multLo), (sube Hi0, multHi),
622 // multHi/Lo: product of multiplication
623 // Lo0: initial value of Lo register
624 // Hi0: initial value of Hi register
625 // Return true if pattern matching was successful.
626 static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
627 // SUBENode's second operand must be a flag output of an SUBC node in order
628 // for the matching to be successful.
629 SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
631 if (SUBCNode->getOpcode() != ISD::SUBC)
634 SDValue MultHi = SUBENode->getOperand(1);
635 SDValue MultLo = SUBCNode->getOperand(1);
636 SDNode *MultNode = MultHi.getNode();
637 unsigned MultOpc = MultHi.getOpcode();
639 // MultHi and MultLo must be generated by the same node,
640 if (MultLo.getNode() != MultNode)
643 // and it must be a multiplication.
644 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
647 // MultLo amd MultHi must be the first and second output of MultNode
649 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
652 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
653 // of the values of MultNode, in which case MultNode will be removed in later
655 // If there exist users other than SUBENode or SUBCNode, this function returns
656 // here, which will result in MultNode being mapped to a single MULT
657 // instruction node rather than a pair of MULT and MSUB instructions being
659 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
662 SDValue Chain = CurDAG->getEntryNode();
663 DebugLoc dl = SUBENode->getDebugLoc();
665 // create MipsSub(u) node
666 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
668 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
669 MultNode->getOperand(0),// Factor 0
670 MultNode->getOperand(1),// Factor 1
671 SUBCNode->getOperand(0),// Lo0
672 SUBENode->getOperand(0));// Hi0
674 // create CopyFromReg nodes
675 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
677 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
679 CopyFromLo.getValue(2));
681 // replace uses of sube and subc here
682 if (!SDValue(SUBCNode, 0).use_empty())
683 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
685 if (!SDValue(SUBENode, 0).use_empty())
686 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
691 static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
692 TargetLowering::DAGCombinerInfo &DCI,
693 const MipsSubtarget *Subtarget) {
694 if (DCI.isBeforeLegalize())
697 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
699 return SDValue(N, 0);
704 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
705 TargetLowering::DAGCombinerInfo &DCI,
706 const MipsSubtarget *Subtarget) {
707 if (DCI.isBeforeLegalize())
710 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
712 return SDValue(N, 0);
717 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
718 TargetLowering::DAGCombinerInfo &DCI,
719 const MipsSubtarget *Subtarget) {
720 if (DCI.isBeforeLegalizeOps())
723 EVT Ty = N->getValueType(0);
724 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
725 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
726 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
728 DebugLoc dl = N->getDebugLoc();
730 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
731 N->getOperand(0), N->getOperand(1));
732 SDValue InChain = DAG.getEntryNode();
733 SDValue InGlue = DivRem;
736 if (N->hasAnyUseOfValue(0)) {
737 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
739 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
740 InChain = CopyFromLo.getValue(1);
741 InGlue = CopyFromLo.getValue(2);
745 if (N->hasAnyUseOfValue(1)) {
746 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
748 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
754 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
756 default: llvm_unreachable("Unknown fp condition code!");
758 case ISD::SETOEQ: return Mips::FCOND_OEQ;
759 case ISD::SETUNE: return Mips::FCOND_UNE;
761 case ISD::SETOLT: return Mips::FCOND_OLT;
763 case ISD::SETOGT: return Mips::FCOND_OGT;
765 case ISD::SETOLE: return Mips::FCOND_OLE;
767 case ISD::SETOGE: return Mips::FCOND_OGE;
768 case ISD::SETULT: return Mips::FCOND_ULT;
769 case ISD::SETULE: return Mips::FCOND_ULE;
770 case ISD::SETUGT: return Mips::FCOND_UGT;
771 case ISD::SETUGE: return Mips::FCOND_UGE;
772 case ISD::SETUO: return Mips::FCOND_UN;
773 case ISD::SETO: return Mips::FCOND_OR;
775 case ISD::SETONE: return Mips::FCOND_ONE;
776 case ISD::SETUEQ: return Mips::FCOND_UEQ;
781 // Returns true if condition code has to be inverted.
782 static bool InvertFPCondCode(Mips::CondCode CC) {
783 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
786 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
787 "Illegal Condition Code");
792 // Creates and returns an FPCmp node from a setcc node.
793 // Returns Op if setcc is not a floating point comparison.
794 static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
795 // must be a SETCC node
796 if (Op.getOpcode() != ISD::SETCC)
799 SDValue LHS = Op.getOperand(0);
801 if (!LHS.getValueType().isFloatingPoint())
804 SDValue RHS = Op.getOperand(1);
805 DebugLoc dl = Op.getDebugLoc();
807 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
808 // node if necessary.
809 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
811 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
812 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
815 // Creates and returns a CMovFPT/F node.
816 static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
817 SDValue False, DebugLoc DL) {
818 bool invert = InvertFPCondCode((Mips::CondCode)
819 cast<ConstantSDNode>(Cond.getOperand(2))
822 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
823 True.getValueType(), True, False, Cond);
826 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
827 TargetLowering::DAGCombinerInfo &DCI,
828 const MipsSubtarget *Subtarget) {
829 if (DCI.isBeforeLegalizeOps())
832 SDValue SetCC = N->getOperand(0);
834 if ((SetCC.getOpcode() != ISD::SETCC) ||
835 !SetCC.getOperand(0).getValueType().isInteger())
838 SDValue False = N->getOperand(2);
839 EVT FalseTy = False.getValueType();
841 if (!FalseTy.isInteger())
844 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
846 if (!CN || CN->getZExtValue())
849 const DebugLoc DL = N->getDebugLoc();
850 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
851 SDValue True = N->getOperand(1);
853 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
854 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
856 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
859 static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
860 TargetLowering::DAGCombinerInfo &DCI,
861 const MipsSubtarget *Subtarget) {
862 // Pattern match EXT.
863 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
864 // => ext $dst, $src, size, pos
865 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
868 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
869 unsigned ShiftRightOpc = ShiftRight.getOpcode();
871 // Op's first operand must be a shift right.
872 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
875 // The second operand of the shift must be an immediate.
877 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
880 uint64_t Pos = CN->getZExtValue();
881 uint64_t SMPos, SMSize;
883 // Op's second operand must be a shifted mask.
884 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
885 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
888 // Return if the shifted mask does not start at bit 0 or the sum of its size
889 // and Pos exceeds the word's size.
890 EVT ValTy = N->getValueType(0);
891 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
894 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
895 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
896 DAG.getConstant(SMSize, MVT::i32));
899 static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
900 TargetLowering::DAGCombinerInfo &DCI,
901 const MipsSubtarget *Subtarget) {
902 // Pattern match INS.
903 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
904 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
905 // => ins $dst, $src, size, pos, $src1
906 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
909 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
910 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
913 // See if Op's first operand matches (and $src1 , mask0).
914 if (And0.getOpcode() != ISD::AND)
917 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
918 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
921 // See if Op's second operand matches (and (shl $src, pos), mask1).
922 if (And1.getOpcode() != ISD::AND)
925 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
926 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
929 // The shift masks must have the same position and size.
930 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
933 SDValue Shl = And1.getOperand(0);
934 if (Shl.getOpcode() != ISD::SHL)
937 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
940 unsigned Shamt = CN->getZExtValue();
942 // Return if the shift amount and the first bit position of mask are not the
944 EVT ValTy = N->getValueType(0);
945 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
948 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
949 DAG.getConstant(SMPos0, MVT::i32),
950 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
953 static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
954 TargetLowering::DAGCombinerInfo &DCI,
955 const MipsSubtarget *Subtarget) {
956 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
958 if (DCI.isBeforeLegalizeOps())
961 SDValue Add = N->getOperand(1);
963 if (Add.getOpcode() != ISD::ADD)
966 SDValue Lo = Add.getOperand(1);
968 if ((Lo.getOpcode() != MipsISD::Lo) ||
969 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
972 EVT ValTy = N->getValueType(0);
973 DebugLoc DL = N->getDebugLoc();
975 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
977 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
980 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
982 SelectionDAG &DAG = DCI.DAG;
983 unsigned opc = N->getOpcode();
988 return PerformADDECombine(N, DAG, DCI, Subtarget);
990 return PerformSUBECombine(N, DAG, DCI, Subtarget);
993 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
995 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
997 return PerformANDCombine(N, DAG, DCI, Subtarget);
999 return PerformORCombine(N, DAG, DCI, Subtarget);
1001 return PerformADDCombine(N, DAG, DCI, Subtarget);
1008 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1009 SmallVectorImpl<SDValue> &Results,
1010 SelectionDAG &DAG) const {
1011 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1013 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1014 Results.push_back(Res.getValue(I));
1018 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1019 SmallVectorImpl<SDValue> &Results,
1020 SelectionDAG &DAG) const {
1021 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1023 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1024 Results.push_back(Res.getValue(I));
1027 SDValue MipsTargetLowering::
1028 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1030 switch (Op.getOpcode())
1032 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1033 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
1034 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
1035 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
1036 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
1037 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
1038 case ISD::SELECT: return LowerSELECT(Op, DAG);
1039 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
1040 case ISD::SETCC: return LowerSETCC(Op, DAG);
1041 case ISD::VASTART: return LowerVASTART(Op, DAG);
1042 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
1043 case ISD::FABS: return LowerFABS(Op, DAG);
1044 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
1045 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
1046 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
1047 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
1048 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
1049 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
1050 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
1051 case ISD::LOAD: return LowerLOAD(Op, DAG);
1052 case ISD::STORE: return LowerSTORE(Op, DAG);
1053 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1054 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
1055 case ISD::ADD: return LowerADD(Op, DAG);
1060 //===----------------------------------------------------------------------===//
1061 // Lower helper functions
1062 //===----------------------------------------------------------------------===//
1064 // AddLiveIn - This helper function adds the specified physical register to the
1065 // MachineFunction as a live in value. It also creates a corresponding
1066 // virtual register for it.
1068 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1070 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1071 MF.getRegInfo().addLiveIn(PReg, VReg);
1075 // Get fp branch code (not opcode) from condition code.
1076 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
1077 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
1078 return Mips::BRANCH_T;
1080 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
1081 "Invalid CondCode.");
1083 return Mips::BRANCH_F;
1087 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
1089 const MipsSubtarget *Subtarget,
1090 const TargetInstrInfo *TII,
1091 bool isFPCmp, unsigned Opc) {
1092 // There is no need to expand CMov instructions if target has
1093 // conditional moves.
1094 if (Subtarget->hasCondMov())
1097 // To "insert" a SELECT_CC instruction, we actually have to insert the
1098 // diamond control-flow pattern. The incoming instruction knows the
1099 // destination vreg to set, the condition code register to branch on, the
1100 // true/false values to select between, and a branch opcode to use.
1101 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1102 MachineFunction::iterator It = BB;
1109 // bNE r1, r0, copy1MBB
1110 // fallthrough --> copy0MBB
1111 MachineBasicBlock *thisMBB = BB;
1112 MachineFunction *F = BB->getParent();
1113 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1114 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1115 F->insert(It, copy0MBB);
1116 F->insert(It, sinkMBB);
1118 // Transfer the remainder of BB and its successor edges to sinkMBB.
1119 sinkMBB->splice(sinkMBB->begin(), BB,
1120 llvm::next(MachineBasicBlock::iterator(MI)),
1122 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1124 // Next, add the true and fallthrough blocks as its successors.
1125 BB->addSuccessor(copy0MBB);
1126 BB->addSuccessor(sinkMBB);
1128 // Emit the right instruction according to the type of the operands compared
1130 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
1132 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
1133 .addReg(Mips::ZERO).addMBB(sinkMBB);
1136 // %FalseValue = ...
1137 // # fallthrough to sinkMBB
1140 // Update machine-CFG edges
1141 BB->addSuccessor(sinkMBB);
1144 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1149 BuildMI(*BB, BB->begin(), dl,
1150 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1151 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
1152 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1154 BuildMI(*BB, BB->begin(), dl,
1155 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1156 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
1157 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1159 MI->eraseFromParent(); // The pseudo instruction is gone now.
1165 MipsTargetLowering::EmitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
1167 // bposge32_pseudo $vr0
1177 // $vr0 = phi($vr2, $fbb, $vr1, $tbb)
1179 MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
1180 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1181 const TargetRegisterClass *RC = &Mips::CPURegsRegClass;
1182 DebugLoc DL = MI->getDebugLoc();
1183 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1184 MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
1185 MachineFunction *F = BB->getParent();
1186 MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
1187 MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
1188 MachineBasicBlock *Sink = F->CreateMachineBasicBlock(LLVM_BB);
1191 F->insert(It, Sink);
1193 // Transfer the remainder of BB and its successor edges to Sink.
1194 Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
1196 Sink->transferSuccessorsAndUpdatePHIs(BB);
1199 BB->addSuccessor(FBB);
1200 BB->addSuccessor(TBB);
1201 FBB->addSuccessor(Sink);
1202 TBB->addSuccessor(Sink);
1204 // Insert the real bposge32 instruction to $BB.
1205 BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
1208 unsigned VR2 = RegInfo.createVirtualRegister(RC);
1209 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
1210 .addReg(Mips::ZERO).addImm(0);
1211 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
1214 unsigned VR1 = RegInfo.createVirtualRegister(RC);
1215 BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
1216 .addReg(Mips::ZERO).addImm(1);
1218 // Insert phi function to $Sink.
1219 BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
1220 MI->getOperand(0).getReg())
1221 .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
1223 MI->eraseFromParent(); // The pseudo instruction is gone now.
1228 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1229 MachineBasicBlock *BB) const {
1230 switch (MI->getOpcode()) {
1231 default: llvm_unreachable("Unexpected instr type to insert");
1232 case Mips::ATOMIC_LOAD_ADD_I8:
1233 case Mips::ATOMIC_LOAD_ADD_I8_P8:
1234 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1235 case Mips::ATOMIC_LOAD_ADD_I16:
1236 case Mips::ATOMIC_LOAD_ADD_I16_P8:
1237 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1238 case Mips::ATOMIC_LOAD_ADD_I32:
1239 case Mips::ATOMIC_LOAD_ADD_I32_P8:
1240 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
1241 case Mips::ATOMIC_LOAD_ADD_I64:
1242 case Mips::ATOMIC_LOAD_ADD_I64_P8:
1243 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
1245 case Mips::ATOMIC_LOAD_AND_I8:
1246 case Mips::ATOMIC_LOAD_AND_I8_P8:
1247 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1248 case Mips::ATOMIC_LOAD_AND_I16:
1249 case Mips::ATOMIC_LOAD_AND_I16_P8:
1250 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1251 case Mips::ATOMIC_LOAD_AND_I32:
1252 case Mips::ATOMIC_LOAD_AND_I32_P8:
1253 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
1254 case Mips::ATOMIC_LOAD_AND_I64:
1255 case Mips::ATOMIC_LOAD_AND_I64_P8:
1256 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
1258 case Mips::ATOMIC_LOAD_OR_I8:
1259 case Mips::ATOMIC_LOAD_OR_I8_P8:
1260 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1261 case Mips::ATOMIC_LOAD_OR_I16:
1262 case Mips::ATOMIC_LOAD_OR_I16_P8:
1263 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1264 case Mips::ATOMIC_LOAD_OR_I32:
1265 case Mips::ATOMIC_LOAD_OR_I32_P8:
1266 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
1267 case Mips::ATOMIC_LOAD_OR_I64:
1268 case Mips::ATOMIC_LOAD_OR_I64_P8:
1269 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
1271 case Mips::ATOMIC_LOAD_XOR_I8:
1272 case Mips::ATOMIC_LOAD_XOR_I8_P8:
1273 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1274 case Mips::ATOMIC_LOAD_XOR_I16:
1275 case Mips::ATOMIC_LOAD_XOR_I16_P8:
1276 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1277 case Mips::ATOMIC_LOAD_XOR_I32:
1278 case Mips::ATOMIC_LOAD_XOR_I32_P8:
1279 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
1280 case Mips::ATOMIC_LOAD_XOR_I64:
1281 case Mips::ATOMIC_LOAD_XOR_I64_P8:
1282 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
1284 case Mips::ATOMIC_LOAD_NAND_I8:
1285 case Mips::ATOMIC_LOAD_NAND_I8_P8:
1286 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
1287 case Mips::ATOMIC_LOAD_NAND_I16:
1288 case Mips::ATOMIC_LOAD_NAND_I16_P8:
1289 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
1290 case Mips::ATOMIC_LOAD_NAND_I32:
1291 case Mips::ATOMIC_LOAD_NAND_I32_P8:
1292 return EmitAtomicBinary(MI, BB, 4, 0, true);
1293 case Mips::ATOMIC_LOAD_NAND_I64:
1294 case Mips::ATOMIC_LOAD_NAND_I64_P8:
1295 return EmitAtomicBinary(MI, BB, 8, 0, true);
1297 case Mips::ATOMIC_LOAD_SUB_I8:
1298 case Mips::ATOMIC_LOAD_SUB_I8_P8:
1299 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1300 case Mips::ATOMIC_LOAD_SUB_I16:
1301 case Mips::ATOMIC_LOAD_SUB_I16_P8:
1302 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1303 case Mips::ATOMIC_LOAD_SUB_I32:
1304 case Mips::ATOMIC_LOAD_SUB_I32_P8:
1305 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1306 case Mips::ATOMIC_LOAD_SUB_I64:
1307 case Mips::ATOMIC_LOAD_SUB_I64_P8:
1308 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1310 case Mips::ATOMIC_SWAP_I8:
1311 case Mips::ATOMIC_SWAP_I8_P8:
1312 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1313 case Mips::ATOMIC_SWAP_I16:
1314 case Mips::ATOMIC_SWAP_I16_P8:
1315 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1316 case Mips::ATOMIC_SWAP_I32:
1317 case Mips::ATOMIC_SWAP_I32_P8:
1318 return EmitAtomicBinary(MI, BB, 4, 0);
1319 case Mips::ATOMIC_SWAP_I64:
1320 case Mips::ATOMIC_SWAP_I64_P8:
1321 return EmitAtomicBinary(MI, BB, 8, 0);
1323 case Mips::ATOMIC_CMP_SWAP_I8:
1324 case Mips::ATOMIC_CMP_SWAP_I8_P8:
1325 return EmitAtomicCmpSwapPartword(MI, BB, 1);
1326 case Mips::ATOMIC_CMP_SWAP_I16:
1327 case Mips::ATOMIC_CMP_SWAP_I16_P8:
1328 return EmitAtomicCmpSwapPartword(MI, BB, 2);
1329 case Mips::ATOMIC_CMP_SWAP_I32:
1330 case Mips::ATOMIC_CMP_SWAP_I32_P8:
1331 return EmitAtomicCmpSwap(MI, BB, 4);
1332 case Mips::ATOMIC_CMP_SWAP_I64:
1333 case Mips::ATOMIC_CMP_SWAP_I64_P8:
1334 return EmitAtomicCmpSwap(MI, BB, 8);
1335 case Mips::BPOSGE32_PSEUDO:
1336 return EmitBPOSGE32(MI, BB);
1340 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1341 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1343 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1344 unsigned Size, unsigned BinOpcode,
1346 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1348 MachineFunction *MF = BB->getParent();
1349 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1350 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1351 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1352 DebugLoc dl = MI->getDebugLoc();
1353 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1356 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1357 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1364 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1365 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1368 ZERO = Mips::ZERO_64;
1372 unsigned OldVal = MI->getOperand(0).getReg();
1373 unsigned Ptr = MI->getOperand(1).getReg();
1374 unsigned Incr = MI->getOperand(2).getReg();
1376 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1377 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1378 unsigned Success = RegInfo.createVirtualRegister(RC);
1380 // insert new blocks after the current block
1381 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1382 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1383 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1384 MachineFunction::iterator It = BB;
1386 MF->insert(It, loopMBB);
1387 MF->insert(It, exitMBB);
1389 // Transfer the remainder of BB and its successor edges to exitMBB.
1390 exitMBB->splice(exitMBB->begin(), BB,
1391 llvm::next(MachineBasicBlock::iterator(MI)),
1393 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1397 // fallthrough --> loopMBB
1398 BB->addSuccessor(loopMBB);
1399 loopMBB->addSuccessor(loopMBB);
1400 loopMBB->addSuccessor(exitMBB);
1403 // ll oldval, 0(ptr)
1404 // <binop> storeval, oldval, incr
1405 // sc success, storeval, 0(ptr)
1406 // beq success, $0, loopMBB
1408 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1410 // and andres, oldval, incr
1411 // nor storeval, $0, andres
1412 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1413 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1414 } else if (BinOpcode) {
1415 // <binop> storeval, oldval, incr
1416 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1420 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1421 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1423 MI->eraseFromParent(); // The instruction is gone now.
1429 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1430 MachineBasicBlock *BB,
1431 unsigned Size, unsigned BinOpcode,
1433 assert((Size == 1 || Size == 2) &&
1434 "Unsupported size for EmitAtomicBinaryPartial.");
1436 MachineFunction *MF = BB->getParent();
1437 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1438 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1439 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1440 DebugLoc dl = MI->getDebugLoc();
1441 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1442 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1444 unsigned Dest = MI->getOperand(0).getReg();
1445 unsigned Ptr = MI->getOperand(1).getReg();
1446 unsigned Incr = MI->getOperand(2).getReg();
1448 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1449 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1450 unsigned Mask = RegInfo.createVirtualRegister(RC);
1451 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1452 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1453 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1454 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1455 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1456 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1457 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1458 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1459 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1460 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1461 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1462 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1463 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1464 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1465 unsigned Success = RegInfo.createVirtualRegister(RC);
1467 // insert new blocks after the current block
1468 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1469 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1470 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1471 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1472 MachineFunction::iterator It = BB;
1474 MF->insert(It, loopMBB);
1475 MF->insert(It, sinkMBB);
1476 MF->insert(It, exitMBB);
1478 // Transfer the remainder of BB and its successor edges to exitMBB.
1479 exitMBB->splice(exitMBB->begin(), BB,
1480 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1481 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1483 BB->addSuccessor(loopMBB);
1484 loopMBB->addSuccessor(loopMBB);
1485 loopMBB->addSuccessor(sinkMBB);
1486 sinkMBB->addSuccessor(exitMBB);
1489 // addiu masklsb2,$0,-4 # 0xfffffffc
1490 // and alignedaddr,ptr,masklsb2
1491 // andi ptrlsb2,ptr,3
1492 // sll shiftamt,ptrlsb2,3
1493 // ori maskupper,$0,255 # 0xff
1494 // sll mask,maskupper,shiftamt
1495 // nor mask2,$0,mask
1496 // sll incr2,incr,shiftamt
1498 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1499 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1500 .addReg(Mips::ZERO).addImm(-4);
1501 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1502 .addReg(Ptr).addReg(MaskLSB2);
1503 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1504 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).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(ShiftAmt).addReg(MaskUpper);
1509 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1510 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1512 // atomic.load.binop
1514 // ll oldval,0(alignedaddr)
1515 // binop binopres,oldval,incr2
1516 // and newval,binopres,mask
1517 // and maskedoldval0,oldval,mask2
1518 // or storeval,maskedoldval0,newval
1519 // sc success,storeval,0(alignedaddr)
1520 // beq success,$0,loopMBB
1524 // ll oldval,0(alignedaddr)
1525 // and newval,incr2,mask
1526 // and maskedoldval0,oldval,mask2
1527 // or storeval,maskedoldval0,newval
1528 // sc success,storeval,0(alignedaddr)
1529 // beq success,$0,loopMBB
1532 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1534 // and andres, oldval, incr2
1535 // nor binopres, $0, andres
1536 // and newval, binopres, mask
1537 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1538 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1539 .addReg(Mips::ZERO).addReg(AndRes);
1540 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1541 } else if (BinOpcode) {
1542 // <binop> binopres, oldval, incr2
1543 // and newval, binopres, mask
1544 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1545 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1546 } else {// atomic.swap
1547 // and newval, incr2, mask
1548 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1551 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1552 .addReg(OldVal).addReg(Mask2);
1553 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1554 .addReg(MaskedOldVal0).addReg(NewVal);
1555 BuildMI(BB, dl, TII->get(SC), Success)
1556 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1557 BuildMI(BB, dl, TII->get(Mips::BEQ))
1558 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1561 // and maskedoldval1,oldval,mask
1562 // srl srlres,maskedoldval1,shiftamt
1563 // sll sllres,srlres,24
1564 // sra dest,sllres,24
1566 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1568 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1569 .addReg(OldVal).addReg(Mask);
1570 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1571 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1572 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1573 .addReg(SrlRes).addImm(ShiftImm);
1574 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1575 .addReg(SllRes).addImm(ShiftImm);
1577 MI->eraseFromParent(); // The instruction is gone now.
1583 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1584 MachineBasicBlock *BB,
1585 unsigned Size) const {
1586 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1588 MachineFunction *MF = BB->getParent();
1589 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1590 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1591 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1592 DebugLoc dl = MI->getDebugLoc();
1593 unsigned LL, SC, ZERO, BNE, BEQ;
1596 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1597 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1603 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1604 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1605 ZERO = Mips::ZERO_64;
1610 unsigned Dest = MI->getOperand(0).getReg();
1611 unsigned Ptr = MI->getOperand(1).getReg();
1612 unsigned OldVal = MI->getOperand(2).getReg();
1613 unsigned NewVal = MI->getOperand(3).getReg();
1615 unsigned Success = RegInfo.createVirtualRegister(RC);
1617 // insert new blocks after the current block
1618 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1619 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1620 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1621 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1622 MachineFunction::iterator It = BB;
1624 MF->insert(It, loop1MBB);
1625 MF->insert(It, loop2MBB);
1626 MF->insert(It, exitMBB);
1628 // Transfer the remainder of BB and its successor edges to exitMBB.
1629 exitMBB->splice(exitMBB->begin(), BB,
1630 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1631 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1635 // fallthrough --> loop1MBB
1636 BB->addSuccessor(loop1MBB);
1637 loop1MBB->addSuccessor(exitMBB);
1638 loop1MBB->addSuccessor(loop2MBB);
1639 loop2MBB->addSuccessor(loop1MBB);
1640 loop2MBB->addSuccessor(exitMBB);
1644 // bne dest, oldval, exitMBB
1646 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1647 BuildMI(BB, dl, TII->get(BNE))
1648 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1651 // sc success, newval, 0(ptr)
1652 // beq success, $0, loop1MBB
1654 BuildMI(BB, dl, TII->get(SC), Success)
1655 .addReg(NewVal).addReg(Ptr).addImm(0);
1656 BuildMI(BB, dl, TII->get(BEQ))
1657 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1659 MI->eraseFromParent(); // The instruction is gone now.
1665 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1666 MachineBasicBlock *BB,
1667 unsigned Size) const {
1668 assert((Size == 1 || Size == 2) &&
1669 "Unsupported size for EmitAtomicCmpSwapPartial.");
1671 MachineFunction *MF = BB->getParent();
1672 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1673 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1674 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1675 DebugLoc dl = MI->getDebugLoc();
1676 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1677 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1679 unsigned Dest = MI->getOperand(0).getReg();
1680 unsigned Ptr = MI->getOperand(1).getReg();
1681 unsigned CmpVal = MI->getOperand(2).getReg();
1682 unsigned NewVal = MI->getOperand(3).getReg();
1684 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1685 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1686 unsigned Mask = RegInfo.createVirtualRegister(RC);
1687 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1688 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1689 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1690 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1691 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1692 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1693 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1694 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1695 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1696 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1697 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1698 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1699 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1700 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1701 unsigned Success = RegInfo.createVirtualRegister(RC);
1703 // insert new blocks after the current block
1704 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1705 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1706 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1707 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1708 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1709 MachineFunction::iterator It = BB;
1711 MF->insert(It, loop1MBB);
1712 MF->insert(It, loop2MBB);
1713 MF->insert(It, sinkMBB);
1714 MF->insert(It, exitMBB);
1716 // Transfer the remainder of BB and its successor edges to exitMBB.
1717 exitMBB->splice(exitMBB->begin(), BB,
1718 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1719 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1721 BB->addSuccessor(loop1MBB);
1722 loop1MBB->addSuccessor(sinkMBB);
1723 loop1MBB->addSuccessor(loop2MBB);
1724 loop2MBB->addSuccessor(loop1MBB);
1725 loop2MBB->addSuccessor(sinkMBB);
1726 sinkMBB->addSuccessor(exitMBB);
1728 // FIXME: computation of newval2 can be moved to loop2MBB.
1730 // addiu masklsb2,$0,-4 # 0xfffffffc
1731 // and alignedaddr,ptr,masklsb2
1732 // andi ptrlsb2,ptr,3
1733 // sll shiftamt,ptrlsb2,3
1734 // ori maskupper,$0,255 # 0xff
1735 // sll mask,maskupper,shiftamt
1736 // nor mask2,$0,mask
1737 // andi maskedcmpval,cmpval,255
1738 // sll shiftedcmpval,maskedcmpval,shiftamt
1739 // andi maskednewval,newval,255
1740 // sll shiftednewval,maskednewval,shiftamt
1741 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1742 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1743 .addReg(Mips::ZERO).addImm(-4);
1744 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1745 .addReg(Ptr).addReg(MaskLSB2);
1746 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1747 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1748 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1749 .addReg(Mips::ZERO).addImm(MaskImm);
1750 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1751 .addReg(ShiftAmt).addReg(MaskUpper);
1752 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1753 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1754 .addReg(CmpVal).addImm(MaskImm);
1755 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1756 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1757 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1758 .addReg(NewVal).addImm(MaskImm);
1759 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1760 .addReg(ShiftAmt).addReg(MaskedNewVal);
1763 // ll oldval,0(alginedaddr)
1764 // and maskedoldval0,oldval,mask
1765 // bne maskedoldval0,shiftedcmpval,sinkMBB
1767 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1768 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1769 .addReg(OldVal).addReg(Mask);
1770 BuildMI(BB, dl, TII->get(Mips::BNE))
1771 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1774 // and maskedoldval1,oldval,mask2
1775 // or storeval,maskedoldval1,shiftednewval
1776 // sc success,storeval,0(alignedaddr)
1777 // beq success,$0,loop1MBB
1779 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1780 .addReg(OldVal).addReg(Mask2);
1781 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1782 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1783 BuildMI(BB, dl, TII->get(SC), Success)
1784 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1785 BuildMI(BB, dl, TII->get(Mips::BEQ))
1786 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1789 // srl srlres,maskedoldval0,shiftamt
1790 // sll sllres,srlres,24
1791 // sra dest,sllres,24
1793 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1795 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1796 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1797 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1798 .addReg(SrlRes).addImm(ShiftImm);
1799 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1800 .addReg(SllRes).addImm(ShiftImm);
1802 MI->eraseFromParent(); // The instruction is gone now.
1807 //===----------------------------------------------------------------------===//
1808 // Misc Lower Operation implementation
1809 //===----------------------------------------------------------------------===//
1810 SDValue MipsTargetLowering::
1811 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1813 // The first operand is the chain, the second is the condition, the third is
1814 // the block to branch to if the condition is true.
1815 SDValue Chain = Op.getOperand(0);
1816 SDValue Dest = Op.getOperand(2);
1817 DebugLoc dl = Op.getDebugLoc();
1819 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1821 // Return if flag is not set by a floating point comparison.
1822 if (CondRes.getOpcode() != MipsISD::FPCmp)
1825 SDValue CCNode = CondRes.getOperand(2);
1827 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1828 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1830 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1834 SDValue MipsTargetLowering::
1835 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1837 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1839 // Return if flag is not set by a floating point comparison.
1840 if (Cond.getOpcode() != MipsISD::FPCmp)
1843 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1847 SDValue MipsTargetLowering::
1848 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1850 DebugLoc DL = Op.getDebugLoc();
1851 EVT Ty = Op.getOperand(0).getValueType();
1852 SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1853 Op.getOperand(0), Op.getOperand(1),
1856 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1860 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1861 SDValue Cond = CreateFPCmp(DAG, Op);
1863 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1864 "Floating point operand expected.");
1866 SDValue True = DAG.getConstant(1, MVT::i32);
1867 SDValue False = DAG.getConstant(0, MVT::i32);
1869 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1872 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1873 SelectionDAG &DAG) const {
1874 // FIXME there isn't actually debug info here
1875 DebugLoc dl = Op.getDebugLoc();
1876 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1878 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1879 const MipsTargetObjectFile &TLOF =
1880 (const MipsTargetObjectFile&)getObjFileLowering();
1882 // %gp_rel relocation
1883 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1884 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1886 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl,
1887 DAG.getVTList(MVT::i32), &GA, 1);
1888 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1889 return DAG.getNode(ISD::ADD, dl, MVT::i32, GPReg, GPRelNode);
1892 // %hi/%lo relocation
1893 return getAddrNonPIC(Op, DAG);
1896 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1897 return getAddrLocal(Op, DAG, HasMips64);
1900 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1901 MipsII::MO_GOT_LO16);
1903 return getAddrGlobal(Op, DAG,
1904 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1907 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1908 SelectionDAG &DAG) const {
1909 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1910 return getAddrNonPIC(Op, DAG);
1912 return getAddrLocal(Op, DAG, HasMips64);
1915 SDValue MipsTargetLowering::
1916 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1918 // If the relocation model is PIC, use the General Dynamic TLS Model or
1919 // Local Dynamic TLS model, otherwise use the Initial Exec or
1920 // Local Exec TLS Model.
1922 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1923 DebugLoc dl = GA->getDebugLoc();
1924 const GlobalValue *GV = GA->getGlobal();
1925 EVT PtrVT = getPointerTy();
1927 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1929 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1930 // General Dynamic and Local Dynamic TLS Model.
1931 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1934 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1935 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1936 GetGlobalReg(DAG, PtrVT), TGA);
1937 unsigned PtrSize = PtrVT.getSizeInBits();
1938 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1940 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1944 Entry.Node = Argument;
1946 Args.push_back(Entry);
1948 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1949 false, false, false, false, 0, CallingConv::C,
1950 /*isTailCall=*/false, /*doesNotRet=*/false,
1951 /*isReturnValueUsed=*/true,
1952 TlsGetAddr, Args, DAG, dl);
1953 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1955 SDValue Ret = CallResult.first;
1957 if (model != TLSModel::LocalDynamic)
1960 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1961 MipsII::MO_DTPREL_HI);
1962 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1963 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1964 MipsII::MO_DTPREL_LO);
1965 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1966 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1967 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1971 if (model == TLSModel::InitialExec) {
1972 // Initial Exec TLS Model
1973 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1974 MipsII::MO_GOTTPREL);
1975 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1977 Offset = DAG.getLoad(PtrVT, dl,
1978 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1979 false, false, false, 0);
1981 // Local Exec TLS Model
1982 assert(model == TLSModel::LocalExec);
1983 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1984 MipsII::MO_TPREL_HI);
1985 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1986 MipsII::MO_TPREL_LO);
1987 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1988 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1989 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1992 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1993 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1996 SDValue MipsTargetLowering::
1997 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1999 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2000 return getAddrNonPIC(Op, DAG);
2002 return getAddrLocal(Op, DAG, HasMips64);
2005 SDValue MipsTargetLowering::
2006 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2008 // gp_rel relocation
2009 // FIXME: we should reference the constant pool using small data sections,
2010 // but the asm printer currently doesn't support this feature without
2011 // hacking it. This feature should come soon so we can uncomment the
2013 //if (IsInSmallSection(C->getType())) {
2014 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
2015 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
2016 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
2018 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2019 return getAddrNonPIC(Op, DAG);
2021 return getAddrLocal(Op, DAG, HasMips64);
2024 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2025 MachineFunction &MF = DAG.getMachineFunction();
2026 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2028 DebugLoc dl = Op.getDebugLoc();
2029 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2032 // vastart just stores the address of the VarArgsFrameIndex slot into the
2033 // memory location argument.
2034 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2035 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
2036 MachinePointerInfo(SV), false, false, 0);
2039 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2040 EVT TyX = Op.getOperand(0).getValueType();
2041 EVT TyY = Op.getOperand(1).getValueType();
2042 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2043 SDValue Const31 = DAG.getConstant(31, MVT::i32);
2044 DebugLoc DL = Op.getDebugLoc();
2047 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2049 SDValue X = (TyX == MVT::f32) ?
2050 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2051 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2053 SDValue Y = (TyY == MVT::f32) ?
2054 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2055 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2059 // ext E, Y, 31, 1 ; extract bit31 of Y
2060 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2061 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2062 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2065 // srl SrlX, SllX, 1
2067 // sll SllY, SrlX, 31
2068 // or Or, SrlX, SllY
2069 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2070 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2071 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2072 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2073 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2076 if (TyX == MVT::f32)
2077 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2079 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2080 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2081 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2084 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2085 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2086 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2087 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2088 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2089 DebugLoc DL = Op.getDebugLoc();
2091 // Bitcast to integer nodes.
2092 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2093 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2096 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2097 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2098 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2099 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
2101 if (WidthX > WidthY)
2102 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2103 else if (WidthY > WidthX)
2104 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2106 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2107 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2108 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2111 // (d)sll SllX, X, 1
2112 // (d)srl SrlX, SllX, 1
2113 // (d)srl SrlY, Y, width(Y)-1
2114 // (d)sll SllY, SrlX, width(Y)-1
2115 // or Or, SrlX, SllY
2116 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2117 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2118 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2119 DAG.getConstant(WidthY - 1, MVT::i32));
2121 if (WidthX > WidthY)
2122 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2123 else if (WidthY > WidthX)
2124 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2126 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2127 DAG.getConstant(WidthX - 1, MVT::i32));
2128 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2129 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2133 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2134 if (Subtarget->hasMips64())
2135 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
2137 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
2140 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2141 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2142 DebugLoc DL = Op.getDebugLoc();
2144 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2146 SDValue X = (Op.getValueType() == MVT::f32) ?
2147 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2148 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2153 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2154 DAG.getRegister(Mips::ZERO, MVT::i32),
2155 DAG.getConstant(31, MVT::i32), Const1, X);
2157 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2158 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2161 if (Op.getValueType() == MVT::f32)
2162 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2164 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2165 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2166 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2169 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2170 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2171 DebugLoc DL = Op.getDebugLoc();
2173 // Bitcast to integer node.
2174 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2178 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2179 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2180 DAG.getConstant(63, MVT::i32), Const1, X);
2182 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2183 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2186 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2190 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
2191 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2192 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2194 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2197 SDValue MipsTargetLowering::
2198 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2200 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2201 "Frame address can only be determined for current frame.");
2203 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2204 MFI->setFrameAddressIsTaken(true);
2205 EVT VT = Op.getValueType();
2206 DebugLoc dl = Op.getDebugLoc();
2207 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2208 IsN64 ? Mips::FP_64 : Mips::FP, VT);
2212 SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2213 SelectionDAG &DAG) const {
2215 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2216 "Return address can be determined only for current frame.");
2218 MachineFunction &MF = DAG.getMachineFunction();
2219 MachineFrameInfo *MFI = MF.getFrameInfo();
2220 MVT VT = Op.getSimpleValueType();
2221 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2222 MFI->setReturnAddressIsTaken(true);
2224 // Return RA, which contains the return address. Mark it an implicit live-in.
2225 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2226 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2229 // TODO: set SType according to the desired memory barrier behavior.
2231 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2233 DebugLoc dl = Op.getDebugLoc();
2234 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2235 DAG.getConstant(SType, MVT::i32));
2238 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2239 SelectionDAG &DAG) const {
2240 // FIXME: Need pseudo-fence for 'singlethread' fences
2241 // FIXME: Set SType for weaker fences where supported/appropriate.
2243 DebugLoc dl = Op.getDebugLoc();
2244 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2245 DAG.getConstant(SType, MVT::i32));
2248 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2249 SelectionDAG &DAG) const {
2250 DebugLoc DL = Op.getDebugLoc();
2251 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2252 SDValue Shamt = Op.getOperand(2);
2255 // lo = (shl lo, shamt)
2256 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2259 // hi = (shl lo, shamt[4:0])
2260 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2261 DAG.getConstant(-1, MVT::i32));
2262 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2263 DAG.getConstant(1, MVT::i32));
2264 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2266 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2267 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2268 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2269 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2270 DAG.getConstant(0x20, MVT::i32));
2271 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2272 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2273 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2275 SDValue Ops[2] = {Lo, Hi};
2276 return DAG.getMergeValues(Ops, 2, DL);
2279 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2281 DebugLoc DL = Op.getDebugLoc();
2282 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2283 SDValue Shamt = Op.getOperand(2);
2286 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2288 // hi = (sra hi, shamt)
2290 // hi = (srl hi, shamt)
2293 // lo = (sra hi, shamt[4:0])
2294 // hi = (sra hi, 31)
2296 // lo = (srl hi, shamt[4:0])
2298 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2299 DAG.getConstant(-1, MVT::i32));
2300 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2301 DAG.getConstant(1, MVT::i32));
2302 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2303 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2304 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2305 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2307 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2308 DAG.getConstant(0x20, MVT::i32));
2309 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2310 DAG.getConstant(31, MVT::i32));
2311 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2312 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2313 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2316 SDValue Ops[2] = {Lo, Hi};
2317 return DAG.getMergeValues(Ops, 2, DL);
2320 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2321 SDValue Chain, SDValue Src, unsigned Offset) {
2322 SDValue Ptr = LD->getBasePtr();
2323 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2324 EVT BasePtrVT = Ptr.getValueType();
2325 DebugLoc DL = LD->getDebugLoc();
2326 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2329 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2330 DAG.getConstant(Offset, BasePtrVT));
2332 SDValue Ops[] = { Chain, Ptr, Src };
2333 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2334 LD->getMemOperand());
2337 // Expand an unaligned 32 or 64-bit integer load node.
2338 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2339 LoadSDNode *LD = cast<LoadSDNode>(Op);
2340 EVT MemVT = LD->getMemoryVT();
2342 // Return if load is aligned or if MemVT is neither i32 nor i64.
2343 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2344 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2347 bool IsLittle = Subtarget->isLittle();
2348 EVT VT = Op.getValueType();
2349 ISD::LoadExtType ExtType = LD->getExtensionType();
2350 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2352 assert((VT == MVT::i32) || (VT == MVT::i64));
2355 // (set dst, (i64 (load baseptr)))
2357 // (set tmp, (ldl (add baseptr, 7), undef))
2358 // (set dst, (ldr baseptr, tmp))
2359 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2360 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2362 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2366 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2368 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2372 // (set dst, (i32 (load baseptr))) or
2373 // (set dst, (i64 (sextload baseptr))) or
2374 // (set dst, (i64 (extload baseptr)))
2376 // (set tmp, (lwl (add baseptr, 3), undef))
2377 // (set dst, (lwr baseptr, tmp))
2378 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2379 (ExtType == ISD::EXTLOAD))
2382 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2385 // (set dst, (i64 (zextload baseptr)))
2387 // (set tmp0, (lwl (add baseptr, 3), undef))
2388 // (set tmp1, (lwr baseptr, tmp0))
2389 // (set tmp2, (shl tmp1, 32))
2390 // (set dst, (srl tmp2, 32))
2391 DebugLoc DL = LD->getDebugLoc();
2392 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2393 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2394 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2395 SDValue Ops[] = { SRL, LWR.getValue(1) };
2396 return DAG.getMergeValues(Ops, 2, DL);
2399 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2400 SDValue Chain, unsigned Offset) {
2401 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2402 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2403 DebugLoc DL = SD->getDebugLoc();
2404 SDVTList VTList = DAG.getVTList(MVT::Other);
2407 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2408 DAG.getConstant(Offset, BasePtrVT));
2410 SDValue Ops[] = { Chain, Value, Ptr };
2411 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2412 SD->getMemOperand());
2415 // Expand an unaligned 32 or 64-bit integer store node.
2416 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2417 StoreSDNode *SD = cast<StoreSDNode>(Op);
2418 EVT MemVT = SD->getMemoryVT();
2420 // Return if store is aligned or if MemVT is neither i32 nor i64.
2421 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2422 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2425 bool IsLittle = Subtarget->isLittle();
2426 SDValue Value = SD->getValue(), Chain = SD->getChain();
2427 EVT VT = Value.getValueType();
2430 // (store val, baseptr) or
2431 // (truncstore val, baseptr)
2433 // (swl val, (add baseptr, 3))
2434 // (swr val, baseptr)
2435 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2436 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2438 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2441 assert(VT == MVT::i64);
2444 // (store val, baseptr)
2446 // (sdl val, (add baseptr, 7))
2447 // (sdr val, baseptr)
2448 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2449 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2452 // This function expands mips intrinsic nodes which have 64-bit input operands
2453 // or output values.
2455 // out64 = intrinsic-node in64
2457 // lo = copy (extract-element (in64, 0))
2458 // hi = copy (extract-element (in64, 1))
2459 // mips-specific-node
2462 // out64 = merge-values (v0, v1)
2464 static SDValue LowerDSPIntr(SDValue Op, SelectionDAG &DAG,
2465 unsigned Opc, bool HasI64In, bool HasI64Out) {
2466 DebugLoc DL = Op.getDebugLoc();
2467 bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
2468 SDValue Chain = HasChainIn ? Op->getOperand(0) : DAG.getEntryNode();
2469 SmallVector<SDValue, 3> Ops;
2472 SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2473 Op->getOperand(1 + HasChainIn),
2474 DAG.getConstant(0, MVT::i32));
2475 SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2476 Op->getOperand(1 + HasChainIn),
2477 DAG.getConstant(1, MVT::i32));
2479 Chain = DAG.getCopyToReg(Chain, DL, Mips::LO, InLo, SDValue());
2480 Chain = DAG.getCopyToReg(Chain, DL, Mips::HI, InHi, Chain.getValue(1));
2482 Ops.push_back(Chain);
2483 Ops.append(Op->op_begin() + HasChainIn + 2, Op->op_end());
2484 Ops.push_back(Chain.getValue(1));
2486 Ops.push_back(Chain);
2487 Ops.append(Op->op_begin() + HasChainIn + 1, Op->op_end());
2491 return DAG.getNode(Opc, DL, Op->value_begin(), Op->getNumValues(),
2492 Ops.begin(), Ops.size());
2494 SDValue Intr = DAG.getNode(Opc, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2495 Ops.begin(), Ops.size());
2496 SDValue OutLo = DAG.getCopyFromReg(Intr.getValue(0), DL, Mips::LO, MVT::i32,
2498 SDValue OutHi = DAG.getCopyFromReg(OutLo.getValue(1), DL, Mips::HI, MVT::i32,
2500 SDValue Out = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, OutLo, OutHi);
2505 SDValue Vals[] = { Out, OutHi.getValue(1) };
2506 return DAG.getMergeValues(Vals, 2, DL);
2509 SDValue MipsTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2510 SelectionDAG &DAG) const {
2511 switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
2514 case Intrinsic::mips_shilo:
2515 return LowerDSPIntr(Op, DAG, MipsISD::SHILO, true, true);
2516 case Intrinsic::mips_dpau_h_qbl:
2517 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL, true, true);
2518 case Intrinsic::mips_dpau_h_qbr:
2519 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR, true, true);
2520 case Intrinsic::mips_dpsu_h_qbl:
2521 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL, true, true);
2522 case Intrinsic::mips_dpsu_h_qbr:
2523 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR, true, true);
2524 case Intrinsic::mips_dpa_w_ph:
2525 return LowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH, true, true);
2526 case Intrinsic::mips_dps_w_ph:
2527 return LowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH, true, true);
2528 case Intrinsic::mips_dpax_w_ph:
2529 return LowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH, true, true);
2530 case Intrinsic::mips_dpsx_w_ph:
2531 return LowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH, true, true);
2532 case Intrinsic::mips_mulsa_w_ph:
2533 return LowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH, true, true);
2534 case Intrinsic::mips_mult:
2535 return LowerDSPIntr(Op, DAG, MipsISD::MULT, false, true);
2536 case Intrinsic::mips_multu:
2537 return LowerDSPIntr(Op, DAG, MipsISD::MULTU, false, true);
2538 case Intrinsic::mips_madd:
2539 return LowerDSPIntr(Op, DAG, MipsISD::MADD_DSP, true, true);
2540 case Intrinsic::mips_maddu:
2541 return LowerDSPIntr(Op, DAG, MipsISD::MADDU_DSP, true, true);
2542 case Intrinsic::mips_msub:
2543 return LowerDSPIntr(Op, DAG, MipsISD::MSUB_DSP, true, true);
2544 case Intrinsic::mips_msubu:
2545 return LowerDSPIntr(Op, DAG, MipsISD::MSUBU_DSP, true, true);
2549 SDValue MipsTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2550 SelectionDAG &DAG) const {
2551 switch (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue()) {
2554 case Intrinsic::mips_extp:
2555 return LowerDSPIntr(Op, DAG, MipsISD::EXTP, true, false);
2556 case Intrinsic::mips_extpdp:
2557 return LowerDSPIntr(Op, DAG, MipsISD::EXTPDP, true, false);
2558 case Intrinsic::mips_extr_w:
2559 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_W, true, false);
2560 case Intrinsic::mips_extr_r_w:
2561 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W, true, false);
2562 case Intrinsic::mips_extr_rs_w:
2563 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W, true, false);
2564 case Intrinsic::mips_extr_s_h:
2565 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H, true, false);
2566 case Intrinsic::mips_mthlip:
2567 return LowerDSPIntr(Op, DAG, MipsISD::MTHLIP, true, true);
2568 case Intrinsic::mips_mulsaq_s_w_ph:
2569 return LowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH, true, true);
2570 case Intrinsic::mips_maq_s_w_phl:
2571 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL, true, true);
2572 case Intrinsic::mips_maq_s_w_phr:
2573 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR, true, true);
2574 case Intrinsic::mips_maq_sa_w_phl:
2575 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL, true, true);
2576 case Intrinsic::mips_maq_sa_w_phr:
2577 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR, true, true);
2578 case Intrinsic::mips_dpaq_s_w_ph:
2579 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH, true, true);
2580 case Intrinsic::mips_dpsq_s_w_ph:
2581 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH, true, true);
2582 case Intrinsic::mips_dpaq_sa_l_w:
2583 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W, true, true);
2584 case Intrinsic::mips_dpsq_sa_l_w:
2585 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W, true, true);
2586 case Intrinsic::mips_dpaqx_s_w_ph:
2587 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH, true, true);
2588 case Intrinsic::mips_dpaqx_sa_w_ph:
2589 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH, true, true);
2590 case Intrinsic::mips_dpsqx_s_w_ph:
2591 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH, true, true);
2592 case Intrinsic::mips_dpsqx_sa_w_ph:
2593 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH, true, true);
2597 SDValue MipsTargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
2598 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2599 || cast<ConstantSDNode>
2600 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2601 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2605 // (add (frameaddr 0), (frame_to_args_offset))
2606 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2607 // (add FrameObject, 0)
2608 // where FrameObject is a fixed StackObject with offset 0 which points to
2609 // the old stack pointer.
2610 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2611 EVT ValTy = Op->getValueType(0);
2612 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2613 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2614 return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2615 DAG.getConstant(0, ValTy));
2618 //===----------------------------------------------------------------------===//
2619 // Calling Convention Implementation
2620 //===----------------------------------------------------------------------===//
2622 //===----------------------------------------------------------------------===//
2623 // TODO: Implement a generic logic using tblgen that can support this.
2624 // Mips O32 ABI rules:
2626 // i32 - Passed in A0, A1, A2, A3 and stack
2627 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2628 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2629 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2630 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2631 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2634 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2635 //===----------------------------------------------------------------------===//
2637 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2638 MVT LocVT, CCValAssign::LocInfo LocInfo,
2639 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2641 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2643 static const uint16_t IntRegs[] = {
2644 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2646 static const uint16_t F32Regs[] = {
2647 Mips::F12, Mips::F14
2649 static const uint16_t F64Regs[] = {
2653 // Do not process byval args here.
2654 if (ArgFlags.isByVal())
2657 // Promote i8 and i16
2658 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2660 if (ArgFlags.isSExt())
2661 LocInfo = CCValAssign::SExt;
2662 else if (ArgFlags.isZExt())
2663 LocInfo = CCValAssign::ZExt;
2665 LocInfo = CCValAssign::AExt;
2670 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2671 // is true: function is vararg, argument is 3rd or higher, there is previous
2672 // argument which is not f32 or f64.
2673 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2674 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2675 unsigned OrigAlign = ArgFlags.getOrigAlign();
2676 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2678 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2679 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2680 // If this is the first part of an i64 arg,
2681 // the allocated register must be either A0 or A2.
2682 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2683 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2685 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2686 // Allocate int register and shadow next int register. If first
2687 // available register is Mips::A1 or Mips::A3, shadow it too.
2688 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2689 if (Reg == Mips::A1 || Reg == Mips::A3)
2690 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2691 State.AllocateReg(IntRegs, IntRegsSize);
2693 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2694 // we are guaranteed to find an available float register
2695 if (ValVT == MVT::f32) {
2696 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2697 // Shadow int register
2698 State.AllocateReg(IntRegs, IntRegsSize);
2700 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2701 // Shadow int registers
2702 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2703 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2704 State.AllocateReg(IntRegs, IntRegsSize);
2705 State.AllocateReg(IntRegs, IntRegsSize);
2708 llvm_unreachable("Cannot handle this ValVT.");
2711 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2713 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2715 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2720 #include "MipsGenCallingConv.inc"
2722 //===----------------------------------------------------------------------===//
2723 // Call Calling Convention Implementation
2724 //===----------------------------------------------------------------------===//
2726 static const unsigned O32IntRegsSize = 4;
2728 // Return next O32 integer argument register.
2729 static unsigned getNextIntArgReg(unsigned Reg) {
2730 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2731 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2734 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2735 /// for tail call optimization.
2736 bool MipsTargetLowering::
2737 IsEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
2738 unsigned NextStackOffset,
2739 const MipsFunctionInfo& FI) const {
2740 if (!EnableMipsTailCalls)
2743 // No tail call optimization for mips16.
2744 if (Subtarget->inMips16Mode())
2747 // Return false if either the callee or caller has a byval argument.
2748 if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
2751 // Return true if the callee's argument area is no larger than the
2753 return NextStackOffset <= FI.getIncomingArgSize();
2757 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2758 SDValue Chain, SDValue Arg, DebugLoc DL,
2759 bool IsTailCall, SelectionDAG &DAG) const {
2761 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2762 DAG.getIntPtrConstant(Offset));
2763 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2767 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2768 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2769 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2770 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2771 /*isVolatile=*/ true, false, 0);
2775 // The Mips16 hard float is a crazy quilt inherited from gcc. I have a much
2776 // cleaner way to do all of this but it will have to wait until the traditional
2777 // gcc mechanism is completed.
2779 // For Pic, in order for Mips16 code to call Mips32 code which according the abi
2780 // have either arguments or returned values placed in floating point registers,
2781 // we use a set of helper functions. (This includes functions which return type
2782 // complex which on Mips are returned in a pair of floating point registers).
2784 // This is an encoding that we inherited from gcc.
2785 // In Mips traditional O32, N32 ABI, floating point numbers are passed in
2786 // floating point argument registers 1,2 only when the first and optionally
2787 // the second arguments are float (sf) or double (df).
2788 // For Mips16 we are only concerned with the situations where floating point
2789 // arguments are being passed in floating point registers by the ABI, because
2790 // Mips16 mode code cannot execute floating point instructions to load those
2791 // values and hence helper functions are needed.
2792 // The possibilities are (), (sf), (sf, sf), (sf, df), (df), (df, sf), (df, df)
2793 // the helper function suffixs for these are:
2794 // 0, 1, 5, 9, 2, 6, 10
2795 // this suffix can then be calculated as follows:
2796 // for a given argument Arg:
2797 // Arg1x, Arg2x = 1 : Arg is sf
2799 // 0: Arg is neither sf or df
2800 // So this stub is the string for number Arg1x + Arg2x*4.
2801 // However not all numbers between 0 and 10 are possible, we check anyway and
2802 // assert if the impossible exists.
2805 unsigned int MipsTargetLowering::getMips16HelperFunctionStubNumber
2806 (ArgListTy &Args) const {
2807 unsigned int resultNum = 0;
2808 if (Args.size() >= 1) {
2809 Type *t = Args[0].Ty;
2810 if (t->isFloatTy()) {
2813 else if (t->isDoubleTy()) {
2818 if (Args.size() >=2) {
2819 Type *t = Args[1].Ty;
2820 if (t->isFloatTy()) {
2823 else if (t->isDoubleTy()) {
2832 // prefixs are attached to stub numbers depending on the return type .
2833 // return type: float sf_
2835 // single complex sc_
2836 // double complext dc_
2840 // The full name of a helper function is__mips16_call_stub +
2841 // return type dependent prefix + stub number
2844 // This is something that probably should be in a different source file and
2845 // perhaps done differently but my main purpose is to not waste runtime
2846 // on something that we can enumerate in the source. Another possibility is
2847 // to have a python script to generate these mapping tables. This will do
2848 // for now. There are a whole series of helper function mapping arrays, one
2849 // for each return type class as outlined above. There there are 11 possible
2850 // entries. Ones with 0 are ones which should never be selected
2852 // All the arrays are similar except for ones which return neither
2853 // sf, df, sc, dc, in which only care about ones which have sf or df as a
2856 #define P_ "__mips16_call_stub_"
2857 #define MAX_STUB_NUMBER 10
2858 #define T1 P "1", P "2", 0, 0, P "5", P "6", 0, 0, P "9", P "10"
2859 #define T P "0" , T1
2861 static char const * vMips16Helper[MAX_STUB_NUMBER+1] =
2865 static char const * sfMips16Helper[MAX_STUB_NUMBER+1] =
2869 static char const * dfMips16Helper[MAX_STUB_NUMBER+1] =
2873 static char const * scMips16Helper[MAX_STUB_NUMBER+1] =
2877 static char const * dcMips16Helper[MAX_STUB_NUMBER+1] =
2883 const char* MipsTargetLowering::
2884 getMips16HelperFunction
2885 (Type* RetTy, ArgListTy &Args, bool &needHelper) const {
2886 const unsigned int stubNum = getMips16HelperFunctionStubNumber(Args);
2888 const unsigned int maxStubNum = 10;
2889 assert(stubNum <= maxStubNum);
2890 const bool validStubNum[maxStubNum+1] =
2891 {true, true, true, false, false, true, true, false, false, true, true};
2892 assert(validStubNum[stubNum]);
2895 if (RetTy->isFloatTy()) {
2896 result = sfMips16Helper[stubNum];
2898 else if (RetTy ->isDoubleTy()) {
2899 result = dfMips16Helper[stubNum];
2901 else if (RetTy->isStructTy()) {
2902 // check if it's complex
2903 if (RetTy->getNumContainedTypes() == 2) {
2904 if ((RetTy->getContainedType(0)->isFloatTy()) &&
2905 (RetTy->getContainedType(1)->isFloatTy())) {
2906 result = scMips16Helper[stubNum];
2908 else if ((RetTy->getContainedType(0)->isDoubleTy()) &&
2909 (RetTy->getContainedType(1)->isDoubleTy())) {
2910 result = dcMips16Helper[stubNum];
2913 llvm_unreachable("Uncovered condition");
2917 llvm_unreachable("Uncovered condition");
2925 result = vMips16Helper[stubNum];
2931 /// LowerCall - functions arguments are copied from virtual regs to
2932 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2934 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2935 SmallVectorImpl<SDValue> &InVals) const {
2936 SelectionDAG &DAG = CLI.DAG;
2937 DebugLoc &dl = CLI.DL;
2938 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2939 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2940 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2941 SDValue Chain = CLI.Chain;
2942 SDValue Callee = CLI.Callee;
2943 bool &isTailCall = CLI.IsTailCall;
2944 CallingConv::ID CallConv = CLI.CallConv;
2945 bool isVarArg = CLI.IsVarArg;
2947 const char* mips16HelperFunction = 0;
2948 bool needMips16Helper = false;
2950 if (Subtarget->inMips16Mode() && getTargetMachine().Options.UseSoftFloat &&
2953 // currently we don't have symbols tagged with the mips16 or mips32
2954 // qualifier so we will assume that we don't know what kind it is.
2955 // and generate the helper
2957 bool lookupHelper = true;
2958 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2959 if (noHelperNeeded.find(S->getSymbol()) != noHelperNeeded.end()) {
2960 lookupHelper = false;
2963 if (lookupHelper) mips16HelperFunction =
2964 getMips16HelperFunction(CLI.RetTy, CLI.Args, needMips16Helper);
2967 MachineFunction &MF = DAG.getMachineFunction();
2968 MachineFrameInfo *MFI = MF.getFrameInfo();
2969 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2970 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2972 // Analyze operands of the call, assigning locations to each operand.
2973 SmallVector<CCValAssign, 16> ArgLocs;
2974 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2975 getTargetMachine(), ArgLocs, *DAG.getContext());
2976 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
2978 MipsCCInfo.analyzeCallOperands(Outs);
2980 // Get a count of how many bytes are to be pushed on the stack.
2981 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2983 // Check if it's really possible to do a tail call.
2986 IsEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2987 *MF.getInfo<MipsFunctionInfo>());
2992 // Chain is the output chain of the last Load/Store or CopyToReg node.
2993 // ByValChain is the output chain of the last Memcpy node created for copying
2994 // byval arguments to the stack.
2995 unsigned StackAlignment = TFL->getStackAlignment();
2996 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2997 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
3000 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
3002 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl,
3003 IsN64 ? Mips::SP_64 : Mips::SP,
3006 // With EABI is it possible to have 16 args on registers.
3007 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
3008 SmallVector<SDValue, 8> MemOpChains;
3009 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3011 // Walk the register/memloc assignments, inserting copies/loads.
3012 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3013 SDValue Arg = OutVals[i];
3014 CCValAssign &VA = ArgLocs[i];
3015 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3016 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3019 if (Flags.isByVal()) {
3020 assert(Flags.getByValSize() &&
3021 "ByVal args of size 0 should have been ignored by front-end.");
3022 assert(ByValArg != MipsCCInfo.byval_end());
3023 assert(!isTailCall &&
3024 "Do not tail-call optimize if there is a byval argument.");
3025 passByValArg(Chain, dl, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3026 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
3031 // Promote the value if needed.
3032 switch (VA.getLocInfo()) {
3033 default: llvm_unreachable("Unknown loc info!");
3034 case CCValAssign::Full:
3035 if (VA.isRegLoc()) {
3036 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3037 (ValVT == MVT::f64 && LocVT == MVT::i64))
3038 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
3039 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3040 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3041 Arg, DAG.getConstant(0, MVT::i32));
3042 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3043 Arg, DAG.getConstant(1, MVT::i32));
3044 if (!Subtarget->isLittle())
3046 unsigned LocRegLo = VA.getLocReg();
3047 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3048 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3049 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3054 case CCValAssign::SExt:
3055 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
3057 case CCValAssign::ZExt:
3058 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
3060 case CCValAssign::AExt:
3061 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
3065 // Arguments that can be passed on register must be kept at
3066 // RegsToPass vector
3067 if (VA.isRegLoc()) {
3068 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3072 // Register can't get to this point...
3073 assert(VA.isMemLoc());
3075 // emit ISD::STORE whichs stores the
3076 // parameter value to a stack Location
3077 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3078 Chain, Arg, dl, isTailCall, DAG));
3081 // Transform all store nodes into one single node because all store
3082 // nodes are independent of each other.
3083 if (!MemOpChains.empty())
3084 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3085 &MemOpChains[0], MemOpChains.size());
3087 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3088 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3089 // node so that legalize doesn't hack it.
3090 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
3091 bool GlobalOrExternal = false, InternalLinkage = false;
3094 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3096 InternalLinkage = G->getGlobal()->hasInternalLinkage();
3098 if (InternalLinkage)
3099 Callee = getAddrLocal(Callee, DAG, HasMips64);
3101 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3102 MipsII::MO_CALL_LO16);
3104 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3106 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
3107 MipsII::MO_NO_FLAG);
3108 GlobalOrExternal = true;
3110 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3111 if (!IsN64 && !IsPIC) // !N64 && static
3112 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3113 MipsII::MO_NO_FLAG);
3115 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3116 MipsII::MO_CALL_LO16);
3118 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_DISP);
3120 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3122 GlobalOrExternal = true;
3125 SDValue JumpTarget = Callee;
3127 // T9 should contain the address of the callee function if
3128 // -reloction-model=pic or it is an indirect call.
3129 if (IsPICCall || !GlobalOrExternal) {
3130 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
3131 unsigned V0Reg = Mips::V0;
3132 if (needMips16Helper) {
3133 RegsToPass.push_front(std::make_pair(V0Reg, Callee));
3134 JumpTarget = DAG.getExternalSymbol(
3135 mips16HelperFunction, getPointerTy());
3136 JumpTarget = getAddrGlobal(JumpTarget, DAG, MipsII::MO_GOT);
3139 RegsToPass.push_front(std::make_pair(T9Reg, Callee));
3141 if (!Subtarget->inMips16Mode())
3142 JumpTarget = SDValue();
3146 // Insert node "GP copy globalreg" before call to function.
3148 // R_MIPS_CALL* operators (emitted when non-internal functions are called
3149 // in PIC mode) allow symbols to be resolved via lazy binding.
3150 // The lazy binding stub requires GP to point to the GOT.
3151 if (IsPICCall && !InternalLinkage) {
3152 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
3153 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
3154 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
3157 // Build a sequence of copy-to-reg nodes chained together with token
3158 // chain and flag operands which copy the outgoing args into registers.
3159 // The InFlag in necessary since all emitted instructions must be
3163 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3164 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3165 RegsToPass[i].second, InFlag);
3166 InFlag = Chain.getValue(1);
3169 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
3170 // = Chain, Callee, Reg#1, Reg#2, ...
3172 // Returns a chain & a flag for retval copy to use.
3173 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3174 SmallVector<SDValue, 8> Ops(1, Chain);
3176 if (JumpTarget.getNode())
3177 Ops.push_back(JumpTarget);
3179 // Add argument registers to the end of the list so that they are
3180 // known live into the call.
3181 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3182 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3183 RegsToPass[i].second.getValueType()));
3185 // Add a register mask operand representing the call-preserved registers.
3186 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3187 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3188 assert(Mask && "Missing call preserved mask for calling convention");
3189 Ops.push_back(DAG.getRegisterMask(Mask));
3191 if (InFlag.getNode())
3192 Ops.push_back(InFlag);
3195 return DAG.getNode(MipsISD::TailCall, dl, MVT::Other, &Ops[0], Ops.size());
3197 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
3198 InFlag = Chain.getValue(1);
3200 // Create the CALLSEQ_END node.
3201 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3202 DAG.getIntPtrConstant(0, true), InFlag);
3203 InFlag = Chain.getValue(1);
3205 // Handle result values, copying them out of physregs into vregs that we
3207 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3208 Ins, dl, DAG, InVals);
3211 /// LowerCallResult - Lower the result values of a call into the
3212 /// appropriate copies out of appropriate physical registers.
3214 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3215 CallingConv::ID CallConv, bool isVarArg,
3216 const SmallVectorImpl<ISD::InputArg> &Ins,
3217 DebugLoc dl, SelectionDAG &DAG,
3218 SmallVectorImpl<SDValue> &InVals) const {
3219 // Assign locations to each value returned by this call.
3220 SmallVector<CCValAssign, 16> RVLocs;
3221 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3222 getTargetMachine(), RVLocs, *DAG.getContext());
3224 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3226 // Copy all of the result registers out of their specified physreg.
3227 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3228 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
3229 RVLocs[i].getValVT(), InFlag).getValue(1);
3230 InFlag = Chain.getValue(2);
3231 InVals.push_back(Chain.getValue(0));
3237 //===----------------------------------------------------------------------===//
3238 // Formal Arguments Calling Convention Implementation
3239 //===----------------------------------------------------------------------===//
3240 /// LowerFormalArguments - transform physical registers into virtual registers
3241 /// and generate load operations for arguments places on the stack.
3243 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3244 CallingConv::ID CallConv,
3246 const SmallVectorImpl<ISD::InputArg> &Ins,
3247 DebugLoc dl, SelectionDAG &DAG,
3248 SmallVectorImpl<SDValue> &InVals)
3250 MachineFunction &MF = DAG.getMachineFunction();
3251 MachineFrameInfo *MFI = MF.getFrameInfo();
3252 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3254 MipsFI->setVarArgsFrameIndex(0);
3256 // Used with vargs to acumulate store chains.
3257 std::vector<SDValue> OutChains;
3259 // Assign locations to all of the incoming arguments.
3260 SmallVector<CCValAssign, 16> ArgLocs;
3261 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3262 getTargetMachine(), ArgLocs, *DAG.getContext());
3263 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
3265 MipsCCInfo.analyzeFormalArguments(Ins);
3266 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3267 MipsCCInfo.hasByValArg());
3269 Function::const_arg_iterator FuncArg =
3270 DAG.getMachineFunction().getFunction()->arg_begin();
3271 unsigned CurArgIdx = 0;
3272 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3274 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3275 CCValAssign &VA = ArgLocs[i];
3276 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
3277 CurArgIdx = Ins[i].OrigArgIndex;
3278 EVT ValVT = VA.getValVT();
3279 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3280 bool IsRegLoc = VA.isRegLoc();
3282 if (Flags.isByVal()) {
3283 assert(Flags.getByValSize() &&
3284 "ByVal args of size 0 should have been ignored by front-end.");
3285 assert(ByValArg != MipsCCInfo.byval_end());
3286 copyByValRegs(Chain, dl, OutChains, DAG, Flags, InVals, &*FuncArg,
3287 MipsCCInfo, *ByValArg);
3292 // Arguments stored on registers
3294 EVT RegVT = VA.getLocVT();
3295 unsigned ArgReg = VA.getLocReg();
3296 const TargetRegisterClass *RC;
3298 if (RegVT == MVT::i32)
3299 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
3300 &Mips::CPURegsRegClass;
3301 else if (RegVT == MVT::i64)
3302 RC = &Mips::CPU64RegsRegClass;
3303 else if (RegVT == MVT::f32)
3304 RC = &Mips::FGR32RegClass;
3305 else if (RegVT == MVT::f64)
3306 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3308 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3310 // Transform the arguments stored on
3311 // physical registers into virtual ones
3312 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3313 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3315 // If this is an 8 or 16-bit value, it has been passed promoted
3316 // to 32 bits. Insert an assert[sz]ext to capture this, then
3317 // truncate to the right size.
3318 if (VA.getLocInfo() != CCValAssign::Full) {
3319 unsigned Opcode = 0;
3320 if (VA.getLocInfo() == CCValAssign::SExt)
3321 Opcode = ISD::AssertSext;
3322 else if (VA.getLocInfo() == CCValAssign::ZExt)
3323 Opcode = ISD::AssertZext;
3325 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3326 DAG.getValueType(ValVT));
3327 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3330 // Handle floating point arguments passed in integer registers.
3331 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3332 (RegVT == MVT::i64 && ValVT == MVT::f64))
3333 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3334 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3335 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3336 getNextIntArgReg(ArgReg), RC);
3337 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3338 if (!Subtarget->isLittle())
3339 std::swap(ArgValue, ArgValue2);
3340 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3341 ArgValue, ArgValue2);
3344 InVals.push_back(ArgValue);
3345 } else { // VA.isRegLoc()
3348 assert(VA.isMemLoc());
3350 // The stack pointer offset is relative to the caller stack frame.
3351 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3352 VA.getLocMemOffset(), true);
3354 // Create load nodes to retrieve arguments from the stack
3355 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3356 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3357 MachinePointerInfo::getFixedStack(FI),
3358 false, false, false, 0));
3362 // The mips ABIs for returning structs by value requires that we copy
3363 // the sret argument into $v0 for the return. Save the argument into
3364 // a virtual register so that we can access it from the return points.
3365 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3366 unsigned Reg = MipsFI->getSRetReturnReg();
3368 Reg = MF.getRegInfo().
3369 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
3370 MipsFI->setSRetReturnReg(Reg);
3372 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3373 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3377 writeVarArgRegs(OutChains, MipsCCInfo, Chain, dl, DAG);
3379 // All stores are grouped in one node to allow the matching between
3380 // the size of Ins and InVals. This only happens when on varg functions
3381 if (!OutChains.empty()) {
3382 OutChains.push_back(Chain);
3383 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3384 &OutChains[0], OutChains.size());
3390 //===----------------------------------------------------------------------===//
3391 // Return Value Calling Convention Implementation
3392 //===----------------------------------------------------------------------===//
3395 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3396 MachineFunction &MF, bool isVarArg,
3397 const SmallVectorImpl<ISD::OutputArg> &Outs,
3398 LLVMContext &Context) const {
3399 SmallVector<CCValAssign, 16> RVLocs;
3400 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
3402 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3406 MipsTargetLowering::LowerReturn(SDValue Chain,
3407 CallingConv::ID CallConv, bool isVarArg,
3408 const SmallVectorImpl<ISD::OutputArg> &Outs,
3409 const SmallVectorImpl<SDValue> &OutVals,
3410 DebugLoc dl, SelectionDAG &DAG) const {
3412 // CCValAssign - represent the assignment of
3413 // the return value to a location
3414 SmallVector<CCValAssign, 16> RVLocs;
3416 // CCState - Info about the registers and stack slot.
3417 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3418 getTargetMachine(), RVLocs, *DAG.getContext());
3420 // Analize return values.
3421 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3423 // If this is the first return lowered for this function, add
3424 // the regs to the liveout set for the function.
3425 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3426 for (unsigned i = 0; i != RVLocs.size(); ++i)
3427 if (RVLocs[i].isRegLoc())
3428 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3433 // Copy the result values into the output registers.
3434 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3435 CCValAssign &VA = RVLocs[i];
3436 assert(VA.isRegLoc() && "Can only return in registers!");
3438 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3440 // guarantee that all emitted copies are
3441 // stuck together, avoiding something bad
3442 Flag = Chain.getValue(1);
3445 // The mips ABIs for returning structs by value requires that we copy
3446 // the sret argument into $v0 for the return. We saved the argument into
3447 // a virtual register in the entry block, so now we copy the value out
3449 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3450 MachineFunction &MF = DAG.getMachineFunction();
3451 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3452 unsigned Reg = MipsFI->getSRetReturnReg();
3455 llvm_unreachable("sret virtual register not created in the entry block");
3456 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3457 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
3459 Chain = DAG.getCopyToReg(Chain, dl, V0, Val, Flag);
3460 Flag = Chain.getValue(1);
3461 MF.getRegInfo().addLiveOut(V0);
3464 // Return on Mips is always a "jr $ra"
3466 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain, Flag);
3469 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain);
3472 //===----------------------------------------------------------------------===//
3473 // Mips Inline Assembly Support
3474 //===----------------------------------------------------------------------===//
3476 /// getConstraintType - Given a constraint letter, return the type of
3477 /// constraint it is for this target.
3478 MipsTargetLowering::ConstraintType MipsTargetLowering::
3479 getConstraintType(const std::string &Constraint) const
3481 // Mips specific constrainy
3482 // GCC config/mips/constraints.md
3484 // 'd' : An address register. Equivalent to r
3485 // unless generating MIPS16 code.
3486 // 'y' : Equivalent to r; retained for
3487 // backwards compatibility.
3488 // 'c' : A register suitable for use in an indirect
3489 // jump. This will always be $25 for -mabicalls.
3490 // 'l' : The lo register. 1 word storage.
3491 // 'x' : The hilo register pair. Double word storage.
3492 if (Constraint.size() == 1) {
3493 switch (Constraint[0]) {
3501 return C_RegisterClass;
3504 return TargetLowering::getConstraintType(Constraint);
3507 /// Examine constraint type and operand type and determine a weight value.
3508 /// This object must already have been set up with the operand type
3509 /// and the current alternative constraint selected.
3510 TargetLowering::ConstraintWeight
3511 MipsTargetLowering::getSingleConstraintMatchWeight(
3512 AsmOperandInfo &info, const char *constraint) const {
3513 ConstraintWeight weight = CW_Invalid;
3514 Value *CallOperandVal = info.CallOperandVal;
3515 // If we don't have a value, we can't do a match,
3516 // but allow it at the lowest weight.
3517 if (CallOperandVal == NULL)
3519 Type *type = CallOperandVal->getType();
3520 // Look at the constraint type.
3521 switch (*constraint) {
3523 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3527 if (type->isIntegerTy())
3528 weight = CW_Register;
3531 if (type->isFloatTy())
3532 weight = CW_Register;
3534 case 'c': // $25 for indirect jumps
3535 case 'l': // lo register
3536 case 'x': // hilo register pair
3537 if (type->isIntegerTy())
3538 weight = CW_SpecificReg;
3540 case 'I': // signed 16 bit immediate
3541 case 'J': // integer zero
3542 case 'K': // unsigned 16 bit immediate
3543 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3544 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3545 case 'O': // signed 15 bit immediate (+- 16383)
3546 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3547 if (isa<ConstantInt>(CallOperandVal))
3548 weight = CW_Constant;
3554 /// Given a register class constraint, like 'r', if this corresponds directly
3555 /// to an LLVM register class, return a register of 0 and the register class
3557 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3558 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3560 if (Constraint.size() == 1) {
3561 switch (Constraint[0]) {
3562 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3563 case 'y': // Same as 'r'. Exists for compatibility.
3565 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3566 if (Subtarget->inMips16Mode())
3567 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3568 return std::make_pair(0U, &Mips::CPURegsRegClass);
3570 if (VT == MVT::i64 && !HasMips64)
3571 return std::make_pair(0U, &Mips::CPURegsRegClass);
3572 if (VT == MVT::i64 && HasMips64)
3573 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3574 // This will generate an error message
3575 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3578 return std::make_pair(0U, &Mips::FGR32RegClass);
3579 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3580 if (Subtarget->isFP64bit())
3581 return std::make_pair(0U, &Mips::FGR64RegClass);
3582 return std::make_pair(0U, &Mips::AFGR64RegClass);
3585 case 'c': // register suitable for indirect jump
3587 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3588 assert(VT == MVT::i64 && "Unexpected type.");
3589 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3590 case 'l': // register suitable for indirect jump
3592 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3593 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3594 case 'x': // register suitable for indirect jump
3595 // Fixme: Not triggering the use of both hi and low
3596 // This will generate an error message
3597 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3600 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3603 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3604 /// vector. If it is invalid, don't add anything to Ops.
3605 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3606 std::string &Constraint,
3607 std::vector<SDValue>&Ops,
3608 SelectionDAG &DAG) const {
3609 SDValue Result(0, 0);
3611 // Only support length 1 constraints for now.
3612 if (Constraint.length() > 1) return;
3614 char ConstraintLetter = Constraint[0];
3615 switch (ConstraintLetter) {
3616 default: break; // This will fall through to the generic implementation
3617 case 'I': // Signed 16 bit constant
3618 // If this fails, the parent routine will give an error
3619 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3620 EVT Type = Op.getValueType();
3621 int64_t Val = C->getSExtValue();
3622 if (isInt<16>(Val)) {
3623 Result = DAG.getTargetConstant(Val, Type);
3628 case 'J': // integer zero
3629 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3630 EVT Type = Op.getValueType();
3631 int64_t Val = C->getZExtValue();
3633 Result = DAG.getTargetConstant(0, Type);
3638 case 'K': // unsigned 16 bit immediate
3639 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3640 EVT Type = Op.getValueType();
3641 uint64_t Val = (uint64_t)C->getZExtValue();
3642 if (isUInt<16>(Val)) {
3643 Result = DAG.getTargetConstant(Val, Type);
3648 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3649 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3650 EVT Type = Op.getValueType();
3651 int64_t Val = C->getSExtValue();
3652 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3653 Result = DAG.getTargetConstant(Val, Type);
3658 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3659 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3660 EVT Type = Op.getValueType();
3661 int64_t Val = C->getSExtValue();
3662 if ((Val >= -65535) && (Val <= -1)) {
3663 Result = DAG.getTargetConstant(Val, Type);
3668 case 'O': // signed 15 bit immediate
3669 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3670 EVT Type = Op.getValueType();
3671 int64_t Val = C->getSExtValue();
3672 if ((isInt<15>(Val))) {
3673 Result = DAG.getTargetConstant(Val, Type);
3678 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3679 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3680 EVT Type = Op.getValueType();
3681 int64_t Val = C->getSExtValue();
3682 if ((Val <= 65535) && (Val >= 1)) {
3683 Result = DAG.getTargetConstant(Val, Type);
3690 if (Result.getNode()) {
3691 Ops.push_back(Result);
3695 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3699 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3700 // No global is ever allowed as a base.
3705 case 0: // "r+i" or just "i", depending on HasBaseReg.
3708 if (!AM.HasBaseReg) // allow "r+i".
3710 return false; // disallow "r+r" or "r+r+i".
3719 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3720 // The Mips target isn't yet aware of offsets.
3724 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3726 bool IsMemset, bool ZeroMemset,
3728 MachineFunction &MF) const {
3729 if (Subtarget->hasMips64())
3735 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3736 if (VT != MVT::f32 && VT != MVT::f64)
3738 if (Imm.isNegZero())
3740 return Imm.isZero();
3743 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3745 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3747 return TargetLowering::getJumpTableEncoding();
3750 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CallConv, bool IsVarArg,
3751 bool IsO32, CCState &Info) : CCInfo(Info) {
3752 UseRegsForByval = true;
3756 NumIntArgRegs = array_lengthof(O32IntRegs);
3757 ReservedArgArea = 16;
3758 IntArgRegs = ShadowRegs = O32IntRegs;
3759 FixedFn = VarFn = CC_MipsO32;
3762 NumIntArgRegs = array_lengthof(Mips64IntRegs);
3763 ReservedArgArea = 0;
3764 IntArgRegs = Mips64IntRegs;
3765 ShadowRegs = Mips64DPRegs;
3767 VarFn = CC_MipsN_VarArg;
3770 if (CallConv == CallingConv::Fast) {
3772 UseRegsForByval = false;
3773 ReservedArgArea = 0;
3774 FixedFn = VarFn = CC_Mips_FastCC;
3777 // Pre-allocate reserved argument area.
3778 CCInfo.AllocateStack(ReservedArgArea, 1);
3781 void MipsTargetLowering::MipsCC::
3782 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args) {
3783 unsigned NumOpnds = Args.size();
3785 for (unsigned I = 0; I != NumOpnds; ++I) {
3786 MVT ArgVT = Args[I].VT;
3787 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3790 if (ArgFlags.isByVal()) {
3791 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3795 if (Args[I].IsFixed)
3796 R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3798 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3802 dbgs() << "Call operand #" << I << " has unhandled type "
3803 << EVT(ArgVT).getEVTString();
3805 llvm_unreachable(0);
3810 void MipsTargetLowering::MipsCC::
3811 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args) {
3812 unsigned NumArgs = Args.size();
3814 for (unsigned I = 0; I != NumArgs; ++I) {
3815 MVT ArgVT = Args[I].VT;
3816 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3818 if (ArgFlags.isByVal()) {
3819 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3823 if (!FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo))
3827 dbgs() << "Formal Arg #" << I << " has unhandled type "
3828 << EVT(ArgVT).getEVTString();
3830 llvm_unreachable(0);
3835 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3837 CCValAssign::LocInfo LocInfo,
3838 ISD::ArgFlagsTy ArgFlags) {
3839 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3841 struct ByValArgInfo ByVal;
3842 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3843 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3846 if (UseRegsForByval)
3847 allocateRegs(ByVal, ByValSize, Align);
3849 // Allocate space on caller's stack.
3850 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3852 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3854 ByValArgs.push_back(ByVal);
3857 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3860 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3861 "Byval argument's size and alignment should be a multiple of"
3864 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3866 // If Align > RegSize, the first arg register must be even.
3867 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3868 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3872 // Mark the registers allocated.
3873 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3874 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3875 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3878 void MipsTargetLowering::
3879 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
3880 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3881 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3882 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3883 MachineFunction &MF = DAG.getMachineFunction();
3884 MachineFrameInfo *MFI = MF.getFrameInfo();
3885 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3886 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3890 FrameObjOffset = (int)CC.reservedArgArea() -
3891 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3893 FrameObjOffset = ByVal.Address;
3895 // Create frame object.
3896 EVT PtrTy = getPointerTy();
3897 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3898 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3899 InVals.push_back(FIN);
3904 // Copy arg registers.
3905 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3906 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3908 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3909 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3910 unsigned VReg = AddLiveIn(MF, ArgReg, RC);
3911 unsigned Offset = I * CC.regSize();
3912 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3913 DAG.getConstant(Offset, PtrTy));
3914 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3915 StorePtr, MachinePointerInfo(FuncArg, Offset),
3917 OutChains.push_back(Store);
3921 // Copy byVal arg to registers and stack.
3922 void MipsTargetLowering::
3923 passByValArg(SDValue Chain, DebugLoc DL,
3924 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3925 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3926 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3927 const MipsCC &CC, const ByValArgInfo &ByVal,
3928 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3929 unsigned ByValSize = Flags.getByValSize();
3930 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3931 unsigned RegSize = CC.regSize();
3932 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3933 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3935 if (ByVal.NumRegs) {
3936 const uint16_t *ArgRegs = CC.intArgRegs();
3937 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3940 // Copy words to registers.
3941 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3942 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3943 DAG.getConstant(Offset, PtrTy));
3944 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3945 MachinePointerInfo(), false, false, false,
3947 MemOpChains.push_back(LoadVal.getValue(1));
3948 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3949 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3952 // Return if the struct has been fully copied.
3953 if (ByValSize == Offset)
3956 // Copy the remainder of the byval argument with sub-word loads and shifts.
3957 if (LeftoverBytes) {
3958 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3959 "Size of the remainder should be smaller than RegSize.");
3962 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3963 Offset < ByValSize; LoadSize /= 2) {
3964 unsigned RemSize = ByValSize - Offset;
3966 if (RemSize < LoadSize)
3970 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3971 DAG.getConstant(Offset, PtrTy));
3973 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3974 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3975 false, false, Alignment);
3976 MemOpChains.push_back(LoadVal.getValue(1));
3978 // Shift the loaded value.
3982 Shamt = TotalSizeLoaded;
3984 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3986 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3987 DAG.getConstant(Shamt, MVT::i32));
3990 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3995 TotalSizeLoaded += LoadSize;
3996 Alignment = std::min(Alignment, LoadSize);
3999 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
4000 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4005 // Copy remainder of byval arg to it with memcpy.
4006 unsigned MemCpySize = ByValSize - Offset;
4007 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4008 DAG.getConstant(Offset, PtrTy));
4009 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4010 DAG.getIntPtrConstant(ByVal.Address));
4011 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4012 DAG.getConstant(MemCpySize, PtrTy), Alignment,
4013 /*isVolatile=*/false, /*AlwaysInline=*/false,
4014 MachinePointerInfo(0), MachinePointerInfo(0));
4015 MemOpChains.push_back(Chain);
4019 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4020 const MipsCC &CC, SDValue Chain,
4021 DebugLoc DL, SelectionDAG &DAG) const {
4022 unsigned NumRegs = CC.numIntArgRegs();
4023 const uint16_t *ArgRegs = CC.intArgRegs();
4024 const CCState &CCInfo = CC.getCCInfo();
4025 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
4026 unsigned RegSize = CC.regSize();
4027 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
4028 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4029 MachineFunction &MF = DAG.getMachineFunction();
4030 MachineFrameInfo *MFI = MF.getFrameInfo();
4031 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4033 // Offset of the first variable argument from stack pointer.
4037 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
4040 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
4042 // Record the frame index of the first variable argument
4043 // which is a value necessary to VASTART.
4044 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4045 MipsFI->setVarArgsFrameIndex(FI);
4047 // Copy the integer registers that have not been used for argument passing
4048 // to the argument register save area. For O32, the save area is allocated
4049 // in the caller's stack frame, while for N32/64, it is allocated in the
4050 // callee's stack frame.
4051 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
4052 unsigned Reg = AddLiveIn(MF, ArgRegs[I], RC);
4053 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4054 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4055 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
4056 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
4057 MachinePointerInfo(), false, false, 0);
4058 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
4059 OutChains.push_back(Store);