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::EH_RETURN: return "MipsISD::EH_RETURN";
166 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
167 case MipsISD::FPCmp: return "MipsISD::FPCmp";
168 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
169 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
170 case MipsISD::FPRound: return "MipsISD::FPRound";
171 case MipsISD::MAdd: return "MipsISD::MAdd";
172 case MipsISD::MAddu: return "MipsISD::MAddu";
173 case MipsISD::MSub: return "MipsISD::MSub";
174 case MipsISD::MSubu: return "MipsISD::MSubu";
175 case MipsISD::DivRem: return "MipsISD::DivRem";
176 case MipsISD::DivRemU: return "MipsISD::DivRemU";
177 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
178 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
179 case MipsISD::Wrapper: return "MipsISD::Wrapper";
180 case MipsISD::Sync: return "MipsISD::Sync";
181 case MipsISD::Ext: return "MipsISD::Ext";
182 case MipsISD::Ins: return "MipsISD::Ins";
183 case MipsISD::LWL: return "MipsISD::LWL";
184 case MipsISD::LWR: return "MipsISD::LWR";
185 case MipsISD::SWL: return "MipsISD::SWL";
186 case MipsISD::SWR: return "MipsISD::SWR";
187 case MipsISD::LDL: return "MipsISD::LDL";
188 case MipsISD::LDR: return "MipsISD::LDR";
189 case MipsISD::SDL: return "MipsISD::SDL";
190 case MipsISD::SDR: return "MipsISD::SDR";
191 case MipsISD::EXTP: return "MipsISD::EXTP";
192 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
193 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
194 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
195 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
196 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
197 case MipsISD::SHILO: return "MipsISD::SHILO";
198 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
199 case MipsISD::MULT: return "MipsISD::MULT";
200 case MipsISD::MULTU: return "MipsISD::MULTU";
201 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSPDSP";
202 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
203 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
204 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
205 default: return NULL;
211 bool operator()(const char *s1, const char *s2) const
213 return strcmp(s1, s2) < 0;
217 std::set<const char*, ltstr> noHelperNeeded;
220 void MipsTargetLowering::SetMips16LibcallName
221 (RTLIB::Libcall l, const char *Name) {
222 setLibcallName(l, Name);
223 noHelperNeeded.insert(Name);
226 void MipsTargetLowering::setMips16HardFloatLibCalls() {
227 SetMips16LibcallName(RTLIB::ADD_F32, "__mips16_addsf3");
228 SetMips16LibcallName(RTLIB::ADD_F64, "__mips16_adddf3");
229 SetMips16LibcallName(RTLIB::SUB_F32, "__mips16_subsf3");
230 SetMips16LibcallName(RTLIB::SUB_F64, "__mips16_subdf3");
231 SetMips16LibcallName(RTLIB::MUL_F32, "__mips16_mulsf3");
232 SetMips16LibcallName(RTLIB::MUL_F64, "__mips16_muldf3");
233 SetMips16LibcallName(RTLIB::DIV_F32, "__mips16_divsf3");
234 SetMips16LibcallName(RTLIB::DIV_F64, "__mips16_divdf3");
235 SetMips16LibcallName(RTLIB::FPEXT_F32_F64, "__mips16_extendsfdf2");
236 SetMips16LibcallName(RTLIB::FPROUND_F64_F32, "__mips16_truncdfsf2");
237 SetMips16LibcallName(RTLIB::FPTOSINT_F32_I32, "__mips16_fix_truncsfsi");
238 SetMips16LibcallName(RTLIB::FPTOSINT_F64_I32, "__mips16_fix_truncdfsi");
239 SetMips16LibcallName(RTLIB::SINTTOFP_I32_F32, "__mips16_floatsisf");
240 SetMips16LibcallName(RTLIB::SINTTOFP_I32_F64, "__mips16_floatsidf");
241 SetMips16LibcallName(RTLIB::UINTTOFP_I32_F32, "__mips16_floatunsisf");
242 SetMips16LibcallName(RTLIB::UINTTOFP_I32_F64, "__mips16_floatunsidf");
243 SetMips16LibcallName(RTLIB::OEQ_F32, "__mips16_eqsf2");
244 SetMips16LibcallName(RTLIB::OEQ_F64, "__mips16_eqdf2");
245 SetMips16LibcallName(RTLIB::UNE_F32, "__mips16_nesf2");
246 SetMips16LibcallName(RTLIB::UNE_F64, "__mips16_nedf2");
247 SetMips16LibcallName(RTLIB::OGE_F32, "__mips16_gesf2");
248 SetMips16LibcallName(RTLIB::OGE_F64, "__mips16_gedf2");
249 SetMips16LibcallName(RTLIB::OLT_F32, "__mips16_ltsf2");
250 SetMips16LibcallName(RTLIB::OLT_F64, "__mips16_ltdf2");
251 SetMips16LibcallName(RTLIB::OLE_F32, "__mips16_lesf2");
252 SetMips16LibcallName(RTLIB::OLE_F64, "__mips16_ledf2");
253 SetMips16LibcallName(RTLIB::OGT_F32, "__mips16_gtsf2");
254 SetMips16LibcallName(RTLIB::OGT_F64, "__mips16_gtdf2");
255 SetMips16LibcallName(RTLIB::UO_F32, "__mips16_unordsf2");
256 SetMips16LibcallName(RTLIB::UO_F64, "__mips16_unorddf2");
257 SetMips16LibcallName(RTLIB::O_F32, "__mips16_unordsf2");
258 SetMips16LibcallName(RTLIB::O_F64, "__mips16_unorddf2");
262 MipsTargetLowering(MipsTargetMachine &TM)
263 : TargetLowering(TM, new MipsTargetObjectFile()),
264 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
265 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
266 IsO32(Subtarget->isABI_O32()) {
268 // Mips does not have i1 type, so use i32 for
269 // setcc operations results (slt, sgt, ...).
270 setBooleanContents(ZeroOrOneBooleanContent);
271 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
273 // Set up the register classes
274 addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
277 addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
279 if (Subtarget->inMips16Mode()) {
280 addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
282 setMips16HardFloatLibCalls();
285 if (Subtarget->hasDSP()) {
286 MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
288 for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
289 addRegisterClass(VecTys[i], &Mips::DSPRegsRegClass);
291 // Expand all builtin opcodes.
292 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
293 setOperationAction(Opc, VecTys[i], Expand);
295 setOperationAction(ISD::LOAD, VecTys[i], Legal);
296 setOperationAction(ISD::STORE, VecTys[i], Legal);
297 setOperationAction(ISD::BITCAST, VecTys[i], Legal);
301 if (!TM.Options.UseSoftFloat) {
302 addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
304 // When dealing with single precision only, use libcalls
305 if (!Subtarget->isSingleFloat()) {
307 addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
309 addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
313 // Load extented operations for i1 types must be promoted
314 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
315 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
316 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
318 // MIPS doesn't have extending float->double load/store
319 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
320 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
322 // Used by legalize types to correctly generate the setcc result.
323 // Without this, every float setcc comes with a AND/OR with the result,
324 // we don't want this, since the fpcmp result goes to a flag register,
325 // which is used implicitly by brcond and select operations.
326 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
328 // Mips Custom Operations
329 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
330 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
331 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
332 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
333 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
334 setOperationAction(ISD::SELECT, MVT::f32, Custom);
335 setOperationAction(ISD::SELECT, MVT::f64, Custom);
336 setOperationAction(ISD::SELECT, MVT::i32, Custom);
337 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
338 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
339 setOperationAction(ISD::SETCC, MVT::f32, Custom);
340 setOperationAction(ISD::SETCC, MVT::f64, Custom);
341 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
342 setOperationAction(ISD::VASTART, MVT::Other, Custom);
343 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
344 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
345 if (Subtarget->inMips16Mode()) {
346 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
347 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
350 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
351 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
353 if (!Subtarget->inMips16Mode()) {
354 setOperationAction(ISD::LOAD, MVT::i32, Custom);
355 setOperationAction(ISD::STORE, MVT::i32, Custom);
358 if (!TM.Options.NoNaNsFPMath) {
359 setOperationAction(ISD::FABS, MVT::f32, Custom);
360 setOperationAction(ISD::FABS, MVT::f64, Custom);
364 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
365 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
366 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
367 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
368 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
369 setOperationAction(ISD::SELECT, MVT::i64, Custom);
370 setOperationAction(ISD::LOAD, MVT::i64, Custom);
371 setOperationAction(ISD::STORE, MVT::i64, Custom);
375 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
376 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
377 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
380 setOperationAction(ISD::ADD, MVT::i32, Custom);
382 setOperationAction(ISD::ADD, MVT::i64, Custom);
384 setOperationAction(ISD::SDIV, MVT::i32, Expand);
385 setOperationAction(ISD::SREM, MVT::i32, Expand);
386 setOperationAction(ISD::UDIV, MVT::i32, Expand);
387 setOperationAction(ISD::UREM, MVT::i32, Expand);
388 setOperationAction(ISD::SDIV, MVT::i64, Expand);
389 setOperationAction(ISD::SREM, MVT::i64, Expand);
390 setOperationAction(ISD::UDIV, MVT::i64, Expand);
391 setOperationAction(ISD::UREM, MVT::i64, Expand);
393 // Operations not directly supported by Mips.
394 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
395 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
396 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
397 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
398 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
399 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
400 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
401 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
402 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
403 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
404 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
405 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
406 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
407 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
408 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
409 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
410 setOperationAction(ISD::ROTL, MVT::i32, Expand);
411 setOperationAction(ISD::ROTL, MVT::i64, Expand);
412 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
413 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
415 if (!Subtarget->hasMips32r2())
416 setOperationAction(ISD::ROTR, MVT::i32, Expand);
418 if (!Subtarget->hasMips64r2())
419 setOperationAction(ISD::ROTR, MVT::i64, Expand);
421 setOperationAction(ISD::FSIN, MVT::f32, Expand);
422 setOperationAction(ISD::FSIN, MVT::f64, Expand);
423 setOperationAction(ISD::FCOS, MVT::f32, Expand);
424 setOperationAction(ISD::FCOS, MVT::f64, Expand);
425 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
426 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
427 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
428 setOperationAction(ISD::FPOW, MVT::f32, Expand);
429 setOperationAction(ISD::FPOW, MVT::f64, Expand);
430 setOperationAction(ISD::FLOG, MVT::f32, Expand);
431 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
432 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
433 setOperationAction(ISD::FEXP, MVT::f32, Expand);
434 setOperationAction(ISD::FMA, MVT::f32, Expand);
435 setOperationAction(ISD::FMA, MVT::f64, Expand);
436 setOperationAction(ISD::FREM, MVT::f32, Expand);
437 setOperationAction(ISD::FREM, MVT::f64, Expand);
439 if (!TM.Options.NoNaNsFPMath) {
440 setOperationAction(ISD::FNEG, MVT::f32, Expand);
441 setOperationAction(ISD::FNEG, MVT::f64, Expand);
444 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
445 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
446 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
447 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
449 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
451 setOperationAction(ISD::VAARG, MVT::Other, Expand);
452 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
453 setOperationAction(ISD::VAEND, MVT::Other, Expand);
455 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
456 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
458 // Use the default for now
459 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
460 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
462 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
463 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
464 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
465 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
467 if (Subtarget->inMips16Mode()) {
468 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
469 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
470 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
471 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
472 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
473 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
474 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
475 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
476 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
477 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
478 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
479 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
482 setInsertFencesForAtomic(true);
484 if (!Subtarget->hasSEInReg()) {
485 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
486 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
489 if (!Subtarget->hasBitCount()) {
490 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
491 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
494 if (!Subtarget->hasSwap()) {
495 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
496 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
500 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
501 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
502 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
503 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
506 setTargetDAGCombine(ISD::ADDE);
507 setTargetDAGCombine(ISD::SUBE);
508 setTargetDAGCombine(ISD::SDIVREM);
509 setTargetDAGCombine(ISD::UDIVREM);
510 setTargetDAGCombine(ISD::SELECT);
511 setTargetDAGCombine(ISD::AND);
512 setTargetDAGCombine(ISD::OR);
513 setTargetDAGCombine(ISD::ADD);
515 setMinFunctionAlignment(HasMips64 ? 3 : 2);
517 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
518 computeRegisterProperties();
520 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
521 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
523 maxStoresPerMemcpy = 16;
527 MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
528 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
530 if (Subtarget->inMips16Mode())
544 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
547 return VT.changeVectorElementTypeToInteger();
551 // Transforms a subgraph in CurDAG if the following pattern is found:
552 // (addc multLo, Lo0), (adde multHi, Hi0),
554 // multHi/Lo: product of multiplication
555 // Lo0: initial value of Lo register
556 // Hi0: initial value of Hi register
557 // Return true if pattern matching was successful.
558 static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
559 // ADDENode's second operand must be a flag output of an ADDC node in order
560 // for the matching to be successful.
561 SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
563 if (ADDCNode->getOpcode() != ISD::ADDC)
566 SDValue MultHi = ADDENode->getOperand(0);
567 SDValue MultLo = ADDCNode->getOperand(0);
568 SDNode *MultNode = MultHi.getNode();
569 unsigned MultOpc = MultHi.getOpcode();
571 // MultHi and MultLo must be generated by the same node,
572 if (MultLo.getNode() != MultNode)
575 // and it must be a multiplication.
576 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
579 // MultLo amd MultHi must be the first and second output of MultNode
581 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
584 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
585 // of the values of MultNode, in which case MultNode will be removed in later
587 // If there exist users other than ADDENode or ADDCNode, this function returns
588 // here, which will result in MultNode being mapped to a single MULT
589 // instruction node rather than a pair of MULT and MADD instructions being
591 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
594 SDValue Chain = CurDAG->getEntryNode();
595 DebugLoc dl = ADDENode->getDebugLoc();
597 // create MipsMAdd(u) node
598 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
600 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
601 MultNode->getOperand(0),// Factor 0
602 MultNode->getOperand(1),// Factor 1
603 ADDCNode->getOperand(1),// Lo0
604 ADDENode->getOperand(1));// Hi0
606 // create CopyFromReg nodes
607 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
609 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
611 CopyFromLo.getValue(2));
613 // replace uses of adde and addc here
614 if (!SDValue(ADDCNode, 0).use_empty())
615 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
617 if (!SDValue(ADDENode, 0).use_empty())
618 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
624 // Transforms a subgraph in CurDAG if the following pattern is found:
625 // (addc Lo0, multLo), (sube Hi0, multHi),
627 // multHi/Lo: product of multiplication
628 // Lo0: initial value of Lo register
629 // Hi0: initial value of Hi register
630 // Return true if pattern matching was successful.
631 static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
632 // SUBENode's second operand must be a flag output of an SUBC node in order
633 // for the matching to be successful.
634 SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
636 if (SUBCNode->getOpcode() != ISD::SUBC)
639 SDValue MultHi = SUBENode->getOperand(1);
640 SDValue MultLo = SUBCNode->getOperand(1);
641 SDNode *MultNode = MultHi.getNode();
642 unsigned MultOpc = MultHi.getOpcode();
644 // MultHi and MultLo must be generated by the same node,
645 if (MultLo.getNode() != MultNode)
648 // and it must be a multiplication.
649 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
652 // MultLo amd MultHi must be the first and second output of MultNode
654 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
657 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
658 // of the values of MultNode, in which case MultNode will be removed in later
660 // If there exist users other than SUBENode or SUBCNode, this function returns
661 // here, which will result in MultNode being mapped to a single MULT
662 // instruction node rather than a pair of MULT and MSUB instructions being
664 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
667 SDValue Chain = CurDAG->getEntryNode();
668 DebugLoc dl = SUBENode->getDebugLoc();
670 // create MipsSub(u) node
671 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
673 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
674 MultNode->getOperand(0),// Factor 0
675 MultNode->getOperand(1),// Factor 1
676 SUBCNode->getOperand(0),// Lo0
677 SUBENode->getOperand(0));// Hi0
679 // create CopyFromReg nodes
680 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
682 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
684 CopyFromLo.getValue(2));
686 // replace uses of sube and subc here
687 if (!SDValue(SUBCNode, 0).use_empty())
688 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
690 if (!SDValue(SUBENode, 0).use_empty())
691 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
696 static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
697 TargetLowering::DAGCombinerInfo &DCI,
698 const MipsSubtarget *Subtarget) {
699 if (DCI.isBeforeLegalize())
702 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
704 return SDValue(N, 0);
709 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
710 TargetLowering::DAGCombinerInfo &DCI,
711 const MipsSubtarget *Subtarget) {
712 if (DCI.isBeforeLegalize())
715 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
717 return SDValue(N, 0);
722 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
723 TargetLowering::DAGCombinerInfo &DCI,
724 const MipsSubtarget *Subtarget) {
725 if (DCI.isBeforeLegalizeOps())
728 EVT Ty = N->getValueType(0);
729 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
730 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
731 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
733 DebugLoc dl = N->getDebugLoc();
735 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
736 N->getOperand(0), N->getOperand(1));
737 SDValue InChain = DAG.getEntryNode();
738 SDValue InGlue = DivRem;
741 if (N->hasAnyUseOfValue(0)) {
742 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
744 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
745 InChain = CopyFromLo.getValue(1);
746 InGlue = CopyFromLo.getValue(2);
750 if (N->hasAnyUseOfValue(1)) {
751 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
753 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
759 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
761 default: llvm_unreachable("Unknown fp condition code!");
763 case ISD::SETOEQ: return Mips::FCOND_OEQ;
764 case ISD::SETUNE: return Mips::FCOND_UNE;
766 case ISD::SETOLT: return Mips::FCOND_OLT;
768 case ISD::SETOGT: return Mips::FCOND_OGT;
770 case ISD::SETOLE: return Mips::FCOND_OLE;
772 case ISD::SETOGE: return Mips::FCOND_OGE;
773 case ISD::SETULT: return Mips::FCOND_ULT;
774 case ISD::SETULE: return Mips::FCOND_ULE;
775 case ISD::SETUGT: return Mips::FCOND_UGT;
776 case ISD::SETUGE: return Mips::FCOND_UGE;
777 case ISD::SETUO: return Mips::FCOND_UN;
778 case ISD::SETO: return Mips::FCOND_OR;
780 case ISD::SETONE: return Mips::FCOND_ONE;
781 case ISD::SETUEQ: return Mips::FCOND_UEQ;
786 // Returns true if condition code has to be inverted.
787 static bool InvertFPCondCode(Mips::CondCode CC) {
788 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
791 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
792 "Illegal Condition Code");
797 // Creates and returns an FPCmp node from a setcc node.
798 // Returns Op if setcc is not a floating point comparison.
799 static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
800 // must be a SETCC node
801 if (Op.getOpcode() != ISD::SETCC)
804 SDValue LHS = Op.getOperand(0);
806 if (!LHS.getValueType().isFloatingPoint())
809 SDValue RHS = Op.getOperand(1);
810 DebugLoc dl = Op.getDebugLoc();
812 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
813 // node if necessary.
814 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
816 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
817 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
820 // Creates and returns a CMovFPT/F node.
821 static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
822 SDValue False, DebugLoc DL) {
823 bool invert = InvertFPCondCode((Mips::CondCode)
824 cast<ConstantSDNode>(Cond.getOperand(2))
827 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
828 True.getValueType(), True, False, Cond);
831 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
832 TargetLowering::DAGCombinerInfo &DCI,
833 const MipsSubtarget *Subtarget) {
834 if (DCI.isBeforeLegalizeOps())
837 SDValue SetCC = N->getOperand(0);
839 if ((SetCC.getOpcode() != ISD::SETCC) ||
840 !SetCC.getOperand(0).getValueType().isInteger())
843 SDValue False = N->getOperand(2);
844 EVT FalseTy = False.getValueType();
846 if (!FalseTy.isInteger())
849 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
851 if (!CN || CN->getZExtValue())
854 const DebugLoc DL = N->getDebugLoc();
855 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
856 SDValue True = N->getOperand(1);
858 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
859 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
861 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
864 static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
865 TargetLowering::DAGCombinerInfo &DCI,
866 const MipsSubtarget *Subtarget) {
867 // Pattern match EXT.
868 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
869 // => ext $dst, $src, size, pos
870 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
873 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
874 unsigned ShiftRightOpc = ShiftRight.getOpcode();
876 // Op's first operand must be a shift right.
877 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
880 // The second operand of the shift must be an immediate.
882 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
885 uint64_t Pos = CN->getZExtValue();
886 uint64_t SMPos, SMSize;
888 // Op's second operand must be a shifted mask.
889 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
890 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
893 // Return if the shifted mask does not start at bit 0 or the sum of its size
894 // and Pos exceeds the word's size.
895 EVT ValTy = N->getValueType(0);
896 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
899 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
900 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
901 DAG.getConstant(SMSize, MVT::i32));
904 static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
905 TargetLowering::DAGCombinerInfo &DCI,
906 const MipsSubtarget *Subtarget) {
907 // Pattern match INS.
908 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
909 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
910 // => ins $dst, $src, size, pos, $src1
911 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
914 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
915 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
918 // See if Op's first operand matches (and $src1 , mask0).
919 if (And0.getOpcode() != ISD::AND)
922 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
923 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
926 // See if Op's second operand matches (and (shl $src, pos), mask1).
927 if (And1.getOpcode() != ISD::AND)
930 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
931 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
934 // The shift masks must have the same position and size.
935 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
938 SDValue Shl = And1.getOperand(0);
939 if (Shl.getOpcode() != ISD::SHL)
942 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
945 unsigned Shamt = CN->getZExtValue();
947 // Return if the shift amount and the first bit position of mask are not the
949 EVT ValTy = N->getValueType(0);
950 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
953 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
954 DAG.getConstant(SMPos0, MVT::i32),
955 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
958 static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
959 TargetLowering::DAGCombinerInfo &DCI,
960 const MipsSubtarget *Subtarget) {
961 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
963 if (DCI.isBeforeLegalizeOps())
966 SDValue Add = N->getOperand(1);
968 if (Add.getOpcode() != ISD::ADD)
971 SDValue Lo = Add.getOperand(1);
973 if ((Lo.getOpcode() != MipsISD::Lo) ||
974 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
977 EVT ValTy = N->getValueType(0);
978 DebugLoc DL = N->getDebugLoc();
980 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
982 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
985 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
987 SelectionDAG &DAG = DCI.DAG;
988 unsigned opc = N->getOpcode();
993 return PerformADDECombine(N, DAG, DCI, Subtarget);
995 return PerformSUBECombine(N, DAG, DCI, Subtarget);
998 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
1000 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
1002 return PerformANDCombine(N, DAG, DCI, Subtarget);
1004 return PerformORCombine(N, DAG, DCI, Subtarget);
1006 return PerformADDCombine(N, DAG, DCI, Subtarget);
1013 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1014 SmallVectorImpl<SDValue> &Results,
1015 SelectionDAG &DAG) const {
1016 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1018 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1019 Results.push_back(Res.getValue(I));
1023 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1024 SmallVectorImpl<SDValue> &Results,
1025 SelectionDAG &DAG) const {
1026 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1028 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1029 Results.push_back(Res.getValue(I));
1032 SDValue MipsTargetLowering::
1033 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1035 switch (Op.getOpcode())
1037 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1038 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
1039 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
1040 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
1041 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
1042 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
1043 case ISD::SELECT: return LowerSELECT(Op, DAG);
1044 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
1045 case ISD::SETCC: return LowerSETCC(Op, DAG);
1046 case ISD::VASTART: return LowerVASTART(Op, DAG);
1047 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
1048 case ISD::FABS: return LowerFABS(Op, DAG);
1049 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
1050 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
1051 case ISD::EH_RETURN: return LowerEH_RETURN(Op, DAG);
1052 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
1053 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
1054 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
1055 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
1056 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
1057 case ISD::LOAD: return LowerLOAD(Op, DAG);
1058 case ISD::STORE: return LowerSTORE(Op, DAG);
1059 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1060 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
1061 case ISD::ADD: return LowerADD(Op, DAG);
1066 //===----------------------------------------------------------------------===//
1067 // Lower helper functions
1068 //===----------------------------------------------------------------------===//
1070 // AddLiveIn - This helper function adds the specified physical register to the
1071 // MachineFunction as a live in value. It also creates a corresponding
1072 // virtual register for it.
1074 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1076 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1077 MF.getRegInfo().addLiveIn(PReg, VReg);
1081 // Get fp branch code (not opcode) from condition code.
1082 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
1083 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
1084 return Mips::BRANCH_T;
1086 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
1087 "Invalid CondCode.");
1089 return Mips::BRANCH_F;
1093 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
1095 const MipsSubtarget *Subtarget,
1096 const TargetInstrInfo *TII,
1097 bool isFPCmp, unsigned Opc) {
1098 // There is no need to expand CMov instructions if target has
1099 // conditional moves.
1100 if (Subtarget->hasCondMov())
1103 // To "insert" a SELECT_CC instruction, we actually have to insert the
1104 // diamond control-flow pattern. The incoming instruction knows the
1105 // destination vreg to set, the condition code register to branch on, the
1106 // true/false values to select between, and a branch opcode to use.
1107 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1108 MachineFunction::iterator It = BB;
1115 // bNE r1, r0, copy1MBB
1116 // fallthrough --> copy0MBB
1117 MachineBasicBlock *thisMBB = BB;
1118 MachineFunction *F = BB->getParent();
1119 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1120 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1121 F->insert(It, copy0MBB);
1122 F->insert(It, sinkMBB);
1124 // Transfer the remainder of BB and its successor edges to sinkMBB.
1125 sinkMBB->splice(sinkMBB->begin(), BB,
1126 llvm::next(MachineBasicBlock::iterator(MI)),
1128 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1130 // Next, add the true and fallthrough blocks as its successors.
1131 BB->addSuccessor(copy0MBB);
1132 BB->addSuccessor(sinkMBB);
1134 // Emit the right instruction according to the type of the operands compared
1136 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
1138 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
1139 .addReg(Mips::ZERO).addMBB(sinkMBB);
1142 // %FalseValue = ...
1143 // # fallthrough to sinkMBB
1146 // Update machine-CFG edges
1147 BB->addSuccessor(sinkMBB);
1150 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1155 BuildMI(*BB, BB->begin(), dl,
1156 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1157 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
1158 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1160 BuildMI(*BB, BB->begin(), dl,
1161 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1162 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
1163 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1165 MI->eraseFromParent(); // The pseudo instruction is gone now.
1171 MipsTargetLowering::EmitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
1173 // bposge32_pseudo $vr0
1183 // $vr0 = phi($vr2, $fbb, $vr1, $tbb)
1185 MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
1186 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1187 const TargetRegisterClass *RC = &Mips::CPURegsRegClass;
1188 DebugLoc DL = MI->getDebugLoc();
1189 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1190 MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
1191 MachineFunction *F = BB->getParent();
1192 MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
1193 MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
1194 MachineBasicBlock *Sink = F->CreateMachineBasicBlock(LLVM_BB);
1197 F->insert(It, Sink);
1199 // Transfer the remainder of BB and its successor edges to Sink.
1200 Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
1202 Sink->transferSuccessorsAndUpdatePHIs(BB);
1205 BB->addSuccessor(FBB);
1206 BB->addSuccessor(TBB);
1207 FBB->addSuccessor(Sink);
1208 TBB->addSuccessor(Sink);
1210 // Insert the real bposge32 instruction to $BB.
1211 BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
1214 unsigned VR2 = RegInfo.createVirtualRegister(RC);
1215 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
1216 .addReg(Mips::ZERO).addImm(0);
1217 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
1220 unsigned VR1 = RegInfo.createVirtualRegister(RC);
1221 BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
1222 .addReg(Mips::ZERO).addImm(1);
1224 // Insert phi function to $Sink.
1225 BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
1226 MI->getOperand(0).getReg())
1227 .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
1229 MI->eraseFromParent(); // The pseudo instruction is gone now.
1234 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1235 MachineBasicBlock *BB) const {
1236 switch (MI->getOpcode()) {
1237 default: llvm_unreachable("Unexpected instr type to insert");
1238 case Mips::ATOMIC_LOAD_ADD_I8:
1239 case Mips::ATOMIC_LOAD_ADD_I8_P8:
1240 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1241 case Mips::ATOMIC_LOAD_ADD_I16:
1242 case Mips::ATOMIC_LOAD_ADD_I16_P8:
1243 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1244 case Mips::ATOMIC_LOAD_ADD_I32:
1245 case Mips::ATOMIC_LOAD_ADD_I32_P8:
1246 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
1247 case Mips::ATOMIC_LOAD_ADD_I64:
1248 case Mips::ATOMIC_LOAD_ADD_I64_P8:
1249 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
1251 case Mips::ATOMIC_LOAD_AND_I8:
1252 case Mips::ATOMIC_LOAD_AND_I8_P8:
1253 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1254 case Mips::ATOMIC_LOAD_AND_I16:
1255 case Mips::ATOMIC_LOAD_AND_I16_P8:
1256 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1257 case Mips::ATOMIC_LOAD_AND_I32:
1258 case Mips::ATOMIC_LOAD_AND_I32_P8:
1259 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
1260 case Mips::ATOMIC_LOAD_AND_I64:
1261 case Mips::ATOMIC_LOAD_AND_I64_P8:
1262 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
1264 case Mips::ATOMIC_LOAD_OR_I8:
1265 case Mips::ATOMIC_LOAD_OR_I8_P8:
1266 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1267 case Mips::ATOMIC_LOAD_OR_I16:
1268 case Mips::ATOMIC_LOAD_OR_I16_P8:
1269 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1270 case Mips::ATOMIC_LOAD_OR_I32:
1271 case Mips::ATOMIC_LOAD_OR_I32_P8:
1272 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
1273 case Mips::ATOMIC_LOAD_OR_I64:
1274 case Mips::ATOMIC_LOAD_OR_I64_P8:
1275 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
1277 case Mips::ATOMIC_LOAD_XOR_I8:
1278 case Mips::ATOMIC_LOAD_XOR_I8_P8:
1279 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1280 case Mips::ATOMIC_LOAD_XOR_I16:
1281 case Mips::ATOMIC_LOAD_XOR_I16_P8:
1282 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1283 case Mips::ATOMIC_LOAD_XOR_I32:
1284 case Mips::ATOMIC_LOAD_XOR_I32_P8:
1285 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
1286 case Mips::ATOMIC_LOAD_XOR_I64:
1287 case Mips::ATOMIC_LOAD_XOR_I64_P8:
1288 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
1290 case Mips::ATOMIC_LOAD_NAND_I8:
1291 case Mips::ATOMIC_LOAD_NAND_I8_P8:
1292 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
1293 case Mips::ATOMIC_LOAD_NAND_I16:
1294 case Mips::ATOMIC_LOAD_NAND_I16_P8:
1295 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
1296 case Mips::ATOMIC_LOAD_NAND_I32:
1297 case Mips::ATOMIC_LOAD_NAND_I32_P8:
1298 return EmitAtomicBinary(MI, BB, 4, 0, true);
1299 case Mips::ATOMIC_LOAD_NAND_I64:
1300 case Mips::ATOMIC_LOAD_NAND_I64_P8:
1301 return EmitAtomicBinary(MI, BB, 8, 0, true);
1303 case Mips::ATOMIC_LOAD_SUB_I8:
1304 case Mips::ATOMIC_LOAD_SUB_I8_P8:
1305 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1306 case Mips::ATOMIC_LOAD_SUB_I16:
1307 case Mips::ATOMIC_LOAD_SUB_I16_P8:
1308 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1309 case Mips::ATOMIC_LOAD_SUB_I32:
1310 case Mips::ATOMIC_LOAD_SUB_I32_P8:
1311 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1312 case Mips::ATOMIC_LOAD_SUB_I64:
1313 case Mips::ATOMIC_LOAD_SUB_I64_P8:
1314 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1316 case Mips::ATOMIC_SWAP_I8:
1317 case Mips::ATOMIC_SWAP_I8_P8:
1318 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1319 case Mips::ATOMIC_SWAP_I16:
1320 case Mips::ATOMIC_SWAP_I16_P8:
1321 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1322 case Mips::ATOMIC_SWAP_I32:
1323 case Mips::ATOMIC_SWAP_I32_P8:
1324 return EmitAtomicBinary(MI, BB, 4, 0);
1325 case Mips::ATOMIC_SWAP_I64:
1326 case Mips::ATOMIC_SWAP_I64_P8:
1327 return EmitAtomicBinary(MI, BB, 8, 0);
1329 case Mips::ATOMIC_CMP_SWAP_I8:
1330 case Mips::ATOMIC_CMP_SWAP_I8_P8:
1331 return EmitAtomicCmpSwapPartword(MI, BB, 1);
1332 case Mips::ATOMIC_CMP_SWAP_I16:
1333 case Mips::ATOMIC_CMP_SWAP_I16_P8:
1334 return EmitAtomicCmpSwapPartword(MI, BB, 2);
1335 case Mips::ATOMIC_CMP_SWAP_I32:
1336 case Mips::ATOMIC_CMP_SWAP_I32_P8:
1337 return EmitAtomicCmpSwap(MI, BB, 4);
1338 case Mips::ATOMIC_CMP_SWAP_I64:
1339 case Mips::ATOMIC_CMP_SWAP_I64_P8:
1340 return EmitAtomicCmpSwap(MI, BB, 8);
1341 case Mips::BPOSGE32_PSEUDO:
1342 return EmitBPOSGE32(MI, BB);
1346 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1347 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1349 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1350 unsigned Size, unsigned BinOpcode,
1352 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1354 MachineFunction *MF = BB->getParent();
1355 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1356 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1357 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1358 DebugLoc dl = MI->getDebugLoc();
1359 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1362 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1363 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1370 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1371 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1374 ZERO = Mips::ZERO_64;
1378 unsigned OldVal = MI->getOperand(0).getReg();
1379 unsigned Ptr = MI->getOperand(1).getReg();
1380 unsigned Incr = MI->getOperand(2).getReg();
1382 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1383 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1384 unsigned Success = RegInfo.createVirtualRegister(RC);
1386 // insert new blocks after the current block
1387 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1388 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1389 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1390 MachineFunction::iterator It = BB;
1392 MF->insert(It, loopMBB);
1393 MF->insert(It, exitMBB);
1395 // Transfer the remainder of BB and its successor edges to exitMBB.
1396 exitMBB->splice(exitMBB->begin(), BB,
1397 llvm::next(MachineBasicBlock::iterator(MI)),
1399 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1403 // fallthrough --> loopMBB
1404 BB->addSuccessor(loopMBB);
1405 loopMBB->addSuccessor(loopMBB);
1406 loopMBB->addSuccessor(exitMBB);
1409 // ll oldval, 0(ptr)
1410 // <binop> storeval, oldval, incr
1411 // sc success, storeval, 0(ptr)
1412 // beq success, $0, loopMBB
1414 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1416 // and andres, oldval, incr
1417 // nor storeval, $0, andres
1418 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1419 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1420 } else if (BinOpcode) {
1421 // <binop> storeval, oldval, incr
1422 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1426 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1427 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1429 MI->eraseFromParent(); // The instruction is gone now.
1435 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1436 MachineBasicBlock *BB,
1437 unsigned Size, unsigned BinOpcode,
1439 assert((Size == 1 || Size == 2) &&
1440 "Unsupported size for EmitAtomicBinaryPartial.");
1442 MachineFunction *MF = BB->getParent();
1443 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1444 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1445 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1446 DebugLoc dl = MI->getDebugLoc();
1447 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1448 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1450 unsigned Dest = MI->getOperand(0).getReg();
1451 unsigned Ptr = MI->getOperand(1).getReg();
1452 unsigned Incr = MI->getOperand(2).getReg();
1454 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1455 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1456 unsigned Mask = RegInfo.createVirtualRegister(RC);
1457 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1458 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1459 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1460 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1461 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1462 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1463 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1464 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1465 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1466 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1467 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1468 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1469 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1470 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1471 unsigned Success = RegInfo.createVirtualRegister(RC);
1473 // insert new blocks after the current block
1474 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1475 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1476 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1477 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1478 MachineFunction::iterator It = BB;
1480 MF->insert(It, loopMBB);
1481 MF->insert(It, sinkMBB);
1482 MF->insert(It, exitMBB);
1484 // Transfer the remainder of BB and its successor edges to exitMBB.
1485 exitMBB->splice(exitMBB->begin(), BB,
1486 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1487 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1489 BB->addSuccessor(loopMBB);
1490 loopMBB->addSuccessor(loopMBB);
1491 loopMBB->addSuccessor(sinkMBB);
1492 sinkMBB->addSuccessor(exitMBB);
1495 // addiu masklsb2,$0,-4 # 0xfffffffc
1496 // and alignedaddr,ptr,masklsb2
1497 // andi ptrlsb2,ptr,3
1498 // sll shiftamt,ptrlsb2,3
1499 // ori maskupper,$0,255 # 0xff
1500 // sll mask,maskupper,shiftamt
1501 // nor mask2,$0,mask
1502 // sll incr2,incr,shiftamt
1504 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1505 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1506 .addReg(Mips::ZERO).addImm(-4);
1507 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1508 .addReg(Ptr).addReg(MaskLSB2);
1509 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1510 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1511 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1512 .addReg(Mips::ZERO).addImm(MaskImm);
1513 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1514 .addReg(ShiftAmt).addReg(MaskUpper);
1515 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1516 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1518 // atomic.load.binop
1520 // ll oldval,0(alignedaddr)
1521 // binop binopres,oldval,incr2
1522 // and newval,binopres,mask
1523 // and maskedoldval0,oldval,mask2
1524 // or storeval,maskedoldval0,newval
1525 // sc success,storeval,0(alignedaddr)
1526 // beq success,$0,loopMBB
1530 // ll oldval,0(alignedaddr)
1531 // and newval,incr2,mask
1532 // and maskedoldval0,oldval,mask2
1533 // or storeval,maskedoldval0,newval
1534 // sc success,storeval,0(alignedaddr)
1535 // beq success,$0,loopMBB
1538 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1540 // and andres, oldval, incr2
1541 // nor binopres, $0, andres
1542 // and newval, binopres, mask
1543 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1544 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1545 .addReg(Mips::ZERO).addReg(AndRes);
1546 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1547 } else if (BinOpcode) {
1548 // <binop> binopres, oldval, incr2
1549 // and newval, binopres, mask
1550 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1551 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1552 } else {// atomic.swap
1553 // and newval, incr2, mask
1554 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1557 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1558 .addReg(OldVal).addReg(Mask2);
1559 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1560 .addReg(MaskedOldVal0).addReg(NewVal);
1561 BuildMI(BB, dl, TII->get(SC), Success)
1562 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1563 BuildMI(BB, dl, TII->get(Mips::BEQ))
1564 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1567 // and maskedoldval1,oldval,mask
1568 // srl srlres,maskedoldval1,shiftamt
1569 // sll sllres,srlres,24
1570 // sra dest,sllres,24
1572 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1574 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1575 .addReg(OldVal).addReg(Mask);
1576 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1577 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1578 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1579 .addReg(SrlRes).addImm(ShiftImm);
1580 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1581 .addReg(SllRes).addImm(ShiftImm);
1583 MI->eraseFromParent(); // The instruction is gone now.
1589 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1590 MachineBasicBlock *BB,
1591 unsigned Size) const {
1592 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1594 MachineFunction *MF = BB->getParent();
1595 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1596 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1597 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1598 DebugLoc dl = MI->getDebugLoc();
1599 unsigned LL, SC, ZERO, BNE, BEQ;
1602 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1603 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1609 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1610 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1611 ZERO = Mips::ZERO_64;
1616 unsigned Dest = MI->getOperand(0).getReg();
1617 unsigned Ptr = MI->getOperand(1).getReg();
1618 unsigned OldVal = MI->getOperand(2).getReg();
1619 unsigned NewVal = MI->getOperand(3).getReg();
1621 unsigned Success = RegInfo.createVirtualRegister(RC);
1623 // insert new blocks after the current block
1624 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1625 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1626 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1627 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1628 MachineFunction::iterator It = BB;
1630 MF->insert(It, loop1MBB);
1631 MF->insert(It, loop2MBB);
1632 MF->insert(It, exitMBB);
1634 // Transfer the remainder of BB and its successor edges to exitMBB.
1635 exitMBB->splice(exitMBB->begin(), BB,
1636 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1637 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1641 // fallthrough --> loop1MBB
1642 BB->addSuccessor(loop1MBB);
1643 loop1MBB->addSuccessor(exitMBB);
1644 loop1MBB->addSuccessor(loop2MBB);
1645 loop2MBB->addSuccessor(loop1MBB);
1646 loop2MBB->addSuccessor(exitMBB);
1650 // bne dest, oldval, exitMBB
1652 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1653 BuildMI(BB, dl, TII->get(BNE))
1654 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1657 // sc success, newval, 0(ptr)
1658 // beq success, $0, loop1MBB
1660 BuildMI(BB, dl, TII->get(SC), Success)
1661 .addReg(NewVal).addReg(Ptr).addImm(0);
1662 BuildMI(BB, dl, TII->get(BEQ))
1663 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1665 MI->eraseFromParent(); // The instruction is gone now.
1671 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1672 MachineBasicBlock *BB,
1673 unsigned Size) const {
1674 assert((Size == 1 || Size == 2) &&
1675 "Unsupported size for EmitAtomicCmpSwapPartial.");
1677 MachineFunction *MF = BB->getParent();
1678 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1679 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1680 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1681 DebugLoc dl = MI->getDebugLoc();
1682 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1683 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1685 unsigned Dest = MI->getOperand(0).getReg();
1686 unsigned Ptr = MI->getOperand(1).getReg();
1687 unsigned CmpVal = MI->getOperand(2).getReg();
1688 unsigned NewVal = MI->getOperand(3).getReg();
1690 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1691 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1692 unsigned Mask = RegInfo.createVirtualRegister(RC);
1693 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1694 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1695 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1696 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1697 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1698 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1699 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1700 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1701 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1702 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1703 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1704 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1705 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1706 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1707 unsigned Success = RegInfo.createVirtualRegister(RC);
1709 // insert new blocks after the current block
1710 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1711 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1712 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1713 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1714 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1715 MachineFunction::iterator It = BB;
1717 MF->insert(It, loop1MBB);
1718 MF->insert(It, loop2MBB);
1719 MF->insert(It, sinkMBB);
1720 MF->insert(It, exitMBB);
1722 // Transfer the remainder of BB and its successor edges to exitMBB.
1723 exitMBB->splice(exitMBB->begin(), BB,
1724 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1725 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1727 BB->addSuccessor(loop1MBB);
1728 loop1MBB->addSuccessor(sinkMBB);
1729 loop1MBB->addSuccessor(loop2MBB);
1730 loop2MBB->addSuccessor(loop1MBB);
1731 loop2MBB->addSuccessor(sinkMBB);
1732 sinkMBB->addSuccessor(exitMBB);
1734 // FIXME: computation of newval2 can be moved to loop2MBB.
1736 // addiu masklsb2,$0,-4 # 0xfffffffc
1737 // and alignedaddr,ptr,masklsb2
1738 // andi ptrlsb2,ptr,3
1739 // sll shiftamt,ptrlsb2,3
1740 // ori maskupper,$0,255 # 0xff
1741 // sll mask,maskupper,shiftamt
1742 // nor mask2,$0,mask
1743 // andi maskedcmpval,cmpval,255
1744 // sll shiftedcmpval,maskedcmpval,shiftamt
1745 // andi maskednewval,newval,255
1746 // sll shiftednewval,maskednewval,shiftamt
1747 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1748 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1749 .addReg(Mips::ZERO).addImm(-4);
1750 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1751 .addReg(Ptr).addReg(MaskLSB2);
1752 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1753 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1754 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1755 .addReg(Mips::ZERO).addImm(MaskImm);
1756 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1757 .addReg(ShiftAmt).addReg(MaskUpper);
1758 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1759 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1760 .addReg(CmpVal).addImm(MaskImm);
1761 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1762 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1763 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1764 .addReg(NewVal).addImm(MaskImm);
1765 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1766 .addReg(ShiftAmt).addReg(MaskedNewVal);
1769 // ll oldval,0(alginedaddr)
1770 // and maskedoldval0,oldval,mask
1771 // bne maskedoldval0,shiftedcmpval,sinkMBB
1773 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1774 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1775 .addReg(OldVal).addReg(Mask);
1776 BuildMI(BB, dl, TII->get(Mips::BNE))
1777 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1780 // and maskedoldval1,oldval,mask2
1781 // or storeval,maskedoldval1,shiftednewval
1782 // sc success,storeval,0(alignedaddr)
1783 // beq success,$0,loop1MBB
1785 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1786 .addReg(OldVal).addReg(Mask2);
1787 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1788 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1789 BuildMI(BB, dl, TII->get(SC), Success)
1790 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1791 BuildMI(BB, dl, TII->get(Mips::BEQ))
1792 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1795 // srl srlres,maskedoldval0,shiftamt
1796 // sll sllres,srlres,24
1797 // sra dest,sllres,24
1799 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1801 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1802 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1803 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1804 .addReg(SrlRes).addImm(ShiftImm);
1805 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1806 .addReg(SllRes).addImm(ShiftImm);
1808 MI->eraseFromParent(); // The instruction is gone now.
1813 //===----------------------------------------------------------------------===//
1814 // Misc Lower Operation implementation
1815 //===----------------------------------------------------------------------===//
1816 SDValue MipsTargetLowering::
1817 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1819 // The first operand is the chain, the second is the condition, the third is
1820 // the block to branch to if the condition is true.
1821 SDValue Chain = Op.getOperand(0);
1822 SDValue Dest = Op.getOperand(2);
1823 DebugLoc dl = Op.getDebugLoc();
1825 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1827 // Return if flag is not set by a floating point comparison.
1828 if (CondRes.getOpcode() != MipsISD::FPCmp)
1831 SDValue CCNode = CondRes.getOperand(2);
1833 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1834 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1836 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1840 SDValue MipsTargetLowering::
1841 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1843 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1845 // Return if flag is not set by a floating point comparison.
1846 if (Cond.getOpcode() != MipsISD::FPCmp)
1849 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1853 SDValue MipsTargetLowering::
1854 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1856 DebugLoc DL = Op.getDebugLoc();
1857 EVT Ty = Op.getOperand(0).getValueType();
1858 SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1859 Op.getOperand(0), Op.getOperand(1),
1862 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1866 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1867 SDValue Cond = CreateFPCmp(DAG, Op);
1869 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1870 "Floating point operand expected.");
1872 SDValue True = DAG.getConstant(1, MVT::i32);
1873 SDValue False = DAG.getConstant(0, MVT::i32);
1875 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1878 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1879 SelectionDAG &DAG) const {
1880 // FIXME there isn't actually debug info here
1881 DebugLoc dl = Op.getDebugLoc();
1882 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1884 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1885 const MipsTargetObjectFile &TLOF =
1886 (const MipsTargetObjectFile&)getObjFileLowering();
1888 // %gp_rel relocation
1889 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1890 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1892 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl,
1893 DAG.getVTList(MVT::i32), &GA, 1);
1894 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1895 return DAG.getNode(ISD::ADD, dl, MVT::i32, GPReg, GPRelNode);
1898 // %hi/%lo relocation
1899 return getAddrNonPIC(Op, DAG);
1902 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1903 return getAddrLocal(Op, DAG, HasMips64);
1906 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1907 MipsII::MO_GOT_LO16);
1909 return getAddrGlobal(Op, DAG,
1910 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1913 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1914 SelectionDAG &DAG) const {
1915 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1916 return getAddrNonPIC(Op, DAG);
1918 return getAddrLocal(Op, DAG, HasMips64);
1921 SDValue MipsTargetLowering::
1922 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1924 // If the relocation model is PIC, use the General Dynamic TLS Model or
1925 // Local Dynamic TLS model, otherwise use the Initial Exec or
1926 // Local Exec TLS Model.
1928 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1929 DebugLoc dl = GA->getDebugLoc();
1930 const GlobalValue *GV = GA->getGlobal();
1931 EVT PtrVT = getPointerTy();
1933 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1935 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1936 // General Dynamic and Local Dynamic TLS Model.
1937 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1940 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1941 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1942 GetGlobalReg(DAG, PtrVT), TGA);
1943 unsigned PtrSize = PtrVT.getSizeInBits();
1944 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1946 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1950 Entry.Node = Argument;
1952 Args.push_back(Entry);
1954 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1955 false, false, false, false, 0, CallingConv::C,
1956 /*isTailCall=*/false, /*doesNotRet=*/false,
1957 /*isReturnValueUsed=*/true,
1958 TlsGetAddr, Args, DAG, dl);
1959 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1961 SDValue Ret = CallResult.first;
1963 if (model != TLSModel::LocalDynamic)
1966 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1967 MipsII::MO_DTPREL_HI);
1968 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1969 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1970 MipsII::MO_DTPREL_LO);
1971 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1972 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1973 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1977 if (model == TLSModel::InitialExec) {
1978 // Initial Exec TLS Model
1979 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1980 MipsII::MO_GOTTPREL);
1981 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1983 Offset = DAG.getLoad(PtrVT, dl,
1984 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1985 false, false, false, 0);
1987 // Local Exec TLS Model
1988 assert(model == TLSModel::LocalExec);
1989 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1990 MipsII::MO_TPREL_HI);
1991 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1992 MipsII::MO_TPREL_LO);
1993 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1994 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1995 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1998 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1999 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
2002 SDValue MipsTargetLowering::
2003 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2005 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2006 return getAddrNonPIC(Op, DAG);
2008 return getAddrLocal(Op, DAG, HasMips64);
2011 SDValue MipsTargetLowering::
2012 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2014 // gp_rel relocation
2015 // FIXME: we should reference the constant pool using small data sections,
2016 // but the asm printer currently doesn't support this feature without
2017 // hacking it. This feature should come soon so we can uncomment the
2019 //if (IsInSmallSection(C->getType())) {
2020 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
2021 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
2022 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
2024 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2025 return getAddrNonPIC(Op, DAG);
2027 return getAddrLocal(Op, DAG, HasMips64);
2030 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2031 MachineFunction &MF = DAG.getMachineFunction();
2032 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2034 DebugLoc dl = Op.getDebugLoc();
2035 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2038 // vastart just stores the address of the VarArgsFrameIndex slot into the
2039 // memory location argument.
2040 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2041 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
2042 MachinePointerInfo(SV), false, false, 0);
2045 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2046 EVT TyX = Op.getOperand(0).getValueType();
2047 EVT TyY = Op.getOperand(1).getValueType();
2048 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2049 SDValue Const31 = DAG.getConstant(31, MVT::i32);
2050 DebugLoc DL = Op.getDebugLoc();
2053 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2055 SDValue X = (TyX == MVT::f32) ?
2056 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2057 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2059 SDValue Y = (TyY == MVT::f32) ?
2060 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2061 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2065 // ext E, Y, 31, 1 ; extract bit31 of Y
2066 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2067 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2068 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2071 // srl SrlX, SllX, 1
2073 // sll SllY, SrlX, 31
2074 // or Or, SrlX, SllY
2075 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2076 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2077 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2078 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2079 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2082 if (TyX == MVT::f32)
2083 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2085 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2086 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2087 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2090 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2091 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2092 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2093 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2094 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2095 DebugLoc DL = Op.getDebugLoc();
2097 // Bitcast to integer nodes.
2098 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2099 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2102 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2103 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2104 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2105 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
2107 if (WidthX > WidthY)
2108 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2109 else if (WidthY > WidthX)
2110 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2112 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2113 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2114 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2117 // (d)sll SllX, X, 1
2118 // (d)srl SrlX, SllX, 1
2119 // (d)srl SrlY, Y, width(Y)-1
2120 // (d)sll SllY, SrlX, width(Y)-1
2121 // or Or, SrlX, SllY
2122 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2123 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2124 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2125 DAG.getConstant(WidthY - 1, MVT::i32));
2127 if (WidthX > WidthY)
2128 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2129 else if (WidthY > WidthX)
2130 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2132 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2133 DAG.getConstant(WidthX - 1, MVT::i32));
2134 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2135 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2139 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2140 if (Subtarget->hasMips64())
2141 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
2143 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
2146 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2147 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2148 DebugLoc DL = Op.getDebugLoc();
2150 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2152 SDValue X = (Op.getValueType() == MVT::f32) ?
2153 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2154 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2159 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2160 DAG.getRegister(Mips::ZERO, MVT::i32),
2161 DAG.getConstant(31, MVT::i32), Const1, X);
2163 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2164 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2167 if (Op.getValueType() == MVT::f32)
2168 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2170 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2171 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2172 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2175 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2176 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2177 DebugLoc DL = Op.getDebugLoc();
2179 // Bitcast to integer node.
2180 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2184 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2185 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2186 DAG.getConstant(63, MVT::i32), Const1, X);
2188 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2189 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2192 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2196 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
2197 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2198 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2200 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2203 SDValue MipsTargetLowering::
2204 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2206 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2207 "Frame address can only be determined for current frame.");
2209 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2210 MFI->setFrameAddressIsTaken(true);
2211 EVT VT = Op.getValueType();
2212 DebugLoc dl = Op.getDebugLoc();
2213 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2214 IsN64 ? Mips::FP_64 : Mips::FP, VT);
2218 SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2219 SelectionDAG &DAG) const {
2221 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2222 "Return address can be determined only for current frame.");
2224 MachineFunction &MF = DAG.getMachineFunction();
2225 MachineFrameInfo *MFI = MF.getFrameInfo();
2226 MVT VT = Op.getSimpleValueType();
2227 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2228 MFI->setReturnAddressIsTaken(true);
2230 // Return RA, which contains the return address. Mark it an implicit live-in.
2231 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2232 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2235 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2236 // generated from __builtin_eh_return (offset, handler)
2237 // The effect of this is to adjust the stack pointer by "offset"
2238 // and then branch to "handler".
2239 SDValue MipsTargetLowering::LowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2241 MachineFunction &MF = DAG.getMachineFunction();
2242 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2244 MipsFI->setCallsEhReturn();
2245 SDValue Chain = Op.getOperand(0);
2246 SDValue Offset = Op.getOperand(1);
2247 SDValue Handler = Op.getOperand(2);
2248 DebugLoc DL = Op.getDebugLoc();
2249 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2251 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2252 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2253 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
2254 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
2255 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2256 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2257 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2258 DAG.getRegister(OffsetReg, Ty),
2259 DAG.getRegister(AddrReg, getPointerTy()),
2263 // TODO: set SType according to the desired memory barrier behavior.
2265 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2267 DebugLoc dl = Op.getDebugLoc();
2268 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2269 DAG.getConstant(SType, MVT::i32));
2272 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2273 SelectionDAG &DAG) const {
2274 // FIXME: Need pseudo-fence for 'singlethread' fences
2275 // FIXME: Set SType for weaker fences where supported/appropriate.
2277 DebugLoc dl = Op.getDebugLoc();
2278 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2279 DAG.getConstant(SType, MVT::i32));
2282 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2283 SelectionDAG &DAG) const {
2284 DebugLoc DL = Op.getDebugLoc();
2285 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2286 SDValue Shamt = Op.getOperand(2);
2289 // lo = (shl lo, shamt)
2290 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2293 // hi = (shl lo, shamt[4:0])
2294 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2295 DAG.getConstant(-1, MVT::i32));
2296 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2297 DAG.getConstant(1, MVT::i32));
2298 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2300 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2301 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2302 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2303 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2304 DAG.getConstant(0x20, MVT::i32));
2305 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2306 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2307 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2309 SDValue Ops[2] = {Lo, Hi};
2310 return DAG.getMergeValues(Ops, 2, DL);
2313 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2315 DebugLoc DL = Op.getDebugLoc();
2316 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2317 SDValue Shamt = Op.getOperand(2);
2320 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2322 // hi = (sra hi, shamt)
2324 // hi = (srl hi, shamt)
2327 // lo = (sra hi, shamt[4:0])
2328 // hi = (sra hi, 31)
2330 // lo = (srl hi, shamt[4:0])
2332 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2333 DAG.getConstant(-1, MVT::i32));
2334 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2335 DAG.getConstant(1, MVT::i32));
2336 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2337 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2338 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2339 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2341 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2342 DAG.getConstant(0x20, MVT::i32));
2343 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2344 DAG.getConstant(31, MVT::i32));
2345 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2346 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2347 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2350 SDValue Ops[2] = {Lo, Hi};
2351 return DAG.getMergeValues(Ops, 2, DL);
2354 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2355 SDValue Chain, SDValue Src, unsigned Offset) {
2356 SDValue Ptr = LD->getBasePtr();
2357 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2358 EVT BasePtrVT = Ptr.getValueType();
2359 DebugLoc DL = LD->getDebugLoc();
2360 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2363 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2364 DAG.getConstant(Offset, BasePtrVT));
2366 SDValue Ops[] = { Chain, Ptr, Src };
2367 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2368 LD->getMemOperand());
2371 // Expand an unaligned 32 or 64-bit integer load node.
2372 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2373 LoadSDNode *LD = cast<LoadSDNode>(Op);
2374 EVT MemVT = LD->getMemoryVT();
2376 // Return if load is aligned or if MemVT is neither i32 nor i64.
2377 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2378 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2381 bool IsLittle = Subtarget->isLittle();
2382 EVT VT = Op.getValueType();
2383 ISD::LoadExtType ExtType = LD->getExtensionType();
2384 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2386 assert((VT == MVT::i32) || (VT == MVT::i64));
2389 // (set dst, (i64 (load baseptr)))
2391 // (set tmp, (ldl (add baseptr, 7), undef))
2392 // (set dst, (ldr baseptr, tmp))
2393 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2394 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2396 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2400 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2402 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2406 // (set dst, (i32 (load baseptr))) or
2407 // (set dst, (i64 (sextload baseptr))) or
2408 // (set dst, (i64 (extload baseptr)))
2410 // (set tmp, (lwl (add baseptr, 3), undef))
2411 // (set dst, (lwr baseptr, tmp))
2412 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2413 (ExtType == ISD::EXTLOAD))
2416 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2419 // (set dst, (i64 (zextload baseptr)))
2421 // (set tmp0, (lwl (add baseptr, 3), undef))
2422 // (set tmp1, (lwr baseptr, tmp0))
2423 // (set tmp2, (shl tmp1, 32))
2424 // (set dst, (srl tmp2, 32))
2425 DebugLoc DL = LD->getDebugLoc();
2426 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2427 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2428 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2429 SDValue Ops[] = { SRL, LWR.getValue(1) };
2430 return DAG.getMergeValues(Ops, 2, DL);
2433 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2434 SDValue Chain, unsigned Offset) {
2435 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2436 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2437 DebugLoc DL = SD->getDebugLoc();
2438 SDVTList VTList = DAG.getVTList(MVT::Other);
2441 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2442 DAG.getConstant(Offset, BasePtrVT));
2444 SDValue Ops[] = { Chain, Value, Ptr };
2445 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2446 SD->getMemOperand());
2449 // Expand an unaligned 32 or 64-bit integer store node.
2450 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2451 StoreSDNode *SD = cast<StoreSDNode>(Op);
2452 EVT MemVT = SD->getMemoryVT();
2454 // Return if store is aligned or if MemVT is neither i32 nor i64.
2455 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2456 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2459 bool IsLittle = Subtarget->isLittle();
2460 SDValue Value = SD->getValue(), Chain = SD->getChain();
2461 EVT VT = Value.getValueType();
2464 // (store val, baseptr) or
2465 // (truncstore val, baseptr)
2467 // (swl val, (add baseptr, 3))
2468 // (swr val, baseptr)
2469 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2470 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2472 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2475 assert(VT == MVT::i64);
2478 // (store val, baseptr)
2480 // (sdl val, (add baseptr, 7))
2481 // (sdr val, baseptr)
2482 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2483 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2486 // This function expands mips intrinsic nodes which have 64-bit input operands
2487 // or output values.
2489 // out64 = intrinsic-node in64
2491 // lo = copy (extract-element (in64, 0))
2492 // hi = copy (extract-element (in64, 1))
2493 // mips-specific-node
2496 // out64 = merge-values (v0, v1)
2498 static SDValue LowerDSPIntr(SDValue Op, SelectionDAG &DAG,
2499 unsigned Opc, bool HasI64In, bool HasI64Out) {
2500 DebugLoc DL = Op.getDebugLoc();
2501 bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
2502 SDValue Chain = HasChainIn ? Op->getOperand(0) : DAG.getEntryNode();
2503 SmallVector<SDValue, 3> Ops;
2506 SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2507 Op->getOperand(1 + HasChainIn),
2508 DAG.getConstant(0, MVT::i32));
2509 SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2510 Op->getOperand(1 + HasChainIn),
2511 DAG.getConstant(1, MVT::i32));
2513 Chain = DAG.getCopyToReg(Chain, DL, Mips::LO, InLo, SDValue());
2514 Chain = DAG.getCopyToReg(Chain, DL, Mips::HI, InHi, Chain.getValue(1));
2516 Ops.push_back(Chain);
2517 Ops.append(Op->op_begin() + HasChainIn + 2, Op->op_end());
2518 Ops.push_back(Chain.getValue(1));
2520 Ops.push_back(Chain);
2521 Ops.append(Op->op_begin() + HasChainIn + 1, Op->op_end());
2525 return DAG.getNode(Opc, DL, Op->value_begin(), Op->getNumValues(),
2526 Ops.begin(), Ops.size());
2528 SDValue Intr = DAG.getNode(Opc, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2529 Ops.begin(), Ops.size());
2530 SDValue OutLo = DAG.getCopyFromReg(Intr.getValue(0), DL, Mips::LO, MVT::i32,
2532 SDValue OutHi = DAG.getCopyFromReg(OutLo.getValue(1), DL, Mips::HI, MVT::i32,
2534 SDValue Out = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, OutLo, OutHi);
2539 SDValue Vals[] = { Out, OutHi.getValue(1) };
2540 return DAG.getMergeValues(Vals, 2, DL);
2543 SDValue MipsTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2544 SelectionDAG &DAG) const {
2545 switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
2548 case Intrinsic::mips_shilo:
2549 return LowerDSPIntr(Op, DAG, MipsISD::SHILO, true, true);
2550 case Intrinsic::mips_dpau_h_qbl:
2551 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL, true, true);
2552 case Intrinsic::mips_dpau_h_qbr:
2553 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR, true, true);
2554 case Intrinsic::mips_dpsu_h_qbl:
2555 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL, true, true);
2556 case Intrinsic::mips_dpsu_h_qbr:
2557 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR, true, true);
2558 case Intrinsic::mips_dpa_w_ph:
2559 return LowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH, true, true);
2560 case Intrinsic::mips_dps_w_ph:
2561 return LowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH, true, true);
2562 case Intrinsic::mips_dpax_w_ph:
2563 return LowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH, true, true);
2564 case Intrinsic::mips_dpsx_w_ph:
2565 return LowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH, true, true);
2566 case Intrinsic::mips_mulsa_w_ph:
2567 return LowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH, true, true);
2568 case Intrinsic::mips_mult:
2569 return LowerDSPIntr(Op, DAG, MipsISD::MULT, false, true);
2570 case Intrinsic::mips_multu:
2571 return LowerDSPIntr(Op, DAG, MipsISD::MULTU, false, true);
2572 case Intrinsic::mips_madd:
2573 return LowerDSPIntr(Op, DAG, MipsISD::MADD_DSP, true, true);
2574 case Intrinsic::mips_maddu:
2575 return LowerDSPIntr(Op, DAG, MipsISD::MADDU_DSP, true, true);
2576 case Intrinsic::mips_msub:
2577 return LowerDSPIntr(Op, DAG, MipsISD::MSUB_DSP, true, true);
2578 case Intrinsic::mips_msubu:
2579 return LowerDSPIntr(Op, DAG, MipsISD::MSUBU_DSP, true, true);
2583 SDValue MipsTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2584 SelectionDAG &DAG) const {
2585 switch (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue()) {
2588 case Intrinsic::mips_extp:
2589 return LowerDSPIntr(Op, DAG, MipsISD::EXTP, true, false);
2590 case Intrinsic::mips_extpdp:
2591 return LowerDSPIntr(Op, DAG, MipsISD::EXTPDP, true, false);
2592 case Intrinsic::mips_extr_w:
2593 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_W, true, false);
2594 case Intrinsic::mips_extr_r_w:
2595 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W, true, false);
2596 case Intrinsic::mips_extr_rs_w:
2597 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W, true, false);
2598 case Intrinsic::mips_extr_s_h:
2599 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H, true, false);
2600 case Intrinsic::mips_mthlip:
2601 return LowerDSPIntr(Op, DAG, MipsISD::MTHLIP, true, true);
2602 case Intrinsic::mips_mulsaq_s_w_ph:
2603 return LowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH, true, true);
2604 case Intrinsic::mips_maq_s_w_phl:
2605 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL, true, true);
2606 case Intrinsic::mips_maq_s_w_phr:
2607 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR, true, true);
2608 case Intrinsic::mips_maq_sa_w_phl:
2609 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL, true, true);
2610 case Intrinsic::mips_maq_sa_w_phr:
2611 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR, true, true);
2612 case Intrinsic::mips_dpaq_s_w_ph:
2613 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH, true, true);
2614 case Intrinsic::mips_dpsq_s_w_ph:
2615 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH, true, true);
2616 case Intrinsic::mips_dpaq_sa_l_w:
2617 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W, true, true);
2618 case Intrinsic::mips_dpsq_sa_l_w:
2619 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W, true, true);
2620 case Intrinsic::mips_dpaqx_s_w_ph:
2621 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH, true, true);
2622 case Intrinsic::mips_dpaqx_sa_w_ph:
2623 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH, true, true);
2624 case Intrinsic::mips_dpsqx_s_w_ph:
2625 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH, true, true);
2626 case Intrinsic::mips_dpsqx_sa_w_ph:
2627 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH, true, true);
2631 SDValue MipsTargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
2632 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2633 || cast<ConstantSDNode>
2634 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2635 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2639 // (add (frameaddr 0), (frame_to_args_offset))
2640 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2641 // (add FrameObject, 0)
2642 // where FrameObject is a fixed StackObject with offset 0 which points to
2643 // the old stack pointer.
2644 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2645 EVT ValTy = Op->getValueType(0);
2646 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2647 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2648 return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2649 DAG.getConstant(0, ValTy));
2652 //===----------------------------------------------------------------------===//
2653 // Calling Convention Implementation
2654 //===----------------------------------------------------------------------===//
2656 //===----------------------------------------------------------------------===//
2657 // TODO: Implement a generic logic using tblgen that can support this.
2658 // Mips O32 ABI rules:
2660 // i32 - Passed in A0, A1, A2, A3 and stack
2661 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2662 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2663 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2664 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2665 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2668 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2669 //===----------------------------------------------------------------------===//
2671 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2672 MVT LocVT, CCValAssign::LocInfo LocInfo,
2673 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2675 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2677 static const uint16_t IntRegs[] = {
2678 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2680 static const uint16_t F32Regs[] = {
2681 Mips::F12, Mips::F14
2683 static const uint16_t F64Regs[] = {
2687 // Do not process byval args here.
2688 if (ArgFlags.isByVal())
2691 // Promote i8 and i16
2692 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2694 if (ArgFlags.isSExt())
2695 LocInfo = CCValAssign::SExt;
2696 else if (ArgFlags.isZExt())
2697 LocInfo = CCValAssign::ZExt;
2699 LocInfo = CCValAssign::AExt;
2704 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2705 // is true: function is vararg, argument is 3rd or higher, there is previous
2706 // argument which is not f32 or f64.
2707 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2708 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2709 unsigned OrigAlign = ArgFlags.getOrigAlign();
2710 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2712 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2713 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2714 // If this is the first part of an i64 arg,
2715 // the allocated register must be either A0 or A2.
2716 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2717 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2719 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2720 // Allocate int register and shadow next int register. If first
2721 // available register is Mips::A1 or Mips::A3, shadow it too.
2722 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2723 if (Reg == Mips::A1 || Reg == Mips::A3)
2724 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2725 State.AllocateReg(IntRegs, IntRegsSize);
2727 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2728 // we are guaranteed to find an available float register
2729 if (ValVT == MVT::f32) {
2730 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2731 // Shadow int register
2732 State.AllocateReg(IntRegs, IntRegsSize);
2734 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2735 // Shadow int registers
2736 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2737 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2738 State.AllocateReg(IntRegs, IntRegsSize);
2739 State.AllocateReg(IntRegs, IntRegsSize);
2742 llvm_unreachable("Cannot handle this ValVT.");
2745 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2747 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2749 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2754 #include "MipsGenCallingConv.inc"
2756 //===----------------------------------------------------------------------===//
2757 // Call Calling Convention Implementation
2758 //===----------------------------------------------------------------------===//
2760 static const unsigned O32IntRegsSize = 4;
2762 // Return next O32 integer argument register.
2763 static unsigned getNextIntArgReg(unsigned Reg) {
2764 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2765 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2768 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2769 /// for tail call optimization.
2770 bool MipsTargetLowering::
2771 IsEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
2772 unsigned NextStackOffset,
2773 const MipsFunctionInfo& FI) const {
2774 if (!EnableMipsTailCalls)
2777 // No tail call optimization for mips16.
2778 if (Subtarget->inMips16Mode())
2781 // Return false if either the callee or caller has a byval argument.
2782 if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
2785 // Return true if the callee's argument area is no larger than the
2787 return NextStackOffset <= FI.getIncomingArgSize();
2791 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2792 SDValue Chain, SDValue Arg, DebugLoc DL,
2793 bool IsTailCall, SelectionDAG &DAG) const {
2795 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2796 DAG.getIntPtrConstant(Offset));
2797 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2801 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2802 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2803 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2804 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2805 /*isVolatile=*/ true, false, 0);
2809 // The Mips16 hard float is a crazy quilt inherited from gcc. I have a much
2810 // cleaner way to do all of this but it will have to wait until the traditional
2811 // gcc mechanism is completed.
2813 // For Pic, in order for Mips16 code to call Mips32 code which according the abi
2814 // have either arguments or returned values placed in floating point registers,
2815 // we use a set of helper functions. (This includes functions which return type
2816 // complex which on Mips are returned in a pair of floating point registers).
2818 // This is an encoding that we inherited from gcc.
2819 // In Mips traditional O32, N32 ABI, floating point numbers are passed in
2820 // floating point argument registers 1,2 only when the first and optionally
2821 // the second arguments are float (sf) or double (df).
2822 // For Mips16 we are only concerned with the situations where floating point
2823 // arguments are being passed in floating point registers by the ABI, because
2824 // Mips16 mode code cannot execute floating point instructions to load those
2825 // values and hence helper functions are needed.
2826 // The possibilities are (), (sf), (sf, sf), (sf, df), (df), (df, sf), (df, df)
2827 // the helper function suffixs for these are:
2828 // 0, 1, 5, 9, 2, 6, 10
2829 // this suffix can then be calculated as follows:
2830 // for a given argument Arg:
2831 // Arg1x, Arg2x = 1 : Arg is sf
2833 // 0: Arg is neither sf or df
2834 // So this stub is the string for number Arg1x + Arg2x*4.
2835 // However not all numbers between 0 and 10 are possible, we check anyway and
2836 // assert if the impossible exists.
2839 unsigned int MipsTargetLowering::getMips16HelperFunctionStubNumber
2840 (ArgListTy &Args) const {
2841 unsigned int resultNum = 0;
2842 if (Args.size() >= 1) {
2843 Type *t = Args[0].Ty;
2844 if (t->isFloatTy()) {
2847 else if (t->isDoubleTy()) {
2852 if (Args.size() >=2) {
2853 Type *t = Args[1].Ty;
2854 if (t->isFloatTy()) {
2857 else if (t->isDoubleTy()) {
2866 // prefixs are attached to stub numbers depending on the return type .
2867 // return type: float sf_
2869 // single complex sc_
2870 // double complext dc_
2874 // The full name of a helper function is__mips16_call_stub +
2875 // return type dependent prefix + stub number
2878 // This is something that probably should be in a different source file and
2879 // perhaps done differently but my main purpose is to not waste runtime
2880 // on something that we can enumerate in the source. Another possibility is
2881 // to have a python script to generate these mapping tables. This will do
2882 // for now. There are a whole series of helper function mapping arrays, one
2883 // for each return type class as outlined above. There there are 11 possible
2884 // entries. Ones with 0 are ones which should never be selected
2886 // All the arrays are similar except for ones which return neither
2887 // sf, df, sc, dc, in which only care about ones which have sf or df as a
2890 #define P_ "__mips16_call_stub_"
2891 #define MAX_STUB_NUMBER 10
2892 #define T1 P "1", P "2", 0, 0, P "5", P "6", 0, 0, P "9", P "10"
2893 #define T P "0" , T1
2895 static char const * vMips16Helper[MAX_STUB_NUMBER+1] =
2899 static char const * sfMips16Helper[MAX_STUB_NUMBER+1] =
2903 static char const * dfMips16Helper[MAX_STUB_NUMBER+1] =
2907 static char const * scMips16Helper[MAX_STUB_NUMBER+1] =
2911 static char const * dcMips16Helper[MAX_STUB_NUMBER+1] =
2917 const char* MipsTargetLowering::
2918 getMips16HelperFunction
2919 (Type* RetTy, ArgListTy &Args, bool &needHelper) const {
2920 const unsigned int stubNum = getMips16HelperFunctionStubNumber(Args);
2922 const unsigned int maxStubNum = 10;
2923 assert(stubNum <= maxStubNum);
2924 const bool validStubNum[maxStubNum+1] =
2925 {true, true, true, false, false, true, true, false, false, true, true};
2926 assert(validStubNum[stubNum]);
2929 if (RetTy->isFloatTy()) {
2930 result = sfMips16Helper[stubNum];
2932 else if (RetTy ->isDoubleTy()) {
2933 result = dfMips16Helper[stubNum];
2935 else if (RetTy->isStructTy()) {
2936 // check if it's complex
2937 if (RetTy->getNumContainedTypes() == 2) {
2938 if ((RetTy->getContainedType(0)->isFloatTy()) &&
2939 (RetTy->getContainedType(1)->isFloatTy())) {
2940 result = scMips16Helper[stubNum];
2942 else if ((RetTy->getContainedType(0)->isDoubleTy()) &&
2943 (RetTy->getContainedType(1)->isDoubleTy())) {
2944 result = dcMips16Helper[stubNum];
2947 llvm_unreachable("Uncovered condition");
2951 llvm_unreachable("Uncovered condition");
2959 result = vMips16Helper[stubNum];
2965 /// LowerCall - functions arguments are copied from virtual regs to
2966 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2968 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2969 SmallVectorImpl<SDValue> &InVals) const {
2970 SelectionDAG &DAG = CLI.DAG;
2971 DebugLoc &dl = CLI.DL;
2972 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2973 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2974 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2975 SDValue Chain = CLI.Chain;
2976 SDValue Callee = CLI.Callee;
2977 bool &isTailCall = CLI.IsTailCall;
2978 CallingConv::ID CallConv = CLI.CallConv;
2979 bool isVarArg = CLI.IsVarArg;
2981 const char* mips16HelperFunction = 0;
2982 bool needMips16Helper = false;
2984 if (Subtarget->inMips16Mode() && getTargetMachine().Options.UseSoftFloat &&
2987 // currently we don't have symbols tagged with the mips16 or mips32
2988 // qualifier so we will assume that we don't know what kind it is.
2989 // and generate the helper
2991 bool lookupHelper = true;
2992 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2993 if (noHelperNeeded.find(S->getSymbol()) != noHelperNeeded.end()) {
2994 lookupHelper = false;
2997 if (lookupHelper) mips16HelperFunction =
2998 getMips16HelperFunction(CLI.RetTy, CLI.Args, needMips16Helper);
3001 MachineFunction &MF = DAG.getMachineFunction();
3002 MachineFrameInfo *MFI = MF.getFrameInfo();
3003 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
3004 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
3006 // Analyze operands of the call, assigning locations to each operand.
3007 SmallVector<CCValAssign, 16> ArgLocs;
3008 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3009 getTargetMachine(), ArgLocs, *DAG.getContext());
3010 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
3012 MipsCCInfo.analyzeCallOperands(Outs);
3014 // Get a count of how many bytes are to be pushed on the stack.
3015 unsigned NextStackOffset = CCInfo.getNextStackOffset();
3017 // Check if it's really possible to do a tail call.
3020 IsEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
3021 *MF.getInfo<MipsFunctionInfo>());
3026 // Chain is the output chain of the last Load/Store or CopyToReg node.
3027 // ByValChain is the output chain of the last Memcpy node created for copying
3028 // byval arguments to the stack.
3029 unsigned StackAlignment = TFL->getStackAlignment();
3030 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
3031 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
3034 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
3036 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl,
3037 IsN64 ? Mips::SP_64 : Mips::SP,
3040 // With EABI is it possible to have 16 args on registers.
3041 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
3042 SmallVector<SDValue, 8> MemOpChains;
3043 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3045 // Walk the register/memloc assignments, inserting copies/loads.
3046 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3047 SDValue Arg = OutVals[i];
3048 CCValAssign &VA = ArgLocs[i];
3049 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3050 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3053 if (Flags.isByVal()) {
3054 assert(Flags.getByValSize() &&
3055 "ByVal args of size 0 should have been ignored by front-end.");
3056 assert(ByValArg != MipsCCInfo.byval_end());
3057 assert(!isTailCall &&
3058 "Do not tail-call optimize if there is a byval argument.");
3059 passByValArg(Chain, dl, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3060 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
3065 // Promote the value if needed.
3066 switch (VA.getLocInfo()) {
3067 default: llvm_unreachable("Unknown loc info!");
3068 case CCValAssign::Full:
3069 if (VA.isRegLoc()) {
3070 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3071 (ValVT == MVT::f64 && LocVT == MVT::i64))
3072 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
3073 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3074 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3075 Arg, DAG.getConstant(0, MVT::i32));
3076 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
3077 Arg, DAG.getConstant(1, MVT::i32));
3078 if (!Subtarget->isLittle())
3080 unsigned LocRegLo = VA.getLocReg();
3081 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3082 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3083 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3088 case CCValAssign::SExt:
3089 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
3091 case CCValAssign::ZExt:
3092 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
3094 case CCValAssign::AExt:
3095 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
3099 // Arguments that can be passed on register must be kept at
3100 // RegsToPass vector
3101 if (VA.isRegLoc()) {
3102 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3106 // Register can't get to this point...
3107 assert(VA.isMemLoc());
3109 // emit ISD::STORE whichs stores the
3110 // parameter value to a stack Location
3111 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3112 Chain, Arg, dl, isTailCall, DAG));
3115 // Transform all store nodes into one single node because all store
3116 // nodes are independent of each other.
3117 if (!MemOpChains.empty())
3118 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3119 &MemOpChains[0], MemOpChains.size());
3121 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3122 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3123 // node so that legalize doesn't hack it.
3124 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
3125 bool GlobalOrExternal = false, InternalLinkage = false;
3128 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3130 InternalLinkage = G->getGlobal()->hasInternalLinkage();
3132 if (InternalLinkage)
3133 Callee = getAddrLocal(Callee, DAG, HasMips64);
3135 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3136 MipsII::MO_CALL_LO16);
3138 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3140 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
3141 MipsII::MO_NO_FLAG);
3142 GlobalOrExternal = true;
3144 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3145 if (!IsN64 && !IsPIC) // !N64 && static
3146 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3147 MipsII::MO_NO_FLAG);
3149 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3150 MipsII::MO_CALL_LO16);
3152 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_DISP);
3154 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3156 GlobalOrExternal = true;
3159 SDValue JumpTarget = Callee;
3161 // T9 should contain the address of the callee function if
3162 // -reloction-model=pic or it is an indirect call.
3163 if (IsPICCall || !GlobalOrExternal) {
3164 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
3165 unsigned V0Reg = Mips::V0;
3166 if (needMips16Helper) {
3167 RegsToPass.push_front(std::make_pair(V0Reg, Callee));
3168 JumpTarget = DAG.getExternalSymbol(
3169 mips16HelperFunction, getPointerTy());
3170 JumpTarget = getAddrGlobal(JumpTarget, DAG, MipsII::MO_GOT);
3173 RegsToPass.push_front(std::make_pair(T9Reg, Callee));
3175 if (!Subtarget->inMips16Mode())
3176 JumpTarget = SDValue();
3180 // Insert node "GP copy globalreg" before call to function.
3182 // R_MIPS_CALL* operators (emitted when non-internal functions are called
3183 // in PIC mode) allow symbols to be resolved via lazy binding.
3184 // The lazy binding stub requires GP to point to the GOT.
3185 if (IsPICCall && !InternalLinkage) {
3186 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
3187 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
3188 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
3191 // Build a sequence of copy-to-reg nodes chained together with token
3192 // chain and flag operands which copy the outgoing args into registers.
3193 // The InFlag in necessary since all emitted instructions must be
3197 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3198 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
3199 RegsToPass[i].second, InFlag);
3200 InFlag = Chain.getValue(1);
3203 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
3204 // = Chain, Callee, Reg#1, Reg#2, ...
3206 // Returns a chain & a flag for retval copy to use.
3207 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3208 SmallVector<SDValue, 8> Ops(1, Chain);
3210 if (JumpTarget.getNode())
3211 Ops.push_back(JumpTarget);
3213 // Add argument registers to the end of the list so that they are
3214 // known live into the call.
3215 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3216 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3217 RegsToPass[i].second.getValueType()));
3219 // Add a register mask operand representing the call-preserved registers.
3220 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3221 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3222 assert(Mask && "Missing call preserved mask for calling convention");
3223 Ops.push_back(DAG.getRegisterMask(Mask));
3225 if (InFlag.getNode())
3226 Ops.push_back(InFlag);
3229 return DAG.getNode(MipsISD::TailCall, dl, MVT::Other, &Ops[0], Ops.size());
3231 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
3232 InFlag = Chain.getValue(1);
3234 // Create the CALLSEQ_END node.
3235 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3236 DAG.getIntPtrConstant(0, true), InFlag);
3237 InFlag = Chain.getValue(1);
3239 // Handle result values, copying them out of physregs into vregs that we
3241 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3242 Ins, dl, DAG, InVals);
3245 /// LowerCallResult - Lower the result values of a call into the
3246 /// appropriate copies out of appropriate physical registers.
3248 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3249 CallingConv::ID CallConv, bool isVarArg,
3250 const SmallVectorImpl<ISD::InputArg> &Ins,
3251 DebugLoc dl, SelectionDAG &DAG,
3252 SmallVectorImpl<SDValue> &InVals) const {
3253 // Assign locations to each value returned by this call.
3254 SmallVector<CCValAssign, 16> RVLocs;
3255 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3256 getTargetMachine(), RVLocs, *DAG.getContext());
3258 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3260 // Copy all of the result registers out of their specified physreg.
3261 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3262 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
3263 RVLocs[i].getValVT(), InFlag).getValue(1);
3264 InFlag = Chain.getValue(2);
3265 InVals.push_back(Chain.getValue(0));
3271 //===----------------------------------------------------------------------===//
3272 // Formal Arguments Calling Convention Implementation
3273 //===----------------------------------------------------------------------===//
3274 /// LowerFormalArguments - transform physical registers into virtual registers
3275 /// and generate load operations for arguments places on the stack.
3277 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3278 CallingConv::ID CallConv,
3280 const SmallVectorImpl<ISD::InputArg> &Ins,
3281 DebugLoc dl, SelectionDAG &DAG,
3282 SmallVectorImpl<SDValue> &InVals)
3284 MachineFunction &MF = DAG.getMachineFunction();
3285 MachineFrameInfo *MFI = MF.getFrameInfo();
3286 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3288 MipsFI->setVarArgsFrameIndex(0);
3290 // Used with vargs to acumulate store chains.
3291 std::vector<SDValue> OutChains;
3293 // Assign locations to all of the incoming arguments.
3294 SmallVector<CCValAssign, 16> ArgLocs;
3295 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3296 getTargetMachine(), ArgLocs, *DAG.getContext());
3297 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
3299 MipsCCInfo.analyzeFormalArguments(Ins);
3300 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3301 MipsCCInfo.hasByValArg());
3303 Function::const_arg_iterator FuncArg =
3304 DAG.getMachineFunction().getFunction()->arg_begin();
3305 unsigned CurArgIdx = 0;
3306 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3308 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3309 CCValAssign &VA = ArgLocs[i];
3310 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
3311 CurArgIdx = Ins[i].OrigArgIndex;
3312 EVT ValVT = VA.getValVT();
3313 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3314 bool IsRegLoc = VA.isRegLoc();
3316 if (Flags.isByVal()) {
3317 assert(Flags.getByValSize() &&
3318 "ByVal args of size 0 should have been ignored by front-end.");
3319 assert(ByValArg != MipsCCInfo.byval_end());
3320 copyByValRegs(Chain, dl, OutChains, DAG, Flags, InVals, &*FuncArg,
3321 MipsCCInfo, *ByValArg);
3326 // Arguments stored on registers
3328 EVT RegVT = VA.getLocVT();
3329 unsigned ArgReg = VA.getLocReg();
3330 const TargetRegisterClass *RC;
3332 if (RegVT == MVT::i32)
3333 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
3334 &Mips::CPURegsRegClass;
3335 else if (RegVT == MVT::i64)
3336 RC = &Mips::CPU64RegsRegClass;
3337 else if (RegVT == MVT::f32)
3338 RC = &Mips::FGR32RegClass;
3339 else if (RegVT == MVT::f64)
3340 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3342 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3344 // Transform the arguments stored on
3345 // physical registers into virtual ones
3346 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3347 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3349 // If this is an 8 or 16-bit value, it has been passed promoted
3350 // to 32 bits. Insert an assert[sz]ext to capture this, then
3351 // truncate to the right size.
3352 if (VA.getLocInfo() != CCValAssign::Full) {
3353 unsigned Opcode = 0;
3354 if (VA.getLocInfo() == CCValAssign::SExt)
3355 Opcode = ISD::AssertSext;
3356 else if (VA.getLocInfo() == CCValAssign::ZExt)
3357 Opcode = ISD::AssertZext;
3359 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3360 DAG.getValueType(ValVT));
3361 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3364 // Handle floating point arguments passed in integer registers.
3365 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3366 (RegVT == MVT::i64 && ValVT == MVT::f64))
3367 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3368 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3369 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3370 getNextIntArgReg(ArgReg), RC);
3371 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3372 if (!Subtarget->isLittle())
3373 std::swap(ArgValue, ArgValue2);
3374 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3375 ArgValue, ArgValue2);
3378 InVals.push_back(ArgValue);
3379 } else { // VA.isRegLoc()
3382 assert(VA.isMemLoc());
3384 // The stack pointer offset is relative to the caller stack frame.
3385 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3386 VA.getLocMemOffset(), true);
3388 // Create load nodes to retrieve arguments from the stack
3389 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3390 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3391 MachinePointerInfo::getFixedStack(FI),
3392 false, false, false, 0));
3396 // The mips ABIs for returning structs by value requires that we copy
3397 // the sret argument into $v0 for the return. Save the argument into
3398 // a virtual register so that we can access it from the return points.
3399 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3400 unsigned Reg = MipsFI->getSRetReturnReg();
3402 Reg = MF.getRegInfo().
3403 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
3404 MipsFI->setSRetReturnReg(Reg);
3406 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3407 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3411 writeVarArgRegs(OutChains, MipsCCInfo, Chain, dl, DAG);
3413 // All stores are grouped in one node to allow the matching between
3414 // the size of Ins and InVals. This only happens when on varg functions
3415 if (!OutChains.empty()) {
3416 OutChains.push_back(Chain);
3417 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3418 &OutChains[0], OutChains.size());
3424 //===----------------------------------------------------------------------===//
3425 // Return Value Calling Convention Implementation
3426 //===----------------------------------------------------------------------===//
3429 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3430 MachineFunction &MF, bool isVarArg,
3431 const SmallVectorImpl<ISD::OutputArg> &Outs,
3432 LLVMContext &Context) const {
3433 SmallVector<CCValAssign, 16> RVLocs;
3434 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
3436 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3440 MipsTargetLowering::LowerReturn(SDValue Chain,
3441 CallingConv::ID CallConv, bool isVarArg,
3442 const SmallVectorImpl<ISD::OutputArg> &Outs,
3443 const SmallVectorImpl<SDValue> &OutVals,
3444 DebugLoc dl, SelectionDAG &DAG) const {
3446 // CCValAssign - represent the assignment of
3447 // the return value to a location
3448 SmallVector<CCValAssign, 16> RVLocs;
3450 // CCState - Info about the registers and stack slot.
3451 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3452 getTargetMachine(), RVLocs, *DAG.getContext());
3454 // Analize return values.
3455 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3458 SmallVector<SDValue, 4> RetOps(1, Chain);
3460 // Copy the result values into the output registers.
3461 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3462 CCValAssign &VA = RVLocs[i];
3463 assert(VA.isRegLoc() && "Can only return in registers!");
3465 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3467 // Guarantee that all emitted copies are stuck together with flags.
3468 Flag = Chain.getValue(1);
3469 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3472 // The mips ABIs for returning structs by value requires that we copy
3473 // the sret argument into $v0 for the return. We saved the argument into
3474 // a virtual register in the entry block, so now we copy the value out
3476 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3477 MachineFunction &MF = DAG.getMachineFunction();
3478 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3479 unsigned Reg = MipsFI->getSRetReturnReg();
3482 llvm_unreachable("sret virtual register not created in the entry block");
3483 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3484 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
3486 Chain = DAG.getCopyToReg(Chain, dl, V0, Val, Flag);
3487 Flag = Chain.getValue(1);
3488 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3491 RetOps[0] = Chain; // Update chain.
3493 // Add the flag if we have it.
3495 RetOps.push_back(Flag);
3497 // Return on Mips is always a "jr $ra"
3498 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, &RetOps[0], RetOps.size());
3501 //===----------------------------------------------------------------------===//
3502 // Mips Inline Assembly Support
3503 //===----------------------------------------------------------------------===//
3505 /// getConstraintType - Given a constraint letter, return the type of
3506 /// constraint it is for this target.
3507 MipsTargetLowering::ConstraintType MipsTargetLowering::
3508 getConstraintType(const std::string &Constraint) const
3510 // Mips specific constrainy
3511 // GCC config/mips/constraints.md
3513 // 'd' : An address register. Equivalent to r
3514 // unless generating MIPS16 code.
3515 // 'y' : Equivalent to r; retained for
3516 // backwards compatibility.
3517 // 'c' : A register suitable for use in an indirect
3518 // jump. This will always be $25 for -mabicalls.
3519 // 'l' : The lo register. 1 word storage.
3520 // 'x' : The hilo register pair. Double word storage.
3521 if (Constraint.size() == 1) {
3522 switch (Constraint[0]) {
3530 return C_RegisterClass;
3533 return TargetLowering::getConstraintType(Constraint);
3536 /// Examine constraint type and operand type and determine a weight value.
3537 /// This object must already have been set up with the operand type
3538 /// and the current alternative constraint selected.
3539 TargetLowering::ConstraintWeight
3540 MipsTargetLowering::getSingleConstraintMatchWeight(
3541 AsmOperandInfo &info, const char *constraint) const {
3542 ConstraintWeight weight = CW_Invalid;
3543 Value *CallOperandVal = info.CallOperandVal;
3544 // If we don't have a value, we can't do a match,
3545 // but allow it at the lowest weight.
3546 if (CallOperandVal == NULL)
3548 Type *type = CallOperandVal->getType();
3549 // Look at the constraint type.
3550 switch (*constraint) {
3552 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3556 if (type->isIntegerTy())
3557 weight = CW_Register;
3560 if (type->isFloatTy())
3561 weight = CW_Register;
3563 case 'c': // $25 for indirect jumps
3564 case 'l': // lo register
3565 case 'x': // hilo register pair
3566 if (type->isIntegerTy())
3567 weight = CW_SpecificReg;
3569 case 'I': // signed 16 bit immediate
3570 case 'J': // integer zero
3571 case 'K': // unsigned 16 bit immediate
3572 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3573 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3574 case 'O': // signed 15 bit immediate (+- 16383)
3575 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3576 if (isa<ConstantInt>(CallOperandVal))
3577 weight = CW_Constant;
3583 /// Given a register class constraint, like 'r', if this corresponds directly
3584 /// to an LLVM register class, return a register of 0 and the register class
3586 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3587 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3589 if (Constraint.size() == 1) {
3590 switch (Constraint[0]) {
3591 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3592 case 'y': // Same as 'r'. Exists for compatibility.
3594 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3595 if (Subtarget->inMips16Mode())
3596 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3597 return std::make_pair(0U, &Mips::CPURegsRegClass);
3599 if (VT == MVT::i64 && !HasMips64)
3600 return std::make_pair(0U, &Mips::CPURegsRegClass);
3601 if (VT == MVT::i64 && HasMips64)
3602 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3603 // This will generate an error message
3604 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3607 return std::make_pair(0U, &Mips::FGR32RegClass);
3608 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3609 if (Subtarget->isFP64bit())
3610 return std::make_pair(0U, &Mips::FGR64RegClass);
3611 return std::make_pair(0U, &Mips::AFGR64RegClass);
3614 case 'c': // register suitable for indirect jump
3616 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3617 assert(VT == MVT::i64 && "Unexpected type.");
3618 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3619 case 'l': // register suitable for indirect jump
3621 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3622 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3623 case 'x': // register suitable for indirect jump
3624 // Fixme: Not triggering the use of both hi and low
3625 // This will generate an error message
3626 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3629 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3632 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3633 /// vector. If it is invalid, don't add anything to Ops.
3634 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3635 std::string &Constraint,
3636 std::vector<SDValue>&Ops,
3637 SelectionDAG &DAG) const {
3638 SDValue Result(0, 0);
3640 // Only support length 1 constraints for now.
3641 if (Constraint.length() > 1) return;
3643 char ConstraintLetter = Constraint[0];
3644 switch (ConstraintLetter) {
3645 default: break; // This will fall through to the generic implementation
3646 case 'I': // Signed 16 bit constant
3647 // If this fails, the parent routine will give an error
3648 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3649 EVT Type = Op.getValueType();
3650 int64_t Val = C->getSExtValue();
3651 if (isInt<16>(Val)) {
3652 Result = DAG.getTargetConstant(Val, Type);
3657 case 'J': // integer zero
3658 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3659 EVT Type = Op.getValueType();
3660 int64_t Val = C->getZExtValue();
3662 Result = DAG.getTargetConstant(0, Type);
3667 case 'K': // unsigned 16 bit immediate
3668 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3669 EVT Type = Op.getValueType();
3670 uint64_t Val = (uint64_t)C->getZExtValue();
3671 if (isUInt<16>(Val)) {
3672 Result = DAG.getTargetConstant(Val, Type);
3677 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3678 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3679 EVT Type = Op.getValueType();
3680 int64_t Val = C->getSExtValue();
3681 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3682 Result = DAG.getTargetConstant(Val, Type);
3687 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3688 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3689 EVT Type = Op.getValueType();
3690 int64_t Val = C->getSExtValue();
3691 if ((Val >= -65535) && (Val <= -1)) {
3692 Result = DAG.getTargetConstant(Val, Type);
3697 case 'O': // signed 15 bit immediate
3698 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3699 EVT Type = Op.getValueType();
3700 int64_t Val = C->getSExtValue();
3701 if ((isInt<15>(Val))) {
3702 Result = DAG.getTargetConstant(Val, Type);
3707 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3708 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3709 EVT Type = Op.getValueType();
3710 int64_t Val = C->getSExtValue();
3711 if ((Val <= 65535) && (Val >= 1)) {
3712 Result = DAG.getTargetConstant(Val, Type);
3719 if (Result.getNode()) {
3720 Ops.push_back(Result);
3724 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3728 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3729 // No global is ever allowed as a base.
3734 case 0: // "r+i" or just "i", depending on HasBaseReg.
3737 if (!AM.HasBaseReg) // allow "r+i".
3739 return false; // disallow "r+r" or "r+r+i".
3748 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3749 // The Mips target isn't yet aware of offsets.
3753 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3755 bool IsMemset, bool ZeroMemset,
3757 MachineFunction &MF) const {
3758 if (Subtarget->hasMips64())
3764 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3765 if (VT != MVT::f32 && VT != MVT::f64)
3767 if (Imm.isNegZero())
3769 return Imm.isZero();
3772 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3774 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3776 return TargetLowering::getJumpTableEncoding();
3779 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CallConv, bool IsVarArg,
3780 bool IsO32, CCState &Info) : CCInfo(Info) {
3781 UseRegsForByval = true;
3785 NumIntArgRegs = array_lengthof(O32IntRegs);
3786 ReservedArgArea = 16;
3787 IntArgRegs = ShadowRegs = O32IntRegs;
3788 FixedFn = VarFn = CC_MipsO32;
3791 NumIntArgRegs = array_lengthof(Mips64IntRegs);
3792 ReservedArgArea = 0;
3793 IntArgRegs = Mips64IntRegs;
3794 ShadowRegs = Mips64DPRegs;
3796 VarFn = IsVarArg ? CC_MipsN_VarArg : CC_MipsN;
3799 if (CallConv == CallingConv::Fast) {
3801 UseRegsForByval = false;
3802 ReservedArgArea = 0;
3803 FixedFn = VarFn = CC_Mips_FastCC;
3806 // Pre-allocate reserved argument area.
3807 CCInfo.AllocateStack(ReservedArgArea, 1);
3810 void MipsTargetLowering::MipsCC::
3811 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args) {
3812 unsigned NumOpnds = Args.size();
3814 for (unsigned I = 0; I != NumOpnds; ++I) {
3815 MVT ArgVT = Args[I].VT;
3816 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3819 if (ArgFlags.isByVal()) {
3820 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3824 if (Args[I].IsFixed)
3825 R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3827 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3831 dbgs() << "Call operand #" << I << " has unhandled type "
3832 << EVT(ArgVT).getEVTString();
3834 llvm_unreachable(0);
3839 void MipsTargetLowering::MipsCC::
3840 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args) {
3841 unsigned NumArgs = Args.size();
3843 for (unsigned I = 0; I != NumArgs; ++I) {
3844 MVT ArgVT = Args[I].VT;
3845 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3847 if (ArgFlags.isByVal()) {
3848 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3852 if (!FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo))
3856 dbgs() << "Formal Arg #" << I << " has unhandled type "
3857 << EVT(ArgVT).getEVTString();
3859 llvm_unreachable(0);
3864 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3866 CCValAssign::LocInfo LocInfo,
3867 ISD::ArgFlagsTy ArgFlags) {
3868 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3870 struct ByValArgInfo ByVal;
3871 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3872 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3875 if (UseRegsForByval)
3876 allocateRegs(ByVal, ByValSize, Align);
3878 // Allocate space on caller's stack.
3879 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3881 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3883 ByValArgs.push_back(ByVal);
3886 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3889 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3890 "Byval argument's size and alignment should be a multiple of"
3893 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3895 // If Align > RegSize, the first arg register must be even.
3896 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3897 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3901 // Mark the registers allocated.
3902 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3903 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3904 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3907 void MipsTargetLowering::
3908 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
3909 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3910 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3911 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3912 MachineFunction &MF = DAG.getMachineFunction();
3913 MachineFrameInfo *MFI = MF.getFrameInfo();
3914 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3915 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3919 FrameObjOffset = (int)CC.reservedArgArea() -
3920 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3922 FrameObjOffset = ByVal.Address;
3924 // Create frame object.
3925 EVT PtrTy = getPointerTy();
3926 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3927 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3928 InVals.push_back(FIN);
3933 // Copy arg registers.
3934 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3935 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3937 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3938 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3939 unsigned VReg = AddLiveIn(MF, ArgReg, RC);
3940 unsigned Offset = I * CC.regSize();
3941 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3942 DAG.getConstant(Offset, PtrTy));
3943 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3944 StorePtr, MachinePointerInfo(FuncArg, Offset),
3946 OutChains.push_back(Store);
3950 // Copy byVal arg to registers and stack.
3951 void MipsTargetLowering::
3952 passByValArg(SDValue Chain, DebugLoc DL,
3953 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3954 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3955 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3956 const MipsCC &CC, const ByValArgInfo &ByVal,
3957 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3958 unsigned ByValSize = Flags.getByValSize();
3959 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3960 unsigned RegSize = CC.regSize();
3961 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3962 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3964 if (ByVal.NumRegs) {
3965 const uint16_t *ArgRegs = CC.intArgRegs();
3966 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3969 // Copy words to registers.
3970 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3971 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3972 DAG.getConstant(Offset, PtrTy));
3973 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3974 MachinePointerInfo(), false, false, false,
3976 MemOpChains.push_back(LoadVal.getValue(1));
3977 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3978 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3981 // Return if the struct has been fully copied.
3982 if (ByValSize == Offset)
3985 // Copy the remainder of the byval argument with sub-word loads and shifts.
3986 if (LeftoverBytes) {
3987 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3988 "Size of the remainder should be smaller than RegSize.");
3991 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3992 Offset < ByValSize; LoadSize /= 2) {
3993 unsigned RemSize = ByValSize - Offset;
3995 if (RemSize < LoadSize)
3999 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4000 DAG.getConstant(Offset, PtrTy));
4002 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
4003 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
4004 false, false, Alignment);
4005 MemOpChains.push_back(LoadVal.getValue(1));
4007 // Shift the loaded value.
4011 Shamt = TotalSizeLoaded;
4013 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
4015 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4016 DAG.getConstant(Shamt, MVT::i32));
4019 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4024 TotalSizeLoaded += LoadSize;
4025 Alignment = std::min(Alignment, LoadSize);
4028 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
4029 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4034 // Copy remainder of byval arg to it with memcpy.
4035 unsigned MemCpySize = ByValSize - Offset;
4036 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4037 DAG.getConstant(Offset, PtrTy));
4038 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4039 DAG.getIntPtrConstant(ByVal.Address));
4040 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4041 DAG.getConstant(MemCpySize, PtrTy), Alignment,
4042 /*isVolatile=*/false, /*AlwaysInline=*/false,
4043 MachinePointerInfo(0), MachinePointerInfo(0));
4044 MemOpChains.push_back(Chain);
4048 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4049 const MipsCC &CC, SDValue Chain,
4050 DebugLoc DL, SelectionDAG &DAG) const {
4051 unsigned NumRegs = CC.numIntArgRegs();
4052 const uint16_t *ArgRegs = CC.intArgRegs();
4053 const CCState &CCInfo = CC.getCCInfo();
4054 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
4055 unsigned RegSize = CC.regSize();
4056 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
4057 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4058 MachineFunction &MF = DAG.getMachineFunction();
4059 MachineFrameInfo *MFI = MF.getFrameInfo();
4060 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4062 // Offset of the first variable argument from stack pointer.
4066 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
4069 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
4071 // Record the frame index of the first variable argument
4072 // which is a value necessary to VASTART.
4073 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4074 MipsFI->setVarArgsFrameIndex(FI);
4076 // Copy the integer registers that have not been used for argument passing
4077 // to the argument register save area. For O32, the save area is allocated
4078 // in the caller's stack frame, while for N32/64, it is allocated in the
4079 // callee's stack frame.
4080 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
4081 unsigned Reg = AddLiveIn(MF, ArgRegs[I], RC);
4082 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4083 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4084 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
4085 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
4086 MachinePointerInfo(), false, false, 0);
4087 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
4088 OutChains.push_back(Store);