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/GlobalVariable.h"
34 #include "llvm/IR/Intrinsics.h"
35 #include "llvm/Support/CommandLine.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/ErrorHandling.h"
38 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NumTailCalls, "Number of tail calls");
45 EnableMipsTailCalls("enable-mips-tail-calls", cl::Hidden,
46 cl::desc("MIPS: Enable tail calls."), cl::init(false));
49 LargeGOT("mxgot", cl::Hidden,
50 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
53 Mips16HardFloat("mips16-hard-float", cl::NotHidden,
54 cl::desc("MIPS: mips16 hard float enable."),
57 static cl::opt<bool> DontExpandCondPseudos16(
58 "mips16-dont-expand-cond-pseudo",
60 cl::desc("Dont expand conditional move related "
61 "pseudos for Mips 16"),
65 static const uint16_t O32IntRegs[4] = {
66 Mips::A0, Mips::A1, Mips::A2, Mips::A3
69 static const uint16_t Mips64IntRegs[8] = {
70 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
71 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
74 static const uint16_t Mips64DPRegs[8] = {
75 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
76 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
79 // If I is a shifted mask, set the size (Size) and the first bit of the
80 // mask (Pos), and return true.
81 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
82 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
83 if (!isShiftedMask_64(I))
86 Size = CountPopulation_64(I);
87 Pos = CountTrailingZeros_64(I);
91 static SDValue getGlobalReg(SelectionDAG &DAG, EVT Ty) {
92 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
93 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
96 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
97 EVT Ty = Op.getValueType();
99 if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
100 return DAG.getTargetGlobalAddress(N->getGlobal(), Op.getDebugLoc(), Ty, 0,
102 if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
103 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
104 if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
105 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
106 if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
107 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
108 if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
109 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
110 N->getOffset(), Flag);
112 llvm_unreachable("Unexpected node type.");
116 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
117 DebugLoc DL = Op.getDebugLoc();
118 EVT Ty = Op.getValueType();
119 SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
120 SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
121 return DAG.getNode(ISD::ADD, DL, Ty,
122 DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
123 DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
126 static SDValue getAddrLocal(SDValue Op, SelectionDAG &DAG, bool HasMips64) {
127 DebugLoc DL = Op.getDebugLoc();
128 EVT Ty = Op.getValueType();
129 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
130 SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
131 getTargetNode(Op, DAG, GOTFlag));
132 SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
133 MachinePointerInfo::getGOT(), false, false, false,
135 unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
136 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
137 return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
140 static SDValue getAddrGlobal(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
141 DebugLoc DL = Op.getDebugLoc();
142 EVT Ty = Op.getValueType();
143 SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
144 getTargetNode(Op, DAG, Flag));
145 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
146 MachinePointerInfo::getGOT(), false, false, false, 0);
149 static SDValue getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
150 unsigned HiFlag, unsigned LoFlag) {
151 DebugLoc DL = Op.getDebugLoc();
152 EVT Ty = Op.getValueType();
153 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
154 Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, getGlobalReg(DAG, Ty));
155 SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
156 getTargetNode(Op, DAG, LoFlag));
157 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
158 MachinePointerInfo::getGOT(), false, false, false, 0);
161 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
163 case MipsISD::JmpLink: return "MipsISD::JmpLink";
164 case MipsISD::TailCall: return "MipsISD::TailCall";
165 case MipsISD::Hi: return "MipsISD::Hi";
166 case MipsISD::Lo: return "MipsISD::Lo";
167 case MipsISD::GPRel: return "MipsISD::GPRel";
168 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
169 case MipsISD::Ret: return "MipsISD::Ret";
170 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
171 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
172 case MipsISD::FPCmp: return "MipsISD::FPCmp";
173 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
174 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
175 case MipsISD::FPRound: return "MipsISD::FPRound";
176 case MipsISD::MAdd: return "MipsISD::MAdd";
177 case MipsISD::MAddu: return "MipsISD::MAddu";
178 case MipsISD::MSub: return "MipsISD::MSub";
179 case MipsISD::MSubu: return "MipsISD::MSubu";
180 case MipsISD::DivRem: return "MipsISD::DivRem";
181 case MipsISD::DivRemU: return "MipsISD::DivRemU";
182 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
183 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
184 case MipsISD::Wrapper: return "MipsISD::Wrapper";
185 case MipsISD::Sync: return "MipsISD::Sync";
186 case MipsISD::Ext: return "MipsISD::Ext";
187 case MipsISD::Ins: return "MipsISD::Ins";
188 case MipsISD::LWL: return "MipsISD::LWL";
189 case MipsISD::LWR: return "MipsISD::LWR";
190 case MipsISD::SWL: return "MipsISD::SWL";
191 case MipsISD::SWR: return "MipsISD::SWR";
192 case MipsISD::LDL: return "MipsISD::LDL";
193 case MipsISD::LDR: return "MipsISD::LDR";
194 case MipsISD::SDL: return "MipsISD::SDL";
195 case MipsISD::SDR: return "MipsISD::SDR";
196 case MipsISD::EXTP: return "MipsISD::EXTP";
197 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
198 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
199 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
200 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
201 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
202 case MipsISD::SHILO: return "MipsISD::SHILO";
203 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
204 case MipsISD::MULT: return "MipsISD::MULT";
205 case MipsISD::MULTU: return "MipsISD::MULTU";
206 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
207 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
208 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
209 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
210 default: return NULL;
216 bool operator()(const char *S1, const char *S2) const
218 return strcmp(S1, S2) < 0;
222 std::set<const char*, LTStr> NoHelperNeeded;
225 void MipsTargetLowering::setMips16LibcallName
226 (RTLIB::Libcall L, const char *Name) {
227 setLibcallName(L, Name);
228 NoHelperNeeded.insert(Name);
231 void MipsTargetLowering::setMips16HardFloatLibCalls() {
232 setMips16LibcallName(RTLIB::ADD_F32, "__mips16_addsf3");
233 setMips16LibcallName(RTLIB::ADD_F64, "__mips16_adddf3");
234 setMips16LibcallName(RTLIB::SUB_F32, "__mips16_subsf3");
235 setMips16LibcallName(RTLIB::SUB_F64, "__mips16_subdf3");
236 setMips16LibcallName(RTLIB::MUL_F32, "__mips16_mulsf3");
237 setMips16LibcallName(RTLIB::MUL_F64, "__mips16_muldf3");
238 setMips16LibcallName(RTLIB::DIV_F32, "__mips16_divsf3");
239 setMips16LibcallName(RTLIB::DIV_F64, "__mips16_divdf3");
240 setMips16LibcallName(RTLIB::FPEXT_F32_F64, "__mips16_extendsfdf2");
241 setMips16LibcallName(RTLIB::FPROUND_F64_F32, "__mips16_truncdfsf2");
242 setMips16LibcallName(RTLIB::FPTOSINT_F32_I32, "__mips16_fix_truncsfsi");
243 setMips16LibcallName(RTLIB::FPTOSINT_F64_I32, "__mips16_fix_truncdfsi");
244 setMips16LibcallName(RTLIB::SINTTOFP_I32_F32, "__mips16_floatsisf");
245 setMips16LibcallName(RTLIB::SINTTOFP_I32_F64, "__mips16_floatsidf");
246 setMips16LibcallName(RTLIB::UINTTOFP_I32_F32, "__mips16_floatunsisf");
247 setMips16LibcallName(RTLIB::UINTTOFP_I32_F64, "__mips16_floatunsidf");
248 setMips16LibcallName(RTLIB::OEQ_F32, "__mips16_eqsf2");
249 setMips16LibcallName(RTLIB::OEQ_F64, "__mips16_eqdf2");
250 setMips16LibcallName(RTLIB::UNE_F32, "__mips16_nesf2");
251 setMips16LibcallName(RTLIB::UNE_F64, "__mips16_nedf2");
252 setMips16LibcallName(RTLIB::OGE_F32, "__mips16_gesf2");
253 setMips16LibcallName(RTLIB::OGE_F64, "__mips16_gedf2");
254 setMips16LibcallName(RTLIB::OLT_F32, "__mips16_ltsf2");
255 setMips16LibcallName(RTLIB::OLT_F64, "__mips16_ltdf2");
256 setMips16LibcallName(RTLIB::OLE_F32, "__mips16_lesf2");
257 setMips16LibcallName(RTLIB::OLE_F64, "__mips16_ledf2");
258 setMips16LibcallName(RTLIB::OGT_F32, "__mips16_gtsf2");
259 setMips16LibcallName(RTLIB::OGT_F64, "__mips16_gtdf2");
260 setMips16LibcallName(RTLIB::UO_F32, "__mips16_unordsf2");
261 setMips16LibcallName(RTLIB::UO_F64, "__mips16_unorddf2");
262 setMips16LibcallName(RTLIB::O_F32, "__mips16_unordsf2");
263 setMips16LibcallName(RTLIB::O_F64, "__mips16_unorddf2");
267 MipsTargetLowering(MipsTargetMachine &TM)
268 : TargetLowering(TM, new MipsTargetObjectFile()),
269 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
270 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
271 IsO32(Subtarget->isABI_O32()) {
273 // Mips does not have i1 type, so use i32 for
274 // setcc operations results (slt, sgt, ...).
275 setBooleanContents(ZeroOrOneBooleanContent);
276 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
278 // Set up the register classes
279 addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
282 addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
284 if (Subtarget->inMips16Mode()) {
285 addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
287 setMips16HardFloatLibCalls();
290 if (Subtarget->hasDSP()) {
291 MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
293 for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
294 addRegisterClass(VecTys[i], &Mips::DSPRegsRegClass);
296 // Expand all builtin opcodes.
297 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
298 setOperationAction(Opc, VecTys[i], Expand);
300 setOperationAction(ISD::LOAD, VecTys[i], Legal);
301 setOperationAction(ISD::STORE, VecTys[i], Legal);
302 setOperationAction(ISD::BITCAST, VecTys[i], Legal);
306 if (!TM.Options.UseSoftFloat) {
307 addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
309 // When dealing with single precision only, use libcalls
310 if (!Subtarget->isSingleFloat()) {
312 addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
314 addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
318 // Load extented operations for i1 types must be promoted
319 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
320 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
321 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
323 // MIPS doesn't have extending float->double load/store
324 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
325 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
327 // Used by legalize types to correctly generate the setcc result.
328 // Without this, every float setcc comes with a AND/OR with the result,
329 // we don't want this, since the fpcmp result goes to a flag register,
330 // which is used implicitly by brcond and select operations.
331 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
333 // Mips Custom Operations
334 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
335 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
336 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
337 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
338 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
339 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
340 setOperationAction(ISD::SELECT, MVT::f32, Custom);
341 setOperationAction(ISD::SELECT, MVT::f64, Custom);
342 setOperationAction(ISD::SELECT, MVT::i32, Custom);
343 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
344 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
345 setOperationAction(ISD::SETCC, MVT::f32, Custom);
346 setOperationAction(ISD::SETCC, MVT::f64, Custom);
347 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
348 setOperationAction(ISD::VASTART, MVT::Other, Custom);
349 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
350 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
351 if (Subtarget->inMips16Mode()) {
352 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
353 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
356 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
357 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
359 if (!Subtarget->inMips16Mode()) {
360 setOperationAction(ISD::LOAD, MVT::i32, Custom);
361 setOperationAction(ISD::STORE, MVT::i32, Custom);
364 if (!TM.Options.NoNaNsFPMath) {
365 setOperationAction(ISD::FABS, MVT::f32, Custom);
366 setOperationAction(ISD::FABS, MVT::f64, Custom);
370 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
371 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
372 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
373 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
374 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
375 setOperationAction(ISD::SELECT, MVT::i64, Custom);
376 setOperationAction(ISD::LOAD, MVT::i64, Custom);
377 setOperationAction(ISD::STORE, MVT::i64, Custom);
381 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
382 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
383 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
386 setOperationAction(ISD::ADD, MVT::i32, Custom);
388 setOperationAction(ISD::ADD, MVT::i64, Custom);
390 setOperationAction(ISD::SDIV, MVT::i32, Expand);
391 setOperationAction(ISD::SREM, MVT::i32, Expand);
392 setOperationAction(ISD::UDIV, MVT::i32, Expand);
393 setOperationAction(ISD::UREM, MVT::i32, Expand);
394 setOperationAction(ISD::SDIV, MVT::i64, Expand);
395 setOperationAction(ISD::SREM, MVT::i64, Expand);
396 setOperationAction(ISD::UDIV, MVT::i64, Expand);
397 setOperationAction(ISD::UREM, MVT::i64, Expand);
399 // Operations not directly supported by Mips.
400 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
401 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
402 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
403 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
404 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
405 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
406 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
407 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
408 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
409 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
410 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
411 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
412 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
413 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
414 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
415 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
416 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
417 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
418 setOperationAction(ISD::ROTL, MVT::i32, Expand);
419 setOperationAction(ISD::ROTL, MVT::i64, Expand);
420 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
421 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
423 if (!Subtarget->hasMips32r2())
424 setOperationAction(ISD::ROTR, MVT::i32, Expand);
426 if (!Subtarget->hasMips64r2())
427 setOperationAction(ISD::ROTR, MVT::i64, Expand);
429 setOperationAction(ISD::FSIN, MVT::f32, Expand);
430 setOperationAction(ISD::FSIN, MVT::f64, Expand);
431 setOperationAction(ISD::FCOS, MVT::f32, Expand);
432 setOperationAction(ISD::FCOS, MVT::f64, Expand);
433 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
434 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
435 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
436 setOperationAction(ISD::FPOW, MVT::f32, Expand);
437 setOperationAction(ISD::FPOW, MVT::f64, Expand);
438 setOperationAction(ISD::FLOG, MVT::f32, Expand);
439 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
440 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
441 setOperationAction(ISD::FEXP, MVT::f32, Expand);
442 setOperationAction(ISD::FMA, MVT::f32, Expand);
443 setOperationAction(ISD::FMA, MVT::f64, Expand);
444 setOperationAction(ISD::FREM, MVT::f32, Expand);
445 setOperationAction(ISD::FREM, MVT::f64, Expand);
447 if (!TM.Options.NoNaNsFPMath) {
448 setOperationAction(ISD::FNEG, MVT::f32, Expand);
449 setOperationAction(ISD::FNEG, MVT::f64, Expand);
452 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
453 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
454 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
455 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
457 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
459 setOperationAction(ISD::VAARG, MVT::Other, Expand);
460 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
461 setOperationAction(ISD::VAEND, MVT::Other, Expand);
463 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
464 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
466 // Use the default for now
467 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
468 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
470 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
471 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
472 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
473 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
475 if (Subtarget->inMips16Mode()) {
476 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
477 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
478 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
479 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
480 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
481 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
482 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
483 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
484 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
485 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
486 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
487 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
490 setInsertFencesForAtomic(true);
492 if (!Subtarget->hasSEInReg()) {
493 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
494 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
497 if (!Subtarget->hasBitCount()) {
498 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
499 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
502 if (!Subtarget->hasSwap()) {
503 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
504 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
508 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
509 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
510 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
511 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
514 setTargetDAGCombine(ISD::ADDE);
515 setTargetDAGCombine(ISD::SUBE);
516 setTargetDAGCombine(ISD::SDIVREM);
517 setTargetDAGCombine(ISD::UDIVREM);
518 setTargetDAGCombine(ISD::SELECT);
519 setTargetDAGCombine(ISD::AND);
520 setTargetDAGCombine(ISD::OR);
521 setTargetDAGCombine(ISD::ADD);
523 setMinFunctionAlignment(HasMips64 ? 3 : 2);
525 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
526 computeRegisterProperties();
528 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
529 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
531 MaxStoresPerMemcpy = 16;
535 MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
536 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
538 if (Subtarget->inMips16Mode())
552 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
555 return VT.changeVectorElementTypeToInteger();
559 // Transforms a subgraph in CurDAG if the following pattern is found:
560 // (addc multLo, Lo0), (adde multHi, Hi0),
562 // multHi/Lo: product of multiplication
563 // Lo0: initial value of Lo register
564 // Hi0: initial value of Hi register
565 // Return true if pattern matching was successful.
566 static bool selectMADD(SDNode *ADDENode, SelectionDAG *CurDAG) {
567 // ADDENode's second operand must be a flag output of an ADDC node in order
568 // for the matching to be successful.
569 SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
571 if (ADDCNode->getOpcode() != ISD::ADDC)
574 SDValue MultHi = ADDENode->getOperand(0);
575 SDValue MultLo = ADDCNode->getOperand(0);
576 SDNode *MultNode = MultHi.getNode();
577 unsigned MultOpc = MultHi.getOpcode();
579 // MultHi and MultLo must be generated by the same node,
580 if (MultLo.getNode() != MultNode)
583 // and it must be a multiplication.
584 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
587 // MultLo amd MultHi must be the first and second output of MultNode
589 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
592 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
593 // of the values of MultNode, in which case MultNode will be removed in later
595 // If there exist users other than ADDENode or ADDCNode, this function returns
596 // here, which will result in MultNode being mapped to a single MULT
597 // instruction node rather than a pair of MULT and MADD instructions being
599 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
602 SDValue Chain = CurDAG->getEntryNode();
603 DebugLoc DL = ADDENode->getDebugLoc();
605 // create MipsMAdd(u) node
606 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
608 SDValue MAdd = CurDAG->getNode(MultOpc, DL, MVT::Glue,
609 MultNode->getOperand(0),// Factor 0
610 MultNode->getOperand(1),// Factor 1
611 ADDCNode->getOperand(1),// Lo0
612 ADDENode->getOperand(1));// Hi0
614 // create CopyFromReg nodes
615 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, DL, Mips::LO, MVT::i32,
617 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), DL,
619 CopyFromLo.getValue(2));
621 // replace uses of adde and addc here
622 if (!SDValue(ADDCNode, 0).use_empty())
623 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
625 if (!SDValue(ADDENode, 0).use_empty())
626 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
632 // Transforms a subgraph in CurDAG if the following pattern is found:
633 // (addc Lo0, multLo), (sube Hi0, multHi),
635 // multHi/Lo: product of multiplication
636 // Lo0: initial value of Lo register
637 // Hi0: initial value of Hi register
638 // Return true if pattern matching was successful.
639 static bool selectMSUB(SDNode *SUBENode, SelectionDAG *CurDAG) {
640 // SUBENode's second operand must be a flag output of an SUBC node in order
641 // for the matching to be successful.
642 SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
644 if (SUBCNode->getOpcode() != ISD::SUBC)
647 SDValue MultHi = SUBENode->getOperand(1);
648 SDValue MultLo = SUBCNode->getOperand(1);
649 SDNode *MultNode = MultHi.getNode();
650 unsigned MultOpc = MultHi.getOpcode();
652 // MultHi and MultLo must be generated by the same node,
653 if (MultLo.getNode() != MultNode)
656 // and it must be a multiplication.
657 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
660 // MultLo amd MultHi must be the first and second output of MultNode
662 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
665 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
666 // of the values of MultNode, in which case MultNode will be removed in later
668 // If there exist users other than SUBENode or SUBCNode, this function returns
669 // here, which will result in MultNode being mapped to a single MULT
670 // instruction node rather than a pair of MULT and MSUB instructions being
672 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
675 SDValue Chain = CurDAG->getEntryNode();
676 DebugLoc DL = SUBENode->getDebugLoc();
678 // create MipsSub(u) node
679 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
681 SDValue MSub = CurDAG->getNode(MultOpc, DL, MVT::Glue,
682 MultNode->getOperand(0),// Factor 0
683 MultNode->getOperand(1),// Factor 1
684 SUBCNode->getOperand(0),// Lo0
685 SUBENode->getOperand(0));// Hi0
687 // create CopyFromReg nodes
688 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, DL, Mips::LO, MVT::i32,
690 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), DL,
692 CopyFromLo.getValue(2));
694 // replace uses of sube and subc here
695 if (!SDValue(SUBCNode, 0).use_empty())
696 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
698 if (!SDValue(SUBENode, 0).use_empty())
699 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
704 static SDValue performADDECombine(SDNode *N, SelectionDAG &DAG,
705 TargetLowering::DAGCombinerInfo &DCI,
706 const MipsSubtarget *Subtarget) {
707 if (DCI.isBeforeLegalize())
710 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
712 return SDValue(N, 0);
717 static SDValue performSUBECombine(SDNode *N, SelectionDAG &DAG,
718 TargetLowering::DAGCombinerInfo &DCI,
719 const MipsSubtarget *Subtarget) {
720 if (DCI.isBeforeLegalize())
723 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
725 return SDValue(N, 0);
730 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
731 TargetLowering::DAGCombinerInfo &DCI,
732 const MipsSubtarget *Subtarget) {
733 if (DCI.isBeforeLegalizeOps())
736 EVT Ty = N->getValueType(0);
737 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
738 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
739 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
741 DebugLoc DL = N->getDebugLoc();
743 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
744 N->getOperand(0), N->getOperand(1));
745 SDValue InChain = DAG.getEntryNode();
746 SDValue InGlue = DivRem;
749 if (N->hasAnyUseOfValue(0)) {
750 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
752 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
753 InChain = CopyFromLo.getValue(1);
754 InGlue = CopyFromLo.getValue(2);
758 if (N->hasAnyUseOfValue(1)) {
759 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
761 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
767 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
769 default: llvm_unreachable("Unknown fp condition code!");
771 case ISD::SETOEQ: return Mips::FCOND_OEQ;
772 case ISD::SETUNE: return Mips::FCOND_UNE;
774 case ISD::SETOLT: return Mips::FCOND_OLT;
776 case ISD::SETOGT: return Mips::FCOND_OGT;
778 case ISD::SETOLE: return Mips::FCOND_OLE;
780 case ISD::SETOGE: return Mips::FCOND_OGE;
781 case ISD::SETULT: return Mips::FCOND_ULT;
782 case ISD::SETULE: return Mips::FCOND_ULE;
783 case ISD::SETUGT: return Mips::FCOND_UGT;
784 case ISD::SETUGE: return Mips::FCOND_UGE;
785 case ISD::SETUO: return Mips::FCOND_UN;
786 case ISD::SETO: return Mips::FCOND_OR;
788 case ISD::SETONE: return Mips::FCOND_ONE;
789 case ISD::SETUEQ: return Mips::FCOND_UEQ;
794 // Returns true if condition code has to be inverted.
795 static bool invertFPCondCode(Mips::CondCode CC) {
796 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
799 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
800 "Illegal Condition Code");
805 // Creates and returns an FPCmp node from a setcc node.
806 // Returns Op if setcc is not a floating point comparison.
807 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
808 // must be a SETCC node
809 if (Op.getOpcode() != ISD::SETCC)
812 SDValue LHS = Op.getOperand(0);
814 if (!LHS.getValueType().isFloatingPoint())
817 SDValue RHS = Op.getOperand(1);
818 DebugLoc DL = Op.getDebugLoc();
820 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
821 // node if necessary.
822 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
824 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
825 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
828 // Creates and returns a CMovFPT/F node.
829 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
830 SDValue False, DebugLoc DL) {
831 bool invert = invertFPCondCode((Mips::CondCode)
832 cast<ConstantSDNode>(Cond.getOperand(2))
835 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
836 True.getValueType(), True, False, Cond);
839 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
840 TargetLowering::DAGCombinerInfo &DCI,
841 const MipsSubtarget *Subtarget) {
842 if (DCI.isBeforeLegalizeOps())
845 SDValue SetCC = N->getOperand(0);
847 if ((SetCC.getOpcode() != ISD::SETCC) ||
848 !SetCC.getOperand(0).getValueType().isInteger())
851 SDValue False = N->getOperand(2);
852 EVT FalseTy = False.getValueType();
854 if (!FalseTy.isInteger())
857 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
859 if (!CN || CN->getZExtValue())
862 const DebugLoc DL = N->getDebugLoc();
863 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
864 SDValue True = N->getOperand(1);
866 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
867 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
869 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
872 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
873 TargetLowering::DAGCombinerInfo &DCI,
874 const MipsSubtarget *Subtarget) {
875 // Pattern match EXT.
876 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
877 // => ext $dst, $src, size, pos
878 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
881 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
882 unsigned ShiftRightOpc = ShiftRight.getOpcode();
884 // Op's first operand must be a shift right.
885 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
888 // The second operand of the shift must be an immediate.
890 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
893 uint64_t Pos = CN->getZExtValue();
894 uint64_t SMPos, SMSize;
896 // Op's second operand must be a shifted mask.
897 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
898 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
901 // Return if the shifted mask does not start at bit 0 or the sum of its size
902 // and Pos exceeds the word's size.
903 EVT ValTy = N->getValueType(0);
904 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
907 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
908 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
909 DAG.getConstant(SMSize, MVT::i32));
912 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
913 TargetLowering::DAGCombinerInfo &DCI,
914 const MipsSubtarget *Subtarget) {
915 // Pattern match INS.
916 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
917 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
918 // => ins $dst, $src, size, pos, $src1
919 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
922 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
923 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
926 // See if Op's first operand matches (and $src1 , mask0).
927 if (And0.getOpcode() != ISD::AND)
930 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
931 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
934 // See if Op's second operand matches (and (shl $src, pos), mask1).
935 if (And1.getOpcode() != ISD::AND)
938 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
939 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
942 // The shift masks must have the same position and size.
943 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
946 SDValue Shl = And1.getOperand(0);
947 if (Shl.getOpcode() != ISD::SHL)
950 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
953 unsigned Shamt = CN->getZExtValue();
955 // Return if the shift amount and the first bit position of mask are not the
957 EVT ValTy = N->getValueType(0);
958 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
961 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
962 DAG.getConstant(SMPos0, MVT::i32),
963 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
966 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
967 TargetLowering::DAGCombinerInfo &DCI,
968 const MipsSubtarget *Subtarget) {
969 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
971 if (DCI.isBeforeLegalizeOps())
974 SDValue Add = N->getOperand(1);
976 if (Add.getOpcode() != ISD::ADD)
979 SDValue Lo = Add.getOperand(1);
981 if ((Lo.getOpcode() != MipsISD::Lo) ||
982 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
985 EVT ValTy = N->getValueType(0);
986 DebugLoc DL = N->getDebugLoc();
988 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
990 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
993 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
995 SelectionDAG &DAG = DCI.DAG;
996 unsigned Opc = N->getOpcode();
1001 return performADDECombine(N, DAG, DCI, Subtarget);
1003 return performSUBECombine(N, DAG, DCI, Subtarget);
1006 return performDivRemCombine(N, DAG, DCI, Subtarget);
1008 return performSELECTCombine(N, DAG, DCI, Subtarget);
1010 return performANDCombine(N, DAG, DCI, Subtarget);
1012 return performORCombine(N, DAG, DCI, Subtarget);
1014 return performADDCombine(N, DAG, DCI, Subtarget);
1021 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
1022 SmallVectorImpl<SDValue> &Results,
1023 SelectionDAG &DAG) const {
1024 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1026 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1027 Results.push_back(Res.getValue(I));
1031 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1032 SmallVectorImpl<SDValue> &Results,
1033 SelectionDAG &DAG) const {
1034 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1036 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1037 Results.push_back(Res.getValue(I));
1040 SDValue MipsTargetLowering::
1041 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1043 switch (Op.getOpcode())
1045 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
1046 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
1047 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
1048 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
1049 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
1050 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
1051 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
1052 case ISD::SELECT: return lowerSELECT(Op, DAG);
1053 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
1054 case ISD::SETCC: return lowerSETCC(Op, DAG);
1055 case ISD::VASTART: return lowerVASTART(Op, DAG);
1056 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
1057 case ISD::FABS: return lowerFABS(Op, DAG);
1058 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
1059 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
1060 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
1061 case ISD::MEMBARRIER: return lowerMEMBARRIER(Op, DAG);
1062 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
1063 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
1064 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
1065 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
1066 case ISD::LOAD: return lowerLOAD(Op, DAG);
1067 case ISD::STORE: return lowerSTORE(Op, DAG);
1068 case ISD::INTRINSIC_WO_CHAIN: return lowerINTRINSIC_WO_CHAIN(Op, DAG);
1069 case ISD::INTRINSIC_W_CHAIN: return lowerINTRINSIC_W_CHAIN(Op, DAG);
1070 case ISD::ADD: return lowerADD(Op, DAG);
1075 //===----------------------------------------------------------------------===//
1076 // Lower helper functions
1077 //===----------------------------------------------------------------------===//
1079 // addLiveIn - This helper function adds the specified physical register to the
1080 // MachineFunction as a live in value. It also creates a corresponding
1081 // virtual register for it.
1083 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1085 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1086 MF.getRegInfo().addLiveIn(PReg, VReg);
1090 // Get fp branch code (not opcode) from condition code.
1091 static Mips::FPBranchCode getFPBranchCodeFromCond(Mips::CondCode CC) {
1092 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
1093 return Mips::BRANCH_T;
1095 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
1096 "Invalid CondCode.");
1098 return Mips::BRANCH_F;
1102 MipsTargetLowering::emitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
1104 // bposge32_pseudo $vr0
1114 // $vr0 = phi($vr2, $fbb, $vr1, $tbb)
1116 MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
1117 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1118 const TargetRegisterClass *RC = &Mips::CPURegsRegClass;
1119 DebugLoc DL = MI->getDebugLoc();
1120 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1121 MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
1122 MachineFunction *F = BB->getParent();
1123 MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
1124 MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
1125 MachineBasicBlock *Sink = F->CreateMachineBasicBlock(LLVM_BB);
1128 F->insert(It, Sink);
1130 // Transfer the remainder of BB and its successor edges to Sink.
1131 Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
1133 Sink->transferSuccessorsAndUpdatePHIs(BB);
1136 BB->addSuccessor(FBB);
1137 BB->addSuccessor(TBB);
1138 FBB->addSuccessor(Sink);
1139 TBB->addSuccessor(Sink);
1141 // Insert the real bposge32 instruction to $BB.
1142 BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
1145 unsigned VR2 = RegInfo.createVirtualRegister(RC);
1146 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
1147 .addReg(Mips::ZERO).addImm(0);
1148 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
1151 unsigned VR1 = RegInfo.createVirtualRegister(RC);
1152 BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
1153 .addReg(Mips::ZERO).addImm(1);
1155 // Insert phi function to $Sink.
1156 BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
1157 MI->getOperand(0).getReg())
1158 .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
1160 MI->eraseFromParent(); // The pseudo instruction is gone now.
1164 MachineBasicBlock *MipsTargetLowering::emitSel16(unsigned Opc, MachineInstr *MI,
1165 MachineBasicBlock *BB) const {
1166 if (DontExpandCondPseudos16)
1168 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1169 DebugLoc DL = MI->getDebugLoc();
1170 // To "insert" a SELECT_CC instruction, we actually have to insert the
1171 // diamond control-flow pattern. The incoming instruction knows the
1172 // destination vreg to set, the condition code register to branch on, the
1173 // true/false values to select between, and a branch opcode to use.
1174 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1175 MachineFunction::iterator It = BB;
1182 // bNE r1, r0, copy1MBB
1183 // fallthrough --> copy0MBB
1184 MachineBasicBlock *thisMBB = BB;
1185 MachineFunction *F = BB->getParent();
1186 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1187 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1188 F->insert(It, copy0MBB);
1189 F->insert(It, sinkMBB);
1191 // Transfer the remainder of BB and its successor edges to sinkMBB.
1192 sinkMBB->splice(sinkMBB->begin(), BB,
1193 llvm::next(MachineBasicBlock::iterator(MI)),
1195 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1197 // Next, add the true and fallthrough blocks as its successors.
1198 BB->addSuccessor(copy0MBB);
1199 BB->addSuccessor(sinkMBB);
1201 BuildMI(BB, DL, TII->get(Opc)).addReg(MI->getOperand(3).getReg())
1205 // %FalseValue = ...
1206 // # fallthrough to sinkMBB
1209 // Update machine-CFG edges
1210 BB->addSuccessor(sinkMBB);
1213 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1217 BuildMI(*BB, BB->begin(), DL,
1218 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1219 .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
1220 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
1222 MI->eraseFromParent(); // The pseudo instruction is gone now.
1226 MachineBasicBlock *MipsTargetLowering::emitSelT16
1227 (unsigned Opc1, unsigned Opc2,
1228 MachineInstr *MI, MachineBasicBlock *BB) const {
1229 if (DontExpandCondPseudos16)
1231 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1232 DebugLoc DL = MI->getDebugLoc();
1233 // To "insert" a SELECT_CC instruction, we actually have to insert the
1234 // diamond control-flow pattern. The incoming instruction knows the
1235 // destination vreg to set, the condition code register to branch on, the
1236 // true/false values to select between, and a branch opcode to use.
1237 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1238 MachineFunction::iterator It = BB;
1245 // bNE r1, r0, copy1MBB
1246 // fallthrough --> copy0MBB
1247 MachineBasicBlock *thisMBB = BB;
1248 MachineFunction *F = BB->getParent();
1249 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1250 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1251 F->insert(It, copy0MBB);
1252 F->insert(It, sinkMBB);
1254 // Transfer the remainder of BB and its successor edges to sinkMBB.
1255 sinkMBB->splice(sinkMBB->begin(), BB,
1256 llvm::next(MachineBasicBlock::iterator(MI)),
1258 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1260 // Next, add the true and fallthrough blocks as its successors.
1261 BB->addSuccessor(copy0MBB);
1262 BB->addSuccessor(sinkMBB);
1264 BuildMI(BB, DL, TII->get(Opc2)).addReg(MI->getOperand(3).getReg())
1265 .addReg(MI->getOperand(4).getReg());
1266 BuildMI(BB, DL, TII->get(Opc1)).addMBB(sinkMBB);
1269 // %FalseValue = ...
1270 // # fallthrough to sinkMBB
1273 // Update machine-CFG edges
1274 BB->addSuccessor(sinkMBB);
1277 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1281 BuildMI(*BB, BB->begin(), DL,
1282 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1283 .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
1284 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
1286 MI->eraseFromParent(); // The pseudo instruction is gone now.
1292 MachineBasicBlock *MipsTargetLowering::emitSeliT16
1293 (unsigned Opc1, unsigned Opc2,
1294 MachineInstr *MI, MachineBasicBlock *BB) const {
1295 if (DontExpandCondPseudos16)
1297 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1298 DebugLoc DL = MI->getDebugLoc();
1299 // To "insert" a SELECT_CC instruction, we actually have to insert the
1300 // diamond control-flow pattern. The incoming instruction knows the
1301 // destination vreg to set, the condition code register to branch on, the
1302 // true/false values to select between, and a branch opcode to use.
1303 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1304 MachineFunction::iterator It = BB;
1311 // bNE r1, r0, copy1MBB
1312 // fallthrough --> copy0MBB
1313 MachineBasicBlock *thisMBB = BB;
1314 MachineFunction *F = BB->getParent();
1315 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1316 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1317 F->insert(It, copy0MBB);
1318 F->insert(It, sinkMBB);
1320 // Transfer the remainder of BB and its successor edges to sinkMBB.
1321 sinkMBB->splice(sinkMBB->begin(), BB,
1322 llvm::next(MachineBasicBlock::iterator(MI)),
1324 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1326 // Next, add the true and fallthrough blocks as its successors.
1327 BB->addSuccessor(copy0MBB);
1328 BB->addSuccessor(sinkMBB);
1330 BuildMI(BB, DL, TII->get(Opc2)).addReg(MI->getOperand(3).getReg())
1331 .addImm(MI->getOperand(4).getImm());
1332 BuildMI(BB, DL, TII->get(Opc1)).addMBB(sinkMBB);
1335 // %FalseValue = ...
1336 // # fallthrough to sinkMBB
1339 // Update machine-CFG edges
1340 BB->addSuccessor(sinkMBB);
1343 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1347 BuildMI(*BB, BB->begin(), DL,
1348 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1349 .addReg(MI->getOperand(1).getReg()).addMBB(thisMBB)
1350 .addReg(MI->getOperand(2).getReg()).addMBB(copy0MBB);
1352 MI->eraseFromParent(); // The pseudo instruction is gone now.
1359 *MipsTargetLowering::emitFEXT_T8I816_ins(unsigned BtOpc, unsigned CmpOpc,
1361 MachineBasicBlock *BB) const {
1362 if (DontExpandCondPseudos16)
1364 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1365 unsigned regX = MI->getOperand(0).getReg();
1366 unsigned regY = MI->getOperand(1).getReg();
1367 MachineBasicBlock *target = MI->getOperand(2).getMBB();
1368 BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(CmpOpc)).addReg(regX).addReg(regY);
1369 BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(BtOpc)).addMBB(target);
1370 MI->eraseFromParent(); // The pseudo instruction is gone now.
1375 MachineBasicBlock *MipsTargetLowering::emitFEXT_T8I8I16_ins(
1376 unsigned BtOpc, unsigned CmpiOpc, unsigned CmpiXOpc,
1377 MachineInstr *MI, MachineBasicBlock *BB) const {
1378 if (DontExpandCondPseudos16)
1380 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1381 unsigned regX = MI->getOperand(0).getReg();
1382 int64_t imm = MI->getOperand(1).getImm();
1383 MachineBasicBlock *target = MI->getOperand(2).getMBB();
1387 else if (isUInt<16>(imm))
1390 llvm_unreachable("immediate field not usable");
1391 BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(CmpOpc)).addReg(regX).addImm(imm);
1392 BuildMI(*BB, MI, MI->getDebugLoc(), TII->get(BtOpc)).addMBB(target);
1393 MI->eraseFromParent(); // The pseudo instruction is gone now.
1398 static unsigned Mips16WhichOp8uOr16simm
1399 (unsigned shortOp, unsigned longOp, int64_t Imm) {
1402 else if (isInt<16>(Imm))
1405 llvm_unreachable("immediate field not usable");
1408 MachineBasicBlock *MipsTargetLowering::emitFEXT_CCRX16_ins(
1410 MachineInstr *MI, MachineBasicBlock *BB) const {
1411 if (DontExpandCondPseudos16)
1413 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1414 unsigned CC = MI->getOperand(0).getReg();
1415 unsigned regX = MI->getOperand(1).getReg();
1416 unsigned regY = MI->getOperand(2).getReg();
1417 BuildMI(*BB, MI, MI->getDebugLoc(),
1418 TII->get(SltOpc)).addReg(regX).addReg(regY);
1419 BuildMI(*BB, MI, MI->getDebugLoc(),
1420 TII->get(Mips::MoveR3216), CC).addReg(Mips::T8);
1421 MI->eraseFromParent(); // The pseudo instruction is gone now.
1424 MachineBasicBlock *MipsTargetLowering::emitFEXT_CCRXI16_ins(
1425 unsigned SltiOpc, unsigned SltiXOpc,
1426 MachineInstr *MI, MachineBasicBlock *BB )const {
1427 if (DontExpandCondPseudos16)
1429 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1430 unsigned CC = MI->getOperand(0).getReg();
1431 unsigned regX = MI->getOperand(1).getReg();
1432 int64_t Imm = MI->getOperand(2).getImm();
1433 unsigned SltOpc = Mips16WhichOp8uOr16simm(SltiOpc, SltiXOpc, Imm);
1434 BuildMI(*BB, MI, MI->getDebugLoc(),
1435 TII->get(SltOpc)).addReg(regX).addImm(Imm);
1436 BuildMI(*BB, MI, MI->getDebugLoc(),
1437 TII->get(Mips::MoveR3216), CC).addReg(Mips::T8);
1438 MI->eraseFromParent(); // The pseudo instruction is gone now.
1443 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1444 MachineBasicBlock *BB) const {
1445 switch (MI->getOpcode()) {
1447 llvm_unreachable("Unexpected instr type to insert");
1448 case Mips::ATOMIC_LOAD_ADD_I8:
1449 case Mips::ATOMIC_LOAD_ADD_I8_P8:
1450 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1451 case Mips::ATOMIC_LOAD_ADD_I16:
1452 case Mips::ATOMIC_LOAD_ADD_I16_P8:
1453 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1454 case Mips::ATOMIC_LOAD_ADD_I32:
1455 case Mips::ATOMIC_LOAD_ADD_I32_P8:
1456 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
1457 case Mips::ATOMIC_LOAD_ADD_I64:
1458 case Mips::ATOMIC_LOAD_ADD_I64_P8:
1459 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
1461 case Mips::ATOMIC_LOAD_AND_I8:
1462 case Mips::ATOMIC_LOAD_AND_I8_P8:
1463 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1464 case Mips::ATOMIC_LOAD_AND_I16:
1465 case Mips::ATOMIC_LOAD_AND_I16_P8:
1466 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1467 case Mips::ATOMIC_LOAD_AND_I32:
1468 case Mips::ATOMIC_LOAD_AND_I32_P8:
1469 return emitAtomicBinary(MI, BB, 4, Mips::AND);
1470 case Mips::ATOMIC_LOAD_AND_I64:
1471 case Mips::ATOMIC_LOAD_AND_I64_P8:
1472 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
1474 case Mips::ATOMIC_LOAD_OR_I8:
1475 case Mips::ATOMIC_LOAD_OR_I8_P8:
1476 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1477 case Mips::ATOMIC_LOAD_OR_I16:
1478 case Mips::ATOMIC_LOAD_OR_I16_P8:
1479 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1480 case Mips::ATOMIC_LOAD_OR_I32:
1481 case Mips::ATOMIC_LOAD_OR_I32_P8:
1482 return emitAtomicBinary(MI, BB, 4, Mips::OR);
1483 case Mips::ATOMIC_LOAD_OR_I64:
1484 case Mips::ATOMIC_LOAD_OR_I64_P8:
1485 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
1487 case Mips::ATOMIC_LOAD_XOR_I8:
1488 case Mips::ATOMIC_LOAD_XOR_I8_P8:
1489 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1490 case Mips::ATOMIC_LOAD_XOR_I16:
1491 case Mips::ATOMIC_LOAD_XOR_I16_P8:
1492 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1493 case Mips::ATOMIC_LOAD_XOR_I32:
1494 case Mips::ATOMIC_LOAD_XOR_I32_P8:
1495 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
1496 case Mips::ATOMIC_LOAD_XOR_I64:
1497 case Mips::ATOMIC_LOAD_XOR_I64_P8:
1498 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
1500 case Mips::ATOMIC_LOAD_NAND_I8:
1501 case Mips::ATOMIC_LOAD_NAND_I8_P8:
1502 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
1503 case Mips::ATOMIC_LOAD_NAND_I16:
1504 case Mips::ATOMIC_LOAD_NAND_I16_P8:
1505 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
1506 case Mips::ATOMIC_LOAD_NAND_I32:
1507 case Mips::ATOMIC_LOAD_NAND_I32_P8:
1508 return emitAtomicBinary(MI, BB, 4, 0, true);
1509 case Mips::ATOMIC_LOAD_NAND_I64:
1510 case Mips::ATOMIC_LOAD_NAND_I64_P8:
1511 return emitAtomicBinary(MI, BB, 8, 0, true);
1513 case Mips::ATOMIC_LOAD_SUB_I8:
1514 case Mips::ATOMIC_LOAD_SUB_I8_P8:
1515 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1516 case Mips::ATOMIC_LOAD_SUB_I16:
1517 case Mips::ATOMIC_LOAD_SUB_I16_P8:
1518 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1519 case Mips::ATOMIC_LOAD_SUB_I32:
1520 case Mips::ATOMIC_LOAD_SUB_I32_P8:
1521 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
1522 case Mips::ATOMIC_LOAD_SUB_I64:
1523 case Mips::ATOMIC_LOAD_SUB_I64_P8:
1524 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1526 case Mips::ATOMIC_SWAP_I8:
1527 case Mips::ATOMIC_SWAP_I8_P8:
1528 return emitAtomicBinaryPartword(MI, BB, 1, 0);
1529 case Mips::ATOMIC_SWAP_I16:
1530 case Mips::ATOMIC_SWAP_I16_P8:
1531 return emitAtomicBinaryPartword(MI, BB, 2, 0);
1532 case Mips::ATOMIC_SWAP_I32:
1533 case Mips::ATOMIC_SWAP_I32_P8:
1534 return emitAtomicBinary(MI, BB, 4, 0);
1535 case Mips::ATOMIC_SWAP_I64:
1536 case Mips::ATOMIC_SWAP_I64_P8:
1537 return emitAtomicBinary(MI, BB, 8, 0);
1539 case Mips::ATOMIC_CMP_SWAP_I8:
1540 case Mips::ATOMIC_CMP_SWAP_I8_P8:
1541 return emitAtomicCmpSwapPartword(MI, BB, 1);
1542 case Mips::ATOMIC_CMP_SWAP_I16:
1543 case Mips::ATOMIC_CMP_SWAP_I16_P8:
1544 return emitAtomicCmpSwapPartword(MI, BB, 2);
1545 case Mips::ATOMIC_CMP_SWAP_I32:
1546 case Mips::ATOMIC_CMP_SWAP_I32_P8:
1547 return emitAtomicCmpSwap(MI, BB, 4);
1548 case Mips::ATOMIC_CMP_SWAP_I64:
1549 case Mips::ATOMIC_CMP_SWAP_I64_P8:
1550 return emitAtomicCmpSwap(MI, BB, 8);
1551 case Mips::BPOSGE32_PSEUDO:
1552 return emitBPOSGE32(MI, BB);
1554 return emitSel16(Mips::BeqzRxImm16, MI, BB);
1556 return emitSel16(Mips::BnezRxImm16, MI, BB);
1557 case Mips::SelTBteqZCmpi:
1558 return emitSeliT16(Mips::BteqzX16, Mips::CmpiRxImmX16, MI, BB);
1559 case Mips::SelTBteqZSlti:
1560 return emitSeliT16(Mips::BteqzX16, Mips::SltiRxImmX16, MI, BB);
1561 case Mips::SelTBteqZSltiu:
1562 return emitSeliT16(Mips::BteqzX16, Mips::SltiuRxImmX16, MI, BB);
1563 case Mips::SelTBtneZCmpi:
1564 return emitSeliT16(Mips::BtnezX16, Mips::CmpiRxImmX16, MI, BB);
1565 case Mips::SelTBtneZSlti:
1566 return emitSeliT16(Mips::BtnezX16, Mips::SltiRxImmX16, MI, BB);
1567 case Mips::SelTBtneZSltiu:
1568 return emitSeliT16(Mips::BtnezX16, Mips::SltiuRxImmX16, MI, BB);
1569 case Mips::SelTBteqZCmp:
1570 return emitSelT16(Mips::BteqzX16, Mips::CmpRxRy16, MI, BB);
1571 case Mips::SelTBteqZSlt:
1572 return emitSelT16(Mips::BteqzX16, Mips::SltRxRy16, MI, BB);
1573 case Mips::SelTBteqZSltu:
1574 return emitSelT16(Mips::BteqzX16, Mips::SltuRxRy16, MI, BB);
1575 case Mips::SelTBtneZCmp:
1576 return emitSelT16(Mips::BtnezX16, Mips::CmpRxRy16, MI, BB);
1577 case Mips::SelTBtneZSlt:
1578 return emitSelT16(Mips::BtnezX16, Mips::SltRxRy16, MI, BB);
1579 case Mips::SelTBtneZSltu:
1580 return emitSelT16(Mips::BtnezX16, Mips::SltuRxRy16, MI, BB);
1581 case Mips::BteqzT8CmpX16:
1582 return emitFEXT_T8I816_ins(Mips::BteqzX16, Mips::CmpRxRy16, MI, BB);
1583 case Mips::BteqzT8SltX16:
1584 return emitFEXT_T8I816_ins(Mips::BteqzX16, Mips::SltRxRy16, MI, BB);
1585 case Mips::BteqzT8SltuX16:
1586 // TBD: figure out a way to get this or remove the instruction
1588 return emitFEXT_T8I816_ins(Mips::BteqzX16, Mips::SltuRxRy16, MI, BB);
1589 case Mips::BtnezT8CmpX16:
1590 return emitFEXT_T8I816_ins(Mips::BtnezX16, Mips::CmpRxRy16, MI, BB);
1591 case Mips::BtnezT8SltX16:
1592 return emitFEXT_T8I816_ins(Mips::BtnezX16, Mips::SltRxRy16, MI, BB);
1593 case Mips::BtnezT8SltuX16:
1594 // TBD: figure out a way to get this or remove the instruction
1596 return emitFEXT_T8I816_ins(Mips::BtnezX16, Mips::SltuRxRy16, MI, BB);
1597 case Mips::BteqzT8CmpiX16: return emitFEXT_T8I8I16_ins(
1598 Mips::BteqzX16, Mips::CmpiRxImm16, Mips::CmpiRxImmX16, MI, BB);
1599 case Mips::BteqzT8SltiX16: return emitFEXT_T8I8I16_ins(
1600 Mips::BteqzX16, Mips::SltiRxImm16, Mips::SltiRxImmX16, MI, BB);
1601 case Mips::BteqzT8SltiuX16: return emitFEXT_T8I8I16_ins(
1602 Mips::BteqzX16, Mips::SltiuRxImm16, Mips::SltiuRxImmX16, MI, BB);
1603 case Mips::BtnezT8CmpiX16: return emitFEXT_T8I8I16_ins(
1604 Mips::BtnezX16, Mips::CmpiRxImm16, Mips::CmpiRxImmX16, MI, BB);
1605 case Mips::BtnezT8SltiX16: return emitFEXT_T8I8I16_ins(
1606 Mips::BtnezX16, Mips::SltiRxImm16, Mips::SltiRxImmX16, MI, BB);
1607 case Mips::BtnezT8SltiuX16: return emitFEXT_T8I8I16_ins(
1608 Mips::BtnezX16, Mips::SltiuRxImm16, Mips::SltiuRxImmX16, MI, BB);
1610 case Mips::SltCCRxRy16:
1611 return emitFEXT_CCRX16_ins(Mips::SltRxRy16, MI, BB);
1613 case Mips::SltiCCRxImmX16:
1614 return emitFEXT_CCRXI16_ins
1615 (Mips::SltiRxImm16, Mips::SltiRxImmX16, MI, BB);
1616 case Mips::SltiuCCRxImmX16:
1617 return emitFEXT_CCRXI16_ins
1618 (Mips::SltiuRxImm16, Mips::SltiuRxImmX16, MI, BB);
1619 case Mips::SltuCCRxRy16:
1620 return emitFEXT_CCRX16_ins
1621 (Mips::SltuRxRy16, MI, BB);
1625 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1626 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1628 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1629 unsigned Size, unsigned BinOpcode,
1631 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1633 MachineFunction *MF = BB->getParent();
1634 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1635 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1636 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1637 DebugLoc DL = MI->getDebugLoc();
1638 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1641 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1642 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1649 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1650 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1653 ZERO = Mips::ZERO_64;
1657 unsigned OldVal = MI->getOperand(0).getReg();
1658 unsigned Ptr = MI->getOperand(1).getReg();
1659 unsigned Incr = MI->getOperand(2).getReg();
1661 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1662 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1663 unsigned Success = RegInfo.createVirtualRegister(RC);
1665 // insert new blocks after the current block
1666 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1667 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1668 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1669 MachineFunction::iterator It = BB;
1671 MF->insert(It, loopMBB);
1672 MF->insert(It, exitMBB);
1674 // Transfer the remainder of BB and its successor edges to exitMBB.
1675 exitMBB->splice(exitMBB->begin(), BB,
1676 llvm::next(MachineBasicBlock::iterator(MI)),
1678 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1682 // fallthrough --> loopMBB
1683 BB->addSuccessor(loopMBB);
1684 loopMBB->addSuccessor(loopMBB);
1685 loopMBB->addSuccessor(exitMBB);
1688 // ll oldval, 0(ptr)
1689 // <binop> storeval, oldval, incr
1690 // sc success, storeval, 0(ptr)
1691 // beq success, $0, loopMBB
1693 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1695 // and andres, oldval, incr
1696 // nor storeval, $0, andres
1697 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1698 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1699 } else if (BinOpcode) {
1700 // <binop> storeval, oldval, incr
1701 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1705 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1706 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1708 MI->eraseFromParent(); // The instruction is gone now.
1714 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
1715 MachineBasicBlock *BB,
1716 unsigned Size, unsigned BinOpcode,
1718 assert((Size == 1 || Size == 2) &&
1719 "Unsupported size for EmitAtomicBinaryPartial.");
1721 MachineFunction *MF = BB->getParent();
1722 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1723 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1724 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1725 DebugLoc DL = MI->getDebugLoc();
1726 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1727 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1729 unsigned Dest = MI->getOperand(0).getReg();
1730 unsigned Ptr = MI->getOperand(1).getReg();
1731 unsigned Incr = MI->getOperand(2).getReg();
1733 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1734 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1735 unsigned Mask = RegInfo.createVirtualRegister(RC);
1736 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1737 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1738 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1739 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1740 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1741 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1742 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1743 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1744 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1745 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1746 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1747 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1748 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1749 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1750 unsigned Success = RegInfo.createVirtualRegister(RC);
1752 // insert new blocks after the current block
1753 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1754 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1755 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1756 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1757 MachineFunction::iterator It = BB;
1759 MF->insert(It, loopMBB);
1760 MF->insert(It, sinkMBB);
1761 MF->insert(It, exitMBB);
1763 // Transfer the remainder of BB and its successor edges to exitMBB.
1764 exitMBB->splice(exitMBB->begin(), BB,
1765 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1766 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1768 BB->addSuccessor(loopMBB);
1769 loopMBB->addSuccessor(loopMBB);
1770 loopMBB->addSuccessor(sinkMBB);
1771 sinkMBB->addSuccessor(exitMBB);
1774 // addiu masklsb2,$0,-4 # 0xfffffffc
1775 // and alignedaddr,ptr,masklsb2
1776 // andi ptrlsb2,ptr,3
1777 // sll shiftamt,ptrlsb2,3
1778 // ori maskupper,$0,255 # 0xff
1779 // sll mask,maskupper,shiftamt
1780 // nor mask2,$0,mask
1781 // sll incr2,incr,shiftamt
1783 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1784 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1785 .addReg(Mips::ZERO).addImm(-4);
1786 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1787 .addReg(Ptr).addReg(MaskLSB2);
1788 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1789 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1790 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1791 .addReg(Mips::ZERO).addImm(MaskImm);
1792 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1793 .addReg(ShiftAmt).addReg(MaskUpper);
1794 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1795 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1797 // atomic.load.binop
1799 // ll oldval,0(alignedaddr)
1800 // binop binopres,oldval,incr2
1801 // and newval,binopres,mask
1802 // and maskedoldval0,oldval,mask2
1803 // or storeval,maskedoldval0,newval
1804 // sc success,storeval,0(alignedaddr)
1805 // beq success,$0,loopMBB
1809 // ll oldval,0(alignedaddr)
1810 // and newval,incr2,mask
1811 // and maskedoldval0,oldval,mask2
1812 // or storeval,maskedoldval0,newval
1813 // sc success,storeval,0(alignedaddr)
1814 // beq success,$0,loopMBB
1817 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1819 // and andres, oldval, incr2
1820 // nor binopres, $0, andres
1821 // and newval, binopres, mask
1822 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1823 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1824 .addReg(Mips::ZERO).addReg(AndRes);
1825 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1826 } else if (BinOpcode) {
1827 // <binop> binopres, oldval, incr2
1828 // and newval, binopres, mask
1829 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1830 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1831 } else {// atomic.swap
1832 // and newval, incr2, mask
1833 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1836 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1837 .addReg(OldVal).addReg(Mask2);
1838 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1839 .addReg(MaskedOldVal0).addReg(NewVal);
1840 BuildMI(BB, DL, TII->get(SC), Success)
1841 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1842 BuildMI(BB, DL, TII->get(Mips::BEQ))
1843 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1846 // and maskedoldval1,oldval,mask
1847 // srl srlres,maskedoldval1,shiftamt
1848 // sll sllres,srlres,24
1849 // sra dest,sllres,24
1851 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1853 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1854 .addReg(OldVal).addReg(Mask);
1855 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1856 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1857 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1858 .addReg(SrlRes).addImm(ShiftImm);
1859 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1860 .addReg(SllRes).addImm(ShiftImm);
1862 MI->eraseFromParent(); // The instruction is gone now.
1868 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1869 MachineBasicBlock *BB,
1870 unsigned Size) const {
1871 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1873 MachineFunction *MF = BB->getParent();
1874 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1875 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1876 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1877 DebugLoc DL = MI->getDebugLoc();
1878 unsigned LL, SC, ZERO, BNE, BEQ;
1881 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1882 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1888 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1889 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1890 ZERO = Mips::ZERO_64;
1895 unsigned Dest = MI->getOperand(0).getReg();
1896 unsigned Ptr = MI->getOperand(1).getReg();
1897 unsigned OldVal = MI->getOperand(2).getReg();
1898 unsigned NewVal = MI->getOperand(3).getReg();
1900 unsigned Success = RegInfo.createVirtualRegister(RC);
1902 // insert new blocks after the current block
1903 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1904 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1905 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1906 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1907 MachineFunction::iterator It = BB;
1909 MF->insert(It, loop1MBB);
1910 MF->insert(It, loop2MBB);
1911 MF->insert(It, exitMBB);
1913 // Transfer the remainder of BB and its successor edges to exitMBB.
1914 exitMBB->splice(exitMBB->begin(), BB,
1915 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1916 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1920 // fallthrough --> loop1MBB
1921 BB->addSuccessor(loop1MBB);
1922 loop1MBB->addSuccessor(exitMBB);
1923 loop1MBB->addSuccessor(loop2MBB);
1924 loop2MBB->addSuccessor(loop1MBB);
1925 loop2MBB->addSuccessor(exitMBB);
1929 // bne dest, oldval, exitMBB
1931 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1932 BuildMI(BB, DL, TII->get(BNE))
1933 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1936 // sc success, newval, 0(ptr)
1937 // beq success, $0, loop1MBB
1939 BuildMI(BB, DL, TII->get(SC), Success)
1940 .addReg(NewVal).addReg(Ptr).addImm(0);
1941 BuildMI(BB, DL, TII->get(BEQ))
1942 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1944 MI->eraseFromParent(); // The instruction is gone now.
1950 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1951 MachineBasicBlock *BB,
1952 unsigned Size) const {
1953 assert((Size == 1 || Size == 2) &&
1954 "Unsupported size for EmitAtomicCmpSwapPartial.");
1956 MachineFunction *MF = BB->getParent();
1957 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1958 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1959 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1960 DebugLoc DL = MI->getDebugLoc();
1961 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1962 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1964 unsigned Dest = MI->getOperand(0).getReg();
1965 unsigned Ptr = MI->getOperand(1).getReg();
1966 unsigned CmpVal = MI->getOperand(2).getReg();
1967 unsigned NewVal = MI->getOperand(3).getReg();
1969 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1970 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1971 unsigned Mask = RegInfo.createVirtualRegister(RC);
1972 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1973 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1974 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1975 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1976 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1977 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1978 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1979 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1980 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1981 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1982 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1983 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1984 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1985 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1986 unsigned Success = RegInfo.createVirtualRegister(RC);
1988 // insert new blocks after the current block
1989 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1990 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1991 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1992 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1993 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1994 MachineFunction::iterator It = BB;
1996 MF->insert(It, loop1MBB);
1997 MF->insert(It, loop2MBB);
1998 MF->insert(It, sinkMBB);
1999 MF->insert(It, exitMBB);
2001 // Transfer the remainder of BB and its successor edges to exitMBB.
2002 exitMBB->splice(exitMBB->begin(), BB,
2003 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
2004 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
2006 BB->addSuccessor(loop1MBB);
2007 loop1MBB->addSuccessor(sinkMBB);
2008 loop1MBB->addSuccessor(loop2MBB);
2009 loop2MBB->addSuccessor(loop1MBB);
2010 loop2MBB->addSuccessor(sinkMBB);
2011 sinkMBB->addSuccessor(exitMBB);
2013 // FIXME: computation of newval2 can be moved to loop2MBB.
2015 // addiu masklsb2,$0,-4 # 0xfffffffc
2016 // and alignedaddr,ptr,masklsb2
2017 // andi ptrlsb2,ptr,3
2018 // sll shiftamt,ptrlsb2,3
2019 // ori maskupper,$0,255 # 0xff
2020 // sll mask,maskupper,shiftamt
2021 // nor mask2,$0,mask
2022 // andi maskedcmpval,cmpval,255
2023 // sll shiftedcmpval,maskedcmpval,shiftamt
2024 // andi maskednewval,newval,255
2025 // sll shiftednewval,maskednewval,shiftamt
2026 int64_t MaskImm = (Size == 1) ? 255 : 65535;
2027 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
2028 .addReg(Mips::ZERO).addImm(-4);
2029 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
2030 .addReg(Ptr).addReg(MaskLSB2);
2031 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
2032 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
2033 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
2034 .addReg(Mips::ZERO).addImm(MaskImm);
2035 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
2036 .addReg(ShiftAmt).addReg(MaskUpper);
2037 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
2038 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
2039 .addReg(CmpVal).addImm(MaskImm);
2040 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
2041 .addReg(ShiftAmt).addReg(MaskedCmpVal);
2042 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
2043 .addReg(NewVal).addImm(MaskImm);
2044 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
2045 .addReg(ShiftAmt).addReg(MaskedNewVal);
2048 // ll oldval,0(alginedaddr)
2049 // and maskedoldval0,oldval,mask
2050 // bne maskedoldval0,shiftedcmpval,sinkMBB
2052 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
2053 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
2054 .addReg(OldVal).addReg(Mask);
2055 BuildMI(BB, DL, TII->get(Mips::BNE))
2056 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
2059 // and maskedoldval1,oldval,mask2
2060 // or storeval,maskedoldval1,shiftednewval
2061 // sc success,storeval,0(alignedaddr)
2062 // beq success,$0,loop1MBB
2064 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
2065 .addReg(OldVal).addReg(Mask2);
2066 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
2067 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
2068 BuildMI(BB, DL, TII->get(SC), Success)
2069 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
2070 BuildMI(BB, DL, TII->get(Mips::BEQ))
2071 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
2074 // srl srlres,maskedoldval0,shiftamt
2075 // sll sllres,srlres,24
2076 // sra dest,sllres,24
2078 int64_t ShiftImm = (Size == 1) ? 24 : 16;
2080 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
2081 .addReg(ShiftAmt).addReg(MaskedOldVal0);
2082 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
2083 .addReg(SrlRes).addImm(ShiftImm);
2084 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
2085 .addReg(SllRes).addImm(ShiftImm);
2087 MI->eraseFromParent(); // The instruction is gone now.
2092 //===----------------------------------------------------------------------===//
2093 // Misc Lower Operation implementation
2094 //===----------------------------------------------------------------------===//
2095 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
2096 SDValue Chain = Op.getOperand(0);
2097 SDValue Table = Op.getOperand(1);
2098 SDValue Index = Op.getOperand(2);
2099 DebugLoc DL = Op.getDebugLoc();
2100 EVT PTy = getPointerTy();
2101 unsigned EntrySize =
2102 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
2104 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
2105 DAG.getConstant(EntrySize, PTy));
2106 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
2108 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
2109 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
2110 MachinePointerInfo::getJumpTable(), MemVT, false, false,
2112 Chain = Addr.getValue(1);
2114 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
2115 // For PIC, the sequence is:
2116 // BRIND(load(Jumptable + index) + RelocBase)
2117 // RelocBase can be JumpTable, GOT or some sort of global base.
2118 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
2119 getPICJumpTableRelocBase(Table, DAG));
2122 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
2125 SDValue MipsTargetLowering::
2126 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
2128 // The first operand is the chain, the second is the condition, the third is
2129 // the block to branch to if the condition is true.
2130 SDValue Chain = Op.getOperand(0);
2131 SDValue Dest = Op.getOperand(2);
2132 DebugLoc DL = Op.getDebugLoc();
2134 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
2136 // Return if flag is not set by a floating point comparison.
2137 if (CondRes.getOpcode() != MipsISD::FPCmp)
2140 SDValue CCNode = CondRes.getOperand(2);
2142 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
2143 SDValue BrCode = DAG.getConstant(getFPBranchCodeFromCond(CC), MVT::i32);
2145 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
2149 SDValue MipsTargetLowering::
2150 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
2152 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
2154 // Return if flag is not set by a floating point comparison.
2155 if (Cond.getOpcode() != MipsISD::FPCmp)
2158 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
2162 SDValue MipsTargetLowering::
2163 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
2165 DebugLoc DL = Op.getDebugLoc();
2166 EVT Ty = Op.getOperand(0).getValueType();
2167 SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
2168 Op.getOperand(0), Op.getOperand(1),
2171 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
2175 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
2176 SDValue Cond = createFPCmp(DAG, Op);
2178 assert(Cond.getOpcode() == MipsISD::FPCmp &&
2179 "Floating point operand expected.");
2181 SDValue True = DAG.getConstant(1, MVT::i32);
2182 SDValue False = DAG.getConstant(0, MVT::i32);
2184 return createCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
2187 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
2188 SelectionDAG &DAG) const {
2189 // FIXME there isn't actually debug info here
2190 DebugLoc DL = Op.getDebugLoc();
2191 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
2193 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
2194 const MipsTargetObjectFile &TLOF =
2195 (const MipsTargetObjectFile&)getObjFileLowering();
2197 // %gp_rel relocation
2198 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
2199 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
2201 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
2202 DAG.getVTList(MVT::i32), &GA, 1);
2203 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
2204 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
2207 // %hi/%lo relocation
2208 return getAddrNonPIC(Op, DAG);
2211 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
2212 return getAddrLocal(Op, DAG, HasMips64);
2215 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
2216 MipsII::MO_GOT_LO16);
2218 return getAddrGlobal(Op, DAG,
2219 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
2222 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
2223 SelectionDAG &DAG) const {
2224 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2225 return getAddrNonPIC(Op, DAG);
2227 return getAddrLocal(Op, DAG, HasMips64);
2230 SDValue MipsTargetLowering::
2231 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
2233 // If the relocation model is PIC, use the General Dynamic TLS Model or
2234 // Local Dynamic TLS model, otherwise use the Initial Exec or
2235 // Local Exec TLS Model.
2237 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
2238 DebugLoc DL = GA->getDebugLoc();
2239 const GlobalValue *GV = GA->getGlobal();
2240 EVT PtrVT = getPointerTy();
2242 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
2244 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
2245 // General Dynamic and Local Dynamic TLS Model.
2246 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
2249 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
2250 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
2251 getGlobalReg(DAG, PtrVT), TGA);
2252 unsigned PtrSize = PtrVT.getSizeInBits();
2253 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
2255 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
2259 Entry.Node = Argument;
2261 Args.push_back(Entry);
2263 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
2264 false, false, false, false, 0, CallingConv::C,
2265 /*IsTailCall=*/false, /*doesNotRet=*/false,
2266 /*isReturnValueUsed=*/true,
2267 TlsGetAddr, Args, DAG, DL);
2268 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
2270 SDValue Ret = CallResult.first;
2272 if (model != TLSModel::LocalDynamic)
2275 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2276 MipsII::MO_DTPREL_HI);
2277 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
2278 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2279 MipsII::MO_DTPREL_LO);
2280 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2281 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
2282 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
2286 if (model == TLSModel::InitialExec) {
2287 // Initial Exec TLS Model
2288 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2289 MipsII::MO_GOTTPREL);
2290 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
2292 Offset = DAG.getLoad(PtrVT, DL,
2293 DAG.getEntryNode(), TGA, MachinePointerInfo(),
2294 false, false, false, 0);
2296 // Local Exec TLS Model
2297 assert(model == TLSModel::LocalExec);
2298 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2299 MipsII::MO_TPREL_HI);
2300 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
2301 MipsII::MO_TPREL_LO);
2302 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
2303 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
2304 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
2307 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
2308 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
2311 SDValue MipsTargetLowering::
2312 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
2314 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2315 return getAddrNonPIC(Op, DAG);
2317 return getAddrLocal(Op, DAG, HasMips64);
2320 SDValue MipsTargetLowering::
2321 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
2323 // gp_rel relocation
2324 // FIXME: we should reference the constant pool using small data sections,
2325 // but the asm printer currently doesn't support this feature without
2326 // hacking it. This feature should come soon so we can uncomment the
2328 //if (IsInSmallSection(C->getType())) {
2329 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
2330 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
2331 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
2333 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2334 return getAddrNonPIC(Op, DAG);
2336 return getAddrLocal(Op, DAG, HasMips64);
2339 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2340 MachineFunction &MF = DAG.getMachineFunction();
2341 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2343 DebugLoc DL = Op.getDebugLoc();
2344 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2347 // vastart just stores the address of the VarArgsFrameIndex slot into the
2348 // memory location argument.
2349 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2350 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
2351 MachinePointerInfo(SV), false, false, 0);
2354 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2355 EVT TyX = Op.getOperand(0).getValueType();
2356 EVT TyY = Op.getOperand(1).getValueType();
2357 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2358 SDValue Const31 = DAG.getConstant(31, MVT::i32);
2359 DebugLoc DL = Op.getDebugLoc();
2362 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2364 SDValue X = (TyX == MVT::f32) ?
2365 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2366 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2368 SDValue Y = (TyY == MVT::f32) ?
2369 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2370 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2374 // ext E, Y, 31, 1 ; extract bit31 of Y
2375 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2376 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2377 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2380 // srl SrlX, SllX, 1
2382 // sll SllY, SrlX, 31
2383 // or Or, SrlX, SllY
2384 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2385 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2386 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2387 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2388 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2391 if (TyX == MVT::f32)
2392 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2394 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2395 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2396 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2399 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2400 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2401 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2402 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2403 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2404 DebugLoc DL = Op.getDebugLoc();
2406 // Bitcast to integer nodes.
2407 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2408 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2411 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2412 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2413 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2414 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
2416 if (WidthX > WidthY)
2417 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2418 else if (WidthY > WidthX)
2419 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2421 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2422 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2423 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2426 // (d)sll SllX, X, 1
2427 // (d)srl SrlX, SllX, 1
2428 // (d)srl SrlY, Y, width(Y)-1
2429 // (d)sll SllY, SrlX, width(Y)-1
2430 // or Or, SrlX, SllY
2431 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2432 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2433 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2434 DAG.getConstant(WidthY - 1, MVT::i32));
2436 if (WidthX > WidthY)
2437 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2438 else if (WidthY > WidthX)
2439 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2441 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2442 DAG.getConstant(WidthX - 1, MVT::i32));
2443 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2444 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2448 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2449 if (Subtarget->hasMips64())
2450 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
2452 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
2455 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2456 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2457 DebugLoc DL = Op.getDebugLoc();
2459 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2461 SDValue X = (Op.getValueType() == MVT::f32) ?
2462 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2463 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2468 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2469 DAG.getRegister(Mips::ZERO, MVT::i32),
2470 DAG.getConstant(31, MVT::i32), Const1, X);
2472 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2473 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2476 if (Op.getValueType() == MVT::f32)
2477 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2479 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2480 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2481 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2484 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2485 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2486 DebugLoc DL = Op.getDebugLoc();
2488 // Bitcast to integer node.
2489 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2493 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2494 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2495 DAG.getConstant(63, MVT::i32), Const1, X);
2497 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2498 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2501 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2505 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
2506 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2507 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2509 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2512 SDValue MipsTargetLowering::
2513 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2515 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2516 "Frame address can only be determined for current frame.");
2518 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2519 MFI->setFrameAddressIsTaken(true);
2520 EVT VT = Op.getValueType();
2521 DebugLoc DL = Op.getDebugLoc();
2522 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
2523 IsN64 ? Mips::FP_64 : Mips::FP, VT);
2527 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
2528 SelectionDAG &DAG) const {
2530 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2531 "Return address can be determined only for current frame.");
2533 MachineFunction &MF = DAG.getMachineFunction();
2534 MachineFrameInfo *MFI = MF.getFrameInfo();
2535 MVT VT = Op.getSimpleValueType();
2536 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2537 MFI->setReturnAddressIsTaken(true);
2539 // Return RA, which contains the return address. Mark it an implicit live-in.
2540 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2541 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2544 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
2545 // generated from __builtin_eh_return (offset, handler)
2546 // The effect of this is to adjust the stack pointer by "offset"
2547 // and then branch to "handler".
2548 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
2550 MachineFunction &MF = DAG.getMachineFunction();
2551 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2553 MipsFI->setCallsEhReturn();
2554 SDValue Chain = Op.getOperand(0);
2555 SDValue Offset = Op.getOperand(1);
2556 SDValue Handler = Op.getOperand(2);
2557 DebugLoc DL = Op.getDebugLoc();
2558 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2560 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
2561 // EH_RETURN nodes, so that instructions are emitted back-to-back.
2562 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
2563 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
2564 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
2565 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
2566 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
2567 DAG.getRegister(OffsetReg, Ty),
2568 DAG.getRegister(AddrReg, getPointerTy()),
2572 // TODO: set SType according to the desired memory barrier behavior.
2574 MipsTargetLowering::lowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2576 DebugLoc DL = Op.getDebugLoc();
2577 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2578 DAG.getConstant(SType, MVT::i32));
2581 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
2582 SelectionDAG &DAG) const {
2583 // FIXME: Need pseudo-fence for 'singlethread' fences
2584 // FIXME: Set SType for weaker fences where supported/appropriate.
2586 DebugLoc DL = Op.getDebugLoc();
2587 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
2588 DAG.getConstant(SType, MVT::i32));
2591 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
2592 SelectionDAG &DAG) const {
2593 DebugLoc DL = Op.getDebugLoc();
2594 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2595 SDValue Shamt = Op.getOperand(2);
2598 // lo = (shl lo, shamt)
2599 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2602 // hi = (shl lo, shamt[4:0])
2603 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2604 DAG.getConstant(-1, MVT::i32));
2605 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2606 DAG.getConstant(1, MVT::i32));
2607 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2609 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2610 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2611 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2612 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2613 DAG.getConstant(0x20, MVT::i32));
2614 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2615 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2616 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2618 SDValue Ops[2] = {Lo, Hi};
2619 return DAG.getMergeValues(Ops, 2, DL);
2622 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2624 DebugLoc DL = Op.getDebugLoc();
2625 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2626 SDValue Shamt = Op.getOperand(2);
2629 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2631 // hi = (sra hi, shamt)
2633 // hi = (srl hi, shamt)
2636 // lo = (sra hi, shamt[4:0])
2637 // hi = (sra hi, 31)
2639 // lo = (srl hi, shamt[4:0])
2641 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2642 DAG.getConstant(-1, MVT::i32));
2643 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2644 DAG.getConstant(1, MVT::i32));
2645 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2646 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2647 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2648 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2650 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2651 DAG.getConstant(0x20, MVT::i32));
2652 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2653 DAG.getConstant(31, MVT::i32));
2654 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2655 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2656 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2659 SDValue Ops[2] = {Lo, Hi};
2660 return DAG.getMergeValues(Ops, 2, DL);
2663 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2664 SDValue Chain, SDValue Src, unsigned Offset) {
2665 SDValue Ptr = LD->getBasePtr();
2666 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2667 EVT BasePtrVT = Ptr.getValueType();
2668 DebugLoc DL = LD->getDebugLoc();
2669 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2672 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2673 DAG.getConstant(Offset, BasePtrVT));
2675 SDValue Ops[] = { Chain, Ptr, Src };
2676 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2677 LD->getMemOperand());
2680 // Expand an unaligned 32 or 64-bit integer load node.
2681 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2682 LoadSDNode *LD = cast<LoadSDNode>(Op);
2683 EVT MemVT = LD->getMemoryVT();
2685 // Return if load is aligned or if MemVT is neither i32 nor i64.
2686 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2687 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2690 bool IsLittle = Subtarget->isLittle();
2691 EVT VT = Op.getValueType();
2692 ISD::LoadExtType ExtType = LD->getExtensionType();
2693 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2695 assert((VT == MVT::i32) || (VT == MVT::i64));
2698 // (set dst, (i64 (load baseptr)))
2700 // (set tmp, (ldl (add baseptr, 7), undef))
2701 // (set dst, (ldr baseptr, tmp))
2702 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2703 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2705 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2709 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2711 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2715 // (set dst, (i32 (load baseptr))) or
2716 // (set dst, (i64 (sextload baseptr))) or
2717 // (set dst, (i64 (extload baseptr)))
2719 // (set tmp, (lwl (add baseptr, 3), undef))
2720 // (set dst, (lwr baseptr, tmp))
2721 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2722 (ExtType == ISD::EXTLOAD))
2725 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2728 // (set dst, (i64 (zextload baseptr)))
2730 // (set tmp0, (lwl (add baseptr, 3), undef))
2731 // (set tmp1, (lwr baseptr, tmp0))
2732 // (set tmp2, (shl tmp1, 32))
2733 // (set dst, (srl tmp2, 32))
2734 DebugLoc DL = LD->getDebugLoc();
2735 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2736 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2737 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2738 SDValue Ops[] = { SRL, LWR.getValue(1) };
2739 return DAG.getMergeValues(Ops, 2, DL);
2742 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2743 SDValue Chain, unsigned Offset) {
2744 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2745 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2746 DebugLoc DL = SD->getDebugLoc();
2747 SDVTList VTList = DAG.getVTList(MVT::Other);
2750 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2751 DAG.getConstant(Offset, BasePtrVT));
2753 SDValue Ops[] = { Chain, Value, Ptr };
2754 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2755 SD->getMemOperand());
2758 // Expand an unaligned 32 or 64-bit integer store node.
2759 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2760 StoreSDNode *SD = cast<StoreSDNode>(Op);
2761 EVT MemVT = SD->getMemoryVT();
2763 // Return if store is aligned or if MemVT is neither i32 nor i64.
2764 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2765 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2768 bool IsLittle = Subtarget->isLittle();
2769 SDValue Value = SD->getValue(), Chain = SD->getChain();
2770 EVT VT = Value.getValueType();
2773 // (store val, baseptr) or
2774 // (truncstore val, baseptr)
2776 // (swl val, (add baseptr, 3))
2777 // (swr val, baseptr)
2778 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2779 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2781 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2784 assert(VT == MVT::i64);
2787 // (store val, baseptr)
2789 // (sdl val, (add baseptr, 7))
2790 // (sdr val, baseptr)
2791 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2792 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2795 // This function expands mips intrinsic nodes which have 64-bit input operands
2796 // or output values.
2798 // out64 = intrinsic-node in64
2800 // lo = copy (extract-element (in64, 0))
2801 // hi = copy (extract-element (in64, 1))
2802 // mips-specific-node
2805 // out64 = merge-values (v0, v1)
2807 static SDValue lowerDSPIntr(SDValue Op, SelectionDAG &DAG,
2808 unsigned Opc, bool HasI64In, bool HasI64Out) {
2809 DebugLoc DL = Op.getDebugLoc();
2810 bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
2811 SDValue Chain = HasChainIn ? Op->getOperand(0) : DAG.getEntryNode();
2812 SmallVector<SDValue, 3> Ops;
2815 SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2816 Op->getOperand(1 + HasChainIn),
2817 DAG.getConstant(0, MVT::i32));
2818 SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2819 Op->getOperand(1 + HasChainIn),
2820 DAG.getConstant(1, MVT::i32));
2822 Chain = DAG.getCopyToReg(Chain, DL, Mips::LO, InLo, SDValue());
2823 Chain = DAG.getCopyToReg(Chain, DL, Mips::HI, InHi, Chain.getValue(1));
2825 Ops.push_back(Chain);
2826 Ops.append(Op->op_begin() + HasChainIn + 2, Op->op_end());
2827 Ops.push_back(Chain.getValue(1));
2829 Ops.push_back(Chain);
2830 Ops.append(Op->op_begin() + HasChainIn + 1, Op->op_end());
2834 return DAG.getNode(Opc, DL, Op->value_begin(), Op->getNumValues(),
2835 Ops.begin(), Ops.size());
2837 SDValue Intr = DAG.getNode(Opc, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2838 Ops.begin(), Ops.size());
2839 SDValue OutLo = DAG.getCopyFromReg(Intr.getValue(0), DL, Mips::LO, MVT::i32,
2841 SDValue OutHi = DAG.getCopyFromReg(OutLo.getValue(1), DL, Mips::HI, MVT::i32,
2843 SDValue Out = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, OutLo, OutHi);
2848 SDValue Vals[] = { Out, OutHi.getValue(1) };
2849 return DAG.getMergeValues(Vals, 2, DL);
2852 SDValue MipsTargetLowering::lowerINTRINSIC_WO_CHAIN(SDValue Op,
2853 SelectionDAG &DAG) const {
2854 switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
2857 case Intrinsic::mips_shilo:
2858 return lowerDSPIntr(Op, DAG, MipsISD::SHILO, true, true);
2859 case Intrinsic::mips_dpau_h_qbl:
2860 return lowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL, true, true);
2861 case Intrinsic::mips_dpau_h_qbr:
2862 return lowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR, true, true);
2863 case Intrinsic::mips_dpsu_h_qbl:
2864 return lowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL, true, true);
2865 case Intrinsic::mips_dpsu_h_qbr:
2866 return lowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR, true, true);
2867 case Intrinsic::mips_dpa_w_ph:
2868 return lowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH, true, true);
2869 case Intrinsic::mips_dps_w_ph:
2870 return lowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH, true, true);
2871 case Intrinsic::mips_dpax_w_ph:
2872 return lowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH, true, true);
2873 case Intrinsic::mips_dpsx_w_ph:
2874 return lowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH, true, true);
2875 case Intrinsic::mips_mulsa_w_ph:
2876 return lowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH, true, true);
2877 case Intrinsic::mips_mult:
2878 return lowerDSPIntr(Op, DAG, MipsISD::MULT, false, true);
2879 case Intrinsic::mips_multu:
2880 return lowerDSPIntr(Op, DAG, MipsISD::MULTU, false, true);
2881 case Intrinsic::mips_madd:
2882 return lowerDSPIntr(Op, DAG, MipsISD::MADD_DSP, true, true);
2883 case Intrinsic::mips_maddu:
2884 return lowerDSPIntr(Op, DAG, MipsISD::MADDU_DSP, true, true);
2885 case Intrinsic::mips_msub:
2886 return lowerDSPIntr(Op, DAG, MipsISD::MSUB_DSP, true, true);
2887 case Intrinsic::mips_msubu:
2888 return lowerDSPIntr(Op, DAG, MipsISD::MSUBU_DSP, true, true);
2892 SDValue MipsTargetLowering::lowerINTRINSIC_W_CHAIN(SDValue Op,
2893 SelectionDAG &DAG) const {
2894 switch (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue()) {
2897 case Intrinsic::mips_extp:
2898 return lowerDSPIntr(Op, DAG, MipsISD::EXTP, true, false);
2899 case Intrinsic::mips_extpdp:
2900 return lowerDSPIntr(Op, DAG, MipsISD::EXTPDP, true, false);
2901 case Intrinsic::mips_extr_w:
2902 return lowerDSPIntr(Op, DAG, MipsISD::EXTR_W, true, false);
2903 case Intrinsic::mips_extr_r_w:
2904 return lowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W, true, false);
2905 case Intrinsic::mips_extr_rs_w:
2906 return lowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W, true, false);
2907 case Intrinsic::mips_extr_s_h:
2908 return lowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H, true, false);
2909 case Intrinsic::mips_mthlip:
2910 return lowerDSPIntr(Op, DAG, MipsISD::MTHLIP, true, true);
2911 case Intrinsic::mips_mulsaq_s_w_ph:
2912 return lowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH, true, true);
2913 case Intrinsic::mips_maq_s_w_phl:
2914 return lowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL, true, true);
2915 case Intrinsic::mips_maq_s_w_phr:
2916 return lowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR, true, true);
2917 case Intrinsic::mips_maq_sa_w_phl:
2918 return lowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL, true, true);
2919 case Intrinsic::mips_maq_sa_w_phr:
2920 return lowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR, true, true);
2921 case Intrinsic::mips_dpaq_s_w_ph:
2922 return lowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH, true, true);
2923 case Intrinsic::mips_dpsq_s_w_ph:
2924 return lowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH, true, true);
2925 case Intrinsic::mips_dpaq_sa_l_w:
2926 return lowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W, true, true);
2927 case Intrinsic::mips_dpsq_sa_l_w:
2928 return lowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W, true, true);
2929 case Intrinsic::mips_dpaqx_s_w_ph:
2930 return lowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH, true, true);
2931 case Intrinsic::mips_dpaqx_sa_w_ph:
2932 return lowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH, true, true);
2933 case Intrinsic::mips_dpsqx_s_w_ph:
2934 return lowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH, true, true);
2935 case Intrinsic::mips_dpsqx_sa_w_ph:
2936 return lowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH, true, true);
2940 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2941 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2942 || cast<ConstantSDNode>
2943 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2944 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2948 // (add (frameaddr 0), (frame_to_args_offset))
2949 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2950 // (add FrameObject, 0)
2951 // where FrameObject is a fixed StackObject with offset 0 which points to
2952 // the old stack pointer.
2953 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2954 EVT ValTy = Op->getValueType(0);
2955 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2956 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2957 return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2958 DAG.getConstant(0, ValTy));
2961 //===----------------------------------------------------------------------===//
2962 // Calling Convention Implementation
2963 //===----------------------------------------------------------------------===//
2965 //===----------------------------------------------------------------------===//
2966 // TODO: Implement a generic logic using tblgen that can support this.
2967 // Mips O32 ABI rules:
2969 // i32 - Passed in A0, A1, A2, A3 and stack
2970 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2971 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2972 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2973 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2974 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2977 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2978 //===----------------------------------------------------------------------===//
2980 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2981 MVT LocVT, CCValAssign::LocInfo LocInfo,
2982 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2984 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2986 static const uint16_t IntRegs[] = {
2987 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2989 static const uint16_t F32Regs[] = {
2990 Mips::F12, Mips::F14
2992 static const uint16_t F64Regs[] = {
2996 // Do not process byval args here.
2997 if (ArgFlags.isByVal())
3000 // Promote i8 and i16
3001 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
3003 if (ArgFlags.isSExt())
3004 LocInfo = CCValAssign::SExt;
3005 else if (ArgFlags.isZExt())
3006 LocInfo = CCValAssign::ZExt;
3008 LocInfo = CCValAssign::AExt;
3013 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
3014 // is true: function is vararg, argument is 3rd or higher, there is previous
3015 // argument which is not f32 or f64.
3016 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
3017 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
3018 unsigned OrigAlign = ArgFlags.getOrigAlign();
3019 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
3021 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
3022 Reg = State.AllocateReg(IntRegs, IntRegsSize);
3023 // If this is the first part of an i64 arg,
3024 // the allocated register must be either A0 or A2.
3025 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
3026 Reg = State.AllocateReg(IntRegs, IntRegsSize);
3028 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
3029 // Allocate int register and shadow next int register. If first
3030 // available register is Mips::A1 or Mips::A3, shadow it too.
3031 Reg = State.AllocateReg(IntRegs, IntRegsSize);
3032 if (Reg == Mips::A1 || Reg == Mips::A3)
3033 Reg = State.AllocateReg(IntRegs, IntRegsSize);
3034 State.AllocateReg(IntRegs, IntRegsSize);
3036 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
3037 // we are guaranteed to find an available float register
3038 if (ValVT == MVT::f32) {
3039 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
3040 // Shadow int register
3041 State.AllocateReg(IntRegs, IntRegsSize);
3043 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
3044 // Shadow int registers
3045 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
3046 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
3047 State.AllocateReg(IntRegs, IntRegsSize);
3048 State.AllocateReg(IntRegs, IntRegsSize);
3051 llvm_unreachable("Cannot handle this ValVT.");
3054 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
3056 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
3058 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
3063 #include "MipsGenCallingConv.inc"
3065 //===----------------------------------------------------------------------===//
3066 // Call Calling Convention Implementation
3067 //===----------------------------------------------------------------------===//
3069 static const unsigned O32IntRegsSize = 4;
3071 // Return next O32 integer argument register.
3072 static unsigned getNextIntArgReg(unsigned Reg) {
3073 assert((Reg == Mips::A0) || (Reg == Mips::A2));
3074 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
3077 /// isEligibleForTailCallOptimization - Check whether the call is eligible
3078 /// for tail call optimization.
3079 bool MipsTargetLowering::
3080 isEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
3081 unsigned NextStackOffset,
3082 const MipsFunctionInfo& FI) const {
3083 if (!EnableMipsTailCalls)
3086 // No tail call optimization for mips16.
3087 if (Subtarget->inMips16Mode())
3090 // Return false if either the callee or caller has a byval argument.
3091 if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
3094 // Return true if the callee's argument area is no larger than the
3096 return NextStackOffset <= FI.getIncomingArgSize();
3100 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
3101 SDValue Chain, SDValue Arg, DebugLoc DL,
3102 bool IsTailCall, SelectionDAG &DAG) const {
3104 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
3105 DAG.getIntPtrConstant(Offset));
3106 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
3110 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
3111 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
3112 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3113 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
3114 /*isVolatile=*/ true, false, 0);
3118 // The Mips16 hard float is a crazy quilt inherited from gcc. I have a much
3119 // cleaner way to do all of this but it will have to wait until the traditional
3120 // gcc mechanism is completed.
3122 // For Pic, in order for Mips16 code to call Mips32 code which according the abi
3123 // have either arguments or returned values placed in floating point registers,
3124 // we use a set of helper functions. (This includes functions which return type
3125 // complex which on Mips are returned in a pair of floating point registers).
3127 // This is an encoding that we inherited from gcc.
3128 // In Mips traditional O32, N32 ABI, floating point numbers are passed in
3129 // floating point argument registers 1,2 only when the first and optionally
3130 // the second arguments are float (sf) or double (df).
3131 // For Mips16 we are only concerned with the situations where floating point
3132 // arguments are being passed in floating point registers by the ABI, because
3133 // Mips16 mode code cannot execute floating point instructions to load those
3134 // values and hence helper functions are needed.
3135 // The possibilities are (), (sf), (sf, sf), (sf, df), (df), (df, sf), (df, df)
3136 // the helper function suffixs for these are:
3137 // 0, 1, 5, 9, 2, 6, 10
3138 // this suffix can then be calculated as follows:
3139 // for a given argument Arg:
3140 // Arg1x, Arg2x = 1 : Arg is sf
3142 // 0: Arg is neither sf or df
3143 // So this stub is the string for number Arg1x + Arg2x*4.
3144 // However not all numbers between 0 and 10 are possible, we check anyway and
3145 // assert if the impossible exists.
3148 unsigned int MipsTargetLowering::getMips16HelperFunctionStubNumber
3149 (ArgListTy &Args) const {
3150 unsigned int resultNum = 0;
3151 if (Args.size() >= 1) {
3152 Type *t = Args[0].Ty;
3153 if (t->isFloatTy()) {
3156 else if (t->isDoubleTy()) {
3161 if (Args.size() >=2) {
3162 Type *t = Args[1].Ty;
3163 if (t->isFloatTy()) {
3166 else if (t->isDoubleTy()) {
3175 // prefixs are attached to stub numbers depending on the return type .
3176 // return type: float sf_
3178 // single complex sc_
3179 // double complext dc_
3183 // The full name of a helper function is__mips16_call_stub +
3184 // return type dependent prefix + stub number
3187 // This is something that probably should be in a different source file and
3188 // perhaps done differently but my main purpose is to not waste runtime
3189 // on something that we can enumerate in the source. Another possibility is
3190 // to have a python script to generate these mapping tables. This will do
3191 // for now. There are a whole series of helper function mapping arrays, one
3192 // for each return type class as outlined above. There there are 11 possible
3193 // entries. Ones with 0 are ones which should never be selected
3195 // All the arrays are similar except for ones which return neither
3196 // sf, df, sc, dc, in which only care about ones which have sf or df as a
3199 #define P_ "__mips16_call_stub_"
3200 #define MAX_STUB_NUMBER 10
3201 #define T1 P "1", P "2", 0, 0, P "5", P "6", 0, 0, P "9", P "10"
3202 #define T P "0" , T1
3204 static char const * vMips16Helper[MAX_STUB_NUMBER+1] =
3208 static char const * sfMips16Helper[MAX_STUB_NUMBER+1] =
3212 static char const * dfMips16Helper[MAX_STUB_NUMBER+1] =
3216 static char const * scMips16Helper[MAX_STUB_NUMBER+1] =
3220 static char const * dcMips16Helper[MAX_STUB_NUMBER+1] =
3226 const char* MipsTargetLowering::
3227 getMips16HelperFunction
3228 (Type* RetTy, ArgListTy &Args, bool &needHelper) const {
3229 const unsigned int stubNum = getMips16HelperFunctionStubNumber(Args);
3231 const unsigned int maxStubNum = 10;
3232 assert(stubNum <= maxStubNum);
3233 const bool validStubNum[maxStubNum+1] =
3234 {true, true, true, false, false, true, true, false, false, true, true};
3235 assert(validStubNum[stubNum]);
3238 if (RetTy->isFloatTy()) {
3239 result = sfMips16Helper[stubNum];
3241 else if (RetTy ->isDoubleTy()) {
3242 result = dfMips16Helper[stubNum];
3244 else if (RetTy->isStructTy()) {
3245 // check if it's complex
3246 if (RetTy->getNumContainedTypes() == 2) {
3247 if ((RetTy->getContainedType(0)->isFloatTy()) &&
3248 (RetTy->getContainedType(1)->isFloatTy())) {
3249 result = scMips16Helper[stubNum];
3251 else if ((RetTy->getContainedType(0)->isDoubleTy()) &&
3252 (RetTy->getContainedType(1)->isDoubleTy())) {
3253 result = dcMips16Helper[stubNum];
3256 llvm_unreachable("Uncovered condition");
3260 llvm_unreachable("Uncovered condition");
3268 result = vMips16Helper[stubNum];
3274 /// LowerCall - functions arguments are copied from virtual regs to
3275 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
3277 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
3278 SmallVectorImpl<SDValue> &InVals) const {
3279 SelectionDAG &DAG = CLI.DAG;
3280 DebugLoc &DL = CLI.DL;
3281 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
3282 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
3283 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
3284 SDValue Chain = CLI.Chain;
3285 SDValue Callee = CLI.Callee;
3286 bool &IsTailCall = CLI.IsTailCall;
3287 CallingConv::ID CallConv = CLI.CallConv;
3288 bool IsVarArg = CLI.IsVarArg;
3290 const char* Mips16HelperFunction = 0;
3291 bool NeedMips16Helper = false;
3293 if (Subtarget->inMips16Mode() && getTargetMachine().Options.UseSoftFloat &&
3296 // currently we don't have symbols tagged with the mips16 or mips32
3297 // qualifier so we will assume that we don't know what kind it is.
3298 // and generate the helper
3300 bool LookupHelper = true;
3301 if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3302 if (NoHelperNeeded.find(S->getSymbol()) != NoHelperNeeded.end()) {
3303 LookupHelper = false;
3306 if (LookupHelper) Mips16HelperFunction =
3307 getMips16HelperFunction(CLI.RetTy, CLI.Args, NeedMips16Helper);
3310 MachineFunction &MF = DAG.getMachineFunction();
3311 MachineFrameInfo *MFI = MF.getFrameInfo();
3312 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
3313 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
3315 // Analyze operands of the call, assigning locations to each operand.
3316 SmallVector<CCValAssign, 16> ArgLocs;
3317 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
3318 getTargetMachine(), ArgLocs, *DAG.getContext());
3319 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
3321 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
3322 getTargetMachine().Options.UseSoftFloat,
3323 Callee.getNode(), CLI.Args);
3325 // Get a count of how many bytes are to be pushed on the stack.
3326 unsigned NextStackOffset = CCInfo.getNextStackOffset();
3328 // Check if it's really possible to do a tail call.
3331 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
3332 *MF.getInfo<MipsFunctionInfo>());
3337 // Chain is the output chain of the last Load/Store or CopyToReg node.
3338 // ByValChain is the output chain of the last Memcpy node created for copying
3339 // byval arguments to the stack.
3340 unsigned StackAlignment = TFL->getStackAlignment();
3341 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
3342 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
3345 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
3347 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
3348 IsN64 ? Mips::SP_64 : Mips::SP,
3351 // With EABI is it possible to have 16 args on registers.
3352 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
3353 SmallVector<SDValue, 8> MemOpChains;
3354 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3356 // Walk the register/memloc assignments, inserting copies/loads.
3357 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3358 SDValue Arg = OutVals[i];
3359 CCValAssign &VA = ArgLocs[i];
3360 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
3361 ISD::ArgFlagsTy Flags = Outs[i].Flags;
3364 if (Flags.isByVal()) {
3365 assert(Flags.getByValSize() &&
3366 "ByVal args of size 0 should have been ignored by front-end.");
3367 assert(ByValArg != MipsCCInfo.byval_end());
3368 assert(!IsTailCall &&
3369 "Do not tail-call optimize if there is a byval argument.");
3370 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
3371 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
3376 // Promote the value if needed.
3377 switch (VA.getLocInfo()) {
3378 default: llvm_unreachable("Unknown loc info!");
3379 case CCValAssign::Full:
3380 if (VA.isRegLoc()) {
3381 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
3382 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
3383 (ValVT == MVT::i64 && LocVT == MVT::f64))
3384 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
3385 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
3386 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3387 Arg, DAG.getConstant(0, MVT::i32));
3388 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
3389 Arg, DAG.getConstant(1, MVT::i32));
3390 if (!Subtarget->isLittle())
3392 unsigned LocRegLo = VA.getLocReg();
3393 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
3394 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
3395 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
3400 case CCValAssign::SExt:
3401 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
3403 case CCValAssign::ZExt:
3404 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
3406 case CCValAssign::AExt:
3407 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
3411 // Arguments that can be passed on register must be kept at
3412 // RegsToPass vector
3413 if (VA.isRegLoc()) {
3414 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
3418 // Register can't get to this point...
3419 assert(VA.isMemLoc());
3421 // emit ISD::STORE whichs stores the
3422 // parameter value to a stack Location
3423 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
3424 Chain, Arg, DL, IsTailCall, DAG));
3427 // Transform all store nodes into one single node because all store
3428 // nodes are independent of each other.
3429 if (!MemOpChains.empty())
3430 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3431 &MemOpChains[0], MemOpChains.size());
3433 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
3434 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
3435 // node so that legalize doesn't hack it.
3436 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
3437 bool GlobalOrExternal = false, InternalLinkage = false;
3440 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3442 InternalLinkage = G->getGlobal()->hasInternalLinkage();
3444 if (InternalLinkage)
3445 Callee = getAddrLocal(Callee, DAG, HasMips64);
3447 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3448 MipsII::MO_CALL_LO16);
3450 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3452 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
3453 MipsII::MO_NO_FLAG);
3454 GlobalOrExternal = true;
3456 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
3457 if (!IsN64 && !IsPIC) // !N64 && static
3458 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
3459 MipsII::MO_NO_FLAG);
3461 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
3462 MipsII::MO_CALL_LO16);
3464 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
3466 GlobalOrExternal = true;
3469 SDValue JumpTarget = Callee;
3471 // T9 should contain the address of the callee function if
3472 // -reloction-model=pic or it is an indirect call.
3473 if (IsPICCall || !GlobalOrExternal) {
3474 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
3475 unsigned V0Reg = Mips::V0;
3476 if (NeedMips16Helper) {
3477 RegsToPass.push_front(std::make_pair(V0Reg, Callee));
3478 JumpTarget = DAG.getExternalSymbol(
3479 Mips16HelperFunction, getPointerTy());
3480 JumpTarget = getAddrGlobal(JumpTarget, DAG, MipsII::MO_GOT);
3483 RegsToPass.push_front(std::make_pair(T9Reg, Callee));
3485 if (!Subtarget->inMips16Mode())
3486 JumpTarget = SDValue();
3490 // Insert node "GP copy globalreg" before call to function.
3492 // R_MIPS_CALL* operators (emitted when non-internal functions are called
3493 // in PIC mode) allow symbols to be resolved via lazy binding.
3494 // The lazy binding stub requires GP to point to the GOT.
3495 if (IsPICCall && !InternalLinkage) {
3496 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
3497 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
3498 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(DAG, Ty)));
3501 // Build a sequence of copy-to-reg nodes chained together with token
3502 // chain and flag operands which copy the outgoing args into registers.
3503 // The InFlag in necessary since all emitted instructions must be
3507 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
3508 Chain = DAG.getCopyToReg(Chain, DL, RegsToPass[i].first,
3509 RegsToPass[i].second, InFlag);
3510 InFlag = Chain.getValue(1);
3513 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
3514 // = Chain, Callee, Reg#1, Reg#2, ...
3516 // Returns a chain & a flag for retval copy to use.
3517 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
3518 SmallVector<SDValue, 8> Ops(1, Chain);
3520 if (JumpTarget.getNode())
3521 Ops.push_back(JumpTarget);
3523 // Add argument registers to the end of the list so that they are
3524 // known live into the call.
3525 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
3526 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
3527 RegsToPass[i].second.getValueType()));
3529 // Add a register mask operand representing the call-preserved registers.
3530 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
3531 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
3532 assert(Mask && "Missing call preserved mask for calling convention");
3533 Ops.push_back(DAG.getRegisterMask(Mask));
3535 if (InFlag.getNode())
3536 Ops.push_back(InFlag);
3539 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
3541 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
3542 InFlag = Chain.getValue(1);
3544 // Create the CALLSEQ_END node.
3545 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
3546 DAG.getIntPtrConstant(0, true), InFlag);
3547 InFlag = Chain.getValue(1);
3549 // Handle result values, copying them out of physregs into vregs that we
3551 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
3552 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
3555 /// LowerCallResult - Lower the result values of a call into the
3556 /// appropriate copies out of appropriate physical registers.
3558 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3559 CallingConv::ID CallConv, bool IsVarArg,
3560 const SmallVectorImpl<ISD::InputArg> &Ins,
3561 DebugLoc DL, SelectionDAG &DAG,
3562 SmallVectorImpl<SDValue> &InVals,
3563 const SDNode *CallNode,
3564 const Type *RetTy) const {
3565 // Assign locations to each value returned by this call.
3566 SmallVector<CCValAssign, 16> RVLocs;
3567 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
3568 getTargetMachine(), RVLocs, *DAG.getContext());
3569 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
3571 MipsCCInfo.analyzeCallResult(Ins, getTargetMachine().Options.UseSoftFloat,
3574 // Copy all of the result registers out of their specified physreg.
3575 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3576 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
3577 RVLocs[i].getLocVT(), InFlag);
3578 Chain = Val.getValue(1);
3579 InFlag = Val.getValue(2);
3581 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
3582 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
3584 InVals.push_back(Val);
3590 //===----------------------------------------------------------------------===//
3591 // Formal Arguments Calling Convention Implementation
3592 //===----------------------------------------------------------------------===//
3593 /// LowerFormalArguments - transform physical registers into virtual registers
3594 /// and generate load operations for arguments places on the stack.
3596 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3597 CallingConv::ID CallConv,
3599 const SmallVectorImpl<ISD::InputArg> &Ins,
3600 DebugLoc DL, SelectionDAG &DAG,
3601 SmallVectorImpl<SDValue> &InVals)
3603 MachineFunction &MF = DAG.getMachineFunction();
3604 MachineFrameInfo *MFI = MF.getFrameInfo();
3605 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3607 MipsFI->setVarArgsFrameIndex(0);
3609 // Used with vargs to acumulate store chains.
3610 std::vector<SDValue> OutChains;
3612 // Assign locations to all of the incoming arguments.
3613 SmallVector<CCValAssign, 16> ArgLocs;
3614 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
3615 getTargetMachine(), ArgLocs, *DAG.getContext());
3616 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
3617 Function::const_arg_iterator FuncArg =
3618 DAG.getMachineFunction().getFunction()->arg_begin();
3619 bool UseSoftFloat = getTargetMachine().Options.UseSoftFloat;
3621 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
3622 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3623 MipsCCInfo.hasByValArg());
3625 unsigned CurArgIdx = 0;
3626 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3628 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3629 CCValAssign &VA = ArgLocs[i];
3630 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
3631 CurArgIdx = Ins[i].OrigArgIndex;
3632 EVT ValVT = VA.getValVT();
3633 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3634 bool IsRegLoc = VA.isRegLoc();
3636 if (Flags.isByVal()) {
3637 assert(Flags.getByValSize() &&
3638 "ByVal args of size 0 should have been ignored by front-end.");
3639 assert(ByValArg != MipsCCInfo.byval_end());
3640 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
3641 MipsCCInfo, *ByValArg);
3646 // Arguments stored on registers
3648 EVT RegVT = VA.getLocVT();
3649 unsigned ArgReg = VA.getLocReg();
3650 const TargetRegisterClass *RC;
3652 if (RegVT == MVT::i32)
3653 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
3654 &Mips::CPURegsRegClass;
3655 else if (RegVT == MVT::i64)
3656 RC = &Mips::CPU64RegsRegClass;
3657 else if (RegVT == MVT::f32)
3658 RC = &Mips::FGR32RegClass;
3659 else if (RegVT == MVT::f64)
3660 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3662 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3664 // Transform the arguments stored on
3665 // physical registers into virtual ones
3666 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3667 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
3669 // If this is an 8 or 16-bit value, it has been passed promoted
3670 // to 32 bits. Insert an assert[sz]ext to capture this, then
3671 // truncate to the right size.
3672 if (VA.getLocInfo() != CCValAssign::Full) {
3673 unsigned Opcode = 0;
3674 if (VA.getLocInfo() == CCValAssign::SExt)
3675 Opcode = ISD::AssertSext;
3676 else if (VA.getLocInfo() == CCValAssign::ZExt)
3677 Opcode = ISD::AssertZext;
3679 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
3680 DAG.getValueType(ValVT));
3681 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
3684 // Handle floating point arguments passed in integer registers and
3685 // long double arguments passed in floating point registers.
3686 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3687 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
3688 (RegVT == MVT::f64 && ValVT == MVT::i64))
3689 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
3690 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3691 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
3692 getNextIntArgReg(ArgReg), RC);
3693 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
3694 if (!Subtarget->isLittle())
3695 std::swap(ArgValue, ArgValue2);
3696 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
3697 ArgValue, ArgValue2);
3700 InVals.push_back(ArgValue);
3701 } else { // VA.isRegLoc()
3704 assert(VA.isMemLoc());
3706 // The stack pointer offset is relative to the caller stack frame.
3707 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3708 VA.getLocMemOffset(), true);
3710 // Create load nodes to retrieve arguments from the stack
3711 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3712 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
3713 MachinePointerInfo::getFixedStack(FI),
3714 false, false, false, 0));
3718 // The mips ABIs for returning structs by value requires that we copy
3719 // the sret argument into $v0 for the return. Save the argument into
3720 // a virtual register so that we can access it from the return points.
3721 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3722 unsigned Reg = MipsFI->getSRetReturnReg();
3724 Reg = MF.getRegInfo().
3725 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
3726 MipsFI->setSRetReturnReg(Reg);
3728 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
3729 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
3733 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
3735 // All stores are grouped in one node to allow the matching between
3736 // the size of Ins and InVals. This only happens when on varg functions
3737 if (!OutChains.empty()) {
3738 OutChains.push_back(Chain);
3739 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
3740 &OutChains[0], OutChains.size());
3746 //===----------------------------------------------------------------------===//
3747 // Return Value Calling Convention Implementation
3748 //===----------------------------------------------------------------------===//
3751 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3752 MachineFunction &MF, bool IsVarArg,
3753 const SmallVectorImpl<ISD::OutputArg> &Outs,
3754 LLVMContext &Context) const {
3755 SmallVector<CCValAssign, 16> RVLocs;
3756 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
3758 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3762 MipsTargetLowering::LowerReturn(SDValue Chain,
3763 CallingConv::ID CallConv, bool IsVarArg,
3764 const SmallVectorImpl<ISD::OutputArg> &Outs,
3765 const SmallVectorImpl<SDValue> &OutVals,
3766 DebugLoc DL, SelectionDAG &DAG) const {
3767 // CCValAssign - represent the assignment of
3768 // the return value to a location
3769 SmallVector<CCValAssign, 16> RVLocs;
3770 MachineFunction &MF = DAG.getMachineFunction();
3772 // CCState - Info about the registers and stack slot.
3773 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
3775 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
3777 // Analyze return values.
3778 MipsCCInfo.analyzeReturn(Outs, getTargetMachine().Options.UseSoftFloat,
3779 MF.getFunction()->getReturnType());
3782 SmallVector<SDValue, 4> RetOps(1, Chain);
3784 // Copy the result values into the output registers.
3785 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3786 SDValue Val = OutVals[i];
3787 CCValAssign &VA = RVLocs[i];
3788 assert(VA.isRegLoc() && "Can only return in registers!");
3790 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
3791 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
3793 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
3795 // Guarantee that all emitted copies are stuck together with flags.
3796 Flag = Chain.getValue(1);
3797 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
3800 // The mips ABIs for returning structs by value requires that we copy
3801 // the sret argument into $v0 for the return. We saved the argument into
3802 // a virtual register in the entry block, so now we copy the value out
3804 if (MF.getFunction()->hasStructRetAttr()) {
3805 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3806 unsigned Reg = MipsFI->getSRetReturnReg();
3809 llvm_unreachable("sret virtual register not created in the entry block");
3810 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
3811 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
3813 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
3814 Flag = Chain.getValue(1);
3815 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
3818 RetOps[0] = Chain; // Update chain.
3820 // Add the flag if we have it.
3822 RetOps.push_back(Flag);
3824 // Return on Mips is always a "jr $ra"
3825 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
3828 //===----------------------------------------------------------------------===//
3829 // Mips Inline Assembly Support
3830 //===----------------------------------------------------------------------===//
3832 /// getConstraintType - Given a constraint letter, return the type of
3833 /// constraint it is for this target.
3834 MipsTargetLowering::ConstraintType MipsTargetLowering::
3835 getConstraintType(const std::string &Constraint) const
3837 // Mips specific constrainy
3838 // GCC config/mips/constraints.md
3840 // 'd' : An address register. Equivalent to r
3841 // unless generating MIPS16 code.
3842 // 'y' : Equivalent to r; retained for
3843 // backwards compatibility.
3844 // 'c' : A register suitable for use in an indirect
3845 // jump. This will always be $25 for -mabicalls.
3846 // 'l' : The lo register. 1 word storage.
3847 // 'x' : The hilo register pair. Double word storage.
3848 if (Constraint.size() == 1) {
3849 switch (Constraint[0]) {
3857 return C_RegisterClass;
3862 return TargetLowering::getConstraintType(Constraint);
3865 /// Examine constraint type and operand type and determine a weight value.
3866 /// This object must already have been set up with the operand type
3867 /// and the current alternative constraint selected.
3868 TargetLowering::ConstraintWeight
3869 MipsTargetLowering::getSingleConstraintMatchWeight(
3870 AsmOperandInfo &info, const char *constraint) const {
3871 ConstraintWeight weight = CW_Invalid;
3872 Value *CallOperandVal = info.CallOperandVal;
3873 // If we don't have a value, we can't do a match,
3874 // but allow it at the lowest weight.
3875 if (CallOperandVal == NULL)
3877 Type *type = CallOperandVal->getType();
3878 // Look at the constraint type.
3879 switch (*constraint) {
3881 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3885 if (type->isIntegerTy())
3886 weight = CW_Register;
3889 if (type->isFloatTy())
3890 weight = CW_Register;
3892 case 'c': // $25 for indirect jumps
3893 case 'l': // lo register
3894 case 'x': // hilo register pair
3895 if (type->isIntegerTy())
3896 weight = CW_SpecificReg;
3898 case 'I': // signed 16 bit immediate
3899 case 'J': // integer zero
3900 case 'K': // unsigned 16 bit immediate
3901 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3902 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3903 case 'O': // signed 15 bit immediate (+- 16383)
3904 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3905 if (isa<ConstantInt>(CallOperandVal))
3906 weight = CW_Constant;
3915 /// Given a register class constraint, like 'r', if this corresponds directly
3916 /// to an LLVM register class, return a register of 0 and the register class
3918 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3919 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3921 if (Constraint.size() == 1) {
3922 switch (Constraint[0]) {
3923 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3924 case 'y': // Same as 'r'. Exists for compatibility.
3926 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3927 if (Subtarget->inMips16Mode())
3928 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3929 return std::make_pair(0U, &Mips::CPURegsRegClass);
3931 if (VT == MVT::i64 && !HasMips64)
3932 return std::make_pair(0U, &Mips::CPURegsRegClass);
3933 if (VT == MVT::i64 && HasMips64)
3934 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3935 // This will generate an error message
3936 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3939 return std::make_pair(0U, &Mips::FGR32RegClass);
3940 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3941 if (Subtarget->isFP64bit())
3942 return std::make_pair(0U, &Mips::FGR64RegClass);
3943 return std::make_pair(0U, &Mips::AFGR64RegClass);
3946 case 'c': // register suitable for indirect jump
3948 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3949 assert(VT == MVT::i64 && "Unexpected type.");
3950 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3951 case 'l': // register suitable for indirect jump
3953 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3954 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3955 case 'x': // register suitable for indirect jump
3956 // Fixme: Not triggering the use of both hi and low
3957 // This will generate an error message
3958 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3961 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3964 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3965 /// vector. If it is invalid, don't add anything to Ops.
3966 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3967 std::string &Constraint,
3968 std::vector<SDValue>&Ops,
3969 SelectionDAG &DAG) const {
3970 SDValue Result(0, 0);
3972 // Only support length 1 constraints for now.
3973 if (Constraint.length() > 1) return;
3975 char ConstraintLetter = Constraint[0];
3976 switch (ConstraintLetter) {
3977 default: break; // This will fall through to the generic implementation
3978 case 'I': // Signed 16 bit constant
3979 // If this fails, the parent routine will give an error
3980 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3981 EVT Type = Op.getValueType();
3982 int64_t Val = C->getSExtValue();
3983 if (isInt<16>(Val)) {
3984 Result = DAG.getTargetConstant(Val, Type);
3989 case 'J': // integer zero
3990 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3991 EVT Type = Op.getValueType();
3992 int64_t Val = C->getZExtValue();
3994 Result = DAG.getTargetConstant(0, Type);
3999 case 'K': // unsigned 16 bit immediate
4000 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4001 EVT Type = Op.getValueType();
4002 uint64_t Val = (uint64_t)C->getZExtValue();
4003 if (isUInt<16>(Val)) {
4004 Result = DAG.getTargetConstant(Val, Type);
4009 case 'L': // signed 32 bit immediate where lower 16 bits are 0
4010 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4011 EVT Type = Op.getValueType();
4012 int64_t Val = C->getSExtValue();
4013 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
4014 Result = DAG.getTargetConstant(Val, Type);
4019 case 'N': // immediate in the range of -65535 to -1 (inclusive)
4020 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4021 EVT Type = Op.getValueType();
4022 int64_t Val = C->getSExtValue();
4023 if ((Val >= -65535) && (Val <= -1)) {
4024 Result = DAG.getTargetConstant(Val, Type);
4029 case 'O': // signed 15 bit immediate
4030 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4031 EVT Type = Op.getValueType();
4032 int64_t Val = C->getSExtValue();
4033 if ((isInt<15>(Val))) {
4034 Result = DAG.getTargetConstant(Val, Type);
4039 case 'P': // immediate in the range of 1 to 65535 (inclusive)
4040 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
4041 EVT Type = Op.getValueType();
4042 int64_t Val = C->getSExtValue();
4043 if ((Val <= 65535) && (Val >= 1)) {
4044 Result = DAG.getTargetConstant(Val, Type);
4051 if (Result.getNode()) {
4052 Ops.push_back(Result);
4056 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
4060 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
4061 // No global is ever allowed as a base.
4066 case 0: // "r+i" or just "i", depending on HasBaseReg.
4069 if (!AM.HasBaseReg) // allow "r+i".
4071 return false; // disallow "r+r" or "r+r+i".
4080 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
4081 // The Mips target isn't yet aware of offsets.
4085 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
4087 bool IsMemset, bool ZeroMemset,
4089 MachineFunction &MF) const {
4090 if (Subtarget->hasMips64())
4096 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
4097 if (VT != MVT::f32 && VT != MVT::f64)
4099 if (Imm.isNegZero())
4101 return Imm.isZero();
4104 unsigned MipsTargetLowering::getJumpTableEncoding() const {
4106 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
4108 return TargetLowering::getJumpTableEncoding();
4111 /// This function returns true if CallSym is a long double emulation routine.
4112 static bool isF128SoftLibCall(const char *CallSym) {
4113 const char *const LibCalls[] =
4114 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
4115 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
4116 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
4117 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
4118 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
4119 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
4120 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
4121 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
4124 const char * const *End = LibCalls + array_lengthof(LibCalls);
4126 // Check that LibCalls is sorted alphabetically.
4130 for (const char * const *I = LibCalls; I < End - 1; ++I)
4131 assert(Comp(*I, *(I + 1)));
4134 return std::binary_search(LibCalls, End, CallSym, LTStr());
4137 /// This function returns true if Ty is fp128 or i128 which was originally a
4139 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
4140 if (Ty->isFP128Ty())
4143 const ExternalSymbolSDNode *ES =
4144 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
4146 // If the Ty is i128 and the function being called is a long double emulation
4147 // routine, then the original type is f128.
4148 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
4151 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CC, bool IsO32_,
4153 : CCInfo(Info), CallConv(CC), IsO32(IsO32_) {
4154 // Pre-allocate reserved argument area.
4155 CCInfo.AllocateStack(reservedArgArea(), 1);
4158 void MipsTargetLowering::MipsCC::
4159 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
4160 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
4161 std::vector<ArgListEntry> &FuncArgs) {
4162 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
4163 "CallingConv::Fast shouldn't be used for vararg functions.");
4165 unsigned NumOpnds = Args.size();
4166 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
4168 for (unsigned I = 0; I != NumOpnds; ++I) {
4169 MVT ArgVT = Args[I].VT;
4170 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
4173 if (ArgFlags.isByVal()) {
4174 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
4178 if (IsVarArg && !Args[I].IsFixed)
4179 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
4181 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
4183 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
4188 dbgs() << "Call operand #" << I << " has unhandled type "
4189 << EVT(ArgVT).getEVTString();
4191 llvm_unreachable(0);
4196 void MipsTargetLowering::MipsCC::
4197 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
4198 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
4199 unsigned NumArgs = Args.size();
4200 llvm::CCAssignFn *FixedFn = fixedArgFn();
4201 unsigned CurArgIdx = 0;
4203 for (unsigned I = 0; I != NumArgs; ++I) {
4204 MVT ArgVT = Args[I].VT;
4205 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
4206 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
4207 CurArgIdx = Args[I].OrigArgIndex;
4209 if (ArgFlags.isByVal()) {
4210 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
4214 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
4216 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
4220 dbgs() << "Formal Arg #" << I << " has unhandled type "
4221 << EVT(ArgVT).getEVTString();
4223 llvm_unreachable(0);
4227 template<typename Ty>
4228 void MipsTargetLowering::MipsCC::
4229 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
4230 const SDNode *CallNode, const Type *RetTy) const {
4233 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
4234 Fn = RetCC_F128Soft;
4238 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
4239 MVT VT = RetVals[I].VT;
4240 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
4241 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
4243 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
4245 dbgs() << "Call result #" << I << " has unhandled type "
4246 << EVT(VT).getEVTString() << '\n';
4248 llvm_unreachable(0);
4253 void MipsTargetLowering::MipsCC::
4254 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
4255 const SDNode *CallNode, const Type *RetTy) const {
4256 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
4259 void MipsTargetLowering::MipsCC::
4260 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
4261 const Type *RetTy) const {
4262 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
4266 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
4268 CCValAssign::LocInfo LocInfo,
4269 ISD::ArgFlagsTy ArgFlags) {
4270 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
4272 struct ByValArgInfo ByVal;
4273 unsigned RegSize = regSize();
4274 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
4275 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
4278 if (useRegsForByval())
4279 allocateRegs(ByVal, ByValSize, Align);
4281 // Allocate space on caller's stack.
4282 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
4284 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
4286 ByValArgs.push_back(ByVal);
4289 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
4290 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
4293 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
4294 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
4297 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
4298 return IsO32 ? O32IntRegs : Mips64IntRegs;
4301 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
4302 if (CallConv == CallingConv::Fast)
4303 return CC_Mips_FastCC;
4305 return IsO32 ? CC_MipsO32 : CC_MipsN;
4308 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
4309 return IsO32 ? CC_MipsO32 : CC_MipsN_VarArg;
4312 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
4313 return IsO32 ? O32IntRegs : Mips64DPRegs;
4316 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
4319 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
4320 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
4321 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
4322 "Byval argument's size and alignment should be a multiple of"
4325 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
4327 // If Align > RegSize, the first arg register must be even.
4328 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
4329 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
4333 // Mark the registers allocated.
4334 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
4335 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
4336 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
4339 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
4340 const SDNode *CallNode,
4341 bool IsSoftFloat) const {
4342 if (IsSoftFloat || IsO32)
4345 // Check if the original type was fp128.
4346 if (originalTypeIsF128(OrigTy, CallNode)) {
4347 assert(VT == MVT::i64);
4354 void MipsTargetLowering::
4355 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
4356 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
4357 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
4358 const MipsCC &CC, const ByValArgInfo &ByVal) const {
4359 MachineFunction &MF = DAG.getMachineFunction();
4360 MachineFrameInfo *MFI = MF.getFrameInfo();
4361 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
4362 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
4366 FrameObjOffset = (int)CC.reservedArgArea() -
4367 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
4369 FrameObjOffset = ByVal.Address;
4371 // Create frame object.
4372 EVT PtrTy = getPointerTy();
4373 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
4374 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
4375 InVals.push_back(FIN);
4380 // Copy arg registers.
4381 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
4382 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4384 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
4385 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
4386 unsigned VReg = addLiveIn(MF, ArgReg, RC);
4387 unsigned Offset = I * CC.regSize();
4388 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
4389 DAG.getConstant(Offset, PtrTy));
4390 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
4391 StorePtr, MachinePointerInfo(FuncArg, Offset),
4393 OutChains.push_back(Store);
4397 // Copy byVal arg to registers and stack.
4398 void MipsTargetLowering::
4399 passByValArg(SDValue Chain, DebugLoc DL,
4400 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
4401 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
4402 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
4403 const MipsCC &CC, const ByValArgInfo &ByVal,
4404 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
4405 unsigned ByValSize = Flags.getByValSize();
4406 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
4407 unsigned RegSize = CC.regSize();
4408 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
4409 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
4411 if (ByVal.NumRegs) {
4412 const uint16_t *ArgRegs = CC.intArgRegs();
4413 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
4416 // Copy words to registers.
4417 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
4418 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4419 DAG.getConstant(Offset, PtrTy));
4420 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
4421 MachinePointerInfo(), false, false, false,
4423 MemOpChains.push_back(LoadVal.getValue(1));
4424 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
4425 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
4428 // Return if the struct has been fully copied.
4429 if (ByValSize == Offset)
4432 // Copy the remainder of the byval argument with sub-word loads and shifts.
4433 if (LeftoverBytes) {
4434 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
4435 "Size of the remainder should be smaller than RegSize.");
4438 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
4439 Offset < ByValSize; LoadSize /= 2) {
4440 unsigned RemSize = ByValSize - Offset;
4442 if (RemSize < LoadSize)
4446 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4447 DAG.getConstant(Offset, PtrTy));
4449 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
4450 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
4451 false, false, Alignment);
4452 MemOpChains.push_back(LoadVal.getValue(1));
4454 // Shift the loaded value.
4458 Shamt = TotalSizeLoaded;
4460 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
4462 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
4463 DAG.getConstant(Shamt, MVT::i32));
4466 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
4471 TotalSizeLoaded += LoadSize;
4472 Alignment = std::min(Alignment, LoadSize);
4475 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
4476 RegsToPass.push_back(std::make_pair(ArgReg, Val));
4481 // Copy remainder of byval arg to it with memcpy.
4482 unsigned MemCpySize = ByValSize - Offset;
4483 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
4484 DAG.getConstant(Offset, PtrTy));
4485 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
4486 DAG.getIntPtrConstant(ByVal.Address));
4487 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
4488 DAG.getConstant(MemCpySize, PtrTy), Alignment,
4489 /*isVolatile=*/false, /*AlwaysInline=*/false,
4490 MachinePointerInfo(0), MachinePointerInfo(0));
4491 MemOpChains.push_back(Chain);
4495 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
4496 const MipsCC &CC, SDValue Chain,
4497 DebugLoc DL, SelectionDAG &DAG) const {
4498 unsigned NumRegs = CC.numIntArgRegs();
4499 const uint16_t *ArgRegs = CC.intArgRegs();
4500 const CCState &CCInfo = CC.getCCInfo();
4501 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
4502 unsigned RegSize = CC.regSize();
4503 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
4504 const TargetRegisterClass *RC = getRegClassFor(RegTy);
4505 MachineFunction &MF = DAG.getMachineFunction();
4506 MachineFrameInfo *MFI = MF.getFrameInfo();
4507 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
4509 // Offset of the first variable argument from stack pointer.
4513 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
4516 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
4518 // Record the frame index of the first variable argument
4519 // which is a value necessary to VASTART.
4520 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4521 MipsFI->setVarArgsFrameIndex(FI);
4523 // Copy the integer registers that have not been used for argument passing
4524 // to the argument register save area. For O32, the save area is allocated
4525 // in the caller's stack frame, while for N32/64, it is allocated in the
4526 // callee's stack frame.
4527 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
4528 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
4529 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
4530 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
4531 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
4532 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
4533 MachinePointerInfo(), false, false, 0);
4534 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
4535 OutChains.push_back(Store);