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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-lower"
16 #include "MipsISelLowering.h"
17 #include "InstPrinter/MipsInstPrinter.h"
18 #include "MCTargetDesc/MipsBaseInfo.h"
19 #include "MipsMachineFunction.h"
20 #include "MipsSubtarget.h"
21 #include "MipsTargetMachine.h"
22 #include "MipsTargetObjectFile.h"
23 #include "llvm/ADT/Statistic.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/Function.h"
34 #include "llvm/IR/GlobalVariable.h"
35 #include "llvm/IR/Intrinsics.h"
36 #include "llvm/Support/CommandLine.h"
37 #include "llvm/Support/Debug.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Support/raw_ostream.h"
43 STATISTIC(NumTailCalls, "Number of tail calls");
46 EnableMipsTailCalls("enable-mips-tail-calls", cl::Hidden,
47 cl::desc("MIPS: Enable tail calls."), cl::init(false));
50 LargeGOT("mxgot", cl::Hidden,
51 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
54 Mips16HardFloat("mips16-hard-float", cl::NotHidden,
55 cl::desc("MIPS: mips16 hard float enable."),
60 static const uint16_t O32IntRegs[4] = {
61 Mips::A0, Mips::A1, Mips::A2, Mips::A3
64 static const uint16_t Mips64IntRegs[8] = {
65 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
66 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
69 static const uint16_t Mips64DPRegs[8] = {
70 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
71 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
74 // If I is a shifted mask, set the size (Size) and the first bit of the
75 // mask (Pos), and return true.
76 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
77 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
78 if (!isShiftedMask_64(I))
81 Size = CountPopulation_64(I);
82 Pos = CountTrailingZeros_64(I);
86 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
87 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
88 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
91 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
92 EVT Ty = Op.getValueType();
94 if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
95 return DAG.getTargetGlobalAddress(N->getGlobal(), Op.getDebugLoc(), Ty, 0,
97 if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
98 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
99 if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
100 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
101 if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
102 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
103 if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
104 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
105 N->getOffset(), Flag);
107 llvm_unreachable("Unexpected node type.");
111 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
112 DebugLoc DL = Op.getDebugLoc();
113 EVT Ty = Op.getValueType();
114 SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
115 SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
116 return DAG.getNode(ISD::ADD, DL, Ty,
117 DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
118 DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
121 static SDValue getAddrLocal(SDValue Op, SelectionDAG &DAG, bool HasMips64) {
122 DebugLoc DL = Op.getDebugLoc();
123 EVT Ty = Op.getValueType();
124 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
125 SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
126 getTargetNode(Op, DAG, GOTFlag));
127 SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
128 MachinePointerInfo::getGOT(), false, false, false,
130 unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
131 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
132 return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
135 static SDValue getAddrGlobal(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
136 DebugLoc DL = Op.getDebugLoc();
137 EVT Ty = Op.getValueType();
138 SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, GetGlobalReg(DAG, Ty),
139 getTargetNode(Op, DAG, Flag));
140 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
141 MachinePointerInfo::getGOT(), false, false, false, 0);
144 static SDValue getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
145 unsigned HiFlag, unsigned LoFlag) {
146 DebugLoc DL = Op.getDebugLoc();
147 EVT Ty = Op.getValueType();
148 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
149 Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, GetGlobalReg(DAG, Ty));
150 SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
151 getTargetNode(Op, DAG, LoFlag));
152 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
153 MachinePointerInfo::getGOT(), false, false, false, 0);
156 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
158 case MipsISD::JmpLink: return "MipsISD::JmpLink";
159 case MipsISD::TailCall: return "MipsISD::TailCall";
160 case MipsISD::Hi: return "MipsISD::Hi";
161 case MipsISD::Lo: return "MipsISD::Lo";
162 case MipsISD::GPRel: return "MipsISD::GPRel";
163 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
164 case MipsISD::Ret: return "MipsISD::Ret";
165 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
166 case MipsISD::FPCmp: return "MipsISD::FPCmp";
167 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
168 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
169 case MipsISD::FPRound: return "MipsISD::FPRound";
170 case MipsISD::MAdd: return "MipsISD::MAdd";
171 case MipsISD::MAddu: return "MipsISD::MAddu";
172 case MipsISD::MSub: return "MipsISD::MSub";
173 case MipsISD::MSubu: return "MipsISD::MSubu";
174 case MipsISD::DivRem: return "MipsISD::DivRem";
175 case MipsISD::DivRemU: return "MipsISD::DivRemU";
176 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
177 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
178 case MipsISD::Wrapper: return "MipsISD::Wrapper";
179 case MipsISD::Sync: return "MipsISD::Sync";
180 case MipsISD::Ext: return "MipsISD::Ext";
181 case MipsISD::Ins: return "MipsISD::Ins";
182 case MipsISD::LWL: return "MipsISD::LWL";
183 case MipsISD::LWR: return "MipsISD::LWR";
184 case MipsISD::SWL: return "MipsISD::SWL";
185 case MipsISD::SWR: return "MipsISD::SWR";
186 case MipsISD::LDL: return "MipsISD::LDL";
187 case MipsISD::LDR: return "MipsISD::LDR";
188 case MipsISD::SDL: return "MipsISD::SDL";
189 case MipsISD::SDR: return "MipsISD::SDR";
190 case MipsISD::EXTP: return "MipsISD::EXTP";
191 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
192 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
193 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
194 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
195 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
196 case MipsISD::SHILO: return "MipsISD::SHILO";
197 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
198 case MipsISD::MULT: return "MipsISD::MULT";
199 case MipsISD::MULTU: return "MipsISD::MULTU";
200 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSPDSP";
201 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
202 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
203 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
204 default: return NULL;
208 void MipsTargetLowering::setMips16HardFloatLibCalls() {
209 setLibcallName(RTLIB::ADD_F32, "__mips16_addsf3");
210 setLibcallName(RTLIB::ADD_F64, "__mips16_adddf3");
211 setLibcallName(RTLIB::SUB_F32, "__mips16_subsf3");
212 setLibcallName(RTLIB::SUB_F64, "__mips16_subdf3");
213 setLibcallName(RTLIB::MUL_F32, "__mips16_mulsf3");
214 setLibcallName(RTLIB::MUL_F64, "__mips16_muldf3");
215 setLibcallName(RTLIB::DIV_F32, "__mips16_divsf3");
216 setLibcallName(RTLIB::DIV_F64, "__mips16_divdf3");
217 setLibcallName(RTLIB::FPEXT_F32_F64, "__mips16_extendsfdf2");
218 setLibcallName(RTLIB::FPROUND_F64_F32, "__mips16_truncdfsf2");
219 setLibcallName(RTLIB::FPTOSINT_F32_I32, "__mips16_fix_truncsfsi");
220 setLibcallName(RTLIB::FPTOSINT_F64_I32, "__mips16_fix_truncdfsi");
221 setLibcallName(RTLIB::SINTTOFP_I32_F32, "__mips16_floatsisf");
222 setLibcallName(RTLIB::SINTTOFP_I32_F64, "__mips16_floatsidf");
223 setLibcallName(RTLIB::UINTTOFP_I32_F32, "__mips16_floatunsisf");
224 setLibcallName(RTLIB::UINTTOFP_I32_F64, "__mips16_floatunsidf");
225 setLibcallName(RTLIB::OEQ_F32, "__mips16_eqsf2");
226 setLibcallName(RTLIB::OEQ_F64, "__mips16_eqdf2");
227 setLibcallName(RTLIB::UNE_F32, "__mips16_nesf2");
228 setLibcallName(RTLIB::UNE_F64, "__mips16_nedf2");
229 setLibcallName(RTLIB::OGE_F32, "__mips16_gesf2");
230 setLibcallName(RTLIB::OGE_F64, "__mips16_gedf2");
231 setLibcallName(RTLIB::OLT_F32, "__mips16_ltsf2");
232 setLibcallName(RTLIB::OLT_F64, "__mips16_ltdf2");
233 setLibcallName(RTLIB::OLE_F32, "__mips16_lesf2");
234 setLibcallName(RTLIB::OLE_F64, "__mips16_ledf2");
235 setLibcallName(RTLIB::OGT_F32, "__mips16_gtsf2");
236 setLibcallName(RTLIB::OGT_F64, "__mips16_gtdf2");
237 setLibcallName(RTLIB::UO_F32, "__mips16_unordsf2");
238 setLibcallName(RTLIB::UO_F64, "__mips16_unorddf2");
239 setLibcallName(RTLIB::O_F32, "__mips16_unordsf2");
240 setLibcallName(RTLIB::O_F64, "__mips16_unorddf2");
244 MipsTargetLowering(MipsTargetMachine &TM)
245 : TargetLowering(TM, new MipsTargetObjectFile()),
246 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
247 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
248 IsO32(Subtarget->isABI_O32()) {
250 // Mips does not have i1 type, so use i32 for
251 // setcc operations results (slt, sgt, ...).
252 setBooleanContents(ZeroOrOneBooleanContent);
253 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
255 // Set up the register classes
256 addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
259 addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
261 if (Subtarget->inMips16Mode()) {
262 addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
264 setMips16HardFloatLibCalls();
267 if (Subtarget->hasDSP()) {
268 MVT::SimpleValueType VecTys[2] = {MVT::v2i16, MVT::v4i8};
270 for (unsigned i = 0; i < array_lengthof(VecTys); ++i) {
271 addRegisterClass(VecTys[i], &Mips::DSPRegsRegClass);
273 // Expand all builtin opcodes.
274 for (unsigned Opc = 0; Opc < ISD::BUILTIN_OP_END; ++Opc)
275 setOperationAction(Opc, VecTys[i], Expand);
277 setOperationAction(ISD::LOAD, VecTys[i], Legal);
278 setOperationAction(ISD::STORE, VecTys[i], Legal);
279 setOperationAction(ISD::BITCAST, VecTys[i], Legal);
283 if (!TM.Options.UseSoftFloat) {
284 addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
286 // When dealing with single precision only, use libcalls
287 if (!Subtarget->isSingleFloat()) {
289 addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
291 addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
295 // Load extented operations for i1 types must be promoted
296 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
297 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
298 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
300 // MIPS doesn't have extending float->double load/store
301 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
302 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
304 // Used by legalize types to correctly generate the setcc result.
305 // Without this, every float setcc comes with a AND/OR with the result,
306 // we don't want this, since the fpcmp result goes to a flag register,
307 // which is used implicitly by brcond and select operations.
308 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
310 // Mips Custom Operations
311 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
312 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
313 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
314 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
315 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
316 setOperationAction(ISD::SELECT, MVT::f32, Custom);
317 setOperationAction(ISD::SELECT, MVT::f64, Custom);
318 setOperationAction(ISD::SELECT, MVT::i32, Custom);
319 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
320 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
321 setOperationAction(ISD::SETCC, MVT::f32, Custom);
322 setOperationAction(ISD::SETCC, MVT::f64, Custom);
323 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
324 setOperationAction(ISD::VASTART, MVT::Other, Custom);
325 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
326 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
327 if (Subtarget->inMips16Mode()) {
328 setOperationAction(ISD::MEMBARRIER, MVT::Other, Expand);
329 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Expand);
332 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
333 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
335 if (!Subtarget->inMips16Mode()) {
336 setOperationAction(ISD::LOAD, MVT::i32, Custom);
337 setOperationAction(ISD::STORE, MVT::i32, Custom);
340 if (!TM.Options.NoNaNsFPMath) {
341 setOperationAction(ISD::FABS, MVT::f32, Custom);
342 setOperationAction(ISD::FABS, MVT::f64, Custom);
346 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
347 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
348 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
349 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
350 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
351 setOperationAction(ISD::SELECT, MVT::i64, Custom);
352 setOperationAction(ISD::LOAD, MVT::i64, Custom);
353 setOperationAction(ISD::STORE, MVT::i64, Custom);
357 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
358 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
359 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
362 setOperationAction(ISD::ADD, MVT::i32, Custom);
364 setOperationAction(ISD::ADD, MVT::i64, Custom);
366 setOperationAction(ISD::SDIV, MVT::i32, Expand);
367 setOperationAction(ISD::SREM, MVT::i32, Expand);
368 setOperationAction(ISD::UDIV, MVT::i32, Expand);
369 setOperationAction(ISD::UREM, MVT::i32, Expand);
370 setOperationAction(ISD::SDIV, MVT::i64, Expand);
371 setOperationAction(ISD::SREM, MVT::i64, Expand);
372 setOperationAction(ISD::UDIV, MVT::i64, Expand);
373 setOperationAction(ISD::UREM, MVT::i64, Expand);
375 // Operations not directly supported by Mips.
376 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
377 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
378 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
379 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
380 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
381 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
382 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
383 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
384 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
385 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
386 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
387 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
388 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
389 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
390 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
391 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
392 setOperationAction(ISD::ROTL, MVT::i32, Expand);
393 setOperationAction(ISD::ROTL, MVT::i64, Expand);
394 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
395 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
397 if (!Subtarget->hasMips32r2())
398 setOperationAction(ISD::ROTR, MVT::i32, Expand);
400 if (!Subtarget->hasMips64r2())
401 setOperationAction(ISD::ROTR, MVT::i64, Expand);
403 setOperationAction(ISD::FSIN, MVT::f32, Expand);
404 setOperationAction(ISD::FSIN, MVT::f64, Expand);
405 setOperationAction(ISD::FCOS, MVT::f32, Expand);
406 setOperationAction(ISD::FCOS, MVT::f64, Expand);
407 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
408 setOperationAction(ISD::FPOW, MVT::f32, Expand);
409 setOperationAction(ISD::FPOW, MVT::f64, Expand);
410 setOperationAction(ISD::FLOG, MVT::f32, Expand);
411 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
412 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
413 setOperationAction(ISD::FEXP, MVT::f32, Expand);
414 setOperationAction(ISD::FMA, MVT::f32, Expand);
415 setOperationAction(ISD::FMA, MVT::f64, Expand);
416 setOperationAction(ISD::FREM, MVT::f32, Expand);
417 setOperationAction(ISD::FREM, MVT::f64, Expand);
419 if (!TM.Options.NoNaNsFPMath) {
420 setOperationAction(ISD::FNEG, MVT::f32, Expand);
421 setOperationAction(ISD::FNEG, MVT::f64, Expand);
424 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
425 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
426 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
427 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
429 setOperationAction(ISD::VAARG, MVT::Other, Expand);
430 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
431 setOperationAction(ISD::VAEND, MVT::Other, Expand);
433 setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i64, Custom);
434 setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i64, Custom);
436 // Use the default for now
437 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
438 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
440 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
441 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
442 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
443 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
445 if (Subtarget->inMips16Mode()) {
446 setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, Expand);
447 setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, Expand);
448 setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, Expand);
449 setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Expand);
450 setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Expand);
451 setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, Expand);
452 setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, Expand);
453 setOperationAction(ISD::ATOMIC_LOAD_NAND, MVT::i32, Expand);
454 setOperationAction(ISD::ATOMIC_LOAD_MIN, MVT::i32, Expand);
455 setOperationAction(ISD::ATOMIC_LOAD_MAX, MVT::i32, Expand);
456 setOperationAction(ISD::ATOMIC_LOAD_UMIN, MVT::i32, Expand);
457 setOperationAction(ISD::ATOMIC_LOAD_UMAX, MVT::i32, Expand);
460 setInsertFencesForAtomic(true);
462 if (!Subtarget->hasSEInReg()) {
463 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
464 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
467 if (!Subtarget->hasBitCount()) {
468 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
469 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
472 if (!Subtarget->hasSwap()) {
473 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
474 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
478 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
479 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
480 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
481 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
484 setTargetDAGCombine(ISD::ADDE);
485 setTargetDAGCombine(ISD::SUBE);
486 setTargetDAGCombine(ISD::SDIVREM);
487 setTargetDAGCombine(ISD::UDIVREM);
488 setTargetDAGCombine(ISD::SELECT);
489 setTargetDAGCombine(ISD::AND);
490 setTargetDAGCombine(ISD::OR);
491 setTargetDAGCombine(ISD::ADD);
493 setMinFunctionAlignment(HasMips64 ? 3 : 2);
495 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
496 computeRegisterProperties();
498 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
499 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
501 maxStoresPerMemcpy = 16;
505 MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT, bool *Fast) const {
506 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
508 if (Subtarget->inMips16Mode())
522 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
525 return VT.changeVectorElementTypeToInteger();
529 // Transforms a subgraph in CurDAG if the following pattern is found:
530 // (addc multLo, Lo0), (adde multHi, Hi0),
532 // multHi/Lo: product of multiplication
533 // Lo0: initial value of Lo register
534 // Hi0: initial value of Hi register
535 // Return true if pattern matching was successful.
536 static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
537 // ADDENode's second operand must be a flag output of an ADDC node in order
538 // for the matching to be successful.
539 SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
541 if (ADDCNode->getOpcode() != ISD::ADDC)
544 SDValue MultHi = ADDENode->getOperand(0);
545 SDValue MultLo = ADDCNode->getOperand(0);
546 SDNode *MultNode = MultHi.getNode();
547 unsigned MultOpc = MultHi.getOpcode();
549 // MultHi and MultLo must be generated by the same node,
550 if (MultLo.getNode() != MultNode)
553 // and it must be a multiplication.
554 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
557 // MultLo amd MultHi must be the first and second output of MultNode
559 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
562 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
563 // of the values of MultNode, in which case MultNode will be removed in later
565 // If there exist users other than ADDENode or ADDCNode, this function returns
566 // here, which will result in MultNode being mapped to a single MULT
567 // instruction node rather than a pair of MULT and MADD instructions being
569 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
572 SDValue Chain = CurDAG->getEntryNode();
573 DebugLoc dl = ADDENode->getDebugLoc();
575 // create MipsMAdd(u) node
576 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
578 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
579 MultNode->getOperand(0),// Factor 0
580 MultNode->getOperand(1),// Factor 1
581 ADDCNode->getOperand(1),// Lo0
582 ADDENode->getOperand(1));// Hi0
584 // create CopyFromReg nodes
585 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
587 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
589 CopyFromLo.getValue(2));
591 // replace uses of adde and addc here
592 if (!SDValue(ADDCNode, 0).use_empty())
593 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
595 if (!SDValue(ADDENode, 0).use_empty())
596 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
602 // Transforms a subgraph in CurDAG if the following pattern is found:
603 // (addc Lo0, multLo), (sube Hi0, multHi),
605 // multHi/Lo: product of multiplication
606 // Lo0: initial value of Lo register
607 // Hi0: initial value of Hi register
608 // Return true if pattern matching was successful.
609 static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
610 // SUBENode's second operand must be a flag output of an SUBC node in order
611 // for the matching to be successful.
612 SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
614 if (SUBCNode->getOpcode() != ISD::SUBC)
617 SDValue MultHi = SUBENode->getOperand(1);
618 SDValue MultLo = SUBCNode->getOperand(1);
619 SDNode *MultNode = MultHi.getNode();
620 unsigned MultOpc = MultHi.getOpcode();
622 // MultHi and MultLo must be generated by the same node,
623 if (MultLo.getNode() != MultNode)
626 // and it must be a multiplication.
627 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
630 // MultLo amd MultHi must be the first and second output of MultNode
632 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
635 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
636 // of the values of MultNode, in which case MultNode will be removed in later
638 // If there exist users other than SUBENode or SUBCNode, this function returns
639 // here, which will result in MultNode being mapped to a single MULT
640 // instruction node rather than a pair of MULT and MSUB instructions being
642 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
645 SDValue Chain = CurDAG->getEntryNode();
646 DebugLoc dl = SUBENode->getDebugLoc();
648 // create MipsSub(u) node
649 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
651 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
652 MultNode->getOperand(0),// Factor 0
653 MultNode->getOperand(1),// Factor 1
654 SUBCNode->getOperand(0),// Lo0
655 SUBENode->getOperand(0));// Hi0
657 // create CopyFromReg nodes
658 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
660 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
662 CopyFromLo.getValue(2));
664 // replace uses of sube and subc here
665 if (!SDValue(SUBCNode, 0).use_empty())
666 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
668 if (!SDValue(SUBENode, 0).use_empty())
669 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
674 static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
675 TargetLowering::DAGCombinerInfo &DCI,
676 const MipsSubtarget *Subtarget) {
677 if (DCI.isBeforeLegalize())
680 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
682 return SDValue(N, 0);
687 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
688 TargetLowering::DAGCombinerInfo &DCI,
689 const MipsSubtarget *Subtarget) {
690 if (DCI.isBeforeLegalize())
693 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
695 return SDValue(N, 0);
700 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
701 TargetLowering::DAGCombinerInfo &DCI,
702 const MipsSubtarget *Subtarget) {
703 if (DCI.isBeforeLegalizeOps())
706 EVT Ty = N->getValueType(0);
707 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
708 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
709 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
711 DebugLoc dl = N->getDebugLoc();
713 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
714 N->getOperand(0), N->getOperand(1));
715 SDValue InChain = DAG.getEntryNode();
716 SDValue InGlue = DivRem;
719 if (N->hasAnyUseOfValue(0)) {
720 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
722 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
723 InChain = CopyFromLo.getValue(1);
724 InGlue = CopyFromLo.getValue(2);
728 if (N->hasAnyUseOfValue(1)) {
729 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
731 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
737 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
739 default: llvm_unreachable("Unknown fp condition code!");
741 case ISD::SETOEQ: return Mips::FCOND_OEQ;
742 case ISD::SETUNE: return Mips::FCOND_UNE;
744 case ISD::SETOLT: return Mips::FCOND_OLT;
746 case ISD::SETOGT: return Mips::FCOND_OGT;
748 case ISD::SETOLE: return Mips::FCOND_OLE;
750 case ISD::SETOGE: return Mips::FCOND_OGE;
751 case ISD::SETULT: return Mips::FCOND_ULT;
752 case ISD::SETULE: return Mips::FCOND_ULE;
753 case ISD::SETUGT: return Mips::FCOND_UGT;
754 case ISD::SETUGE: return Mips::FCOND_UGE;
755 case ISD::SETUO: return Mips::FCOND_UN;
756 case ISD::SETO: return Mips::FCOND_OR;
758 case ISD::SETONE: return Mips::FCOND_ONE;
759 case ISD::SETUEQ: return Mips::FCOND_UEQ;
764 // Returns true if condition code has to be inverted.
765 static bool InvertFPCondCode(Mips::CondCode CC) {
766 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
769 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
770 "Illegal Condition Code");
775 // Creates and returns an FPCmp node from a setcc node.
776 // Returns Op if setcc is not a floating point comparison.
777 static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
778 // must be a SETCC node
779 if (Op.getOpcode() != ISD::SETCC)
782 SDValue LHS = Op.getOperand(0);
784 if (!LHS.getValueType().isFloatingPoint())
787 SDValue RHS = Op.getOperand(1);
788 DebugLoc dl = Op.getDebugLoc();
790 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
791 // node if necessary.
792 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
794 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
795 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
798 // Creates and returns a CMovFPT/F node.
799 static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
800 SDValue False, DebugLoc DL) {
801 bool invert = InvertFPCondCode((Mips::CondCode)
802 cast<ConstantSDNode>(Cond.getOperand(2))
805 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
806 True.getValueType(), True, False, Cond);
809 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
810 TargetLowering::DAGCombinerInfo &DCI,
811 const MipsSubtarget *Subtarget) {
812 if (DCI.isBeforeLegalizeOps())
815 SDValue SetCC = N->getOperand(0);
817 if ((SetCC.getOpcode() != ISD::SETCC) ||
818 !SetCC.getOperand(0).getValueType().isInteger())
821 SDValue False = N->getOperand(2);
822 EVT FalseTy = False.getValueType();
824 if (!FalseTy.isInteger())
827 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
829 if (!CN || CN->getZExtValue())
832 const DebugLoc DL = N->getDebugLoc();
833 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
834 SDValue True = N->getOperand(1);
836 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
837 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
839 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
842 static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
843 TargetLowering::DAGCombinerInfo &DCI,
844 const MipsSubtarget *Subtarget) {
845 // Pattern match EXT.
846 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
847 // => ext $dst, $src, size, pos
848 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
851 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
852 unsigned ShiftRightOpc = ShiftRight.getOpcode();
854 // Op's first operand must be a shift right.
855 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
858 // The second operand of the shift must be an immediate.
860 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
863 uint64_t Pos = CN->getZExtValue();
864 uint64_t SMPos, SMSize;
866 // Op's second operand must be a shifted mask.
867 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
868 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
871 // Return if the shifted mask does not start at bit 0 or the sum of its size
872 // and Pos exceeds the word's size.
873 EVT ValTy = N->getValueType(0);
874 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
877 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
878 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
879 DAG.getConstant(SMSize, MVT::i32));
882 static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
883 TargetLowering::DAGCombinerInfo &DCI,
884 const MipsSubtarget *Subtarget) {
885 // Pattern match INS.
886 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
887 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
888 // => ins $dst, $src, size, pos, $src1
889 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
892 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
893 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
896 // See if Op's first operand matches (and $src1 , mask0).
897 if (And0.getOpcode() != ISD::AND)
900 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
901 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
904 // See if Op's second operand matches (and (shl $src, pos), mask1).
905 if (And1.getOpcode() != ISD::AND)
908 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
909 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
912 // The shift masks must have the same position and size.
913 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
916 SDValue Shl = And1.getOperand(0);
917 if (Shl.getOpcode() != ISD::SHL)
920 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
923 unsigned Shamt = CN->getZExtValue();
925 // Return if the shift amount and the first bit position of mask are not the
927 EVT ValTy = N->getValueType(0);
928 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
931 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
932 DAG.getConstant(SMPos0, MVT::i32),
933 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
936 static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
937 TargetLowering::DAGCombinerInfo &DCI,
938 const MipsSubtarget *Subtarget) {
939 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
941 if (DCI.isBeforeLegalizeOps())
944 SDValue Add = N->getOperand(1);
946 if (Add.getOpcode() != ISD::ADD)
949 SDValue Lo = Add.getOperand(1);
951 if ((Lo.getOpcode() != MipsISD::Lo) ||
952 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
955 EVT ValTy = N->getValueType(0);
956 DebugLoc DL = N->getDebugLoc();
958 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
960 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
963 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
965 SelectionDAG &DAG = DCI.DAG;
966 unsigned opc = N->getOpcode();
971 return PerformADDECombine(N, DAG, DCI, Subtarget);
973 return PerformSUBECombine(N, DAG, DCI, Subtarget);
976 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
978 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
980 return PerformANDCombine(N, DAG, DCI, Subtarget);
982 return PerformORCombine(N, DAG, DCI, Subtarget);
984 return PerformADDCombine(N, DAG, DCI, Subtarget);
991 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
992 SmallVectorImpl<SDValue> &Results,
993 SelectionDAG &DAG) const {
994 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
996 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
997 Results.push_back(Res.getValue(I));
1001 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
1002 SmallVectorImpl<SDValue> &Results,
1003 SelectionDAG &DAG) const {
1004 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
1006 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
1007 Results.push_back(Res.getValue(I));
1010 SDValue MipsTargetLowering::
1011 LowerOperation(SDValue Op, SelectionDAG &DAG) const
1013 switch (Op.getOpcode())
1015 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
1016 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
1017 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
1018 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
1019 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
1020 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
1021 case ISD::SELECT: return LowerSELECT(Op, DAG);
1022 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
1023 case ISD::SETCC: return LowerSETCC(Op, DAG);
1024 case ISD::VASTART: return LowerVASTART(Op, DAG);
1025 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
1026 case ISD::FABS: return LowerFABS(Op, DAG);
1027 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
1028 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
1029 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
1030 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
1031 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
1032 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
1033 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
1034 case ISD::LOAD: return LowerLOAD(Op, DAG);
1035 case ISD::STORE: return LowerSTORE(Op, DAG);
1036 case ISD::INTRINSIC_WO_CHAIN: return LowerINTRINSIC_WO_CHAIN(Op, DAG);
1037 case ISD::INTRINSIC_W_CHAIN: return LowerINTRINSIC_W_CHAIN(Op, DAG);
1038 case ISD::ADD: return LowerADD(Op, DAG);
1043 //===----------------------------------------------------------------------===//
1044 // Lower helper functions
1045 //===----------------------------------------------------------------------===//
1047 // AddLiveIn - This helper function adds the specified physical register to the
1048 // MachineFunction as a live in value. It also creates a corresponding
1049 // virtual register for it.
1051 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
1053 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
1054 MF.getRegInfo().addLiveIn(PReg, VReg);
1058 // Get fp branch code (not opcode) from condition code.
1059 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
1060 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
1061 return Mips::BRANCH_T;
1063 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
1064 "Invalid CondCode.");
1066 return Mips::BRANCH_F;
1070 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
1072 const MipsSubtarget *Subtarget,
1073 const TargetInstrInfo *TII,
1074 bool isFPCmp, unsigned Opc) {
1075 // There is no need to expand CMov instructions if target has
1076 // conditional moves.
1077 if (Subtarget->hasCondMov())
1080 // To "insert" a SELECT_CC instruction, we actually have to insert the
1081 // diamond control-flow pattern. The incoming instruction knows the
1082 // destination vreg to set, the condition code register to branch on, the
1083 // true/false values to select between, and a branch opcode to use.
1084 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1085 MachineFunction::iterator It = BB;
1092 // bNE r1, r0, copy1MBB
1093 // fallthrough --> copy0MBB
1094 MachineBasicBlock *thisMBB = BB;
1095 MachineFunction *F = BB->getParent();
1096 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
1097 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
1098 F->insert(It, copy0MBB);
1099 F->insert(It, sinkMBB);
1101 // Transfer the remainder of BB and its successor edges to sinkMBB.
1102 sinkMBB->splice(sinkMBB->begin(), BB,
1103 llvm::next(MachineBasicBlock::iterator(MI)),
1105 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
1107 // Next, add the true and fallthrough blocks as its successors.
1108 BB->addSuccessor(copy0MBB);
1109 BB->addSuccessor(sinkMBB);
1111 // Emit the right instruction according to the type of the operands compared
1113 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
1115 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
1116 .addReg(Mips::ZERO).addMBB(sinkMBB);
1119 // %FalseValue = ...
1120 // # fallthrough to sinkMBB
1123 // Update machine-CFG edges
1124 BB->addSuccessor(sinkMBB);
1127 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
1132 BuildMI(*BB, BB->begin(), dl,
1133 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1134 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
1135 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1137 BuildMI(*BB, BB->begin(), dl,
1138 TII->get(Mips::PHI), MI->getOperand(0).getReg())
1139 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
1140 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
1142 MI->eraseFromParent(); // The pseudo instruction is gone now.
1148 MipsTargetLowering::EmitBPOSGE32(MachineInstr *MI, MachineBasicBlock *BB) const{
1150 // bposge32_pseudo $vr0
1160 // $vr0 = phi($vr2, $fbb, $vr1, $tbb)
1162 MachineRegisterInfo &RegInfo = BB->getParent()->getRegInfo();
1163 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1164 const TargetRegisterClass *RC = &Mips::CPURegsRegClass;
1165 DebugLoc DL = MI->getDebugLoc();
1166 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1167 MachineFunction::iterator It = llvm::next(MachineFunction::iterator(BB));
1168 MachineFunction *F = BB->getParent();
1169 MachineBasicBlock *FBB = F->CreateMachineBasicBlock(LLVM_BB);
1170 MachineBasicBlock *TBB = F->CreateMachineBasicBlock(LLVM_BB);
1171 MachineBasicBlock *Sink = F->CreateMachineBasicBlock(LLVM_BB);
1174 F->insert(It, Sink);
1176 // Transfer the remainder of BB and its successor edges to Sink.
1177 Sink->splice(Sink->begin(), BB, llvm::next(MachineBasicBlock::iterator(MI)),
1179 Sink->transferSuccessorsAndUpdatePHIs(BB);
1182 BB->addSuccessor(FBB);
1183 BB->addSuccessor(TBB);
1184 FBB->addSuccessor(Sink);
1185 TBB->addSuccessor(Sink);
1187 // Insert the real bposge32 instruction to $BB.
1188 BuildMI(BB, DL, TII->get(Mips::BPOSGE32)).addMBB(TBB);
1191 unsigned VR2 = RegInfo.createVirtualRegister(RC);
1192 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::ADDiu), VR2)
1193 .addReg(Mips::ZERO).addImm(0);
1194 BuildMI(*FBB, FBB->end(), DL, TII->get(Mips::B)).addMBB(Sink);
1197 unsigned VR1 = RegInfo.createVirtualRegister(RC);
1198 BuildMI(*TBB, TBB->end(), DL, TII->get(Mips::ADDiu), VR1)
1199 .addReg(Mips::ZERO).addImm(1);
1201 // Insert phi function to $Sink.
1202 BuildMI(*Sink, Sink->begin(), DL, TII->get(Mips::PHI),
1203 MI->getOperand(0).getReg())
1204 .addReg(VR2).addMBB(FBB).addReg(VR1).addMBB(TBB);
1206 MI->eraseFromParent(); // The pseudo instruction is gone now.
1211 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
1212 MachineBasicBlock *BB) const {
1213 switch (MI->getOpcode()) {
1214 default: llvm_unreachable("Unexpected instr type to insert");
1215 case Mips::ATOMIC_LOAD_ADD_I8:
1216 case Mips::ATOMIC_LOAD_ADD_I8_P8:
1217 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
1218 case Mips::ATOMIC_LOAD_ADD_I16:
1219 case Mips::ATOMIC_LOAD_ADD_I16_P8:
1220 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
1221 case Mips::ATOMIC_LOAD_ADD_I32:
1222 case Mips::ATOMIC_LOAD_ADD_I32_P8:
1223 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
1224 case Mips::ATOMIC_LOAD_ADD_I64:
1225 case Mips::ATOMIC_LOAD_ADD_I64_P8:
1226 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
1228 case Mips::ATOMIC_LOAD_AND_I8:
1229 case Mips::ATOMIC_LOAD_AND_I8_P8:
1230 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
1231 case Mips::ATOMIC_LOAD_AND_I16:
1232 case Mips::ATOMIC_LOAD_AND_I16_P8:
1233 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
1234 case Mips::ATOMIC_LOAD_AND_I32:
1235 case Mips::ATOMIC_LOAD_AND_I32_P8:
1236 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
1237 case Mips::ATOMIC_LOAD_AND_I64:
1238 case Mips::ATOMIC_LOAD_AND_I64_P8:
1239 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
1241 case Mips::ATOMIC_LOAD_OR_I8:
1242 case Mips::ATOMIC_LOAD_OR_I8_P8:
1243 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
1244 case Mips::ATOMIC_LOAD_OR_I16:
1245 case Mips::ATOMIC_LOAD_OR_I16_P8:
1246 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
1247 case Mips::ATOMIC_LOAD_OR_I32:
1248 case Mips::ATOMIC_LOAD_OR_I32_P8:
1249 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
1250 case Mips::ATOMIC_LOAD_OR_I64:
1251 case Mips::ATOMIC_LOAD_OR_I64_P8:
1252 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
1254 case Mips::ATOMIC_LOAD_XOR_I8:
1255 case Mips::ATOMIC_LOAD_XOR_I8_P8:
1256 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
1257 case Mips::ATOMIC_LOAD_XOR_I16:
1258 case Mips::ATOMIC_LOAD_XOR_I16_P8:
1259 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
1260 case Mips::ATOMIC_LOAD_XOR_I32:
1261 case Mips::ATOMIC_LOAD_XOR_I32_P8:
1262 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
1263 case Mips::ATOMIC_LOAD_XOR_I64:
1264 case Mips::ATOMIC_LOAD_XOR_I64_P8:
1265 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
1267 case Mips::ATOMIC_LOAD_NAND_I8:
1268 case Mips::ATOMIC_LOAD_NAND_I8_P8:
1269 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
1270 case Mips::ATOMIC_LOAD_NAND_I16:
1271 case Mips::ATOMIC_LOAD_NAND_I16_P8:
1272 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
1273 case Mips::ATOMIC_LOAD_NAND_I32:
1274 case Mips::ATOMIC_LOAD_NAND_I32_P8:
1275 return EmitAtomicBinary(MI, BB, 4, 0, true);
1276 case Mips::ATOMIC_LOAD_NAND_I64:
1277 case Mips::ATOMIC_LOAD_NAND_I64_P8:
1278 return EmitAtomicBinary(MI, BB, 8, 0, true);
1280 case Mips::ATOMIC_LOAD_SUB_I8:
1281 case Mips::ATOMIC_LOAD_SUB_I8_P8:
1282 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
1283 case Mips::ATOMIC_LOAD_SUB_I16:
1284 case Mips::ATOMIC_LOAD_SUB_I16_P8:
1285 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1286 case Mips::ATOMIC_LOAD_SUB_I32:
1287 case Mips::ATOMIC_LOAD_SUB_I32_P8:
1288 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1289 case Mips::ATOMIC_LOAD_SUB_I64:
1290 case Mips::ATOMIC_LOAD_SUB_I64_P8:
1291 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1293 case Mips::ATOMIC_SWAP_I8:
1294 case Mips::ATOMIC_SWAP_I8_P8:
1295 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1296 case Mips::ATOMIC_SWAP_I16:
1297 case Mips::ATOMIC_SWAP_I16_P8:
1298 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1299 case Mips::ATOMIC_SWAP_I32:
1300 case Mips::ATOMIC_SWAP_I32_P8:
1301 return EmitAtomicBinary(MI, BB, 4, 0);
1302 case Mips::ATOMIC_SWAP_I64:
1303 case Mips::ATOMIC_SWAP_I64_P8:
1304 return EmitAtomicBinary(MI, BB, 8, 0);
1306 case Mips::ATOMIC_CMP_SWAP_I8:
1307 case Mips::ATOMIC_CMP_SWAP_I8_P8:
1308 return EmitAtomicCmpSwapPartword(MI, BB, 1);
1309 case Mips::ATOMIC_CMP_SWAP_I16:
1310 case Mips::ATOMIC_CMP_SWAP_I16_P8:
1311 return EmitAtomicCmpSwapPartword(MI, BB, 2);
1312 case Mips::ATOMIC_CMP_SWAP_I32:
1313 case Mips::ATOMIC_CMP_SWAP_I32_P8:
1314 return EmitAtomicCmpSwap(MI, BB, 4);
1315 case Mips::ATOMIC_CMP_SWAP_I64:
1316 case Mips::ATOMIC_CMP_SWAP_I64_P8:
1317 return EmitAtomicCmpSwap(MI, BB, 8);
1318 case Mips::BPOSGE32_PSEUDO:
1319 return EmitBPOSGE32(MI, BB);
1323 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1324 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1326 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1327 unsigned Size, unsigned BinOpcode,
1329 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1331 MachineFunction *MF = BB->getParent();
1332 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1333 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1334 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1335 DebugLoc dl = MI->getDebugLoc();
1336 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1339 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1340 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1347 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1348 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1351 ZERO = Mips::ZERO_64;
1355 unsigned OldVal = MI->getOperand(0).getReg();
1356 unsigned Ptr = MI->getOperand(1).getReg();
1357 unsigned Incr = MI->getOperand(2).getReg();
1359 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1360 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1361 unsigned Success = RegInfo.createVirtualRegister(RC);
1363 // insert new blocks after the current block
1364 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1365 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1366 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1367 MachineFunction::iterator It = BB;
1369 MF->insert(It, loopMBB);
1370 MF->insert(It, exitMBB);
1372 // Transfer the remainder of BB and its successor edges to exitMBB.
1373 exitMBB->splice(exitMBB->begin(), BB,
1374 llvm::next(MachineBasicBlock::iterator(MI)),
1376 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1380 // fallthrough --> loopMBB
1381 BB->addSuccessor(loopMBB);
1382 loopMBB->addSuccessor(loopMBB);
1383 loopMBB->addSuccessor(exitMBB);
1386 // ll oldval, 0(ptr)
1387 // <binop> storeval, oldval, incr
1388 // sc success, storeval, 0(ptr)
1389 // beq success, $0, loopMBB
1391 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1393 // and andres, oldval, incr
1394 // nor storeval, $0, andres
1395 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1396 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1397 } else if (BinOpcode) {
1398 // <binop> storeval, oldval, incr
1399 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1403 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1404 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1406 MI->eraseFromParent(); // The instruction is gone now.
1412 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1413 MachineBasicBlock *BB,
1414 unsigned Size, unsigned BinOpcode,
1416 assert((Size == 1 || Size == 2) &&
1417 "Unsupported size for EmitAtomicBinaryPartial.");
1419 MachineFunction *MF = BB->getParent();
1420 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1421 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1422 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1423 DebugLoc dl = MI->getDebugLoc();
1424 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1425 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1427 unsigned Dest = MI->getOperand(0).getReg();
1428 unsigned Ptr = MI->getOperand(1).getReg();
1429 unsigned Incr = MI->getOperand(2).getReg();
1431 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1432 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1433 unsigned Mask = RegInfo.createVirtualRegister(RC);
1434 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1435 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1436 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1437 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1438 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1439 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1440 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1441 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1442 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1443 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1444 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1445 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1446 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1447 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1448 unsigned Success = RegInfo.createVirtualRegister(RC);
1450 // insert new blocks after the current block
1451 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1452 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1453 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1454 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1455 MachineFunction::iterator It = BB;
1457 MF->insert(It, loopMBB);
1458 MF->insert(It, sinkMBB);
1459 MF->insert(It, exitMBB);
1461 // Transfer the remainder of BB and its successor edges to exitMBB.
1462 exitMBB->splice(exitMBB->begin(), BB,
1463 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1464 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1466 BB->addSuccessor(loopMBB);
1467 loopMBB->addSuccessor(loopMBB);
1468 loopMBB->addSuccessor(sinkMBB);
1469 sinkMBB->addSuccessor(exitMBB);
1472 // addiu masklsb2,$0,-4 # 0xfffffffc
1473 // and alignedaddr,ptr,masklsb2
1474 // andi ptrlsb2,ptr,3
1475 // sll shiftamt,ptrlsb2,3
1476 // ori maskupper,$0,255 # 0xff
1477 // sll mask,maskupper,shiftamt
1478 // nor mask2,$0,mask
1479 // sll incr2,incr,shiftamt
1481 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1482 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1483 .addReg(Mips::ZERO).addImm(-4);
1484 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1485 .addReg(Ptr).addReg(MaskLSB2);
1486 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1487 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1488 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1489 .addReg(Mips::ZERO).addImm(MaskImm);
1490 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1491 .addReg(ShiftAmt).addReg(MaskUpper);
1492 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1493 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1495 // atomic.load.binop
1497 // ll oldval,0(alignedaddr)
1498 // binop binopres,oldval,incr2
1499 // and newval,binopres,mask
1500 // and maskedoldval0,oldval,mask2
1501 // or storeval,maskedoldval0,newval
1502 // sc success,storeval,0(alignedaddr)
1503 // beq success,$0,loopMBB
1507 // ll oldval,0(alignedaddr)
1508 // and newval,incr2,mask
1509 // and maskedoldval0,oldval,mask2
1510 // or storeval,maskedoldval0,newval
1511 // sc success,storeval,0(alignedaddr)
1512 // beq success,$0,loopMBB
1515 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1517 // and andres, oldval, incr2
1518 // nor binopres, $0, andres
1519 // and newval, binopres, mask
1520 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1521 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1522 .addReg(Mips::ZERO).addReg(AndRes);
1523 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1524 } else if (BinOpcode) {
1525 // <binop> binopres, oldval, incr2
1526 // and newval, binopres, mask
1527 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1528 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1529 } else {// atomic.swap
1530 // and newval, incr2, mask
1531 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1534 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1535 .addReg(OldVal).addReg(Mask2);
1536 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1537 .addReg(MaskedOldVal0).addReg(NewVal);
1538 BuildMI(BB, dl, TII->get(SC), Success)
1539 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1540 BuildMI(BB, dl, TII->get(Mips::BEQ))
1541 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1544 // and maskedoldval1,oldval,mask
1545 // srl srlres,maskedoldval1,shiftamt
1546 // sll sllres,srlres,24
1547 // sra dest,sllres,24
1549 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1551 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1552 .addReg(OldVal).addReg(Mask);
1553 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1554 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1555 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1556 .addReg(SrlRes).addImm(ShiftImm);
1557 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1558 .addReg(SllRes).addImm(ShiftImm);
1560 MI->eraseFromParent(); // The instruction is gone now.
1566 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1567 MachineBasicBlock *BB,
1568 unsigned Size) const {
1569 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1571 MachineFunction *MF = BB->getParent();
1572 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1573 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1574 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1575 DebugLoc dl = MI->getDebugLoc();
1576 unsigned LL, SC, ZERO, BNE, BEQ;
1579 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1580 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1586 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1587 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1588 ZERO = Mips::ZERO_64;
1593 unsigned Dest = MI->getOperand(0).getReg();
1594 unsigned Ptr = MI->getOperand(1).getReg();
1595 unsigned OldVal = MI->getOperand(2).getReg();
1596 unsigned NewVal = MI->getOperand(3).getReg();
1598 unsigned Success = RegInfo.createVirtualRegister(RC);
1600 // insert new blocks after the current block
1601 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1602 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1603 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1604 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1605 MachineFunction::iterator It = BB;
1607 MF->insert(It, loop1MBB);
1608 MF->insert(It, loop2MBB);
1609 MF->insert(It, exitMBB);
1611 // Transfer the remainder of BB and its successor edges to exitMBB.
1612 exitMBB->splice(exitMBB->begin(), BB,
1613 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1614 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1618 // fallthrough --> loop1MBB
1619 BB->addSuccessor(loop1MBB);
1620 loop1MBB->addSuccessor(exitMBB);
1621 loop1MBB->addSuccessor(loop2MBB);
1622 loop2MBB->addSuccessor(loop1MBB);
1623 loop2MBB->addSuccessor(exitMBB);
1627 // bne dest, oldval, exitMBB
1629 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1630 BuildMI(BB, dl, TII->get(BNE))
1631 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1634 // sc success, newval, 0(ptr)
1635 // beq success, $0, loop1MBB
1637 BuildMI(BB, dl, TII->get(SC), Success)
1638 .addReg(NewVal).addReg(Ptr).addImm(0);
1639 BuildMI(BB, dl, TII->get(BEQ))
1640 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1642 MI->eraseFromParent(); // The instruction is gone now.
1648 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1649 MachineBasicBlock *BB,
1650 unsigned Size) const {
1651 assert((Size == 1 || Size == 2) &&
1652 "Unsupported size for EmitAtomicCmpSwapPartial.");
1654 MachineFunction *MF = BB->getParent();
1655 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1656 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1657 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1658 DebugLoc dl = MI->getDebugLoc();
1659 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1660 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1662 unsigned Dest = MI->getOperand(0).getReg();
1663 unsigned Ptr = MI->getOperand(1).getReg();
1664 unsigned CmpVal = MI->getOperand(2).getReg();
1665 unsigned NewVal = MI->getOperand(3).getReg();
1667 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1668 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1669 unsigned Mask = RegInfo.createVirtualRegister(RC);
1670 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1671 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1672 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1673 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1674 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1675 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1676 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1677 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1678 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1679 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1680 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1681 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1682 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1683 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1684 unsigned Success = RegInfo.createVirtualRegister(RC);
1686 // insert new blocks after the current block
1687 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1688 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1689 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1690 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1691 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1692 MachineFunction::iterator It = BB;
1694 MF->insert(It, loop1MBB);
1695 MF->insert(It, loop2MBB);
1696 MF->insert(It, sinkMBB);
1697 MF->insert(It, exitMBB);
1699 // Transfer the remainder of BB and its successor edges to exitMBB.
1700 exitMBB->splice(exitMBB->begin(), BB,
1701 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1702 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1704 BB->addSuccessor(loop1MBB);
1705 loop1MBB->addSuccessor(sinkMBB);
1706 loop1MBB->addSuccessor(loop2MBB);
1707 loop2MBB->addSuccessor(loop1MBB);
1708 loop2MBB->addSuccessor(sinkMBB);
1709 sinkMBB->addSuccessor(exitMBB);
1711 // FIXME: computation of newval2 can be moved to loop2MBB.
1713 // addiu masklsb2,$0,-4 # 0xfffffffc
1714 // and alignedaddr,ptr,masklsb2
1715 // andi ptrlsb2,ptr,3
1716 // sll shiftamt,ptrlsb2,3
1717 // ori maskupper,$0,255 # 0xff
1718 // sll mask,maskupper,shiftamt
1719 // nor mask2,$0,mask
1720 // andi maskedcmpval,cmpval,255
1721 // sll shiftedcmpval,maskedcmpval,shiftamt
1722 // andi maskednewval,newval,255
1723 // sll shiftednewval,maskednewval,shiftamt
1724 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1725 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1726 .addReg(Mips::ZERO).addImm(-4);
1727 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1728 .addReg(Ptr).addReg(MaskLSB2);
1729 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1730 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1731 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1732 .addReg(Mips::ZERO).addImm(MaskImm);
1733 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1734 .addReg(ShiftAmt).addReg(MaskUpper);
1735 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1736 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1737 .addReg(CmpVal).addImm(MaskImm);
1738 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1739 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1740 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1741 .addReg(NewVal).addImm(MaskImm);
1742 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1743 .addReg(ShiftAmt).addReg(MaskedNewVal);
1746 // ll oldval,0(alginedaddr)
1747 // and maskedoldval0,oldval,mask
1748 // bne maskedoldval0,shiftedcmpval,sinkMBB
1750 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1751 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1752 .addReg(OldVal).addReg(Mask);
1753 BuildMI(BB, dl, TII->get(Mips::BNE))
1754 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1757 // and maskedoldval1,oldval,mask2
1758 // or storeval,maskedoldval1,shiftednewval
1759 // sc success,storeval,0(alignedaddr)
1760 // beq success,$0,loop1MBB
1762 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1763 .addReg(OldVal).addReg(Mask2);
1764 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1765 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1766 BuildMI(BB, dl, TII->get(SC), Success)
1767 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1768 BuildMI(BB, dl, TII->get(Mips::BEQ))
1769 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1772 // srl srlres,maskedoldval0,shiftamt
1773 // sll sllres,srlres,24
1774 // sra dest,sllres,24
1776 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1778 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1779 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1780 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1781 .addReg(SrlRes).addImm(ShiftImm);
1782 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1783 .addReg(SllRes).addImm(ShiftImm);
1785 MI->eraseFromParent(); // The instruction is gone now.
1790 //===----------------------------------------------------------------------===//
1791 // Misc Lower Operation implementation
1792 //===----------------------------------------------------------------------===//
1793 SDValue MipsTargetLowering::
1794 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1796 // The first operand is the chain, the second is the condition, the third is
1797 // the block to branch to if the condition is true.
1798 SDValue Chain = Op.getOperand(0);
1799 SDValue Dest = Op.getOperand(2);
1800 DebugLoc dl = Op.getDebugLoc();
1802 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1804 // Return if flag is not set by a floating point comparison.
1805 if (CondRes.getOpcode() != MipsISD::FPCmp)
1808 SDValue CCNode = CondRes.getOperand(2);
1810 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1811 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1813 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1817 SDValue MipsTargetLowering::
1818 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1820 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1822 // Return if flag is not set by a floating point comparison.
1823 if (Cond.getOpcode() != MipsISD::FPCmp)
1826 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1830 SDValue MipsTargetLowering::
1831 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1833 DebugLoc DL = Op.getDebugLoc();
1834 EVT Ty = Op.getOperand(0).getValueType();
1835 SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1836 Op.getOperand(0), Op.getOperand(1),
1839 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1843 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1844 SDValue Cond = CreateFPCmp(DAG, Op);
1846 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1847 "Floating point operand expected.");
1849 SDValue True = DAG.getConstant(1, MVT::i32);
1850 SDValue False = DAG.getConstant(0, MVT::i32);
1852 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1855 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1856 SelectionDAG &DAG) const {
1857 // FIXME there isn't actually debug info here
1858 DebugLoc dl = Op.getDebugLoc();
1859 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1861 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1862 const MipsTargetObjectFile &TLOF =
1863 (const MipsTargetObjectFile&)getObjFileLowering();
1865 // %gp_rel relocation
1866 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1867 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1869 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl,
1870 DAG.getVTList(MVT::i32), &GA, 1);
1871 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1872 return DAG.getNode(ISD::ADD, dl, MVT::i32, GPReg, GPRelNode);
1875 // %hi/%lo relocation
1876 return getAddrNonPIC(Op, DAG);
1879 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1880 return getAddrLocal(Op, DAG, HasMips64);
1883 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1884 MipsII::MO_GOT_LO16);
1886 return getAddrGlobal(Op, DAG,
1887 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1890 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1891 SelectionDAG &DAG) const {
1892 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1893 return getAddrNonPIC(Op, DAG);
1895 return getAddrLocal(Op, DAG, HasMips64);
1898 SDValue MipsTargetLowering::
1899 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1901 // If the relocation model is PIC, use the General Dynamic TLS Model or
1902 // Local Dynamic TLS model, otherwise use the Initial Exec or
1903 // Local Exec TLS Model.
1905 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1906 DebugLoc dl = GA->getDebugLoc();
1907 const GlobalValue *GV = GA->getGlobal();
1908 EVT PtrVT = getPointerTy();
1910 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1912 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1913 // General Dynamic and Local Dynamic TLS Model.
1914 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1917 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1918 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1919 GetGlobalReg(DAG, PtrVT), TGA);
1920 unsigned PtrSize = PtrVT.getSizeInBits();
1921 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1923 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1927 Entry.Node = Argument;
1929 Args.push_back(Entry);
1931 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1932 false, false, false, false, 0, CallingConv::C,
1933 /*isTailCall=*/false, /*doesNotRet=*/false,
1934 /*isReturnValueUsed=*/true,
1935 TlsGetAddr, Args, DAG, dl);
1936 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1938 SDValue Ret = CallResult.first;
1940 if (model != TLSModel::LocalDynamic)
1943 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1944 MipsII::MO_DTPREL_HI);
1945 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1946 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1947 MipsII::MO_DTPREL_LO);
1948 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1949 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1950 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1954 if (model == TLSModel::InitialExec) {
1955 // Initial Exec TLS Model
1956 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1957 MipsII::MO_GOTTPREL);
1958 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1960 Offset = DAG.getLoad(PtrVT, dl,
1961 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1962 false, false, false, 0);
1964 // Local Exec TLS Model
1965 assert(model == TLSModel::LocalExec);
1966 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1967 MipsII::MO_TPREL_HI);
1968 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1969 MipsII::MO_TPREL_LO);
1970 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1971 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1972 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1975 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1976 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1979 SDValue MipsTargetLowering::
1980 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1982 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1983 return getAddrNonPIC(Op, DAG);
1985 return getAddrLocal(Op, DAG, HasMips64);
1988 SDValue MipsTargetLowering::
1989 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1991 // gp_rel relocation
1992 // FIXME: we should reference the constant pool using small data sections,
1993 // but the asm printer currently doesn't support this feature without
1994 // hacking it. This feature should come soon so we can uncomment the
1996 //if (IsInSmallSection(C->getType())) {
1997 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1998 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1999 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
2001 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
2002 return getAddrNonPIC(Op, DAG);
2004 return getAddrLocal(Op, DAG, HasMips64);
2007 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
2008 MachineFunction &MF = DAG.getMachineFunction();
2009 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2011 DebugLoc dl = Op.getDebugLoc();
2012 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
2015 // vastart just stores the address of the VarArgsFrameIndex slot into the
2016 // memory location argument.
2017 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
2018 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
2019 MachinePointerInfo(SV), false, false, 0);
2022 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2023 EVT TyX = Op.getOperand(0).getValueType();
2024 EVT TyY = Op.getOperand(1).getValueType();
2025 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2026 SDValue Const31 = DAG.getConstant(31, MVT::i32);
2027 DebugLoc DL = Op.getDebugLoc();
2030 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2032 SDValue X = (TyX == MVT::f32) ?
2033 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2034 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2036 SDValue Y = (TyY == MVT::f32) ?
2037 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
2038 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
2042 // ext E, Y, 31, 1 ; extract bit31 of Y
2043 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
2044 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
2045 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
2048 // srl SrlX, SllX, 1
2050 // sll SllY, SrlX, 31
2051 // or Or, SrlX, SllY
2052 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2053 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2054 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
2055 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
2056 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
2059 if (TyX == MVT::f32)
2060 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
2062 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2063 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2064 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2067 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2068 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
2069 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
2070 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
2071 SDValue Const1 = DAG.getConstant(1, MVT::i32);
2072 DebugLoc DL = Op.getDebugLoc();
2074 // Bitcast to integer nodes.
2075 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
2076 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
2079 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
2080 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
2081 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
2082 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
2084 if (WidthX > WidthY)
2085 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
2086 else if (WidthY > WidthX)
2087 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
2089 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
2090 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
2091 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
2094 // (d)sll SllX, X, 1
2095 // (d)srl SrlX, SllX, 1
2096 // (d)srl SrlY, Y, width(Y)-1
2097 // (d)sll SllY, SrlX, width(Y)-1
2098 // or Or, SrlX, SllY
2099 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
2100 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
2101 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
2102 DAG.getConstant(WidthY - 1, MVT::i32));
2104 if (WidthX > WidthY)
2105 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
2106 else if (WidthY > WidthX)
2107 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
2109 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
2110 DAG.getConstant(WidthX - 1, MVT::i32));
2111 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
2112 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
2116 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
2117 if (Subtarget->hasMips64())
2118 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
2120 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
2123 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2124 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2125 DebugLoc DL = Op.getDebugLoc();
2127 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
2129 SDValue X = (Op.getValueType() == MVT::f32) ?
2130 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
2131 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
2136 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
2137 DAG.getRegister(Mips::ZERO, MVT::i32),
2138 DAG.getConstant(31, MVT::i32), Const1, X);
2140 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
2141 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
2144 if (Op.getValueType() == MVT::f32)
2145 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
2147 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2148 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
2149 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
2152 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
2153 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
2154 DebugLoc DL = Op.getDebugLoc();
2156 // Bitcast to integer node.
2157 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
2161 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
2162 DAG.getRegister(Mips::ZERO_64, MVT::i64),
2163 DAG.getConstant(63, MVT::i32), Const1, X);
2165 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
2166 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2169 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2173 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
2174 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2175 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2177 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2180 SDValue MipsTargetLowering::
2181 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2183 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2184 "Frame address can only be determined for current frame.");
2186 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2187 MFI->setFrameAddressIsTaken(true);
2188 EVT VT = Op.getValueType();
2189 DebugLoc dl = Op.getDebugLoc();
2190 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2191 IsN64 ? Mips::FP_64 : Mips::FP, VT);
2195 SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2196 SelectionDAG &DAG) const {
2198 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2199 "Return address can be determined only for current frame.");
2201 MachineFunction &MF = DAG.getMachineFunction();
2202 MachineFrameInfo *MFI = MF.getFrameInfo();
2203 MVT VT = Op.getSimpleValueType();
2204 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2205 MFI->setReturnAddressIsTaken(true);
2207 // Return RA, which contains the return address. Mark it an implicit live-in.
2208 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2209 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2212 // TODO: set SType according to the desired memory barrier behavior.
2214 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2216 DebugLoc dl = Op.getDebugLoc();
2217 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2218 DAG.getConstant(SType, MVT::i32));
2221 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2222 SelectionDAG &DAG) const {
2223 // FIXME: Need pseudo-fence for 'singlethread' fences
2224 // FIXME: Set SType for weaker fences where supported/appropriate.
2226 DebugLoc dl = Op.getDebugLoc();
2227 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2228 DAG.getConstant(SType, MVT::i32));
2231 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2232 SelectionDAG &DAG) const {
2233 DebugLoc DL = Op.getDebugLoc();
2234 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2235 SDValue Shamt = Op.getOperand(2);
2238 // lo = (shl lo, shamt)
2239 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2242 // hi = (shl lo, shamt[4:0])
2243 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2244 DAG.getConstant(-1, MVT::i32));
2245 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2246 DAG.getConstant(1, MVT::i32));
2247 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2249 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2250 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2251 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2252 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2253 DAG.getConstant(0x20, MVT::i32));
2254 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2255 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2256 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2258 SDValue Ops[2] = {Lo, Hi};
2259 return DAG.getMergeValues(Ops, 2, DL);
2262 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2264 DebugLoc DL = Op.getDebugLoc();
2265 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2266 SDValue Shamt = Op.getOperand(2);
2269 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2271 // hi = (sra hi, shamt)
2273 // hi = (srl hi, shamt)
2276 // lo = (sra hi, shamt[4:0])
2277 // hi = (sra hi, 31)
2279 // lo = (srl hi, shamt[4:0])
2281 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2282 DAG.getConstant(-1, MVT::i32));
2283 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2284 DAG.getConstant(1, MVT::i32));
2285 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2286 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2287 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2288 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2290 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2291 DAG.getConstant(0x20, MVT::i32));
2292 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2293 DAG.getConstant(31, MVT::i32));
2294 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2295 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2296 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2299 SDValue Ops[2] = {Lo, Hi};
2300 return DAG.getMergeValues(Ops, 2, DL);
2303 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2304 SDValue Chain, SDValue Src, unsigned Offset) {
2305 SDValue Ptr = LD->getBasePtr();
2306 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2307 EVT BasePtrVT = Ptr.getValueType();
2308 DebugLoc DL = LD->getDebugLoc();
2309 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2312 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2313 DAG.getConstant(Offset, BasePtrVT));
2315 SDValue Ops[] = { Chain, Ptr, Src };
2316 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2317 LD->getMemOperand());
2320 // Expand an unaligned 32 or 64-bit integer load node.
2321 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2322 LoadSDNode *LD = cast<LoadSDNode>(Op);
2323 EVT MemVT = LD->getMemoryVT();
2325 // Return if load is aligned or if MemVT is neither i32 nor i64.
2326 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2327 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2330 bool IsLittle = Subtarget->isLittle();
2331 EVT VT = Op.getValueType();
2332 ISD::LoadExtType ExtType = LD->getExtensionType();
2333 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2335 assert((VT == MVT::i32) || (VT == MVT::i64));
2338 // (set dst, (i64 (load baseptr)))
2340 // (set tmp, (ldl (add baseptr, 7), undef))
2341 // (set dst, (ldr baseptr, tmp))
2342 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2343 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2345 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2349 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2351 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2355 // (set dst, (i32 (load baseptr))) or
2356 // (set dst, (i64 (sextload baseptr))) or
2357 // (set dst, (i64 (extload baseptr)))
2359 // (set tmp, (lwl (add baseptr, 3), undef))
2360 // (set dst, (lwr baseptr, tmp))
2361 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2362 (ExtType == ISD::EXTLOAD))
2365 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2368 // (set dst, (i64 (zextload baseptr)))
2370 // (set tmp0, (lwl (add baseptr, 3), undef))
2371 // (set tmp1, (lwr baseptr, tmp0))
2372 // (set tmp2, (shl tmp1, 32))
2373 // (set dst, (srl tmp2, 32))
2374 DebugLoc DL = LD->getDebugLoc();
2375 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2376 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2377 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2378 SDValue Ops[] = { SRL, LWR.getValue(1) };
2379 return DAG.getMergeValues(Ops, 2, DL);
2382 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2383 SDValue Chain, unsigned Offset) {
2384 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2385 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2386 DebugLoc DL = SD->getDebugLoc();
2387 SDVTList VTList = DAG.getVTList(MVT::Other);
2390 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2391 DAG.getConstant(Offset, BasePtrVT));
2393 SDValue Ops[] = { Chain, Value, Ptr };
2394 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2395 SD->getMemOperand());
2398 // Expand an unaligned 32 or 64-bit integer store node.
2399 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2400 StoreSDNode *SD = cast<StoreSDNode>(Op);
2401 EVT MemVT = SD->getMemoryVT();
2403 // Return if store is aligned or if MemVT is neither i32 nor i64.
2404 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2405 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2408 bool IsLittle = Subtarget->isLittle();
2409 SDValue Value = SD->getValue(), Chain = SD->getChain();
2410 EVT VT = Value.getValueType();
2413 // (store val, baseptr) or
2414 // (truncstore val, baseptr)
2416 // (swl val, (add baseptr, 3))
2417 // (swr val, baseptr)
2418 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2419 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2421 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2424 assert(VT == MVT::i64);
2427 // (store val, baseptr)
2429 // (sdl val, (add baseptr, 7))
2430 // (sdr val, baseptr)
2431 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2432 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2435 // This function expands mips intrinsic nodes which have 64-bit input operands
2436 // or output values.
2438 // out64 = intrinsic-node in64
2440 // lo = copy (extract-element (in64, 0))
2441 // hi = copy (extract-element (in64, 1))
2442 // mips-specific-node
2445 // out64 = merge-values (v0, v1)
2447 static SDValue LowerDSPIntr(SDValue Op, SelectionDAG &DAG,
2448 unsigned Opc, bool HasI64In, bool HasI64Out) {
2449 DebugLoc DL = Op.getDebugLoc();
2450 bool HasChainIn = Op->getOperand(0).getValueType() == MVT::Other;
2451 SDValue Chain = HasChainIn ? Op->getOperand(0) : DAG.getEntryNode();
2452 SmallVector<SDValue, 3> Ops;
2455 SDValue InLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2456 Op->getOperand(1 + HasChainIn),
2457 DAG.getConstant(0, MVT::i32));
2458 SDValue InHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32,
2459 Op->getOperand(1 + HasChainIn),
2460 DAG.getConstant(1, MVT::i32));
2462 Chain = DAG.getCopyToReg(Chain, DL, Mips::LO, InLo, SDValue());
2463 Chain = DAG.getCopyToReg(Chain, DL, Mips::HI, InHi, Chain.getValue(1));
2465 Ops.push_back(Chain);
2466 Ops.append(Op->op_begin() + HasChainIn + 2, Op->op_end());
2467 Ops.push_back(Chain.getValue(1));
2469 Ops.push_back(Chain);
2470 Ops.append(Op->op_begin() + HasChainIn + 1, Op->op_end());
2474 return DAG.getNode(Opc, DL, Op->value_begin(), Op->getNumValues(),
2475 Ops.begin(), Ops.size());
2477 SDValue Intr = DAG.getNode(Opc, DL, DAG.getVTList(MVT::Other, MVT::Glue),
2478 Ops.begin(), Ops.size());
2479 SDValue OutLo = DAG.getCopyFromReg(Intr.getValue(0), DL, Mips::LO, MVT::i32,
2481 SDValue OutHi = DAG.getCopyFromReg(OutLo.getValue(1), DL, Mips::HI, MVT::i32,
2483 SDValue Out = DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, OutLo, OutHi);
2488 SDValue Vals[] = { Out, OutHi.getValue(1) };
2489 return DAG.getMergeValues(Vals, 2, DL);
2492 SDValue MipsTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
2493 SelectionDAG &DAG) const {
2494 switch (cast<ConstantSDNode>(Op->getOperand(0))->getZExtValue()) {
2497 case Intrinsic::mips_shilo:
2498 return LowerDSPIntr(Op, DAG, MipsISD::SHILO, true, true);
2499 case Intrinsic::mips_dpau_h_qbl:
2500 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBL, true, true);
2501 case Intrinsic::mips_dpau_h_qbr:
2502 return LowerDSPIntr(Op, DAG, MipsISD::DPAU_H_QBR, true, true);
2503 case Intrinsic::mips_dpsu_h_qbl:
2504 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBL, true, true);
2505 case Intrinsic::mips_dpsu_h_qbr:
2506 return LowerDSPIntr(Op, DAG, MipsISD::DPSU_H_QBR, true, true);
2507 case Intrinsic::mips_dpa_w_ph:
2508 return LowerDSPIntr(Op, DAG, MipsISD::DPA_W_PH, true, true);
2509 case Intrinsic::mips_dps_w_ph:
2510 return LowerDSPIntr(Op, DAG, MipsISD::DPS_W_PH, true, true);
2511 case Intrinsic::mips_dpax_w_ph:
2512 return LowerDSPIntr(Op, DAG, MipsISD::DPAX_W_PH, true, true);
2513 case Intrinsic::mips_dpsx_w_ph:
2514 return LowerDSPIntr(Op, DAG, MipsISD::DPSX_W_PH, true, true);
2515 case Intrinsic::mips_mulsa_w_ph:
2516 return LowerDSPIntr(Op, DAG, MipsISD::MULSA_W_PH, true, true);
2517 case Intrinsic::mips_mult:
2518 return LowerDSPIntr(Op, DAG, MipsISD::MULT, false, true);
2519 case Intrinsic::mips_multu:
2520 return LowerDSPIntr(Op, DAG, MipsISD::MULTU, false, true);
2521 case Intrinsic::mips_madd:
2522 return LowerDSPIntr(Op, DAG, MipsISD::MADD_DSP, true, true);
2523 case Intrinsic::mips_maddu:
2524 return LowerDSPIntr(Op, DAG, MipsISD::MADDU_DSP, true, true);
2525 case Intrinsic::mips_msub:
2526 return LowerDSPIntr(Op, DAG, MipsISD::MSUB_DSP, true, true);
2527 case Intrinsic::mips_msubu:
2528 return LowerDSPIntr(Op, DAG, MipsISD::MSUBU_DSP, true, true);
2532 SDValue MipsTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
2533 SelectionDAG &DAG) const {
2534 switch (cast<ConstantSDNode>(Op->getOperand(1))->getZExtValue()) {
2537 case Intrinsic::mips_extp:
2538 return LowerDSPIntr(Op, DAG, MipsISD::EXTP, true, false);
2539 case Intrinsic::mips_extpdp:
2540 return LowerDSPIntr(Op, DAG, MipsISD::EXTPDP, true, false);
2541 case Intrinsic::mips_extr_w:
2542 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_W, true, false);
2543 case Intrinsic::mips_extr_r_w:
2544 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_R_W, true, false);
2545 case Intrinsic::mips_extr_rs_w:
2546 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_RS_W, true, false);
2547 case Intrinsic::mips_extr_s_h:
2548 return LowerDSPIntr(Op, DAG, MipsISD::EXTR_S_H, true, false);
2549 case Intrinsic::mips_mthlip:
2550 return LowerDSPIntr(Op, DAG, MipsISD::MTHLIP, true, true);
2551 case Intrinsic::mips_mulsaq_s_w_ph:
2552 return LowerDSPIntr(Op, DAG, MipsISD::MULSAQ_S_W_PH, true, true);
2553 case Intrinsic::mips_maq_s_w_phl:
2554 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHL, true, true);
2555 case Intrinsic::mips_maq_s_w_phr:
2556 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_S_W_PHR, true, true);
2557 case Intrinsic::mips_maq_sa_w_phl:
2558 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHL, true, true);
2559 case Intrinsic::mips_maq_sa_w_phr:
2560 return LowerDSPIntr(Op, DAG, MipsISD::MAQ_SA_W_PHR, true, true);
2561 case Intrinsic::mips_dpaq_s_w_ph:
2562 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_S_W_PH, true, true);
2563 case Intrinsic::mips_dpsq_s_w_ph:
2564 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_S_W_PH, true, true);
2565 case Intrinsic::mips_dpaq_sa_l_w:
2566 return LowerDSPIntr(Op, DAG, MipsISD::DPAQ_SA_L_W, true, true);
2567 case Intrinsic::mips_dpsq_sa_l_w:
2568 return LowerDSPIntr(Op, DAG, MipsISD::DPSQ_SA_L_W, true, true);
2569 case Intrinsic::mips_dpaqx_s_w_ph:
2570 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_S_W_PH, true, true);
2571 case Intrinsic::mips_dpaqx_sa_w_ph:
2572 return LowerDSPIntr(Op, DAG, MipsISD::DPAQX_SA_W_PH, true, true);
2573 case Intrinsic::mips_dpsqx_s_w_ph:
2574 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_S_W_PH, true, true);
2575 case Intrinsic::mips_dpsqx_sa_w_ph:
2576 return LowerDSPIntr(Op, DAG, MipsISD::DPSQX_SA_W_PH, true, true);
2580 SDValue MipsTargetLowering::LowerADD(SDValue Op, SelectionDAG &DAG) const {
2581 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2582 || cast<ConstantSDNode>
2583 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2584 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2588 // (add (frameaddr 0), (frame_to_args_offset))
2589 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2590 // (add FrameObject, 0)
2591 // where FrameObject is a fixed StackObject with offset 0 which points to
2592 // the old stack pointer.
2593 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2594 EVT ValTy = Op->getValueType(0);
2595 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2596 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2597 return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2598 DAG.getConstant(0, ValTy));
2601 //===----------------------------------------------------------------------===//
2602 // Calling Convention Implementation
2603 //===----------------------------------------------------------------------===//
2605 //===----------------------------------------------------------------------===//
2606 // TODO: Implement a generic logic using tblgen that can support this.
2607 // Mips O32 ABI rules:
2609 // i32 - Passed in A0, A1, A2, A3 and stack
2610 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2611 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2612 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2613 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2614 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2617 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2618 //===----------------------------------------------------------------------===//
2620 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2621 MVT LocVT, CCValAssign::LocInfo LocInfo,
2622 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2624 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2626 static const uint16_t IntRegs[] = {
2627 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2629 static const uint16_t F32Regs[] = {
2630 Mips::F12, Mips::F14
2632 static const uint16_t F64Regs[] = {
2636 // Do not process byval args here.
2637 if (ArgFlags.isByVal())
2640 // Promote i8 and i16
2641 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2643 if (ArgFlags.isSExt())
2644 LocInfo = CCValAssign::SExt;
2645 else if (ArgFlags.isZExt())
2646 LocInfo = CCValAssign::ZExt;
2648 LocInfo = CCValAssign::AExt;
2653 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2654 // is true: function is vararg, argument is 3rd or higher, there is previous
2655 // argument which is not f32 or f64.
2656 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2657 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2658 unsigned OrigAlign = ArgFlags.getOrigAlign();
2659 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2661 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2662 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2663 // If this is the first part of an i64 arg,
2664 // the allocated register must be either A0 or A2.
2665 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2666 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2668 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2669 // Allocate int register and shadow next int register. If first
2670 // available register is Mips::A1 or Mips::A3, shadow it too.
2671 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2672 if (Reg == Mips::A1 || Reg == Mips::A3)
2673 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2674 State.AllocateReg(IntRegs, IntRegsSize);
2676 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2677 // we are guaranteed to find an available float register
2678 if (ValVT == MVT::f32) {
2679 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2680 // Shadow int register
2681 State.AllocateReg(IntRegs, IntRegsSize);
2683 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2684 // Shadow int registers
2685 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2686 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2687 State.AllocateReg(IntRegs, IntRegsSize);
2688 State.AllocateReg(IntRegs, IntRegsSize);
2691 llvm_unreachable("Cannot handle this ValVT.");
2694 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2696 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2698 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2703 #include "MipsGenCallingConv.inc"
2705 //===----------------------------------------------------------------------===//
2706 // Call Calling Convention Implementation
2707 //===----------------------------------------------------------------------===//
2709 static const unsigned O32IntRegsSize = 4;
2711 // Return next O32 integer argument register.
2712 static unsigned getNextIntArgReg(unsigned Reg) {
2713 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2714 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2717 /// IsEligibleForTailCallOptimization - Check whether the call is eligible
2718 /// for tail call optimization.
2719 bool MipsTargetLowering::
2720 IsEligibleForTailCallOptimization(const MipsCC &MipsCCInfo,
2721 unsigned NextStackOffset,
2722 const MipsFunctionInfo& FI) const {
2723 if (!EnableMipsTailCalls)
2726 // No tail call optimization for mips16.
2727 if (Subtarget->inMips16Mode())
2730 // Return false if either the callee or caller has a byval argument.
2731 if (MipsCCInfo.hasByValArg() || FI.hasByvalArg())
2734 // Return true if the callee's argument area is no larger than the
2736 return NextStackOffset <= FI.getIncomingArgSize();
2740 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2741 SDValue Chain, SDValue Arg, DebugLoc DL,
2742 bool IsTailCall, SelectionDAG &DAG) const {
2744 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2745 DAG.getIntPtrConstant(Offset));
2746 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2750 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2751 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2752 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2753 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2754 /*isVolatile=*/ true, false, 0);
2757 /// LowerCall - functions arguments are copied from virtual regs to
2758 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2760 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2761 SmallVectorImpl<SDValue> &InVals) const {
2762 SelectionDAG &DAG = CLI.DAG;
2763 DebugLoc &dl = CLI.DL;
2764 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2765 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2766 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2767 SDValue Chain = CLI.Chain;
2768 SDValue Callee = CLI.Callee;
2769 bool &isTailCall = CLI.IsTailCall;
2770 CallingConv::ID CallConv = CLI.CallConv;
2771 bool isVarArg = CLI.IsVarArg;
2773 MachineFunction &MF = DAG.getMachineFunction();
2774 MachineFrameInfo *MFI = MF.getFrameInfo();
2775 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2776 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2778 // Analyze operands of the call, assigning locations to each operand.
2779 SmallVector<CCValAssign, 16> ArgLocs;
2780 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2781 getTargetMachine(), ArgLocs, *DAG.getContext());
2782 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
2784 MipsCCInfo.analyzeCallOperands(Outs);
2786 // Get a count of how many bytes are to be pushed on the stack.
2787 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2789 // Check if it's really possible to do a tail call.
2792 IsEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2793 *MF.getInfo<MipsFunctionInfo>());
2798 // Chain is the output chain of the last Load/Store or CopyToReg node.
2799 // ByValChain is the output chain of the last Memcpy node created for copying
2800 // byval arguments to the stack.
2801 unsigned StackAlignment = TFL->getStackAlignment();
2802 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2803 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2806 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
2808 SDValue StackPtr = DAG.getCopyFromReg(Chain, dl,
2809 IsN64 ? Mips::SP_64 : Mips::SP,
2812 // With EABI is it possible to have 16 args on registers.
2813 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2814 SmallVector<SDValue, 8> MemOpChains;
2815 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2817 // Walk the register/memloc assignments, inserting copies/loads.
2818 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2819 SDValue Arg = OutVals[i];
2820 CCValAssign &VA = ArgLocs[i];
2821 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2822 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2825 if (Flags.isByVal()) {
2826 assert(Flags.getByValSize() &&
2827 "ByVal args of size 0 should have been ignored by front-end.");
2828 assert(ByValArg != MipsCCInfo.byval_end());
2829 assert(!isTailCall &&
2830 "Do not tail-call optimize if there is a byval argument.");
2831 passByValArg(Chain, dl, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2832 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2837 // Promote the value if needed.
2838 switch (VA.getLocInfo()) {
2839 default: llvm_unreachable("Unknown loc info!");
2840 case CCValAssign::Full:
2841 if (VA.isRegLoc()) {
2842 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2843 (ValVT == MVT::f64 && LocVT == MVT::i64))
2844 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2845 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2846 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2847 Arg, DAG.getConstant(0, MVT::i32));
2848 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2849 Arg, DAG.getConstant(1, MVT::i32));
2850 if (!Subtarget->isLittle())
2852 unsigned LocRegLo = VA.getLocReg();
2853 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2854 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2855 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2860 case CCValAssign::SExt:
2861 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2863 case CCValAssign::ZExt:
2864 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2866 case CCValAssign::AExt:
2867 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2871 // Arguments that can be passed on register must be kept at
2872 // RegsToPass vector
2873 if (VA.isRegLoc()) {
2874 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2878 // Register can't get to this point...
2879 assert(VA.isMemLoc());
2881 // emit ISD::STORE whichs stores the
2882 // parameter value to a stack Location
2883 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2884 Chain, Arg, dl, isTailCall, DAG));
2887 // Transform all store nodes into one single node because all store
2888 // nodes are independent of each other.
2889 if (!MemOpChains.empty())
2890 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2891 &MemOpChains[0], MemOpChains.size());
2893 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2894 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2895 // node so that legalize doesn't hack it.
2896 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2897 bool GlobalOrExternal = false, InternalLinkage = false;
2900 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2902 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2904 if (InternalLinkage)
2905 Callee = getAddrLocal(Callee, DAG, HasMips64);
2907 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2908 MipsII::MO_CALL_LO16);
2910 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2912 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2913 MipsII::MO_NO_FLAG);
2914 GlobalOrExternal = true;
2916 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2917 if (!IsN64 && !IsPIC) // !N64 && static
2918 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2919 MipsII::MO_NO_FLAG);
2921 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2922 MipsII::MO_CALL_LO16);
2924 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_DISP);
2926 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2928 GlobalOrExternal = true;
2931 SDValue JumpTarget = Callee;
2933 // T9 should contain the address of the callee function if
2934 // -reloction-model=pic or it is an indirect call.
2935 if (IsPICCall || !GlobalOrExternal) {
2936 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2937 RegsToPass.push_front(std::make_pair(T9Reg, Callee));
2939 if (!Subtarget->inMips16Mode())
2940 JumpTarget = SDValue();
2943 // Insert node "GP copy globalreg" before call to function.
2945 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2946 // in PIC mode) allow symbols to be resolved via lazy binding.
2947 // The lazy binding stub requires GP to point to the GOT.
2948 if (IsPICCall && !InternalLinkage) {
2949 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2950 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2951 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
2954 // Build a sequence of copy-to-reg nodes chained together with token
2955 // chain and flag operands which copy the outgoing args into registers.
2956 // The InFlag in necessary since all emitted instructions must be
2960 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2961 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2962 RegsToPass[i].second, InFlag);
2963 InFlag = Chain.getValue(1);
2966 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2967 // = Chain, Callee, Reg#1, Reg#2, ...
2969 // Returns a chain & a flag for retval copy to use.
2970 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2971 SmallVector<SDValue, 8> Ops(1, Chain);
2973 if (JumpTarget.getNode())
2974 Ops.push_back(JumpTarget);
2976 // Add argument registers to the end of the list so that they are
2977 // known live into the call.
2978 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2979 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2980 RegsToPass[i].second.getValueType()));
2982 // Add a register mask operand representing the call-preserved registers.
2983 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2984 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2985 assert(Mask && "Missing call preserved mask for calling convention");
2986 Ops.push_back(DAG.getRegisterMask(Mask));
2988 if (InFlag.getNode())
2989 Ops.push_back(InFlag);
2992 return DAG.getNode(MipsISD::TailCall, dl, MVT::Other, &Ops[0], Ops.size());
2994 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2995 InFlag = Chain.getValue(1);
2997 // Create the CALLSEQ_END node.
2998 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2999 DAG.getIntPtrConstant(0, true), InFlag);
3000 InFlag = Chain.getValue(1);
3002 // Handle result values, copying them out of physregs into vregs that we
3004 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
3005 Ins, dl, DAG, InVals);
3008 /// LowerCallResult - Lower the result values of a call into the
3009 /// appropriate copies out of appropriate physical registers.
3011 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
3012 CallingConv::ID CallConv, bool isVarArg,
3013 const SmallVectorImpl<ISD::InputArg> &Ins,
3014 DebugLoc dl, SelectionDAG &DAG,
3015 SmallVectorImpl<SDValue> &InVals) const {
3016 // Assign locations to each value returned by this call.
3017 SmallVector<CCValAssign, 16> RVLocs;
3018 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3019 getTargetMachine(), RVLocs, *DAG.getContext());
3021 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
3023 // Copy all of the result registers out of their specified physreg.
3024 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3025 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
3026 RVLocs[i].getValVT(), InFlag).getValue(1);
3027 InFlag = Chain.getValue(2);
3028 InVals.push_back(Chain.getValue(0));
3034 //===----------------------------------------------------------------------===//
3035 // Formal Arguments Calling Convention Implementation
3036 //===----------------------------------------------------------------------===//
3037 /// LowerFormalArguments - transform physical registers into virtual registers
3038 /// and generate load operations for arguments places on the stack.
3040 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3041 CallingConv::ID CallConv,
3043 const SmallVectorImpl<ISD::InputArg> &Ins,
3044 DebugLoc dl, SelectionDAG &DAG,
3045 SmallVectorImpl<SDValue> &InVals)
3047 MachineFunction &MF = DAG.getMachineFunction();
3048 MachineFrameInfo *MFI = MF.getFrameInfo();
3049 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3051 MipsFI->setVarArgsFrameIndex(0);
3053 // Used with vargs to acumulate store chains.
3054 std::vector<SDValue> OutChains;
3056 // Assign locations to all of the incoming arguments.
3057 SmallVector<CCValAssign, 16> ArgLocs;
3058 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3059 getTargetMachine(), ArgLocs, *DAG.getContext());
3060 MipsCC MipsCCInfo(CallConv, isVarArg, IsO32, CCInfo);
3062 MipsCCInfo.analyzeFormalArguments(Ins);
3063 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
3064 MipsCCInfo.hasByValArg());
3066 Function::const_arg_iterator FuncArg =
3067 DAG.getMachineFunction().getFunction()->arg_begin();
3068 unsigned CurArgIdx = 0;
3069 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
3071 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
3072 CCValAssign &VA = ArgLocs[i];
3073 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
3074 CurArgIdx = Ins[i].OrigArgIndex;
3075 EVT ValVT = VA.getValVT();
3076 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3077 bool IsRegLoc = VA.isRegLoc();
3079 if (Flags.isByVal()) {
3080 assert(Flags.getByValSize() &&
3081 "ByVal args of size 0 should have been ignored by front-end.");
3082 assert(ByValArg != MipsCCInfo.byval_end());
3083 copyByValRegs(Chain, dl, OutChains, DAG, Flags, InVals, &*FuncArg,
3084 MipsCCInfo, *ByValArg);
3089 // Arguments stored on registers
3091 EVT RegVT = VA.getLocVT();
3092 unsigned ArgReg = VA.getLocReg();
3093 const TargetRegisterClass *RC;
3095 if (RegVT == MVT::i32)
3096 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
3097 &Mips::CPURegsRegClass;
3098 else if (RegVT == MVT::i64)
3099 RC = &Mips::CPU64RegsRegClass;
3100 else if (RegVT == MVT::f32)
3101 RC = &Mips::FGR32RegClass;
3102 else if (RegVT == MVT::f64)
3103 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3105 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3107 // Transform the arguments stored on
3108 // physical registers into virtual ones
3109 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3110 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3112 // If this is an 8 or 16-bit value, it has been passed promoted
3113 // to 32 bits. Insert an assert[sz]ext to capture this, then
3114 // truncate to the right size.
3115 if (VA.getLocInfo() != CCValAssign::Full) {
3116 unsigned Opcode = 0;
3117 if (VA.getLocInfo() == CCValAssign::SExt)
3118 Opcode = ISD::AssertSext;
3119 else if (VA.getLocInfo() == CCValAssign::ZExt)
3120 Opcode = ISD::AssertZext;
3122 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3123 DAG.getValueType(ValVT));
3124 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3127 // Handle floating point arguments passed in integer registers.
3128 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3129 (RegVT == MVT::i64 && ValVT == MVT::f64))
3130 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3131 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3132 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3133 getNextIntArgReg(ArgReg), RC);
3134 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3135 if (!Subtarget->isLittle())
3136 std::swap(ArgValue, ArgValue2);
3137 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3138 ArgValue, ArgValue2);
3141 InVals.push_back(ArgValue);
3142 } else { // VA.isRegLoc()
3145 assert(VA.isMemLoc());
3147 // The stack pointer offset is relative to the caller stack frame.
3148 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3149 VA.getLocMemOffset(), true);
3151 // Create load nodes to retrieve arguments from the stack
3152 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
3153 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3154 MachinePointerInfo::getFixedStack(FI),
3155 false, false, false, 0));
3159 // The mips ABIs for returning structs by value requires that we copy
3160 // the sret argument into $v0 for the return. Save the argument into
3161 // a virtual register so that we can access it from the return points.
3162 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3163 unsigned Reg = MipsFI->getSRetReturnReg();
3165 Reg = MF.getRegInfo().
3166 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
3167 MipsFI->setSRetReturnReg(Reg);
3169 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3170 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3174 writeVarArgRegs(OutChains, MipsCCInfo, Chain, dl, DAG);
3176 // All stores are grouped in one node to allow the matching between
3177 // the size of Ins and InVals. This only happens when on varg functions
3178 if (!OutChains.empty()) {
3179 OutChains.push_back(Chain);
3180 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3181 &OutChains[0], OutChains.size());
3187 //===----------------------------------------------------------------------===//
3188 // Return Value Calling Convention Implementation
3189 //===----------------------------------------------------------------------===//
3192 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
3193 MachineFunction &MF, bool isVarArg,
3194 const SmallVectorImpl<ISD::OutputArg> &Outs,
3195 LLVMContext &Context) const {
3196 SmallVector<CCValAssign, 16> RVLocs;
3197 CCState CCInfo(CallConv, isVarArg, MF, getTargetMachine(),
3199 return CCInfo.CheckReturn(Outs, RetCC_Mips);
3203 MipsTargetLowering::LowerReturn(SDValue Chain,
3204 CallingConv::ID CallConv, bool isVarArg,
3205 const SmallVectorImpl<ISD::OutputArg> &Outs,
3206 const SmallVectorImpl<SDValue> &OutVals,
3207 DebugLoc dl, SelectionDAG &DAG) const {
3209 // CCValAssign - represent the assignment of
3210 // the return value to a location
3211 SmallVector<CCValAssign, 16> RVLocs;
3213 // CCState - Info about the registers and stack slot.
3214 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3215 getTargetMachine(), RVLocs, *DAG.getContext());
3217 // Analize return values.
3218 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3220 // If this is the first return lowered for this function, add
3221 // the regs to the liveout set for the function.
3222 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3223 for (unsigned i = 0; i != RVLocs.size(); ++i)
3224 if (RVLocs[i].isRegLoc())
3225 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3230 // Copy the result values into the output registers.
3231 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3232 CCValAssign &VA = RVLocs[i];
3233 assert(VA.isRegLoc() && "Can only return in registers!");
3235 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3237 // guarantee that all emitted copies are
3238 // stuck together, avoiding something bad
3239 Flag = Chain.getValue(1);
3242 // The mips ABIs for returning structs by value requires that we copy
3243 // the sret argument into $v0 for the return. We saved the argument into
3244 // a virtual register in the entry block, so now we copy the value out
3246 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3247 MachineFunction &MF = DAG.getMachineFunction();
3248 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3249 unsigned Reg = MipsFI->getSRetReturnReg();
3252 llvm_unreachable("sret virtual register not created in the entry block");
3253 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3254 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
3256 Chain = DAG.getCopyToReg(Chain, dl, V0, Val, Flag);
3257 Flag = Chain.getValue(1);
3258 MF.getRegInfo().addLiveOut(V0);
3261 // Return on Mips is always a "jr $ra"
3263 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain, Flag);
3266 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain);
3269 //===----------------------------------------------------------------------===//
3270 // Mips Inline Assembly Support
3271 //===----------------------------------------------------------------------===//
3273 /// getConstraintType - Given a constraint letter, return the type of
3274 /// constraint it is for this target.
3275 MipsTargetLowering::ConstraintType MipsTargetLowering::
3276 getConstraintType(const std::string &Constraint) const
3278 // Mips specific constrainy
3279 // GCC config/mips/constraints.md
3281 // 'd' : An address register. Equivalent to r
3282 // unless generating MIPS16 code.
3283 // 'y' : Equivalent to r; retained for
3284 // backwards compatibility.
3285 // 'c' : A register suitable for use in an indirect
3286 // jump. This will always be $25 for -mabicalls.
3287 // 'l' : The lo register. 1 word storage.
3288 // 'x' : The hilo register pair. Double word storage.
3289 if (Constraint.size() == 1) {
3290 switch (Constraint[0]) {
3298 return C_RegisterClass;
3301 return TargetLowering::getConstraintType(Constraint);
3304 /// Examine constraint type and operand type and determine a weight value.
3305 /// This object must already have been set up with the operand type
3306 /// and the current alternative constraint selected.
3307 TargetLowering::ConstraintWeight
3308 MipsTargetLowering::getSingleConstraintMatchWeight(
3309 AsmOperandInfo &info, const char *constraint) const {
3310 ConstraintWeight weight = CW_Invalid;
3311 Value *CallOperandVal = info.CallOperandVal;
3312 // If we don't have a value, we can't do a match,
3313 // but allow it at the lowest weight.
3314 if (CallOperandVal == NULL)
3316 Type *type = CallOperandVal->getType();
3317 // Look at the constraint type.
3318 switch (*constraint) {
3320 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3324 if (type->isIntegerTy())
3325 weight = CW_Register;
3328 if (type->isFloatTy())
3329 weight = CW_Register;
3331 case 'c': // $25 for indirect jumps
3332 case 'l': // lo register
3333 case 'x': // hilo register pair
3334 if (type->isIntegerTy())
3335 weight = CW_SpecificReg;
3337 case 'I': // signed 16 bit immediate
3338 case 'J': // integer zero
3339 case 'K': // unsigned 16 bit immediate
3340 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3341 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3342 case 'O': // signed 15 bit immediate (+- 16383)
3343 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3344 if (isa<ConstantInt>(CallOperandVal))
3345 weight = CW_Constant;
3351 /// Given a register class constraint, like 'r', if this corresponds directly
3352 /// to an LLVM register class, return a register of 0 and the register class
3354 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3355 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3357 if (Constraint.size() == 1) {
3358 switch (Constraint[0]) {
3359 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3360 case 'y': // Same as 'r'. Exists for compatibility.
3362 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3363 if (Subtarget->inMips16Mode())
3364 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3365 return std::make_pair(0U, &Mips::CPURegsRegClass);
3367 if (VT == MVT::i64 && !HasMips64)
3368 return std::make_pair(0U, &Mips::CPURegsRegClass);
3369 if (VT == MVT::i64 && HasMips64)
3370 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3371 // This will generate an error message
3372 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3375 return std::make_pair(0U, &Mips::FGR32RegClass);
3376 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3377 if (Subtarget->isFP64bit())
3378 return std::make_pair(0U, &Mips::FGR64RegClass);
3379 return std::make_pair(0U, &Mips::AFGR64RegClass);
3382 case 'c': // register suitable for indirect jump
3384 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3385 assert(VT == MVT::i64 && "Unexpected type.");
3386 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3387 case 'l': // register suitable for indirect jump
3389 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3390 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3391 case 'x': // register suitable for indirect jump
3392 // Fixme: Not triggering the use of both hi and low
3393 // This will generate an error message
3394 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3397 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3400 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3401 /// vector. If it is invalid, don't add anything to Ops.
3402 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3403 std::string &Constraint,
3404 std::vector<SDValue>&Ops,
3405 SelectionDAG &DAG) const {
3406 SDValue Result(0, 0);
3408 // Only support length 1 constraints for now.
3409 if (Constraint.length() > 1) return;
3411 char ConstraintLetter = Constraint[0];
3412 switch (ConstraintLetter) {
3413 default: break; // This will fall through to the generic implementation
3414 case 'I': // Signed 16 bit constant
3415 // If this fails, the parent routine will give an error
3416 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3417 EVT Type = Op.getValueType();
3418 int64_t Val = C->getSExtValue();
3419 if (isInt<16>(Val)) {
3420 Result = DAG.getTargetConstant(Val, Type);
3425 case 'J': // integer zero
3426 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3427 EVT Type = Op.getValueType();
3428 int64_t Val = C->getZExtValue();
3430 Result = DAG.getTargetConstant(0, Type);
3435 case 'K': // unsigned 16 bit immediate
3436 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3437 EVT Type = Op.getValueType();
3438 uint64_t Val = (uint64_t)C->getZExtValue();
3439 if (isUInt<16>(Val)) {
3440 Result = DAG.getTargetConstant(Val, Type);
3445 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3446 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3447 EVT Type = Op.getValueType();
3448 int64_t Val = C->getSExtValue();
3449 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3450 Result = DAG.getTargetConstant(Val, Type);
3455 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3456 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3457 EVT Type = Op.getValueType();
3458 int64_t Val = C->getSExtValue();
3459 if ((Val >= -65535) && (Val <= -1)) {
3460 Result = DAG.getTargetConstant(Val, Type);
3465 case 'O': // signed 15 bit immediate
3466 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3467 EVT Type = Op.getValueType();
3468 int64_t Val = C->getSExtValue();
3469 if ((isInt<15>(Val))) {
3470 Result = DAG.getTargetConstant(Val, Type);
3475 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3476 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3477 EVT Type = Op.getValueType();
3478 int64_t Val = C->getSExtValue();
3479 if ((Val <= 65535) && (Val >= 1)) {
3480 Result = DAG.getTargetConstant(Val, Type);
3487 if (Result.getNode()) {
3488 Ops.push_back(Result);
3492 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3496 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3497 // No global is ever allowed as a base.
3502 case 0: // "r+i" or just "i", depending on HasBaseReg.
3505 if (!AM.HasBaseReg) // allow "r+i".
3507 return false; // disallow "r+r" or "r+r+i".
3516 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3517 // The Mips target isn't yet aware of offsets.
3521 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3523 bool IsMemset, bool ZeroMemset,
3525 MachineFunction &MF) const {
3526 if (Subtarget->hasMips64())
3532 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3533 if (VT != MVT::f32 && VT != MVT::f64)
3535 if (Imm.isNegZero())
3537 return Imm.isZero();
3540 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3542 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3544 return TargetLowering::getJumpTableEncoding();
3547 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CallConv, bool IsVarArg,
3548 bool IsO32, CCState &Info) : CCInfo(Info) {
3549 UseRegsForByval = true;
3553 NumIntArgRegs = array_lengthof(O32IntRegs);
3554 ReservedArgArea = 16;
3555 IntArgRegs = ShadowRegs = O32IntRegs;
3556 FixedFn = VarFn = CC_MipsO32;
3559 NumIntArgRegs = array_lengthof(Mips64IntRegs);
3560 ReservedArgArea = 0;
3561 IntArgRegs = Mips64IntRegs;
3562 ShadowRegs = Mips64DPRegs;
3564 VarFn = CC_MipsN_VarArg;
3567 if (CallConv == CallingConv::Fast) {
3569 UseRegsForByval = false;
3570 ReservedArgArea = 0;
3571 FixedFn = VarFn = CC_Mips_FastCC;
3574 // Pre-allocate reserved argument area.
3575 CCInfo.AllocateStack(ReservedArgArea, 1);
3578 void MipsTargetLowering::MipsCC::
3579 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args) {
3580 unsigned NumOpnds = Args.size();
3582 for (unsigned I = 0; I != NumOpnds; ++I) {
3583 MVT ArgVT = Args[I].VT;
3584 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3587 if (ArgFlags.isByVal()) {
3588 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3592 if (Args[I].IsFixed)
3593 R = FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3595 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3599 dbgs() << "Call operand #" << I << " has unhandled type "
3600 << EVT(ArgVT).getEVTString();
3602 llvm_unreachable(0);
3607 void MipsTargetLowering::MipsCC::
3608 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args) {
3609 unsigned NumArgs = Args.size();
3611 for (unsigned I = 0; I != NumArgs; ++I) {
3612 MVT ArgVT = Args[I].VT;
3613 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3615 if (ArgFlags.isByVal()) {
3616 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3620 if (!FixedFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo))
3624 dbgs() << "Formal Arg #" << I << " has unhandled type "
3625 << EVT(ArgVT).getEVTString();
3627 llvm_unreachable(0);
3632 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3634 CCValAssign::LocInfo LocInfo,
3635 ISD::ArgFlagsTy ArgFlags) {
3636 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3638 struct ByValArgInfo ByVal;
3639 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3640 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3643 if (UseRegsForByval)
3644 allocateRegs(ByVal, ByValSize, Align);
3646 // Allocate space on caller's stack.
3647 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3649 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3651 ByValArgs.push_back(ByVal);
3654 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3657 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3658 "Byval argument's size and alignment should be a multiple of"
3661 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3663 // If Align > RegSize, the first arg register must be even.
3664 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3665 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3669 // Mark the registers allocated.
3670 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3671 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3672 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3675 void MipsTargetLowering::
3676 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
3677 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3678 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3679 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3680 MachineFunction &MF = DAG.getMachineFunction();
3681 MachineFrameInfo *MFI = MF.getFrameInfo();
3682 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3683 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3687 FrameObjOffset = (int)CC.reservedArgArea() -
3688 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3690 FrameObjOffset = ByVal.Address;
3692 // Create frame object.
3693 EVT PtrTy = getPointerTy();
3694 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3695 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3696 InVals.push_back(FIN);
3701 // Copy arg registers.
3702 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3703 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3705 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3706 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3707 unsigned VReg = AddLiveIn(MF, ArgReg, RC);
3708 unsigned Offset = I * CC.regSize();
3709 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3710 DAG.getConstant(Offset, PtrTy));
3711 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3712 StorePtr, MachinePointerInfo(FuncArg, Offset),
3714 OutChains.push_back(Store);
3718 // Copy byVal arg to registers and stack.
3719 void MipsTargetLowering::
3720 passByValArg(SDValue Chain, DebugLoc DL,
3721 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3722 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3723 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3724 const MipsCC &CC, const ByValArgInfo &ByVal,
3725 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3726 unsigned ByValSize = Flags.getByValSize();
3727 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3728 unsigned RegSize = CC.regSize();
3729 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3730 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3732 if (ByVal.NumRegs) {
3733 const uint16_t *ArgRegs = CC.intArgRegs();
3734 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3737 // Copy words to registers.
3738 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3739 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3740 DAG.getConstant(Offset, PtrTy));
3741 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3742 MachinePointerInfo(), false, false, false,
3744 MemOpChains.push_back(LoadVal.getValue(1));
3745 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3746 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3749 // Return if the struct has been fully copied.
3750 if (ByValSize == Offset)
3753 // Copy the remainder of the byval argument with sub-word loads and shifts.
3754 if (LeftoverBytes) {
3755 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3756 "Size of the remainder should be smaller than RegSize.");
3759 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3760 Offset < ByValSize; LoadSize /= 2) {
3761 unsigned RemSize = ByValSize - Offset;
3763 if (RemSize < LoadSize)
3767 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3768 DAG.getConstant(Offset, PtrTy));
3770 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3771 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3772 false, false, Alignment);
3773 MemOpChains.push_back(LoadVal.getValue(1));
3775 // Shift the loaded value.
3779 Shamt = TotalSizeLoaded;
3781 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3783 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3784 DAG.getConstant(Shamt, MVT::i32));
3787 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3792 TotalSizeLoaded += LoadSize;
3793 Alignment = std::min(Alignment, LoadSize);
3796 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3797 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3802 // Copy remainder of byval arg to it with memcpy.
3803 unsigned MemCpySize = ByValSize - Offset;
3804 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3805 DAG.getConstant(Offset, PtrTy));
3806 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3807 DAG.getIntPtrConstant(ByVal.Address));
3808 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3809 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3810 /*isVolatile=*/false, /*AlwaysInline=*/false,
3811 MachinePointerInfo(0), MachinePointerInfo(0));
3812 MemOpChains.push_back(Chain);
3816 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3817 const MipsCC &CC, SDValue Chain,
3818 DebugLoc DL, SelectionDAG &DAG) const {
3819 unsigned NumRegs = CC.numIntArgRegs();
3820 const uint16_t *ArgRegs = CC.intArgRegs();
3821 const CCState &CCInfo = CC.getCCInfo();
3822 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3823 unsigned RegSize = CC.regSize();
3824 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3825 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3826 MachineFunction &MF = DAG.getMachineFunction();
3827 MachineFrameInfo *MFI = MF.getFrameInfo();
3828 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3830 // Offset of the first variable argument from stack pointer.
3834 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3837 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3839 // Record the frame index of the first variable argument
3840 // which is a value necessary to VASTART.
3841 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3842 MipsFI->setVarArgsFrameIndex(FI);
3844 // Copy the integer registers that have not been used for argument passing
3845 // to the argument register save area. For O32, the save area is allocated
3846 // in the caller's stack frame, while for N32/64, it is allocated in the
3847 // callee's stack frame.
3848 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3849 unsigned Reg = AddLiveIn(MF, ArgRegs[I], RC);
3850 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3851 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3852 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3853 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3854 MachinePointerInfo(), false, false, 0);
3855 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3856 OutChains.push_back(Store);