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::FSINCOS, MVT::f32, Expand);
425 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
426 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
427 setOperationAction(ISD::FPOW, MVT::f32, Expand);
428 setOperationAction(ISD::FPOW, MVT::f64, Expand);
429 setOperationAction(ISD::FLOG, MVT::f32, Expand);
430 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
431 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
432 setOperationAction(ISD::FEXP, MVT::f32, Expand);
433 setOperationAction(ISD::FMA, MVT::f32, Expand);
434 setOperationAction(ISD::FMA, MVT::f64, Expand);
435 setOperationAction(ISD::FREM, MVT::f32, Expand);
436 setOperationAction(ISD::FREM, MVT::f64, Expand);
438 if (!TM.Options.NoNaNsFPMath) {
439 setOperationAction(ISD::FNEG, MVT::f32, Expand);
440 setOperationAction(ISD::FNEG, MVT::f64, Expand);
443 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
444 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
445 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
446 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
448 setOperationAction(ISD::VAARG, MVT::Other, Expand);
449 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
450 setOperationAction(ISD::VAEND, MVT::Other, Expand);
452 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
453 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
455 // Use the default for now
456 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
457 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
459 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
460 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
461 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
462 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
464 if (Subtarget->inMips16Mode()) {
465 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
466 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
467 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
468 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
469 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
470 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
471 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
472 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
473 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
474 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
475 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
476 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
479 setInsertFencesForAtomic(true);
481 if (!Subtarget->hasSEInReg()) {
482 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
483 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
486 if (!Subtarget->hasBitCount()) {
487 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
488 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
491 if (!Subtarget->hasSwap()) {
492 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
493 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
497 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
498 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
499 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
500 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
503 setTargetDAGCombine(ISD::ADDE);
504 setTargetDAGCombine(ISD::SUBE);
505 setTargetDAGCombine(ISD::SDIVREM);
506 setTargetDAGCombine(ISD::UDIVREM);
507 setTargetDAGCombine(ISD::SELECT);
508 setTargetDAGCombine(ISD::AND);
509 setTargetDAGCombine(ISD::OR);
510 setTargetDAGCombine(ISD::ADD);
512 setMinFunctionAlignment(HasMips64 ? 3 : 2);
514 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
515 computeRegisterProperties();
517 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
518 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
520 maxStoresPerMemcpy = 16;
524 MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
525 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
527 if (Subtarget->inMips16Mode())
541 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
544 return VT.changeVectorElementTypeToInteger();
548 // Transforms a subgraph in CurDAG if the following pattern is found:
549 // (addc multLo, Lo0), (adde multHi, Hi0),
551 // multHi/Lo: product of multiplication
552 // Lo0: initial value of Lo register
553 // Hi0: initial value of Hi register
554 // Return true if pattern matching was successful.
555 static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
556 // ADDENode's second operand must be a flag output of an ADDC node in order
557 // for the matching to be successful.
558 SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
560 if (ADDCNode->getOpcode() != ISD::ADDC)
563 SDValue MultHi = ADDENode->getOperand(0);
564 SDValue MultLo = ADDCNode->getOperand(0);
565 SDNode *MultNode = MultHi.getNode();
566 unsigned MultOpc = MultHi.getOpcode();
568 // MultHi and MultLo must be generated by the same node,
569 if (MultLo.getNode() != MultNode)
572 // and it must be a multiplication.
573 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
576 // MultLo amd MultHi must be the first and second output of MultNode
578 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
581 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
582 // of the values of MultNode, in which case MultNode will be removed in later
584 // If there exist users other than ADDENode or ADDCNode, this function returns
585 // here, which will result in MultNode being mapped to a single MULT
586 // instruction node rather than a pair of MULT and MADD instructions being
588 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
591 SDValue Chain = CurDAG->getEntryNode();
592 DebugLoc dl = ADDENode->getDebugLoc();
594 // create MipsMAdd(u) node
595 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
597 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
598 MultNode->getOperand(0),// Factor 0
599 MultNode->getOperand(1),// Factor 1
600 ADDCNode->getOperand(1),// Lo0
601 ADDENode->getOperand(1));// Hi0
603 // create CopyFromReg nodes
604 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
606 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
608 CopyFromLo.getValue(2));
610 // replace uses of adde and addc here
611 if (!SDValue(ADDCNode, 0).use_empty())
612 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
614 if (!SDValue(ADDENode, 0).use_empty())
615 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
621 // Transforms a subgraph in CurDAG if the following pattern is found:
622 // (addc Lo0, multLo), (sube Hi0, multHi),
624 // multHi/Lo: product of multiplication
625 // Lo0: initial value of Lo register
626 // Hi0: initial value of Hi register
627 // Return true if pattern matching was successful.
628 static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
629 // SUBENode's second operand must be a flag output of an SUBC node in order
630 // for the matching to be successful.
631 SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
633 if (SUBCNode->getOpcode() != ISD::SUBC)
636 SDValue MultHi = SUBENode->getOperand(1);
637 SDValue MultLo = SUBCNode->getOperand(1);
638 SDNode *MultNode = MultHi.getNode();
639 unsigned MultOpc = MultHi.getOpcode();
641 // MultHi and MultLo must be generated by the same node,
642 if (MultLo.getNode() != MultNode)
645 // and it must be a multiplication.
646 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
649 // MultLo amd MultHi must be the first and second output of MultNode
651 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
654 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
655 // of the values of MultNode, in which case MultNode will be removed in later
657 // If there exist users other than SUBENode or SUBCNode, this function returns
658 // here, which will result in MultNode being mapped to a single MULT
659 // instruction node rather than a pair of MULT and MSUB instructions being
661 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
664 SDValue Chain = CurDAG->getEntryNode();
665 DebugLoc dl = SUBENode->getDebugLoc();
667 // create MipsSub(u) node
668 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
670 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
671 MultNode->getOperand(0),// Factor 0
672 MultNode->getOperand(1),// Factor 1
673 SUBCNode->getOperand(0),// Lo0
674 SUBENode->getOperand(0));// Hi0
676 // create CopyFromReg nodes
677 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
679 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
681 CopyFromLo.getValue(2));
683 // replace uses of sube and subc here
684 if (!SDValue(SUBCNode, 0).use_empty())
685 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
687 if (!SDValue(SUBENode, 0).use_empty())
688 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
693 static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
694 TargetLowering::DAGCombinerInfo &DCI,
695 const MipsSubtarget *Subtarget) {
696 if (DCI.isBeforeLegalize())
699 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
701 return SDValue(N, 0);
706 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
707 TargetLowering::DAGCombinerInfo &DCI,
708 const MipsSubtarget *Subtarget) {
709 if (DCI.isBeforeLegalize())
712 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
714 return SDValue(N, 0);
719 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
720 TargetLowering::DAGCombinerInfo &DCI,
721 const MipsSubtarget *Subtarget) {
722 if (DCI.isBeforeLegalizeOps())
725 EVT Ty = N->getValueType(0);
726 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
727 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
728 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
730 DebugLoc dl = N->getDebugLoc();
732 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
733 N->getOperand(0), N->getOperand(1));
734 SDValue InChain = DAG.getEntryNode();
735 SDValue InGlue = DivRem;
738 if (N->hasAnyUseOfValue(0)) {
739 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
741 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
742 InChain = CopyFromLo.getValue(1);
743 InGlue = CopyFromLo.getValue(2);
747 if (N->hasAnyUseOfValue(1)) {
748 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
750 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
756 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
758 default: llvm_unreachable("Unknown fp condition code!");
760 case ISD::SETOEQ: return Mips::FCOND_OEQ;
761 case ISD::SETUNE: return Mips::FCOND_UNE;
763 case ISD::SETOLT: return Mips::FCOND_OLT;
765 case ISD::SETOGT: return Mips::FCOND_OGT;
767 case ISD::SETOLE: return Mips::FCOND_OLE;
769 case ISD::SETOGE: return Mips::FCOND_OGE;
770 case ISD::SETULT: return Mips::FCOND_ULT;
771 case ISD::SETULE: return Mips::FCOND_ULE;
772 case ISD::SETUGT: return Mips::FCOND_UGT;
773 case ISD::SETUGE: return Mips::FCOND_UGE;
774 case ISD::SETUO: return Mips::FCOND_UN;
775 case ISD::SETO: return Mips::FCOND_OR;
777 case ISD::SETONE: return Mips::FCOND_ONE;
778 case ISD::SETUEQ: return Mips::FCOND_UEQ;
783 // Returns true if condition code has to be inverted.
784 static bool InvertFPCondCode(Mips::CondCode CC) {
785 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
788 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
789 "Illegal Condition Code");
794 // Creates and returns an FPCmp node from a setcc node.
795 // Returns Op if setcc is not a floating point comparison.
796 static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
797 // must be a SETCC node
798 if (Op.getOpcode() != ISD::SETCC)
801 SDValue LHS = Op.getOperand(0);
803 if (!LHS.getValueType().isFloatingPoint())
806 SDValue RHS = Op.getOperand(1);
807 DebugLoc dl = Op.getDebugLoc();
809 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
810 // node if necessary.
811 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
813 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
814 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
817 // Creates and returns a CMovFPT/F node.
818 static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
819 SDValue False, DebugLoc DL) {
820 bool invert = InvertFPCondCode((Mips::CondCode)
821 cast<ConstantSDNode>(Cond.getOperand(2))
824 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
825 True.getValueType(), True, False, Cond);
828 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
829 TargetLowering::DAGCombinerInfo &DCI,
830 const MipsSubtarget *Subtarget) {
831 if (DCI.isBeforeLegalizeOps())
834 SDValue SetCC = N->getOperand(0);
836 if ((SetCC.getOpcode() != ISD::SETCC) ||
837 !SetCC.getOperand(0).getValueType().isInteger())
840 SDValue False = N->getOperand(2);
841 EVT FalseTy = False.getValueType();
843 if (!FalseTy.isInteger())
846 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
848 if (!CN || CN->getZExtValue())
851 const DebugLoc DL = N->getDebugLoc();
852 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
853 SDValue True = N->getOperand(1);
855 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
856 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
858 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
861 static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
862 TargetLowering::DAGCombinerInfo &DCI,
863 const MipsSubtarget *Subtarget) {
864 // Pattern match EXT.
865 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
866 // => ext $dst, $src, size, pos
867 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
870 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
871 unsigned ShiftRightOpc = ShiftRight.getOpcode();
873 // Op's first operand must be a shift right.
874 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
877 // The second operand of the shift must be an immediate.
879 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
882 uint64_t Pos = CN->getZExtValue();
883 uint64_t SMPos, SMSize;
885 // Op's second operand must be a shifted mask.
886 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
887 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
890 // Return if the shifted mask does not start at bit 0 or the sum of its size
891 // and Pos exceeds the word's size.
892 EVT ValTy = N->getValueType(0);
893 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
896 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
897 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
898 DAG.getConstant(SMSize, MVT::i32));
901 static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
902 TargetLowering::DAGCombinerInfo &DCI,
903 const MipsSubtarget *Subtarget) {
904 // Pattern match INS.
905 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
906 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
907 // => ins $dst, $src, size, pos, $src1
908 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
911 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
912 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
915 // See if Op's first operand matches (and $src1 , mask0).
916 if (And0.getOpcode() != ISD::AND)
919 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
920 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
923 // See if Op's second operand matches (and (shl $src, pos), mask1).
924 if (And1.getOpcode() != ISD::AND)
927 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
928 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
931 // The shift masks must have the same position and size.
932 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
935 SDValue Shl = And1.getOperand(0);
936 if (Shl.getOpcode() != ISD::SHL)
939 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
942 unsigned Shamt = CN->getZExtValue();
944 // Return if the shift amount and the first bit position of mask are not the
946 EVT ValTy = N->getValueType(0);
947 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
950 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
951 DAG.getConstant(SMPos0, MVT::i32),
952 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
955 static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
956 TargetLowering::DAGCombinerInfo &DCI,
957 const MipsSubtarget *Subtarget) {
958 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
960 if (DCI.isBeforeLegalizeOps())
963 SDValue Add = N->getOperand(1);
965 if (Add.getOpcode() != ISD::ADD)
968 SDValue Lo = Add.getOperand(1);
970 if ((Lo.getOpcode() != MipsISD::Lo) ||
971 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
974 EVT ValTy = N->getValueType(0);
975 DebugLoc DL = N->getDebugLoc();
977 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
979 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
982 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
984 SelectionDAG &DAG = DCI.DAG;
985 unsigned opc = N->getOpcode();
990 return PerformADDECombine(N, DAG, DCI, Subtarget);
992 return PerformSUBECombine(N, DAG, DCI, Subtarget);
995 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
997 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
999 return PerformANDCombine(N, DAG, DCI, Subtarget);
1001 return PerformORCombine(N, DAG, DCI, Subtarget);
1003 return PerformADDCombine(N, DAG, DCI, Subtarget);
1010 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1011 SmallVectorImpl<SDValue> &Results,
1012 SelectionDAG &DAG) const {
1013 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1015 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1016 Results.push_back(Res.getValue(I));
1020 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1021 SmallVectorImpl<SDValue> &Results,
1022 SelectionDAG &DAG) const {
1023 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1025 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1026 Results.push_back(Res.getValue(I));
1029 SDValue MipsTargetLowering::
1030 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1032 switch (Op.getOpcode())
1034 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1035 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
1036 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
1037 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
1038 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
1039 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
1040 case ISD::SELECT: return LowerSELECT(Op, DAG);
1041 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
1042 case ISD::SETCC: return LowerSETCC(Op, DAG);
1043 case ISD::VASTART: return LowerVASTART(Op, DAG);
1044 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
1045 case ISD::FABS: return LowerFABS(Op, DAG);
1046 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
1047 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
1048 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
1049 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
1050 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
1051 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
1052 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
1053 case ISD::LOAD: return LowerLOAD(Op, DAG);
1054 case ISD::STORE: return LowerSTORE(Op, DAG);
1055 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1056 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
1057 case ISD::ADD: return LowerADD(Op, DAG);
1062 //===----------------------------------------------------------------------===//
1063 // Lower helper functions
1064 //===----------------------------------------------------------------------===//
1066 // AddLiveIn - This helper function adds the specified physical register to the
1067 // MachineFunction as a live in value. It also creates a corresponding
1068 // virtual register for it.
1070 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1072 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1073 MF.getRegInfo().addLiveIn(PReg, VReg);
1077 // Get fp branch code (not opcode) from condition code.
1078 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
1079 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
1080 return Mips::BRANCH_T;
1082 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
1083 "Invalid CondCode.");
1085 return Mips::BRANCH_F;
1089 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
1091 const MipsSubtarget *Subtarget,
1092 const TargetInstrInfo *TII,
1093 bool isFPCmp, unsigned Opc) {
1094 // There is no need to expand CMov instructions if target has
1095 // conditional moves.
1096 if (Subtarget->hasCondMov())
1099 // To "insert" a SELECT_CC instruction, we actually have to insert the
1100 // diamond control-flow pattern. The incoming instruction knows the
1101 // destination vreg to set, the condition code register to branch on, the
1102 // true/false values to select between, and a branch opcode to use.
1103 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1104 MachineFunction::iterator It = BB;
1111 // bNE r1, r0, copy1MBB
1112 // fallthrough --> copy0MBB
1113 MachineBasicBlock *thisMBB = BB;
1114 MachineFunction *F = BB->getParent();
1115 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1116 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1117 F->insert(It, copy0MBB);
1118 F->insert(It, sinkMBB);
1120 // Transfer the remainder of BB and its successor edges to sinkMBB.
1121 sinkMBB->splice(sinkMBB->begin(), BB,
1122 llvm::next(MachineBasicBlock::iterator(MI)),
1124 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1126 // Next, add the true and fallthrough blocks as its successors.
1127 BB->addSuccessor(copy0MBB);
1128 BB->addSuccessor(sinkMBB);
1130 // Emit the right instruction according to the type of the operands compared
1132 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
1134 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
1135 .addReg(Mips::ZERO).addMBB(sinkMBB);
1138 // %FalseValue = ...
1139 // # fallthrough to sinkMBB
1142 // Update machine-CFG edges
1143 BB->addSuccessor(sinkMBB);
1146 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1151 BuildMI(*BB, BB->begin(), dl,
1152 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1153 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
1154 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1156 BuildMI(*BB, BB->begin(), dl,
1157 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1158 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
1159 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1161 MI->eraseFromParent(); // The pseudo instruction is gone now.
1167 MipsTargetLowering::EmitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
1169 // bposge32_pseudo $vr0
1179 // $vr0 = phi($vr2, $fbb, $vr1, $tbb)
1181 MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
1182 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1183 const TargetRegisterClass *RC = &Mips::CPURegsRegClass;
1184 DebugLoc DL = MI->getDebugLoc();
1185 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1186 MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
1187 MachineFunction *F = BB->getParent();
1188 MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
1189 MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
1190 MachineBasicBlock *Sink = F->CreateMachineBasicBlock(LLVM_BB);
1193 F->insert(It, Sink);
1195 // Transfer the remainder of BB and its successor edges to Sink.
1196 Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
1198 Sink->transferSuccessorsAndUpdatePHIs(BB);
1201 BB->addSuccessor(FBB);
1202 BB->addSuccessor(TBB);
1203 FBB->addSuccessor(Sink);
1204 TBB->addSuccessor(Sink);
1206 // Insert the real bposge32 instruction to $BB.
1207 BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
1210 unsigned VR2 = RegInfo.createVirtualRegister(RC);
1211 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
1212 .addReg(Mips::ZERO).addImm(0);
1213 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
1216 unsigned VR1 = RegInfo.createVirtualRegister(RC);
1217 BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
1218 .addReg(Mips::ZERO).addImm(1);
1220 // Insert phi function to $Sink.
1221 BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
1222 MI->getOperand(0).getReg())
1223 .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
1225 MI->eraseFromParent(); // The pseudo instruction is gone now.
1230 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1231 MachineBasicBlock *BB) const {
1232 switch (MI->getOpcode()) {
1233 default: llvm_unreachable("Unexpected instr type to insert");
1234 case Mips::ATOMIC_LOAD_ADD_I8:
1235 case Mips::ATOMIC_LOAD_ADD_I8_P8:
1236 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1237 case Mips::ATOMIC_LOAD_ADD_I16:
1238 case Mips::ATOMIC_LOAD_ADD_I16_P8:
1239 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1240 case Mips::ATOMIC_LOAD_ADD_I32:
1241 case Mips::ATOMIC_LOAD_ADD_I32_P8:
1242 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
1243 case Mips::ATOMIC_LOAD_ADD_I64:
1244 case Mips::ATOMIC_LOAD_ADD_I64_P8:
1245 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
1247 case Mips::ATOMIC_LOAD_AND_I8:
1248 case Mips::ATOMIC_LOAD_AND_I8_P8:
1249 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1250 case Mips::ATOMIC_LOAD_AND_I16:
1251 case Mips::ATOMIC_LOAD_AND_I16_P8:
1252 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1253 case Mips::ATOMIC_LOAD_AND_I32:
1254 case Mips::ATOMIC_LOAD_AND_I32_P8:
1255 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
1256 case Mips::ATOMIC_LOAD_AND_I64:
1257 case Mips::ATOMIC_LOAD_AND_I64_P8:
1258 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
1260 case Mips::ATOMIC_LOAD_OR_I8:
1261 case Mips::ATOMIC_LOAD_OR_I8_P8:
1262 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1263 case Mips::ATOMIC_LOAD_OR_I16:
1264 case Mips::ATOMIC_LOAD_OR_I16_P8:
1265 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1266 case Mips::ATOMIC_LOAD_OR_I32:
1267 case Mips::ATOMIC_LOAD_OR_I32_P8:
1268 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
1269 case Mips::ATOMIC_LOAD_OR_I64:
1270 case Mips::ATOMIC_LOAD_OR_I64_P8:
1271 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
1273 case Mips::ATOMIC_LOAD_XOR_I8:
1274 case Mips::ATOMIC_LOAD_XOR_I8_P8:
1275 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1276 case Mips::ATOMIC_LOAD_XOR_I16:
1277 case Mips::ATOMIC_LOAD_XOR_I16_P8:
1278 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1279 case Mips::ATOMIC_LOAD_XOR_I32:
1280 case Mips::ATOMIC_LOAD_XOR_I32_P8:
1281 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
1282 case Mips::ATOMIC_LOAD_XOR_I64:
1283 case Mips::ATOMIC_LOAD_XOR_I64_P8:
1284 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
1286 case Mips::ATOMIC_LOAD_NAND_I8:
1287 case Mips::ATOMIC_LOAD_NAND_I8_P8:
1288 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
1289 case Mips::ATOMIC_LOAD_NAND_I16:
1290 case Mips::ATOMIC_LOAD_NAND_I16_P8:
1291 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
1292 case Mips::ATOMIC_LOAD_NAND_I32:
1293 case Mips::ATOMIC_LOAD_NAND_I32_P8:
1294 return EmitAtomicBinary(MI, BB, 4, 0, true);
1295 case Mips::ATOMIC_LOAD_NAND_I64:
1296 case Mips::ATOMIC_LOAD_NAND_I64_P8:
1297 return EmitAtomicBinary(MI, BB, 8, 0, true);
1299 case Mips::ATOMIC_LOAD_SUB_I8:
1300 case Mips::ATOMIC_LOAD_SUB_I8_P8:
1301 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1302 case Mips::ATOMIC_LOAD_SUB_I16:
1303 case Mips::ATOMIC_LOAD_SUB_I16_P8:
1304 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1305 case Mips::ATOMIC_LOAD_SUB_I32:
1306 case Mips::ATOMIC_LOAD_SUB_I32_P8:
1307 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1308 case Mips::ATOMIC_LOAD_SUB_I64:
1309 case Mips::ATOMIC_LOAD_SUB_I64_P8:
1310 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1312 case Mips::ATOMIC_SWAP_I8:
1313 case Mips::ATOMIC_SWAP_I8_P8:
1314 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1315 case Mips::ATOMIC_SWAP_I16:
1316 case Mips::ATOMIC_SWAP_I16_P8:
1317 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1318 case Mips::ATOMIC_SWAP_I32:
1319 case Mips::ATOMIC_SWAP_I32_P8:
1320 return EmitAtomicBinary(MI, BB, 4, 0);
1321 case Mips::ATOMIC_SWAP_I64:
1322 case Mips::ATOMIC_SWAP_I64_P8:
1323 return EmitAtomicBinary(MI, BB, 8, 0);
1325 case Mips::ATOMIC_CMP_SWAP_I8:
1326 case Mips::ATOMIC_CMP_SWAP_I8_P8:
1327 return EmitAtomicCmpSwapPartword(MI, BB, 1);
1328 case Mips::ATOMIC_CMP_SWAP_I16:
1329 case Mips::ATOMIC_CMP_SWAP_I16_P8:
1330 return EmitAtomicCmpSwapPartword(MI, BB, 2);
1331 case Mips::ATOMIC_CMP_SWAP_I32:
1332 case Mips::ATOMIC_CMP_SWAP_I32_P8:
1333 return EmitAtomicCmpSwap(MI, BB, 4);
1334 case Mips::ATOMIC_CMP_SWAP_I64:
1335 case Mips::ATOMIC_CMP_SWAP_I64_P8:
1336 return EmitAtomicCmpSwap(MI, BB, 8);
1337 case Mips::BPOSGE32_PSEUDO:
1338 return EmitBPOSGE32(MI, BB);
1342 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1343 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1345 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1346 unsigned Size, unsigned BinOpcode,
1348 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1350 MachineFunction *MF = BB->getParent();
1351 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1352 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1353 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1354 DebugLoc dl = MI->getDebugLoc();
1355 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1358 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1359 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1366 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1367 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1370 ZERO = Mips::ZERO_64;
1374 unsigned OldVal = MI->getOperand(0).getReg();
1375 unsigned Ptr = MI->getOperand(1).getReg();
1376 unsigned Incr = MI->getOperand(2).getReg();
1378 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1379 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1380 unsigned Success = RegInfo.createVirtualRegister(RC);
1382 // insert new blocks after the current block
1383 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1384 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1385 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1386 MachineFunction::iterator It = BB;
1388 MF->insert(It, loopMBB);
1389 MF->insert(It, exitMBB);
1391 // Transfer the remainder of BB and its successor edges to exitMBB.
1392 exitMBB->splice(exitMBB->begin(), BB,
1393 llvm::next(MachineBasicBlock::iterator(MI)),
1395 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1399 // fallthrough --> loopMBB
1400 BB->addSuccessor(loopMBB);
1401 loopMBB->addSuccessor(loopMBB);
1402 loopMBB->addSuccessor(exitMBB);
1405 // ll oldval, 0(ptr)
1406 // <binop> storeval, oldval, incr
1407 // sc success, storeval, 0(ptr)
1408 // beq success, $0, loopMBB
1410 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1412 // and andres, oldval, incr
1413 // nor storeval, $0, andres
1414 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1415 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1416 } else if (BinOpcode) {
1417 // <binop> storeval, oldval, incr
1418 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1422 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1423 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1425 MI->eraseFromParent(); // The instruction is gone now.
1431 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1432 MachineBasicBlock *BB,
1433 unsigned Size, unsigned BinOpcode,
1435 assert((Size == 1 || Size == 2) &&
1436 "Unsupported size for EmitAtomicBinaryPartial.");
1438 MachineFunction *MF = BB->getParent();
1439 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1440 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1441 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1442 DebugLoc dl = MI->getDebugLoc();
1443 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1444 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1446 unsigned Dest = MI->getOperand(0).getReg();
1447 unsigned Ptr = MI->getOperand(1).getReg();
1448 unsigned Incr = MI->getOperand(2).getReg();
1450 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1451 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1452 unsigned Mask = RegInfo.createVirtualRegister(RC);
1453 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1454 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1455 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1456 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1457 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1458 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1459 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1460 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1461 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1462 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1463 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1464 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1465 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1466 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1467 unsigned Success = RegInfo.createVirtualRegister(RC);
1469 // insert new blocks after the current block
1470 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1471 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1472 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1473 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1474 MachineFunction::iterator It = BB;
1476 MF->insert(It, loopMBB);
1477 MF->insert(It, sinkMBB);
1478 MF->insert(It, exitMBB);
1480 // Transfer the remainder of BB and its successor edges to exitMBB.
1481 exitMBB->splice(exitMBB->begin(), BB,
1482 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1483 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1485 BB->addSuccessor(loopMBB);
1486 loopMBB->addSuccessor(loopMBB);
1487 loopMBB->addSuccessor(sinkMBB);
1488 sinkMBB->addSuccessor(exitMBB);
1491 // addiu masklsb2,$0,-4 # 0xfffffffc
1492 // and alignedaddr,ptr,masklsb2
1493 // andi ptrlsb2,ptr,3
1494 // sll shiftamt,ptrlsb2,3
1495 // ori maskupper,$0,255 # 0xff
1496 // sll mask,maskupper,shiftamt
1497 // nor mask2,$0,mask
1498 // sll incr2,incr,shiftamt
1500 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1501 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1502 .addReg(Mips::ZERO).addImm(-4);
1503 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1504 .addReg(Ptr).addReg(MaskLSB2);
1505 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1506 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1507 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1508 .addReg(Mips::ZERO).addImm(MaskImm);
1509 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1510 .addReg(ShiftAmt).addReg(MaskUpper);
1511 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1512 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1514 // atomic.load.binop
1516 // ll oldval,0(alignedaddr)
1517 // binop binopres,oldval,incr2
1518 // and newval,binopres,mask
1519 // and maskedoldval0,oldval,mask2
1520 // or storeval,maskedoldval0,newval
1521 // sc success,storeval,0(alignedaddr)
1522 // beq success,$0,loopMBB
1526 // ll oldval,0(alignedaddr)
1527 // and newval,incr2,mask
1528 // and maskedoldval0,oldval,mask2
1529 // or storeval,maskedoldval0,newval
1530 // sc success,storeval,0(alignedaddr)
1531 // beq success,$0,loopMBB
1534 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1536 // and andres, oldval, incr2
1537 // nor binopres, $0, andres
1538 // and newval, binopres, mask
1539 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1540 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1541 .addReg(Mips::ZERO).addReg(AndRes);
1542 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1543 } else if (BinOpcode) {
1544 // <binop> binopres, oldval, incr2
1545 // and newval, binopres, mask
1546 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1547 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1548 } else {// atomic.swap
1549 // and newval, incr2, mask
1550 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1553 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1554 .addReg(OldVal).addReg(Mask2);
1555 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1556 .addReg(MaskedOldVal0).addReg(NewVal);
1557 BuildMI(BB, dl, TII->get(SC), Success)
1558 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1559 BuildMI(BB, dl, TII->get(Mips::BEQ))
1560 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1563 // and maskedoldval1,oldval,mask
1564 // srl srlres,maskedoldval1,shiftamt
1565 // sll sllres,srlres,24
1566 // sra dest,sllres,24
1568 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1570 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1571 .addReg(OldVal).addReg(Mask);
1572 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1573 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1574 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1575 .addReg(SrlRes).addImm(ShiftImm);
1576 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1577 .addReg(SllRes).addImm(ShiftImm);
1579 MI->eraseFromParent(); // The instruction is gone now.
1585 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1586 MachineBasicBlock *BB,
1587 unsigned Size) const {
1588 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1590 MachineFunction *MF = BB->getParent();
1591 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1592 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1593 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1594 DebugLoc dl = MI->getDebugLoc();
1595 unsigned LL, SC, ZERO, BNE, BEQ;
1598 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1599 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1605 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1606 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1607 ZERO = Mips::ZERO_64;
1612 unsigned Dest = MI->getOperand(0).getReg();
1613 unsigned Ptr = MI->getOperand(1).getReg();
1614 unsigned OldVal = MI->getOperand(2).getReg();
1615 unsigned NewVal = MI->getOperand(3).getReg();
1617 unsigned Success = RegInfo.createVirtualRegister(RC);
1619 // insert new blocks after the current block
1620 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1621 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1622 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1623 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1624 MachineFunction::iterator It = BB;
1626 MF->insert(It, loop1MBB);
1627 MF->insert(It, loop2MBB);
1628 MF->insert(It, exitMBB);
1630 // Transfer the remainder of BB and its successor edges to exitMBB.
1631 exitMBB->splice(exitMBB->begin(), BB,
1632 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1633 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1637 // fallthrough --> loop1MBB
1638 BB->addSuccessor(loop1MBB);
1639 loop1MBB->addSuccessor(exitMBB);
1640 loop1MBB->addSuccessor(loop2MBB);
1641 loop2MBB->addSuccessor(loop1MBB);
1642 loop2MBB->addSuccessor(exitMBB);
1646 // bne dest, oldval, exitMBB
1648 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1649 BuildMI(BB, dl, TII->get(BNE))
1650 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1653 // sc success, newval, 0(ptr)
1654 // beq success, $0, loop1MBB
1656 BuildMI(BB, dl, TII->get(SC), Success)
1657 .addReg(NewVal).addReg(Ptr).addImm(0);
1658 BuildMI(BB, dl, TII->get(BEQ))
1659 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1661 MI->eraseFromParent(); // The instruction is gone now.
1667 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1668 MachineBasicBlock *BB,
1669 unsigned Size) const {
1670 assert((Size == 1 || Size == 2) &&
1671 "Unsupported size for EmitAtomicCmpSwapPartial.");
1673 MachineFunction *MF = BB->getParent();
1674 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1675 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1676 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1677 DebugLoc dl = MI->getDebugLoc();
1678 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1679 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1681 unsigned Dest = MI->getOperand(0).getReg();
1682 unsigned Ptr = MI->getOperand(1).getReg();
1683 unsigned CmpVal = MI->getOperand(2).getReg();
1684 unsigned NewVal = MI->getOperand(3).getReg();
1686 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1687 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1688 unsigned Mask = RegInfo.createVirtualRegister(RC);
1689 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1690 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1691 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1692 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1693 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1694 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1695 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1696 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1697 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1698 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1699 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1700 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1701 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1702 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1703 unsigned Success = RegInfo.createVirtualRegister(RC);
1705 // insert new blocks after the current block
1706 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1707 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1708 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1709 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1710 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1711 MachineFunction::iterator It = BB;
1713 MF->insert(It, loop1MBB);
1714 MF->insert(It, loop2MBB);
1715 MF->insert(It, sinkMBB);
1716 MF->insert(It, exitMBB);
1718 // Transfer the remainder of BB and its successor edges to exitMBB.
1719 exitMBB->splice(exitMBB->begin(), BB,
1720 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1721 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1723 BB->addSuccessor(loop1MBB);
1724 loop1MBB->addSuccessor(sinkMBB);
1725 loop1MBB->addSuccessor(loop2MBB);
1726 loop2MBB->addSuccessor(loop1MBB);
1727 loop2MBB->addSuccessor(sinkMBB);
1728 sinkMBB->addSuccessor(exitMBB);
1730 // FIXME: computation of newval2 can be moved to loop2MBB.
1732 // addiu masklsb2,$0,-4 # 0xfffffffc
1733 // and alignedaddr,ptr,masklsb2
1734 // andi ptrlsb2,ptr,3
1735 // sll shiftamt,ptrlsb2,3
1736 // ori maskupper,$0,255 # 0xff
1737 // sll mask,maskupper,shiftamt
1738 // nor mask2,$0,mask
1739 // andi maskedcmpval,cmpval,255
1740 // sll shiftedcmpval,maskedcmpval,shiftamt
1741 // andi maskednewval,newval,255
1742 // sll shiftednewval,maskednewval,shiftamt
1743 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1744 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1745 .addReg(Mips::ZERO).addImm(-4);
1746 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1747 .addReg(Ptr).addReg(MaskLSB2);
1748 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1749 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1750 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1751 .addReg(Mips::ZERO).addImm(MaskImm);
1752 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1753 .addReg(ShiftAmt).addReg(MaskUpper);
1754 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1755 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1756 .addReg(CmpVal).addImm(MaskImm);
1757 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1758 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1759 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1760 .addReg(NewVal).addImm(MaskImm);
1761 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1762 .addReg(ShiftAmt).addReg(MaskedNewVal);
1765 // ll oldval,0(alginedaddr)
1766 // and maskedoldval0,oldval,mask
1767 // bne maskedoldval0,shiftedcmpval,sinkMBB
1769 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1770 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1771 .addReg(OldVal).addReg(Mask);
1772 BuildMI(BB, dl, TII->get(Mips::BNE))
1773 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1776 // and maskedoldval1,oldval,mask2
1777 // or storeval,maskedoldval1,shiftednewval
1778 // sc success,storeval,0(alignedaddr)
1779 // beq success,$0,loop1MBB
1781 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1782 .addReg(OldVal).addReg(Mask2);
1783 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1784 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1785 BuildMI(BB, dl, TII->get(SC), Success)
1786 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1787 BuildMI(BB, dl, TII->get(Mips::BEQ))
1788 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1791 // srl srlres,maskedoldval0,shiftamt
1792 // sll sllres,srlres,24
1793 // sra dest,sllres,24
1795 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1797 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1798 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1799 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1800 .addReg(SrlRes).addImm(ShiftImm);
1801 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1802 .addReg(SllRes).addImm(ShiftImm);
1804 MI->eraseFromParent(); // The instruction is gone now.
1809 //===----------------------------------------------------------------------===//
1810 // Misc Lower Operation implementation
1811 //===----------------------------------------------------------------------===//
1812 SDValue MipsTargetLowering::
1813 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1815 // The first operand is the chain, the second is the condition, the third is
1816 // the block to branch to if the condition is true.
1817 SDValue Chain = Op.getOperand(0);
1818 SDValue Dest = Op.getOperand(2);
1819 DebugLoc dl = Op.getDebugLoc();
1821 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1823 // Return if flag is not set by a floating point comparison.
1824 if (CondRes.getOpcode() != MipsISD::FPCmp)
1827 SDValue CCNode = CondRes.getOperand(2);
1829 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1830 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1832 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1836 SDValue MipsTargetLowering::
1837 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1839 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1841 // Return if flag is not set by a floating point comparison.
1842 if (Cond.getOpcode() != MipsISD::FPCmp)
1845 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1849 SDValue MipsTargetLowering::
1850 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1852 DebugLoc DL = Op.getDebugLoc();
1853 EVT Ty = Op.getOperand(0).getValueType();
1854 SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1855 Op.getOperand(0), Op.getOperand(1),
1858 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1862 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1863 SDValue Cond = CreateFPCmp(DAG, Op);
1865 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1866 "Floating point operand expected.");
1868 SDValue True = DAG.getConstant(1, MVT::i32);
1869 SDValue False = DAG.getConstant(0, MVT::i32);
1871 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1874 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1875 SelectionDAG &DAG) const {
1876 // FIXME there isn't actually debug info here
1877 DebugLoc dl = Op.getDebugLoc();
1878 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1880 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1881 const MipsTargetObjectFile &TLOF =
1882 (const MipsTargetObjectFile&)getObjFileLowering();
1884 // %gp_rel relocation
1885 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1886 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1888 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl,
1889 DAG.getVTList(MVT::i32), &GA, 1);
1890 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1891 return DAG.getNode(ISD::ADD, dl, MVT::i32, GPReg, GPRelNode);
1894 // %hi/%lo relocation
1895 return getAddrNonPIC(Op, DAG);
1898 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1899 return getAddrLocal(Op, DAG, HasMips64);
1902 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1903 MipsII::MO_GOT_LO16);
1905 return getAddrGlobal(Op, DAG,
1906 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1909 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1910 SelectionDAG &DAG) const {
1911 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1912 return getAddrNonPIC(Op, DAG);
1914 return getAddrLocal(Op, DAG, HasMips64);
1917 SDValue MipsTargetLowering::
1918 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1920 // If the relocation model is PIC, use the General Dynamic TLS Model or
1921 // Local Dynamic TLS model, otherwise use the Initial Exec or
1922 // Local Exec TLS Model.
1924 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1925 DebugLoc dl = GA->getDebugLoc();
1926 const GlobalValue *GV = GA->getGlobal();
1927 EVT PtrVT = getPointerTy();
1929 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1931 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1932 // General Dynamic and Local Dynamic TLS Model.
1933 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1936 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1937 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1938 GetGlobalReg(DAG, PtrVT), TGA);
1939 unsigned PtrSize = PtrVT.getSizeInBits();
1940 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1942 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1946 Entry.Node = Argument;
1948 Args.push_back(Entry);
1950 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1951 false, false, false, false, 0, CallingConv::C,
1952 /*isTailCall=*/false, /*doesNotRet=*/false,
1953 /*isReturnValueUsed=*/true,
1954 TlsGetAddr, Args, DAG, dl);
1955 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1957 SDValue Ret = CallResult.first;
1959 if (model != TLSModel::LocalDynamic)
1962 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1963 MipsII::MO_DTPREL_HI);
1964 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1965 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1966 MipsII::MO_DTPREL_LO);
1967 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1968 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1969 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1973 if (model == TLSModel::InitialExec) {
1974 // Initial Exec TLS Model
1975 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1976 MipsII::MO_GOTTPREL);
1977 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1979 Offset = DAG.getLoad(PtrVT, dl,
1980 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1981 false, false, false, 0);
1983 // Local Exec TLS Model
1984 assert(model == TLSModel::LocalExec);
1985 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1986 MipsII::MO_TPREL_HI);
1987 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1988 MipsII::MO_TPREL_LO);
1989 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1990 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1991 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1994 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1995 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1998 SDValue MipsTargetLowering::
1999 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2001 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2002 return getAddrNonPIC(Op, DAG);
2004 return getAddrLocal(Op, DAG, HasMips64);
2007 SDValue MipsTargetLowering::
2008 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2010 // gp_rel relocation
2011 // FIXME: we should reference the constant pool using small data sections,
2012 // but the asm printer currently doesn't support this feature without
2013 // hacking it. This feature should come soon so we can uncomment the
2015 //if (IsInSmallSection(C->getType())) {
2016 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
2017 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
2018 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
2020 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2021 return getAddrNonPIC(Op, DAG);
2023 return getAddrLocal(Op, DAG, HasMips64);
2026 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2027 MachineFunction &MF = DAG.getMachineFunction();
2028 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2030 DebugLoc dl = Op.getDebugLoc();
2031 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2034 // vastart just stores the address of the VarArgsFrameIndex slot into the
2035 // memory location argument.
2036 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2037 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
2038 MachinePointerInfo(SV), false, false, 0);
2041 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2042 EVT TyX = Op.getOperand(0).getValueType();
2043 EVT TyY = Op.getOperand(1).getValueType();
2044 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2045 SDValue Const31 = DAG.getConstant(31, MVT::i32);
2046 DebugLoc DL = Op.getDebugLoc();
2049 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2051 SDValue X = (TyX == MVT::f32) ?
2052 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2053 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2055 SDValue Y = (TyY == MVT::f32) ?
2056 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2057 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2061 // ext E, Y, 31, 1 ; extract bit31 of Y
2062 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2063 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2064 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2067 // srl SrlX, SllX, 1
2069 // sll SllY, SrlX, 31
2070 // or Or, SrlX, SllY
2071 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2072 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2073 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2074 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2075 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2078 if (TyX == MVT::f32)
2079 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2081 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2082 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2083 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2086 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2087 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2088 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2089 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2090 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2091 DebugLoc DL = Op.getDebugLoc();
2093 // Bitcast to integer nodes.
2094 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2095 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2098 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2099 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2100 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2101 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
2103 if (WidthX > WidthY)
2104 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2105 else if (WidthY > WidthX)
2106 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2108 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2109 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2110 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2113 // (d)sll SllX, X, 1
2114 // (d)srl SrlX, SllX, 1
2115 // (d)srl SrlY, Y, width(Y)-1
2116 // (d)sll SllY, SrlX, width(Y)-1
2117 // or Or, SrlX, SllY
2118 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2119 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2120 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2121 DAG.getConstant(WidthY - 1, MVT::i32));
2123 if (WidthX > WidthY)
2124 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2125 else if (WidthY > WidthX)
2126 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2128 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2129 DAG.getConstant(WidthX - 1, MVT::i32));
2130 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2131 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2135 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2136 if (Subtarget->hasMips64())
2137 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
2139 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
2142 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2143 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2144 DebugLoc DL = Op.getDebugLoc();
2146 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2148 SDValue X = (Op.getValueType() == MVT::f32) ?
2149 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2150 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2155 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2156 DAG.getRegister(Mips::ZERO, MVT::i32),
2157 DAG.getConstant(31, MVT::i32), Const1, X);
2159 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2160 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2163 if (Op.getValueType() == MVT::f32)
2164 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2166 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2167 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2168 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2171 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2172 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2173 DebugLoc DL = Op.getDebugLoc();
2175 // Bitcast to integer node.
2176 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2180 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2181 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2182 DAG.getConstant(63, MVT::i32), Const1, X);
2184 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2185 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2188 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2192 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
2193 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2194 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2196 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2199 SDValue MipsTargetLowering::
2200 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2202 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2203 "Frame address can only be determined for current frame.");
2205 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2206 MFI->setFrameAddressIsTaken(true);
2207 EVT VT = Op.getValueType();
2208 DebugLoc dl = Op.getDebugLoc();
2209 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2210 IsN64 ? Mips::FP_64 : Mips::FP, VT);
2214 SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2215 SelectionDAG &DAG) const {
2217 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2218 "Return address can be determined only for current frame.");
2220 MachineFunction &MF = DAG.getMachineFunction();
2221 MachineFrameInfo *MFI = MF.getFrameInfo();
2222 MVT VT = Op.getSimpleValueType();
2223 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2224 MFI->setReturnAddressIsTaken(true);
2226 // Return RA, which contains the return address. Mark it an implicit live-in.
2227 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2228 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2231 // TODO: set SType according to the desired memory barrier behavior.
2233 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2235 DebugLoc dl = Op.getDebugLoc();
2236 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2237 DAG.getConstant(SType, MVT::i32));
2240 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2241 SelectionDAG &DAG) const {
2242 // FIXME: Need pseudo-fence for 'singlethread' fences
2243 // FIXME: Set SType for weaker fences where supported/appropriate.
2245 DebugLoc dl = Op.getDebugLoc();
2246 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2247 DAG.getConstant(SType, MVT::i32));
2250 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2251 SelectionDAG &DAG) const {
2252 DebugLoc DL = Op.getDebugLoc();
2253 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2254 SDValue Shamt = Op.getOperand(2);
2257 // lo = (shl lo, shamt)
2258 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2261 // hi = (shl lo, shamt[4:0])
2262 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2263 DAG.getConstant(-1, MVT::i32));
2264 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2265 DAG.getConstant(1, MVT::i32));
2266 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2268 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2269 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2270 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2271 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2272 DAG.getConstant(0x20, MVT::i32));
2273 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2274 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2275 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2277 SDValue Ops[2] = {Lo, Hi};
2278 return DAG.getMergeValues(Ops, 2, DL);
2281 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2283 DebugLoc DL = Op.getDebugLoc();
2284 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2285 SDValue Shamt = Op.getOperand(2);
2288 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2290 // hi = (sra hi, shamt)
2292 // hi = (srl hi, shamt)
2295 // lo = (sra hi, shamt[4:0])
2296 // hi = (sra hi, 31)
2298 // lo = (srl hi, shamt[4:0])
2300 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2301 DAG.getConstant(-1, MVT::i32));
2302 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2303 DAG.getConstant(1, MVT::i32));
2304 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2305 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2306 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2307 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2309 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2310 DAG.getConstant(0x20, MVT::i32));
2311 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2312 DAG.getConstant(31, MVT::i32));
2313 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2314 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2315 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2318 SDValue Ops[2] = {Lo, Hi};
2319 return DAG.getMergeValues(Ops, 2, DL);
2322 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2323 SDValue Chain, SDValue Src, unsigned Offset) {
2324 SDValue Ptr = LD->getBasePtr();
2325 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2326 EVT BasePtrVT = Ptr.getValueType();
2327 DebugLoc DL = LD->getDebugLoc();
2328 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2331 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2332 DAG.getConstant(Offset, BasePtrVT));
2334 SDValue Ops[] = { Chain, Ptr, Src };
2335 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2336 LD->getMemOperand());
2339 // Expand an unaligned 32 or 64-bit integer load node.
2340 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2341 LoadSDNode *LD = cast<LoadSDNode>(Op);
2342 EVT MemVT = LD->getMemoryVT();
2344 // Return if load is aligned or if MemVT is neither i32 nor i64.
2345 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2346 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2349 bool IsLittle = Subtarget->isLittle();
2350 EVT VT = Op.getValueType();
2351 ISD::LoadExtType ExtType = LD->getExtensionType();
2352 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2354 assert((VT == MVT::i32) || (VT == MVT::i64));
2357 // (set dst, (i64 (load baseptr)))
2359 // (set tmp, (ldl (add baseptr, 7), undef))
2360 // (set dst, (ldr baseptr, tmp))
2361 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2362 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2364 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2368 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2370 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2374 // (set dst, (i32 (load baseptr))) or
2375 // (set dst, (i64 (sextload baseptr))) or
2376 // (set dst, (i64 (extload baseptr)))
2378 // (set tmp, (lwl (add baseptr, 3), undef))
2379 // (set dst, (lwr baseptr, tmp))
2380 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2381 (ExtType == ISD::EXTLOAD))
2384 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2387 // (set dst, (i64 (zextload baseptr)))
2389 // (set tmp0, (lwl (add baseptr, 3), undef))
2390 // (set tmp1, (lwr baseptr, tmp0))
2391 // (set tmp2, (shl tmp1, 32))
2392 // (set dst, (srl tmp2, 32))
2393 DebugLoc DL = LD->getDebugLoc();
2394 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2395 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2396 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2397 SDValue Ops[] = { SRL, LWR.getValue(1) };
2398 return DAG.getMergeValues(Ops, 2, DL);
2401 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2402 SDValue Chain, unsigned Offset) {
2403 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2404 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2405 DebugLoc DL = SD->getDebugLoc();
2406 SDVTList VTList = DAG.getVTList(MVT::Other);
2409 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2410 DAG.getConstant(Offset, BasePtrVT));
2412 SDValue Ops[] = { Chain, Value, Ptr };
2413 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2414 SD->getMemOperand());
2417 // Expand an unaligned 32 or 64-bit integer store node.
2418 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2419 StoreSDNode *SD = cast<StoreSDNode>(Op);
2420 EVT MemVT = SD->getMemoryVT();
2422 // Return if store is aligned or if MemVT is neither i32 nor i64.
2423 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2424 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2427 bool IsLittle = Subtarget->isLittle();
2428 SDValue Value = SD->getValue(), Chain = SD->getChain();
2429 EVT VT = Value.getValueType();
2432 // (store val, baseptr) or
2433 // (truncstore val, baseptr)
2435 // (swl val, (add baseptr, 3))
2436 // (swr val, baseptr)
2437 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2438 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2440 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2443 assert(VT == MVT::i64);
2446 // (store val, baseptr)
2448 // (sdl val, (add baseptr, 7))
2449 // (sdr val, baseptr)
2450 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2451 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2454 // This function expands mips intrinsic nodes which have 64-bit input operands
2455 // or output values.
2457 // out64 = intrinsic-node in64
2459 // lo = copy (extract-element (in64, 0))
2460 // hi = copy (extract-element (in64, 1))
2461 // mips-specific-node
2464 // out64 = merge-values (v0, v1)
2466 static SDValue LowerDSPIntr(SDValue Op, SelectionDAG &DAG,
2467 unsigned Opc, bool HasI64In, bool HasI64Out) {
2468 DebugLoc DL = Op.getDebugLoc();
2469 bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
2470 SDValue Chain = HasChainIn ? Op->getOperand(0) : DAG.getEntryNode();
2471 SmallVector<SDValue, 3> Ops;
2474 SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2475 Op->getOperand(1 + HasChainIn),
2476 DAG.getConstant(0, MVT::i32));
2477 SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2478 Op->getOperand(1 + HasChainIn),
2479 DAG.getConstant(1, MVT::i32));
2481 Chain = DAG.getCopyToReg(Chain, DL, Mips::LO, InLo, SDValue());
2482 Chain = DAG.getCopyToReg(Chain, DL, Mips::HI, InHi, Chain.getValue(1));
2484 Ops.push_back(Chain);
2485 Ops.append(Op->op_begin() + HasChainIn + 2, Op->op_end());
2486 Ops.push_back(Chain.getValue(1));
2488 Ops.push_back(Chain);
2489 Ops.append(Op->op_begin() + HasChainIn + 1, Op->op_end());
2493 return DAG.getNode(Opc, DL, Op->value_begin(), Op->getNumValues(),
2494 Ops.begin(), Ops.size());
2496 SDValue Intr = DAG.getNode(Opc, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2497 Ops.begin(), Ops.size());
2498 SDValue OutLo = DAG.getCopyFromReg(Intr.getValue(0), DL, Mips::LO, MVT::i32,
2500 SDValue OutHi = DAG.getCopyFromReg(OutLo.getValue(1), DL, Mips::HI, MVT::i32,
2502 SDValue Out = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, OutLo, OutHi);
2507 SDValue Vals[] = { Out, OutHi.getValue(1) };
2508 return DAG.getMergeValues(Vals, 2, DL);
2511 SDValue MipsTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2512 SelectionDAG &DAG) const {
2513 switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
2516 case Intrinsic::mips_shilo:
2517 return LowerDSPIntr(Op, DAG, MipsISD::SHILO, true, true);
2518 case Intrinsic::mips_dpau_h_qbl:
2519 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL, true, true);
2520 case Intrinsic::mips_dpau_h_qbr:
2521 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR, true, true);
2522 case Intrinsic::mips_dpsu_h_qbl:
2523 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL, true, true);
2524 case Intrinsic::mips_dpsu_h_qbr:
2525 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR, true, true);
2526 case Intrinsic::mips_dpa_w_ph:
2527 return LowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH, true, true);
2528 case Intrinsic::mips_dps_w_ph:
2529 return LowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH, true, true);
2530 case Intrinsic::mips_dpax_w_ph:
2531 return LowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH, true, true);
2532 case Intrinsic::mips_dpsx_w_ph:
2533 return LowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH, true, true);
2534 case Intrinsic::mips_mulsa_w_ph:
2535 return LowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH, true, true);
2536 case Intrinsic::mips_mult:
2537 return LowerDSPIntr(Op, DAG, MipsISD::MULT, false, true);
2538 case Intrinsic::mips_multu:
2539 return LowerDSPIntr(Op, DAG, MipsISD::MULTU, false, true);
2540 case Intrinsic::mips_madd:
2541 return LowerDSPIntr(Op, DAG, MipsISD::MADD_DSP, true, true);
2542 case Intrinsic::mips_maddu:
2543 return LowerDSPIntr(Op, DAG, MipsISD::MADDU_DSP, true, true);
2544 case Intrinsic::mips_msub:
2545 return LowerDSPIntr(Op, DAG, MipsISD::MSUB_DSP, true, true);
2546 case Intrinsic::mips_msubu:
2547 return LowerDSPIntr(Op, DAG, MipsISD::MSUBU_DSP, true, true);
2551 SDValue MipsTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2552 SelectionDAG &DAG) const {
2553 switch (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue()) {
2556 case Intrinsic::mips_extp:
2557 return LowerDSPIntr(Op, DAG, MipsISD::EXTP, true, false);
2558 case Intrinsic::mips_extpdp:
2559 return LowerDSPIntr(Op, DAG, MipsISD::EXTPDP, true, false);
2560 case Intrinsic::mips_extr_w:
2561 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_W, true, false);
2562 case Intrinsic::mips_extr_r_w:
2563 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W, true, false);
2564 case Intrinsic::mips_extr_rs_w:
2565 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W, true, false);
2566 case Intrinsic::mips_extr_s_h:
2567 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H, true, false);
2568 case Intrinsic::mips_mthlip:
2569 return LowerDSPIntr(Op, DAG, MipsISD::MTHLIP, true, true);
2570 case Intrinsic::mips_mulsaq_s_w_ph:
2571 return LowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH, true, true);
2572 case Intrinsic::mips_maq_s_w_phl:
2573 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL, true, true);
2574 case Intrinsic::mips_maq_s_w_phr:
2575 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR, true, true);
2576 case Intrinsic::mips_maq_sa_w_phl:
2577 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL, true, true);
2578 case Intrinsic::mips_maq_sa_w_phr:
2579 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR, true, true);
2580 case Intrinsic::mips_dpaq_s_w_ph:
2581 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH, true, true);
2582 case Intrinsic::mips_dpsq_s_w_ph:
2583 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH, true, true);
2584 case Intrinsic::mips_dpaq_sa_l_w:
2585 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W, true, true);
2586 case Intrinsic::mips_dpsq_sa_l_w:
2587 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W, true, true);
2588 case Intrinsic::mips_dpaqx_s_w_ph:
2589 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH, true, true);
2590 case Intrinsic::mips_dpaqx_sa_w_ph:
2591 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH, true, true);
2592 case Intrinsic::mips_dpsqx_s_w_ph:
2593 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH, true, true);
2594 case Intrinsic::mips_dpsqx_sa_w_ph:
2595 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH, true, true);
2599 SDValue MipsTargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
2600 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2601 || cast<ConstantSDNode>
2602 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2603 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2607 // (add (frameaddr 0), (frame_to_args_offset))
2608 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2609 // (add FrameObject, 0)
2610 // where FrameObject is a fixed StackObject with offset 0 which points to
2611 // the old stack pointer.
2612 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2613 EVT ValTy = Op->getValueType(0);
2614 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2615 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2616 return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2617 DAG.getConstant(0, ValTy));
2620 //===----------------------------------------------------------------------===//
2621 // Calling Convention Implementation
2622 //===----------------------------------------------------------------------===//
2624 //===----------------------------------------------------------------------===//
2625 // TODO: Implement a generic logic using tblgen that can support this.
2626 // Mips O32 ABI rules:
2628 // i32 - Passed in A0, A1, A2, A3 and stack
2629 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2630 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2631 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2632 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2633 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2636 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2637 //===----------------------------------------------------------------------===//
2639 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2640 MVT LocVT, CCValAssign::LocInfo LocInfo,
2641 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2643 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2645 static const uint16_t IntRegs[] = {
2646 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2648 static const uint16_t F32Regs[] = {
2649 Mips::F12, Mips::F14
2651 static const uint16_t F64Regs[] = {
2655 // Do not process byval args here.
2656 if (ArgFlags.isByVal())
2659 // Promote i8 and i16
2660 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2662 if (ArgFlags.isSExt())
2663 LocInfo = CCValAssign::SExt;
2664 else if (ArgFlags.isZExt())
2665 LocInfo = CCValAssign::ZExt;
2667 LocInfo = CCValAssign::AExt;
2672 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2673 // is true: function is vararg, argument is 3rd or higher, there is previous
2674 // argument which is not f32 or f64.
2675 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2676 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2677 unsigned OrigAlign = ArgFlags.getOrigAlign();
2678 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2680 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2681 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2682 // If this is the first part of an i64 arg,
2683 // the allocated register must be either A0 or A2.
2684 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2685 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2687 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2688 // Allocate int register and shadow next int register. If first
2689 // available register is Mips::A1 or Mips::A3, shadow it too.
2690 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2691 if (Reg == Mips::A1 || Reg == Mips::A3)
2692 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2693 State.AllocateReg(IntRegs, IntRegsSize);
2695 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2696 // we are guaranteed to find an available float register
2697 if (ValVT == MVT::f32) {
2698 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2699 // Shadow int register
2700 State.AllocateReg(IntRegs, IntRegsSize);
2702 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2703 // Shadow int registers
2704 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2705 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2706 State.AllocateReg(IntRegs, IntRegsSize);
2707 State.AllocateReg(IntRegs, IntRegsSize);
2710 llvm_unreachable("Cannot handle this ValVT.");
2713 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2715 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2717 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2722 #include "MipsGenCallingConv.inc"
2724 //===----------------------------------------------------------------------===//
2725 // Call Calling Convention Implementation
2726 //===----------------------------------------------------------------------===//
2728 static const unsigned O32IntRegsSize = 4;
2730 // Return next O32 integer argument register.
2731 static unsigned getNextIntArgReg(unsigned Reg) {
2732 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2733 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2736 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2737 /// for tail call optimization.
2738 bool MipsTargetLowering::
2739 IsEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
2740 unsigned NextStackOffset,
2741 const MipsFunctionInfo& FI) const {
2742 if (!EnableMipsTailCalls)
2745 // No tail call optimization for mips16.
2746 if (Subtarget->inMips16Mode())
2749 // Return false if either the callee or caller has a byval argument.
2750 if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
2753 // Return true if the callee's argument area is no larger than the
2755 return NextStackOffset <= FI.getIncomingArgSize();
2759 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2760 SDValue Chain, SDValue Arg, DebugLoc DL,
2761 bool IsTailCall, SelectionDAG &DAG) const {
2763 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2764 DAG.getIntPtrConstant(Offset));
2765 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2769 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2770 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2771 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2772 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2773 /*isVolatile=*/ true, false, 0);
2777 // The Mips16 hard float is a crazy quilt inherited from gcc. I have a much
2778 // cleaner way to do all of this but it will have to wait until the traditional
2779 // gcc mechanism is completed.
2781 // For Pic, in order for Mips16 code to call Mips32 code which according the abi
2782 // have either arguments or returned values placed in floating point registers,
2783 // we use a set of helper functions. (This includes functions which return type
2784 // complex which on Mips are returned in a pair of floating point registers).
2786 // This is an encoding that we inherited from gcc.
2787 // In Mips traditional O32, N32 ABI, floating point numbers are passed in
2788 // floating point argument registers 1,2 only when the first and optionally
2789 // the second arguments are float (sf) or double (df).
2790 // For Mips16 we are only concerned with the situations where floating point
2791 // arguments are being passed in floating point registers by the ABI, because
2792 // Mips16 mode code cannot execute floating point instructions to load those
2793 // values and hence helper functions are needed.
2794 // The possibilities are (), (sf), (sf, sf), (sf, df), (df), (df, sf), (df, df)
2795 // the helper function suffixs for these are:
2796 // 0, 1, 5, 9, 2, 6, 10
2797 // this suffix can then be calculated as follows:
2798 // for a given argument Arg:
2799 // Arg1x, Arg2x = 1 : Arg is sf
2801 // 0: Arg is neither sf or df
2802 // So this stub is the string for number Arg1x + Arg2x*4.
2803 // However not all numbers between 0 and 10 are possible, we check anyway and
2804 // assert if the impossible exists.
2807 unsigned int MipsTargetLowering::getMips16HelperFunctionStubNumber
2808 (ArgListTy &Args) const {
2809 unsigned int resultNum = 0;
2810 if (Args.size() >= 1) {
2811 Type *t = Args[0].Ty;
2812 if (t->isFloatTy()) {
2815 else if (t->isDoubleTy()) {
2820 if (Args.size() >=2) {
2821 Type *t = Args[1].Ty;
2822 if (t->isFloatTy()) {
2825 else if (t->isDoubleTy()) {
2834 // prefixs are attached to stub numbers depending on the return type .
2835 // return type: float sf_
2837 // single complex sc_
2838 // double complext dc_
2842 // The full name of a helper function is__mips16_call_stub +
2843 // return type dependent prefix + stub number
2846 // This is something that probably should be in a different source file and
2847 // perhaps done differently but my main purpose is to not waste runtime
2848 // on something that we can enumerate in the source. Another possibility is
2849 // to have a python script to generate these mapping tables. This will do
2850 // for now. There are a whole series of helper function mapping arrays, one
2851 // for each return type class as outlined above. There there are 11 possible
2852 // entries. Ones with 0 are ones which should never be selected
2854 // All the arrays are similar except for ones which return neither
2855 // sf, df, sc, dc, in which only care about ones which have sf or df as a
2858 #define P_ "__mips16_call_stub_"
2859 #define MAX_STUB_NUMBER 10
2860 #define T1 P "1", P "2", 0, 0, P "5", P "6", 0, 0, P "9", P "10"
2861 #define T P "0" , T1
2863 static char const * vMips16Helper[MAX_STUB_NUMBER+1] =
2867 static char const * sfMips16Helper[MAX_STUB_NUMBER+1] =
2871 static char const * dfMips16Helper[MAX_STUB_NUMBER+1] =
2875 static char const * scMips16Helper[MAX_STUB_NUMBER+1] =
2879 static char const * dcMips16Helper[MAX_STUB_NUMBER+1] =
2885 const char* MipsTargetLowering::
2886 getMips16HelperFunction
2887 (Type* RetTy, ArgListTy &Args, bool &needHelper) const {
2888 const unsigned int stubNum = getMips16HelperFunctionStubNumber(Args);
2890 const unsigned int maxStubNum = 10;
2891 assert(stubNum <= maxStubNum);
2892 const bool validStubNum[maxStubNum+1] =
2893 {true, true, true, false, false, true, true, false, false, true, true};
2894 assert(validStubNum[stubNum]);
2897 if (RetTy->isFloatTy()) {
2898 result = sfMips16Helper[stubNum];
2900 else if (RetTy ->isDoubleTy()) {
2901 result = dfMips16Helper[stubNum];
2903 else if (RetTy->isStructTy()) {
2904 // check if it's complex
2905 if (RetTy->getNumContainedTypes() == 2) {
2906 if ((RetTy->getContainedType(0)->isFloatTy()) &&
2907 (RetTy->getContainedType(1)->isFloatTy())) {
2908 result = scMips16Helper[stubNum];
2910 else if ((RetTy->getContainedType(0)->isDoubleTy()) &&
2911 (RetTy->getContainedType(1)->isDoubleTy())) {
2912 result = dcMips16Helper[stubNum];
2915 llvm_unreachable("Uncovered condition");
2919 llvm_unreachable("Uncovered condition");
2927 result = vMips16Helper[stubNum];
2933 /// LowerCall - functions arguments are copied from virtual regs to
2934 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2936 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2937 SmallVectorImpl<SDValue> &InVals) const {
2938 SelectionDAG &DAG = CLI.DAG;
2939 DebugLoc &dl = CLI.DL;
2940 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2941 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2942 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2943 SDValue Chain = CLI.Chain;
2944 SDValue Callee = CLI.Callee;
2945 bool &isTailCall = CLI.IsTailCall;
2946 CallingConv::ID CallConv = CLI.CallConv;
2947 bool isVarArg = CLI.IsVarArg;
2949 const char* mips16HelperFunction = 0;
2950 bool needMips16Helper = false;
2952 if (Subtarget->inMips16Mode() && getTargetMachine().Options.UseSoftFloat &&
2955 // currently we don't have symbols tagged with the mips16 or mips32
2956 // qualifier so we will assume that we don't know what kind it is.
2957 // and generate the helper
2959 bool lookupHelper = true;
2960 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2961 if (noHelperNeeded.find(S->getSymbol()) != noHelperNeeded.end()) {
2962 lookupHelper = false;
2965 if (lookupHelper) mips16HelperFunction =
2966 getMips16HelperFunction(CLI.RetTy, CLI.Args, needMips16Helper);
2969 MachineFunction &MF = DAG.getMachineFunction();
2970 MachineFrameInfo *MFI = MF.getFrameInfo();
2971 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2972 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2974 // Analyze operands of the call, assigning locations to each operand.
2975 SmallVector<CCValAssign, 16> ArgLocs;
2976 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2977 getTargetMachine(), ArgLocs, *DAG.getContext());
2978 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
2980 MipsCCInfo.analyzeCallOperands(Outs);
2982 // Get a count of how many bytes are to be pushed on the stack.
2983 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2985 // Check if it's really possible to do a tail call.
2988 IsEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2989 *MF.getInfo<MipsFunctionInfo>());
2994 // Chain is the output chain of the last Load/Store or CopyToReg node.
2995 // ByValChain is the output chain of the last Memcpy node created for copying
2996 // byval arguments to the stack.
2997 unsigned StackAlignment = TFL->getStackAlignment();
2998 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2999 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
3002 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
3004 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl,
3005 IsN64 ? Mips::SP_64 : Mips::SP,
3008 // With EABI is it possible to have 16 args on registers.
3009 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
3010 SmallVector<SDValue, 8> MemOpChains;
3011 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3013 // Walk the register/memloc assignments, inserting copies/loads.
3014 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3015 SDValue Arg = OutVals[i];
3016 CCValAssign &VA = ArgLocs[i];
3017 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3018 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3021 if (Flags.isByVal()) {
3022 assert(Flags.getByValSize() &&
3023 "ByVal args of size 0 should have been ignored by front-end.");
3024 assert(ByValArg != MipsCCInfo.byval_end());
3025 assert(!isTailCall &&
3026 "Do not tail-call optimize if there is a byval argument.");
3027 passByValArg(Chain, dl, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3028 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
3033 // Promote the value if needed.
3034 switch (VA.getLocInfo()) {
3035 default: llvm_unreachable("Unknown loc info!");
3036 case CCValAssign::Full:
3037 if (VA.isRegLoc()) {
3038 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3039 (ValVT == MVT::f64 && LocVT == MVT::i64))
3040 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
3041 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3042 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3043 Arg, DAG.getConstant(0, MVT::i32));
3044 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3045 Arg, DAG.getConstant(1, MVT::i32));
3046 if (!Subtarget->isLittle())
3048 unsigned LocRegLo = VA.getLocReg();
3049 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3050 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3051 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3056 case CCValAssign::SExt:
3057 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
3059 case CCValAssign::ZExt:
3060 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
3062 case CCValAssign::AExt:
3063 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
3067 // Arguments that can be passed on register must be kept at
3068 // RegsToPass vector
3069 if (VA.isRegLoc()) {
3070 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3074 // Register can't get to this point...
3075 assert(VA.isMemLoc());
3077 // emit ISD::STORE whichs stores the
3078 // parameter value to a stack Location
3079 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3080 Chain, Arg, dl, isTailCall, DAG));
3083 // Transform all store nodes into one single node because all store
3084 // nodes are independent of each other.
3085 if (!MemOpChains.empty())
3086 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3087 &MemOpChains[0], MemOpChains.size());
3089 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3090 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3091 // node so that legalize doesn't hack it.
3092 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
3093 bool GlobalOrExternal = false, InternalLinkage = false;
3096 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3098 InternalLinkage = G->getGlobal()->hasInternalLinkage();
3100 if (InternalLinkage)
3101 Callee = getAddrLocal(Callee, DAG, HasMips64);
3103 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3104 MipsII::MO_CALL_LO16);
3106 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3108 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
3109 MipsII::MO_NO_FLAG);
3110 GlobalOrExternal = true;
3112 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3113 if (!IsN64 && !IsPIC) // !N64 && static
3114 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3115 MipsII::MO_NO_FLAG);
3117 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3118 MipsII::MO_CALL_LO16);
3120 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_DISP);
3122 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3124 GlobalOrExternal = true;
3127 SDValue JumpTarget = Callee;
3129 // T9 should contain the address of the callee function if
3130 // -reloction-model=pic or it is an indirect call.
3131 if (IsPICCall || !GlobalOrExternal) {
3132 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
3133 unsigned V0Reg = Mips::V0;
3134 if (needMips16Helper) {
3135 RegsToPass.push_front(std::make_pair(V0Reg, Callee));
3136 JumpTarget = DAG.getExternalSymbol(
3137 mips16HelperFunction, getPointerTy());
3138 JumpTarget = getAddrGlobal(JumpTarget, DAG, MipsII::MO_GOT);
3141 RegsToPass.push_front(std::make_pair(T9Reg, Callee));
3143 if (!Subtarget->inMips16Mode())
3144 JumpTarget = SDValue();
3148 // Insert node "GP copy globalreg" before call to function.
3150 // R_MIPS_CALL* operators (emitted when non-internal functions are called
3151 // in PIC mode) allow symbols to be resolved via lazy binding.
3152 // The lazy binding stub requires GP to point to the GOT.
3153 if (IsPICCall && !InternalLinkage) {
3154 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
3155 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
3156 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
3159 // Build a sequence of copy-to-reg nodes chained together with token
3160 // chain and flag operands which copy the outgoing args into registers.
3161 // The InFlag in necessary since all emitted instructions must be
3165 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3166 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3167 RegsToPass[i].second, InFlag);
3168 InFlag = Chain.getValue(1);
3171 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
3172 // = Chain, Callee, Reg#1, Reg#2, ...
3174 // Returns a chain & a flag for retval copy to use.
3175 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3176 SmallVector<SDValue, 8> Ops(1, Chain);
3178 if (JumpTarget.getNode())
3179 Ops.push_back(JumpTarget);
3181 // Add argument registers to the end of the list so that they are
3182 // known live into the call.
3183 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3184 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3185 RegsToPass[i].second.getValueType()));
3187 // Add a register mask operand representing the call-preserved registers.
3188 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3189 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3190 assert(Mask && "Missing call preserved mask for calling convention");
3191 Ops.push_back(DAG.getRegisterMask(Mask));
3193 if (InFlag.getNode())
3194 Ops.push_back(InFlag);
3197 return DAG.getNode(MipsISD::TailCall, dl, MVT::Other, &Ops[0], Ops.size());
3199 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
3200 InFlag = Chain.getValue(1);
3202 // Create the CALLSEQ_END node.
3203 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3204 DAG.getIntPtrConstant(0, true), InFlag);
3205 InFlag = Chain.getValue(1);
3207 // Handle result values, copying them out of physregs into vregs that we
3209 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3210 Ins, dl, DAG, InVals);
3213 /// LowerCallResult - Lower the result values of a call into the
3214 /// appropriate copies out of appropriate physical registers.
3216 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3217 CallingConv::ID CallConv, bool isVarArg,
3218 const SmallVectorImpl<ISD::InputArg> &Ins,
3219 DebugLoc dl, SelectionDAG &DAG,
3220 SmallVectorImpl<SDValue> &InVals) const {
3221 // Assign locations to each value returned by this call.
3222 SmallVector<CCValAssign, 16> RVLocs;
3223 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3224 getTargetMachine(), RVLocs, *DAG.getContext());
3226 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3228 // Copy all of the result registers out of their specified physreg.
3229 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3230 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
3231 RVLocs[i].getValVT(), InFlag).getValue(1);
3232 InFlag = Chain.getValue(2);
3233 InVals.push_back(Chain.getValue(0));
3239 //===----------------------------------------------------------------------===//
3240 // Formal Arguments Calling Convention Implementation
3241 //===----------------------------------------------------------------------===//
3242 /// LowerFormalArguments - transform physical registers into virtual registers
3243 /// and generate load operations for arguments places on the stack.
3245 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3246 CallingConv::ID CallConv,
3248 const SmallVectorImpl<ISD::InputArg> &Ins,
3249 DebugLoc dl, SelectionDAG &DAG,
3250 SmallVectorImpl<SDValue> &InVals)
3252 MachineFunction &MF = DAG.getMachineFunction();
3253 MachineFrameInfo *MFI = MF.getFrameInfo();
3254 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3256 MipsFI->setVarArgsFrameIndex(0);
3258 // Used with vargs to acumulate store chains.
3259 std::vector<SDValue> OutChains;
3261 // Assign locations to all of the incoming arguments.
3262 SmallVector<CCValAssign, 16> ArgLocs;
3263 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3264 getTargetMachine(), ArgLocs, *DAG.getContext());
3265 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
3267 MipsCCInfo.analyzeFormalArguments(Ins);
3268 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3269 MipsCCInfo.hasByValArg());
3271 Function::const_arg_iterator FuncArg =
3272 DAG.getMachineFunction().getFunction()->arg_begin();
3273 unsigned CurArgIdx = 0;
3274 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3276 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3277 CCValAssign &VA = ArgLocs[i];
3278 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
3279 CurArgIdx = Ins[i].OrigArgIndex;
3280 EVT ValVT = VA.getValVT();
3281 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3282 bool IsRegLoc = VA.isRegLoc();
3284 if (Flags.isByVal()) {
3285 assert(Flags.getByValSize() &&
3286 "ByVal args of size 0 should have been ignored by front-end.");
3287 assert(ByValArg != MipsCCInfo.byval_end());
3288 copyByValRegs(Chain, dl, OutChains, DAG, Flags, InVals, &*FuncArg,
3289 MipsCCInfo, *ByValArg);
3294 // Arguments stored on registers
3296 EVT RegVT = VA.getLocVT();
3297 unsigned ArgReg = VA.getLocReg();
3298 const TargetRegisterClass *RC;
3300 if (RegVT == MVT::i32)
3301 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
3302 &Mips::CPURegsRegClass;
3303 else if (RegVT == MVT::i64)
3304 RC = &Mips::CPU64RegsRegClass;
3305 else if (RegVT == MVT::f32)
3306 RC = &Mips::FGR32RegClass;
3307 else if (RegVT == MVT::f64)
3308 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3310 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3312 // Transform the arguments stored on
3313 // physical registers into virtual ones
3314 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3315 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3317 // If this is an 8 or 16-bit value, it has been passed promoted
3318 // to 32 bits. Insert an assert[sz]ext to capture this, then
3319 // truncate to the right size.
3320 if (VA.getLocInfo() != CCValAssign::Full) {
3321 unsigned Opcode = 0;
3322 if (VA.getLocInfo() == CCValAssign::SExt)
3323 Opcode = ISD::AssertSext;
3324 else if (VA.getLocInfo() == CCValAssign::ZExt)
3325 Opcode = ISD::AssertZext;
3327 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3328 DAG.getValueType(ValVT));
3329 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3332 // Handle floating point arguments passed in integer registers.
3333 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3334 (RegVT == MVT::i64 && ValVT == MVT::f64))
3335 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3336 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3337 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3338 getNextIntArgReg(ArgReg), RC);
3339 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3340 if (!Subtarget->isLittle())
3341 std::swap(ArgValue, ArgValue2);
3342 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3343 ArgValue, ArgValue2);
3346 InVals.push_back(ArgValue);
3347 } else { // VA.isRegLoc()
3350 assert(VA.isMemLoc());
3352 // The stack pointer offset is relative to the caller stack frame.
3353 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3354 VA.getLocMemOffset(), true);
3356 // Create load nodes to retrieve arguments from the stack
3357 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3358 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3359 MachinePointerInfo::getFixedStack(FI),
3360 false, false, false, 0));
3364 // The mips ABIs for returning structs by value requires that we copy
3365 // the sret argument into $v0 for the return. Save the argument into
3366 // a virtual register so that we can access it from the return points.
3367 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3368 unsigned Reg = MipsFI->getSRetReturnReg();
3370 Reg = MF.getRegInfo().
3371 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
3372 MipsFI->setSRetReturnReg(Reg);
3374 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3375 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3379 writeVarArgRegs(OutChains, MipsCCInfo, Chain, dl, DAG);
3381 // All stores are grouped in one node to allow the matching between
3382 // the size of Ins and InVals. This only happens when on varg functions
3383 if (!OutChains.empty()) {
3384 OutChains.push_back(Chain);
3385 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3386 &OutChains[0], OutChains.size());
3392 //===----------------------------------------------------------------------===//
3393 // Return Value Calling Convention Implementation
3394 //===----------------------------------------------------------------------===//
3397 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3398 MachineFunction &MF, bool isVarArg,
3399 const SmallVectorImpl<ISD::OutputArg> &Outs,
3400 LLVMContext &Context) const {
3401 SmallVector<CCValAssign, 16> RVLocs;
3402 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
3404 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3408 MipsTargetLowering::LowerReturn(SDValue Chain,
3409 CallingConv::ID CallConv, bool isVarArg,
3410 const SmallVectorImpl<ISD::OutputArg> &Outs,
3411 const SmallVectorImpl<SDValue> &OutVals,
3412 DebugLoc dl, SelectionDAG &DAG) const {
3414 // CCValAssign - represent the assignment of
3415 // the return value to a location
3416 SmallVector<CCValAssign, 16> RVLocs;
3418 // CCState - Info about the registers and stack slot.
3419 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3420 getTargetMachine(), RVLocs, *DAG.getContext());
3422 // Analize return values.
3423 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3425 // If this is the first return lowered for this function, add
3426 // the regs to the liveout set for the function.
3427 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3428 for (unsigned i = 0; i != RVLocs.size(); ++i)
3429 if (RVLocs[i].isRegLoc())
3430 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3435 // Copy the result values into the output registers.
3436 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3437 CCValAssign &VA = RVLocs[i];
3438 assert(VA.isRegLoc() && "Can only return in registers!");
3440 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3442 // guarantee that all emitted copies are
3443 // stuck together, avoiding something bad
3444 Flag = Chain.getValue(1);
3447 // The mips ABIs for returning structs by value requires that we copy
3448 // the sret argument into $v0 for the return. We saved the argument into
3449 // a virtual register in the entry block, so now we copy the value out
3451 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3452 MachineFunction &MF = DAG.getMachineFunction();
3453 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3454 unsigned Reg = MipsFI->getSRetReturnReg();
3457 llvm_unreachable("sret virtual register not created in the entry block");
3458 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3459 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
3461 Chain = DAG.getCopyToReg(Chain, dl, V0, Val, Flag);
3462 Flag = Chain.getValue(1);
3463 MF.getRegInfo().addLiveOut(V0);
3466 // Return on Mips is always a "jr $ra"
3468 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain, Flag);
3471 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain);
3474 //===----------------------------------------------------------------------===//
3475 // Mips Inline Assembly Support
3476 //===----------------------------------------------------------------------===//
3478 /// getConstraintType - Given a constraint letter, return the type of
3479 /// constraint it is for this target.
3480 MipsTargetLowering::ConstraintType MipsTargetLowering::
3481 getConstraintType(const std::string &Constraint) const
3483 // Mips specific constrainy
3484 // GCC config/mips/constraints.md
3486 // 'd' : An address register. Equivalent to r
3487 // unless generating MIPS16 code.
3488 // 'y' : Equivalent to r; retained for
3489 // backwards compatibility.
3490 // 'c' : A register suitable for use in an indirect
3491 // jump. This will always be $25 for -mabicalls.
3492 // 'l' : The lo register. 1 word storage.
3493 // 'x' : The hilo register pair. Double word storage.
3494 if (Constraint.size() == 1) {
3495 switch (Constraint[0]) {
3503 return C_RegisterClass;
3506 return TargetLowering::getConstraintType(Constraint);
3509 /// Examine constraint type and operand type and determine a weight value.
3510 /// This object must already have been set up with the operand type
3511 /// and the current alternative constraint selected.
3512 TargetLowering::ConstraintWeight
3513 MipsTargetLowering::getSingleConstraintMatchWeight(
3514 AsmOperandInfo &info, const char *constraint) const {
3515 ConstraintWeight weight = CW_Invalid;
3516 Value *CallOperandVal = info.CallOperandVal;
3517 // If we don't have a value, we can't do a match,
3518 // but allow it at the lowest weight.
3519 if (CallOperandVal == NULL)
3521 Type *type = CallOperandVal->getType();
3522 // Look at the constraint type.
3523 switch (*constraint) {
3525 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3529 if (type->isIntegerTy())
3530 weight = CW_Register;
3533 if (type->isFloatTy())
3534 weight = CW_Register;
3536 case 'c': // $25 for indirect jumps
3537 case 'l': // lo register
3538 case 'x': // hilo register pair
3539 if (type->isIntegerTy())
3540 weight = CW_SpecificReg;
3542 case 'I': // signed 16 bit immediate
3543 case 'J': // integer zero
3544 case 'K': // unsigned 16 bit immediate
3545 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3546 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3547 case 'O': // signed 15 bit immediate (+- 16383)
3548 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3549 if (isa<ConstantInt>(CallOperandVal))
3550 weight = CW_Constant;
3556 /// Given a register class constraint, like 'r', if this corresponds directly
3557 /// to an LLVM register class, return a register of 0 and the register class
3559 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3560 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3562 if (Constraint.size() == 1) {
3563 switch (Constraint[0]) {
3564 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3565 case 'y': // Same as 'r'. Exists for compatibility.
3567 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3568 if (Subtarget->inMips16Mode())
3569 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3570 return std::make_pair(0U, &Mips::CPURegsRegClass);
3572 if (VT == MVT::i64 && !HasMips64)
3573 return std::make_pair(0U, &Mips::CPURegsRegClass);
3574 if (VT == MVT::i64 && HasMips64)
3575 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3576 // This will generate an error message
3577 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3580 return std::make_pair(0U, &Mips::FGR32RegClass);
3581 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3582 if (Subtarget->isFP64bit())
3583 return std::make_pair(0U, &Mips::FGR64RegClass);
3584 return std::make_pair(0U, &Mips::AFGR64RegClass);
3587 case 'c': // register suitable for indirect jump
3589 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3590 assert(VT == MVT::i64 && "Unexpected type.");
3591 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3592 case 'l': // register suitable for indirect jump
3594 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3595 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3596 case 'x': // register suitable for indirect jump
3597 // Fixme: Not triggering the use of both hi and low
3598 // This will generate an error message
3599 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3602 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3605 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3606 /// vector. If it is invalid, don't add anything to Ops.
3607 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3608 std::string &Constraint,
3609 std::vector<SDValue>&Ops,
3610 SelectionDAG &DAG) const {
3611 SDValue Result(0, 0);
3613 // Only support length 1 constraints for now.
3614 if (Constraint.length() > 1) return;
3616 char ConstraintLetter = Constraint[0];
3617 switch (ConstraintLetter) {
3618 default: break; // This will fall through to the generic implementation
3619 case 'I': // Signed 16 bit constant
3620 // If this fails, the parent routine will give an error
3621 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3622 EVT Type = Op.getValueType();
3623 int64_t Val = C->getSExtValue();
3624 if (isInt<16>(Val)) {
3625 Result = DAG.getTargetConstant(Val, Type);
3630 case 'J': // integer zero
3631 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3632 EVT Type = Op.getValueType();
3633 int64_t Val = C->getZExtValue();
3635 Result = DAG.getTargetConstant(0, Type);
3640 case 'K': // unsigned 16 bit immediate
3641 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3642 EVT Type = Op.getValueType();
3643 uint64_t Val = (uint64_t)C->getZExtValue();
3644 if (isUInt<16>(Val)) {
3645 Result = DAG.getTargetConstant(Val, Type);
3650 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3651 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3652 EVT Type = Op.getValueType();
3653 int64_t Val = C->getSExtValue();
3654 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3655 Result = DAG.getTargetConstant(Val, Type);
3660 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3661 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3662 EVT Type = Op.getValueType();
3663 int64_t Val = C->getSExtValue();
3664 if ((Val >= -65535) && (Val <= -1)) {
3665 Result = DAG.getTargetConstant(Val, Type);
3670 case 'O': // signed 15 bit immediate
3671 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3672 EVT Type = Op.getValueType();
3673 int64_t Val = C->getSExtValue();
3674 if ((isInt<15>(Val))) {
3675 Result = DAG.getTargetConstant(Val, Type);
3680 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3681 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3682 EVT Type = Op.getValueType();
3683 int64_t Val = C->getSExtValue();
3684 if ((Val <= 65535) && (Val >= 1)) {
3685 Result = DAG.getTargetConstant(Val, Type);
3692 if (Result.getNode()) {
3693 Ops.push_back(Result);
3697 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3701 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3702 // No global is ever allowed as a base.
3707 case 0: // "r+i" or just "i", depending on HasBaseReg.
3710 if (!AM.HasBaseReg) // allow "r+i".
3712 return false; // disallow "r+r" or "r+r+i".
3721 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3722 // The Mips target isn't yet aware of offsets.
3726 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3728 bool IsMemset, bool ZeroMemset,
3730 MachineFunction &MF) const {
3731 if (Subtarget->hasMips64())
3737 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3738 if (VT != MVT::f32 && VT != MVT::f64)
3740 if (Imm.isNegZero())
3742 return Imm.isZero();
3745 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3747 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3749 return TargetLowering::getJumpTableEncoding();
3752 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CallConv, bool IsVarArg,
3753 bool IsO32, CCState &Info) : CCInfo(Info) {
3754 UseRegsForByval = true;
3758 NumIntArgRegs = array_lengthof(O32IntRegs);
3759 ReservedArgArea = 16;
3760 IntArgRegs = ShadowRegs = O32IntRegs;
3761 FixedFn = VarFn = CC_MipsO32;
3764 NumIntArgRegs = array_lengthof(Mips64IntRegs);
3765 ReservedArgArea = 0;
3766 IntArgRegs = Mips64IntRegs;
3767 ShadowRegs = Mips64DPRegs;
3769 VarFn = CC_MipsN_VarArg;
3772 if (CallConv == CallingConv::Fast) {
3774 UseRegsForByval = false;
3775 ReservedArgArea = 0;
3776 FixedFn = VarFn = CC_Mips_FastCC;
3779 // Pre-allocate reserved argument area.
3780 CCInfo.AllocateStack(ReservedArgArea, 1);
3783 void MipsTargetLowering::MipsCC::
3784 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args) {
3785 unsigned NumOpnds = Args.size();
3787 for (unsigned I = 0; I != NumOpnds; ++I) {
3788 MVT ArgVT = Args[I].VT;
3789 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3792 if (ArgFlags.isByVal()) {
3793 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3797 if (Args[I].IsFixed)
3798 R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3800 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3804 dbgs() << "Call operand #" << I << " has unhandled type "
3805 << EVT(ArgVT).getEVTString();
3807 llvm_unreachable(0);
3812 void MipsTargetLowering::MipsCC::
3813 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args) {
3814 unsigned NumArgs = Args.size();
3816 for (unsigned I = 0; I != NumArgs; ++I) {
3817 MVT ArgVT = Args[I].VT;
3818 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3820 if (ArgFlags.isByVal()) {
3821 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3825 if (!FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo))
3829 dbgs() << "Formal Arg #" << I << " has unhandled type "
3830 << EVT(ArgVT).getEVTString();
3832 llvm_unreachable(0);
3837 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3839 CCValAssign::LocInfo LocInfo,
3840 ISD::ArgFlagsTy ArgFlags) {
3841 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3843 struct ByValArgInfo ByVal;
3844 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3845 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3848 if (UseRegsForByval)
3849 allocateRegs(ByVal, ByValSize, Align);
3851 // Allocate space on caller's stack.
3852 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3854 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3856 ByValArgs.push_back(ByVal);
3859 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3862 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3863 "Byval argument's size and alignment should be a multiple of"
3866 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3868 // If Align > RegSize, the first arg register must be even.
3869 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3870 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3874 // Mark the registers allocated.
3875 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3876 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3877 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3880 void MipsTargetLowering::
3881 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
3882 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3883 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3884 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3885 MachineFunction &MF = DAG.getMachineFunction();
3886 MachineFrameInfo *MFI = MF.getFrameInfo();
3887 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3888 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3892 FrameObjOffset = (int)CC.reservedArgArea() -
3893 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3895 FrameObjOffset = ByVal.Address;
3897 // Create frame object.
3898 EVT PtrTy = getPointerTy();
3899 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3900 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3901 InVals.push_back(FIN);
3906 // Copy arg registers.
3907 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3908 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3910 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3911 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3912 unsigned VReg = AddLiveIn(MF, ArgReg, RC);
3913 unsigned Offset = I * CC.regSize();
3914 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3915 DAG.getConstant(Offset, PtrTy));
3916 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3917 StorePtr, MachinePointerInfo(FuncArg, Offset),
3919 OutChains.push_back(Store);
3923 // Copy byVal arg to registers and stack.
3924 void MipsTargetLowering::
3925 passByValArg(SDValue Chain, DebugLoc DL,
3926 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3927 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3928 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3929 const MipsCC &CC, const ByValArgInfo &ByVal,
3930 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3931 unsigned ByValSize = Flags.getByValSize();
3932 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3933 unsigned RegSize = CC.regSize();
3934 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3935 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3937 if (ByVal.NumRegs) {
3938 const uint16_t *ArgRegs = CC.intArgRegs();
3939 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3942 // Copy words to registers.
3943 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3944 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3945 DAG.getConstant(Offset, PtrTy));
3946 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3947 MachinePointerInfo(), false, false, false,
3949 MemOpChains.push_back(LoadVal.getValue(1));
3950 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3951 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3954 // Return if the struct has been fully copied.
3955 if (ByValSize == Offset)
3958 // Copy the remainder of the byval argument with sub-word loads and shifts.
3959 if (LeftoverBytes) {
3960 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3961 "Size of the remainder should be smaller than RegSize.");
3964 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3965 Offset < ByValSize; LoadSize /= 2) {
3966 unsigned RemSize = ByValSize - Offset;
3968 if (RemSize < LoadSize)
3972 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3973 DAG.getConstant(Offset, PtrTy));
3975 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3976 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3977 false, false, Alignment);
3978 MemOpChains.push_back(LoadVal.getValue(1));
3980 // Shift the loaded value.
3984 Shamt = TotalSizeLoaded;
3986 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3988 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3989 DAG.getConstant(Shamt, MVT::i32));
3992 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3997 TotalSizeLoaded += LoadSize;
3998 Alignment = std::min(Alignment, LoadSize);
4001 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
4002 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4007 // Copy remainder of byval arg to it with memcpy.
4008 unsigned MemCpySize = ByValSize - Offset;
4009 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4010 DAG.getConstant(Offset, PtrTy));
4011 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4012 DAG.getIntPtrConstant(ByVal.Address));
4013 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4014 DAG.getConstant(MemCpySize, PtrTy), Alignment,
4015 /*isVolatile=*/false, /*AlwaysInline=*/false,
4016 MachinePointerInfo(0), MachinePointerInfo(0));
4017 MemOpChains.push_back(Chain);
4021 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4022 const MipsCC &CC, SDValue Chain,
4023 DebugLoc DL, SelectionDAG &DAG) const {
4024 unsigned NumRegs = CC.numIntArgRegs();
4025 const uint16_t *ArgRegs = CC.intArgRegs();
4026 const CCState &CCInfo = CC.getCCInfo();
4027 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
4028 unsigned RegSize = CC.regSize();
4029 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
4030 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4031 MachineFunction &MF = DAG.getMachineFunction();
4032 MachineFrameInfo *MFI = MF.getFrameInfo();
4033 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4035 // Offset of the first variable argument from stack pointer.
4039 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
4042 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
4044 // Record the frame index of the first variable argument
4045 // which is a value necessary to VASTART.
4046 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4047 MipsFI->setVarArgsFrameIndex(FI);
4049 // Copy the integer registers that have not been used for argument passing
4050 // to the argument register save area. For O32, the save area is allocated
4051 // in the caller's stack frame, while for N32/64, it is allocated in the
4052 // callee's stack frame.
4053 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
4054 unsigned Reg = AddLiveIn(MF, ArgRegs[I], RC);
4055 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4056 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4057 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
4058 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
4059 MachinePointerInfo(), false, false, 0);
4060 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
4061 OutChains.push_back(Store);