1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "mips-lower"
15 #include "MipsISelLowering.h"
16 #include "InstPrinter/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsBaseInfo.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
41 STATISTIC(NumTailCalls, "Number of tail calls");
44 LargeGOT("mxgot", cl::Hidden,
45 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
48 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
49 cl::desc("MIPS: Don't trap on integer division by zero."),
52 static const uint16_t O32IntRegs[4] = {
53 Mips::A0, Mips::A1, Mips::A2, Mips::A3
56 static const uint16_t Mips64IntRegs[8] = {
57 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
58 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
61 static const uint16_t Mips64DPRegs[8] = {
62 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
63 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
66 // If I is a shifted mask, set the size (Size) and the first bit of the
67 // mask (Pos), and return true.
68 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
69 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
70 if (!isShiftedMask_64(I))
73 Size = CountPopulation_64(I);
74 Pos = countTrailingZeros(I);
78 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
79 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
80 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
83 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
84 EVT Ty = Op.getValueType();
86 if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
87 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(Op), Ty, 0,
89 if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
90 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
91 if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
92 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
93 if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
94 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
95 if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
96 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
97 N->getOffset(), Flag);
99 llvm_unreachable("Unexpected node type.");
103 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
105 EVT Ty = Op.getValueType();
106 SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
107 SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
108 return DAG.getNode(ISD::ADD, DL, Ty,
109 DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
110 DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
113 SDValue MipsTargetLowering::getAddrLocal(SDValue Op, SelectionDAG &DAG,
114 bool HasMips64) const {
116 EVT Ty = Op.getValueType();
117 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
118 SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
119 getTargetNode(Op, DAG, GOTFlag));
120 SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
121 MachinePointerInfo::getGOT(), false, false, false,
123 unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
124 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
125 return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
128 SDValue MipsTargetLowering::getAddrGlobal(SDValue Op, SelectionDAG &DAG,
129 unsigned Flag) const {
131 EVT Ty = Op.getValueType();
132 SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
133 getTargetNode(Op, DAG, Flag));
134 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
135 MachinePointerInfo::getGOT(), false, false, false, 0);
138 SDValue MipsTargetLowering::getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
140 unsigned LoFlag) const {
142 EVT Ty = Op.getValueType();
143 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
144 Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, getGlobalReg(DAG, Ty));
145 SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
146 getTargetNode(Op, DAG, LoFlag));
147 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
148 MachinePointerInfo::getGOT(), false, false, false, 0);
151 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
153 case MipsISD::JmpLink: return "MipsISD::JmpLink";
154 case MipsISD::TailCall: return "MipsISD::TailCall";
155 case MipsISD::Hi: return "MipsISD::Hi";
156 case MipsISD::Lo: return "MipsISD::Lo";
157 case MipsISD::GPRel: return "MipsISD::GPRel";
158 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
159 case MipsISD::Ret: return "MipsISD::Ret";
160 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
161 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
162 case MipsISD::FPCmp: return "MipsISD::FPCmp";
163 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
164 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
165 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
166 case MipsISD::ExtractLOHI: return "MipsISD::ExtractLOHI";
167 case MipsISD::InsertLOHI: return "MipsISD::InsertLOHI";
168 case MipsISD::Mult: return "MipsISD::Mult";
169 case MipsISD::Multu: return "MipsISD::Multu";
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::DivRem16: return "MipsISD::DivRem16";
177 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
178 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
179 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
180 case MipsISD::Wrapper: return "MipsISD::Wrapper";
181 case MipsISD::Sync: return "MipsISD::Sync";
182 case MipsISD::Ext: return "MipsISD::Ext";
183 case MipsISD::Ins: return "MipsISD::Ins";
184 case MipsISD::LWL: return "MipsISD::LWL";
185 case MipsISD::LWR: return "MipsISD::LWR";
186 case MipsISD::SWL: return "MipsISD::SWL";
187 case MipsISD::SWR: return "MipsISD::SWR";
188 case MipsISD::LDL: return "MipsISD::LDL";
189 case MipsISD::LDR: return "MipsISD::LDR";
190 case MipsISD::SDL: return "MipsISD::SDL";
191 case MipsISD::SDR: return "MipsISD::SDR";
192 case MipsISD::EXTP: return "MipsISD::EXTP";
193 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
194 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
195 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
196 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
197 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
198 case MipsISD::SHILO: return "MipsISD::SHILO";
199 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
200 case MipsISD::MULT: return "MipsISD::MULT";
201 case MipsISD::MULTU: return "MipsISD::MULTU";
202 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
203 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
204 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
205 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
206 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
207 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
208 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
209 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
210 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
211 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
212 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
213 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
214 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
215 case MipsISD::VCEQ: return "MipsISD::VCEQ";
216 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
217 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
218 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
219 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
220 case MipsISD::VSMAX: return "MipsISD::VSMAX";
221 case MipsISD::VSMIN: return "MipsISD::VSMIN";
222 case MipsISD::VUMAX: return "MipsISD::VUMAX";
223 case MipsISD::VUMIN: return "MipsISD::VUMIN";
224 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
225 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
226 case MipsISD::VNOR: return "MipsISD::VNOR";
227 case MipsISD::VSHF: return "MipsISD::VSHF";
228 default: return NULL;
233 MipsTargetLowering(MipsTargetMachine &TM)
234 : TargetLowering(TM, new MipsTargetObjectFile()),
235 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
236 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
237 IsO32(Subtarget->isABI_O32()) {
238 // Mips does not have i1 type, so use i32 for
239 // setcc operations results (slt, sgt, ...).
240 setBooleanContents(ZeroOrOneBooleanContent);
241 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
243 // Load extented operations for i1 types must be promoted
244 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
245 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
246 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
248 // MIPS doesn't have extending float->double load/store
249 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
250 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
252 // Used by legalize types to correctly generate the setcc result.
253 // Without this, every float setcc comes with a AND/OR with the result,
254 // we don't want this, since the fpcmp result goes to a flag register,
255 // which is used implicitly by brcond and select operations.
256 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
258 // Mips Custom Operations
259 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
260 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
261 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
262 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
263 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
264 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
265 setOperationAction(ISD::SELECT, MVT::f32, Custom);
266 setOperationAction(ISD::SELECT, MVT::f64, Custom);
267 setOperationAction(ISD::SELECT, MVT::i32, Custom);
268 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
269 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
270 setOperationAction(ISD::SETCC, MVT::f32, Custom);
271 setOperationAction(ISD::SETCC, MVT::f64, Custom);
272 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
273 setOperationAction(ISD::VASTART, MVT::Other, Custom);
274 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
275 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
276 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
278 if (!TM.Options.NoNaNsFPMath) {
279 setOperationAction(ISD::FABS, MVT::f32, Custom);
280 setOperationAction(ISD::FABS, MVT::f64, Custom);
284 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
285 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
286 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
287 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
288 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
289 setOperationAction(ISD::SELECT, MVT::i64, Custom);
290 setOperationAction(ISD::LOAD, MVT::i64, Custom);
291 setOperationAction(ISD::STORE, MVT::i64, Custom);
292 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
296 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
297 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
298 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
301 setOperationAction(ISD::ADD, MVT::i32, Custom);
303 setOperationAction(ISD::ADD, MVT::i64, Custom);
305 setOperationAction(ISD::SDIV, MVT::i32, Expand);
306 setOperationAction(ISD::SREM, MVT::i32, Expand);
307 setOperationAction(ISD::UDIV, MVT::i32, Expand);
308 setOperationAction(ISD::UREM, MVT::i32, Expand);
309 setOperationAction(ISD::SDIV, MVT::i64, Expand);
310 setOperationAction(ISD::SREM, MVT::i64, Expand);
311 setOperationAction(ISD::UDIV, MVT::i64, Expand);
312 setOperationAction(ISD::UREM, MVT::i64, Expand);
314 // Operations not directly supported by Mips.
315 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
316 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
317 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
318 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
319 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
320 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
321 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
322 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
323 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
324 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
325 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
326 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
327 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
328 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
329 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
330 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
331 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
332 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
333 setOperationAction(ISD::ROTL, MVT::i32, Expand);
334 setOperationAction(ISD::ROTL, MVT::i64, Expand);
335 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
336 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
338 if (!Subtarget->hasMips32r2())
339 setOperationAction(ISD::ROTR, MVT::i32, Expand);
341 if (!Subtarget->hasMips64r2())
342 setOperationAction(ISD::ROTR, MVT::i64, Expand);
344 setOperationAction(ISD::FSIN, MVT::f32, Expand);
345 setOperationAction(ISD::FSIN, MVT::f64, Expand);
346 setOperationAction(ISD::FCOS, MVT::f32, Expand);
347 setOperationAction(ISD::FCOS, MVT::f64, Expand);
348 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
349 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
350 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
351 setOperationAction(ISD::FPOW, MVT::f32, Expand);
352 setOperationAction(ISD::FPOW, MVT::f64, Expand);
353 setOperationAction(ISD::FLOG, MVT::f32, Expand);
354 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
355 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
356 setOperationAction(ISD::FEXP, MVT::f32, Expand);
357 setOperationAction(ISD::FMA, MVT::f32, Expand);
358 setOperationAction(ISD::FMA, MVT::f64, Expand);
359 setOperationAction(ISD::FREM, MVT::f32, Expand);
360 setOperationAction(ISD::FREM, MVT::f64, Expand);
362 if (!TM.Options.NoNaNsFPMath) {
363 setOperationAction(ISD::FNEG, MVT::f32, Expand);
364 setOperationAction(ISD::FNEG, MVT::f64, Expand);
367 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
369 setOperationAction(ISD::VAARG, MVT::Other, Expand);
370 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
371 setOperationAction(ISD::VAEND, MVT::Other, Expand);
373 // Use the default for now
374 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
375 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
377 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
378 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
379 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
380 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
382 setInsertFencesForAtomic(true);
384 if (!Subtarget->hasSEInReg()) {
385 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
386 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
389 if (!Subtarget->hasBitCount()) {
390 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
391 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
394 if (!Subtarget->hasSwap()) {
395 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
396 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
400 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
401 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
402 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
403 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
406 setOperationAction(ISD::TRAP, MVT::Other, Legal);
408 setTargetDAGCombine(ISD::SDIVREM);
409 setTargetDAGCombine(ISD::UDIVREM);
410 setTargetDAGCombine(ISD::SELECT);
411 setTargetDAGCombine(ISD::AND);
412 setTargetDAGCombine(ISD::OR);
413 setTargetDAGCombine(ISD::ADD);
415 setMinFunctionAlignment(HasMips64 ? 3 : 2);
417 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
419 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
420 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
422 MaxStoresPerMemcpy = 16;
425 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
426 if (TM.getSubtargetImpl()->inMips16Mode())
427 return llvm::createMips16TargetLowering(TM);
429 return llvm::createMipsSETargetLowering(TM);
432 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
435 return VT.changeVectorElementTypeToInteger();
438 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
439 TargetLowering::DAGCombinerInfo &DCI,
440 const MipsSubtarget *Subtarget) {
441 if (DCI.isBeforeLegalizeOps())
444 EVT Ty = N->getValueType(0);
445 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
446 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
447 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
451 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
452 N->getOperand(0), N->getOperand(1));
453 SDValue InChain = DAG.getEntryNode();
454 SDValue InGlue = DivRem;
457 if (N->hasAnyUseOfValue(0)) {
458 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
460 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
461 InChain = CopyFromLo.getValue(1);
462 InGlue = CopyFromLo.getValue(2);
466 if (N->hasAnyUseOfValue(1)) {
467 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
469 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
475 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
477 default: llvm_unreachable("Unknown fp condition code!");
479 case ISD::SETOEQ: return Mips::FCOND_OEQ;
480 case ISD::SETUNE: return Mips::FCOND_UNE;
482 case ISD::SETOLT: return Mips::FCOND_OLT;
484 case ISD::SETOGT: return Mips::FCOND_OGT;
486 case ISD::SETOLE: return Mips::FCOND_OLE;
488 case ISD::SETOGE: return Mips::FCOND_OGE;
489 case ISD::SETULT: return Mips::FCOND_ULT;
490 case ISD::SETULE: return Mips::FCOND_ULE;
491 case ISD::SETUGT: return Mips::FCOND_UGT;
492 case ISD::SETUGE: return Mips::FCOND_UGE;
493 case ISD::SETUO: return Mips::FCOND_UN;
494 case ISD::SETO: return Mips::FCOND_OR;
496 case ISD::SETONE: return Mips::FCOND_ONE;
497 case ISD::SETUEQ: return Mips::FCOND_UEQ;
502 /// This function returns true if the floating point conditional branches and
503 /// conditional moves which use condition code CC should be inverted.
504 static bool invertFPCondCodeUser(Mips::CondCode CC) {
505 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
508 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
509 "Illegal Condition Code");
514 // Creates and returns an FPCmp node from a setcc node.
515 // Returns Op if setcc is not a floating point comparison.
516 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
517 // must be a SETCC node
518 if (Op.getOpcode() != ISD::SETCC)
521 SDValue LHS = Op.getOperand(0);
523 if (!LHS.getValueType().isFloatingPoint())
526 SDValue RHS = Op.getOperand(1);
529 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
530 // node if necessary.
531 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
533 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
534 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
537 // Creates and returns a CMovFPT/F node.
538 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
539 SDValue False, SDLoc DL) {
540 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
541 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
542 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
544 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
545 True.getValueType(), True, FCC0, False, Cond);
548 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
549 TargetLowering::DAGCombinerInfo &DCI,
550 const MipsSubtarget *Subtarget) {
551 if (DCI.isBeforeLegalizeOps())
554 SDValue SetCC = N->getOperand(0);
556 if ((SetCC.getOpcode() != ISD::SETCC) ||
557 !SetCC.getOperand(0).getValueType().isInteger())
560 SDValue False = N->getOperand(2);
561 EVT FalseTy = False.getValueType();
563 if (!FalseTy.isInteger())
566 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
568 if (!CN || CN->getZExtValue())
572 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
573 SDValue True = N->getOperand(1);
575 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
576 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
578 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
581 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
582 TargetLowering::DAGCombinerInfo &DCI,
583 const MipsSubtarget *Subtarget) {
584 // Pattern match EXT.
585 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
586 // => ext $dst, $src, size, pos
587 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
590 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
591 unsigned ShiftRightOpc = ShiftRight.getOpcode();
593 // Op's first operand must be a shift right.
594 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
597 // The second operand of the shift must be an immediate.
599 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
602 uint64_t Pos = CN->getZExtValue();
603 uint64_t SMPos, SMSize;
605 // Op's second operand must be a shifted mask.
606 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
607 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
610 // Return if the shifted mask does not start at bit 0 or the sum of its size
611 // and Pos exceeds the word's size.
612 EVT ValTy = N->getValueType(0);
613 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
616 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
617 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
618 DAG.getConstant(SMSize, MVT::i32));
621 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
622 TargetLowering::DAGCombinerInfo &DCI,
623 const MipsSubtarget *Subtarget) {
624 // Pattern match INS.
625 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
626 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
627 // => ins $dst, $src, size, pos, $src1
628 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
631 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
632 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
635 // See if Op's first operand matches (and $src1 , mask0).
636 if (And0.getOpcode() != ISD::AND)
639 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
640 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
643 // See if Op's second operand matches (and (shl $src, pos), mask1).
644 if (And1.getOpcode() != ISD::AND)
647 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
648 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
651 // The shift masks must have the same position and size.
652 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
655 SDValue Shl = And1.getOperand(0);
656 if (Shl.getOpcode() != ISD::SHL)
659 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
662 unsigned Shamt = CN->getZExtValue();
664 // Return if the shift amount and the first bit position of mask are not the
666 EVT ValTy = N->getValueType(0);
667 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
670 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
671 DAG.getConstant(SMPos0, MVT::i32),
672 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
675 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
676 TargetLowering::DAGCombinerInfo &DCI,
677 const MipsSubtarget *Subtarget) {
678 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
680 if (DCI.isBeforeLegalizeOps())
683 SDValue Add = N->getOperand(1);
685 if (Add.getOpcode() != ISD::ADD)
688 SDValue Lo = Add.getOperand(1);
690 if ((Lo.getOpcode() != MipsISD::Lo) ||
691 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
694 EVT ValTy = N->getValueType(0);
697 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
699 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
702 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
704 SelectionDAG &DAG = DCI.DAG;
705 unsigned Opc = N->getOpcode();
711 return performDivRemCombine(N, DAG, DCI, Subtarget);
713 return performSELECTCombine(N, DAG, DCI, Subtarget);
715 return performANDCombine(N, DAG, DCI, Subtarget);
717 return performORCombine(N, DAG, DCI, Subtarget);
719 return performADDCombine(N, DAG, DCI, Subtarget);
726 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
727 SmallVectorImpl<SDValue> &Results,
728 SelectionDAG &DAG) const {
729 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
731 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
732 Results.push_back(Res.getValue(I));
736 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
737 SmallVectorImpl<SDValue> &Results,
738 SelectionDAG &DAG) const {
739 return LowerOperationWrapper(N, Results, DAG);
742 SDValue MipsTargetLowering::
743 LowerOperation(SDValue Op, SelectionDAG &DAG) const
745 switch (Op.getOpcode())
747 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
748 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
749 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
750 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
751 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
752 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
753 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
754 case ISD::SELECT: return lowerSELECT(Op, DAG);
755 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
756 case ISD::SETCC: return lowerSETCC(Op, DAG);
757 case ISD::VASTART: return lowerVASTART(Op, DAG);
758 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
759 case ISD::FABS: return lowerFABS(Op, DAG);
760 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
761 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
762 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
763 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
764 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
765 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
766 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
767 case ISD::LOAD: return lowerLOAD(Op, DAG);
768 case ISD::STORE: return lowerSTORE(Op, DAG);
769 case ISD::ADD: return lowerADD(Op, DAG);
770 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
775 //===----------------------------------------------------------------------===//
776 // Lower helper functions
777 //===----------------------------------------------------------------------===//
779 // addLiveIn - This helper function adds the specified physical register to the
780 // MachineFunction as a live in value. It also creates a corresponding
781 // virtual register for it.
783 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
785 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
786 MF.getRegInfo().addLiveIn(PReg, VReg);
790 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
791 MachineBasicBlock &MBB,
792 const TargetInstrInfo &TII,
797 // Insert instruction "teq $divisor_reg, $zero, 7".
798 MachineBasicBlock::iterator I(MI);
799 MachineInstrBuilder MIB;
800 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
801 .addOperand(MI->getOperand(2)).addReg(Mips::ZERO).addImm(7);
803 // Use the 32-bit sub-register if this is a 64-bit division.
805 MIB->getOperand(0).setSubReg(Mips::sub_32);
811 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
812 MachineBasicBlock *BB) const {
813 switch (MI->getOpcode()) {
815 llvm_unreachable("Unexpected instr type to insert");
816 case Mips::ATOMIC_LOAD_ADD_I8:
817 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
818 case Mips::ATOMIC_LOAD_ADD_I16:
819 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
820 case Mips::ATOMIC_LOAD_ADD_I32:
821 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
822 case Mips::ATOMIC_LOAD_ADD_I64:
823 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
825 case Mips::ATOMIC_LOAD_AND_I8:
826 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
827 case Mips::ATOMIC_LOAD_AND_I16:
828 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
829 case Mips::ATOMIC_LOAD_AND_I32:
830 return emitAtomicBinary(MI, BB, 4, Mips::AND);
831 case Mips::ATOMIC_LOAD_AND_I64:
832 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
834 case Mips::ATOMIC_LOAD_OR_I8:
835 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
836 case Mips::ATOMIC_LOAD_OR_I16:
837 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
838 case Mips::ATOMIC_LOAD_OR_I32:
839 return emitAtomicBinary(MI, BB, 4, Mips::OR);
840 case Mips::ATOMIC_LOAD_OR_I64:
841 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
843 case Mips::ATOMIC_LOAD_XOR_I8:
844 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
845 case Mips::ATOMIC_LOAD_XOR_I16:
846 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
847 case Mips::ATOMIC_LOAD_XOR_I32:
848 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
849 case Mips::ATOMIC_LOAD_XOR_I64:
850 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
852 case Mips::ATOMIC_LOAD_NAND_I8:
853 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
854 case Mips::ATOMIC_LOAD_NAND_I16:
855 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
856 case Mips::ATOMIC_LOAD_NAND_I32:
857 return emitAtomicBinary(MI, BB, 4, 0, true);
858 case Mips::ATOMIC_LOAD_NAND_I64:
859 return emitAtomicBinary(MI, BB, 8, 0, true);
861 case Mips::ATOMIC_LOAD_SUB_I8:
862 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
863 case Mips::ATOMIC_LOAD_SUB_I16:
864 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
865 case Mips::ATOMIC_LOAD_SUB_I32:
866 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
867 case Mips::ATOMIC_LOAD_SUB_I64:
868 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
870 case Mips::ATOMIC_SWAP_I8:
871 return emitAtomicBinaryPartword(MI, BB, 1, 0);
872 case Mips::ATOMIC_SWAP_I16:
873 return emitAtomicBinaryPartword(MI, BB, 2, 0);
874 case Mips::ATOMIC_SWAP_I32:
875 return emitAtomicBinary(MI, BB, 4, 0);
876 case Mips::ATOMIC_SWAP_I64:
877 return emitAtomicBinary(MI, BB, 8, 0);
879 case Mips::ATOMIC_CMP_SWAP_I8:
880 return emitAtomicCmpSwapPartword(MI, BB, 1);
881 case Mips::ATOMIC_CMP_SWAP_I16:
882 return emitAtomicCmpSwapPartword(MI, BB, 2);
883 case Mips::ATOMIC_CMP_SWAP_I32:
884 return emitAtomicCmpSwap(MI, BB, 4);
885 case Mips::ATOMIC_CMP_SWAP_I64:
886 return emitAtomicCmpSwap(MI, BB, 8);
887 case Mips::PseudoSDIV:
888 case Mips::PseudoUDIV:
889 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
890 case Mips::PseudoDSDIV:
891 case Mips::PseudoDUDIV:
892 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
896 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
897 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
899 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
900 unsigned Size, unsigned BinOpcode,
902 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
904 MachineFunction *MF = BB->getParent();
905 MachineRegisterInfo &RegInfo = MF->getRegInfo();
906 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
907 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
908 DebugLoc DL = MI->getDebugLoc();
909 unsigned LL, SC, AND, NOR, ZERO, BEQ;
924 ZERO = Mips::ZERO_64;
928 unsigned OldVal = MI->getOperand(0).getReg();
929 unsigned Ptr = MI->getOperand(1).getReg();
930 unsigned Incr = MI->getOperand(2).getReg();
932 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
933 unsigned AndRes = RegInfo.createVirtualRegister(RC);
934 unsigned Success = RegInfo.createVirtualRegister(RC);
936 // insert new blocks after the current block
937 const BasicBlock *LLVM_BB = BB->getBasicBlock();
938 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
939 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
940 MachineFunction::iterator It = BB;
942 MF->insert(It, loopMBB);
943 MF->insert(It, exitMBB);
945 // Transfer the remainder of BB and its successor edges to exitMBB.
946 exitMBB->splice(exitMBB->begin(), BB,
947 llvm::next(MachineBasicBlock::iterator(MI)),
949 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
953 // fallthrough --> loopMBB
954 BB->addSuccessor(loopMBB);
955 loopMBB->addSuccessor(loopMBB);
956 loopMBB->addSuccessor(exitMBB);
960 // <binop> storeval, oldval, incr
961 // sc success, storeval, 0(ptr)
962 // beq success, $0, loopMBB
964 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
966 // and andres, oldval, incr
967 // nor storeval, $0, andres
968 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
969 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
970 } else if (BinOpcode) {
971 // <binop> storeval, oldval, incr
972 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
976 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
977 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
979 MI->eraseFromParent(); // The instruction is gone now.
985 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
986 MachineBasicBlock *BB,
987 unsigned Size, unsigned BinOpcode,
989 assert((Size == 1 || Size == 2) &&
990 "Unsupported size for EmitAtomicBinaryPartial.");
992 MachineFunction *MF = BB->getParent();
993 MachineRegisterInfo &RegInfo = MF->getRegInfo();
994 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
995 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
996 DebugLoc DL = MI->getDebugLoc();
998 unsigned Dest = MI->getOperand(0).getReg();
999 unsigned Ptr = MI->getOperand(1).getReg();
1000 unsigned Incr = MI->getOperand(2).getReg();
1002 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1003 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1004 unsigned Mask = RegInfo.createVirtualRegister(RC);
1005 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1006 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1007 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1008 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1009 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1010 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1011 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1012 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1013 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1014 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1015 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1016 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1017 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1018 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1019 unsigned Success = RegInfo.createVirtualRegister(RC);
1021 // insert new blocks after the current block
1022 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1023 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1024 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1025 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1026 MachineFunction::iterator It = BB;
1028 MF->insert(It, loopMBB);
1029 MF->insert(It, sinkMBB);
1030 MF->insert(It, exitMBB);
1032 // Transfer the remainder of BB and its successor edges to exitMBB.
1033 exitMBB->splice(exitMBB->begin(), BB,
1034 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1035 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1037 BB->addSuccessor(loopMBB);
1038 loopMBB->addSuccessor(loopMBB);
1039 loopMBB->addSuccessor(sinkMBB);
1040 sinkMBB->addSuccessor(exitMBB);
1043 // addiu masklsb2,$0,-4 # 0xfffffffc
1044 // and alignedaddr,ptr,masklsb2
1045 // andi ptrlsb2,ptr,3
1046 // sll shiftamt,ptrlsb2,3
1047 // ori maskupper,$0,255 # 0xff
1048 // sll mask,maskupper,shiftamt
1049 // nor mask2,$0,mask
1050 // sll incr2,incr,shiftamt
1052 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1053 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1054 .addReg(Mips::ZERO).addImm(-4);
1055 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1056 .addReg(Ptr).addReg(MaskLSB2);
1057 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1058 if (Subtarget->isLittle()) {
1059 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1061 unsigned Off = RegInfo.createVirtualRegister(RC);
1062 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1063 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1064 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1066 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1067 .addReg(Mips::ZERO).addImm(MaskImm);
1068 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1069 .addReg(MaskUpper).addReg(ShiftAmt);
1070 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1071 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1073 // atomic.load.binop
1075 // ll oldval,0(alignedaddr)
1076 // binop binopres,oldval,incr2
1077 // and newval,binopres,mask
1078 // and maskedoldval0,oldval,mask2
1079 // or storeval,maskedoldval0,newval
1080 // sc success,storeval,0(alignedaddr)
1081 // beq success,$0,loopMBB
1085 // ll oldval,0(alignedaddr)
1086 // and newval,incr2,mask
1087 // and maskedoldval0,oldval,mask2
1088 // or storeval,maskedoldval0,newval
1089 // sc success,storeval,0(alignedaddr)
1090 // beq success,$0,loopMBB
1093 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1095 // and andres, oldval, incr2
1096 // nor binopres, $0, andres
1097 // and newval, binopres, mask
1098 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1099 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1100 .addReg(Mips::ZERO).addReg(AndRes);
1101 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1102 } else if (BinOpcode) {
1103 // <binop> binopres, oldval, incr2
1104 // and newval, binopres, mask
1105 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1106 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1107 } else {// atomic.swap
1108 // and newval, incr2, mask
1109 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1112 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1113 .addReg(OldVal).addReg(Mask2);
1114 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1115 .addReg(MaskedOldVal0).addReg(NewVal);
1116 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1117 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1118 BuildMI(BB, DL, TII->get(Mips::BEQ))
1119 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1122 // and maskedoldval1,oldval,mask
1123 // srl srlres,maskedoldval1,shiftamt
1124 // sll sllres,srlres,24
1125 // sra dest,sllres,24
1127 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1129 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1130 .addReg(OldVal).addReg(Mask);
1131 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1132 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1133 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1134 .addReg(SrlRes).addImm(ShiftImm);
1135 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1136 .addReg(SllRes).addImm(ShiftImm);
1138 MI->eraseFromParent(); // The instruction is gone now.
1144 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1145 MachineBasicBlock *BB,
1146 unsigned Size) const {
1147 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1149 MachineFunction *MF = BB->getParent();
1150 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1151 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1152 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1153 DebugLoc DL = MI->getDebugLoc();
1154 unsigned LL, SC, ZERO, BNE, BEQ;
1166 ZERO = Mips::ZERO_64;
1171 unsigned Dest = MI->getOperand(0).getReg();
1172 unsigned Ptr = MI->getOperand(1).getReg();
1173 unsigned OldVal = MI->getOperand(2).getReg();
1174 unsigned NewVal = MI->getOperand(3).getReg();
1176 unsigned Success = RegInfo.createVirtualRegister(RC);
1178 // insert new blocks after the current block
1179 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1180 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1181 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1182 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1183 MachineFunction::iterator It = BB;
1185 MF->insert(It, loop1MBB);
1186 MF->insert(It, loop2MBB);
1187 MF->insert(It, exitMBB);
1189 // Transfer the remainder of BB and its successor edges to exitMBB.
1190 exitMBB->splice(exitMBB->begin(), BB,
1191 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1192 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1196 // fallthrough --> loop1MBB
1197 BB->addSuccessor(loop1MBB);
1198 loop1MBB->addSuccessor(exitMBB);
1199 loop1MBB->addSuccessor(loop2MBB);
1200 loop2MBB->addSuccessor(loop1MBB);
1201 loop2MBB->addSuccessor(exitMBB);
1205 // bne dest, oldval, exitMBB
1207 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1208 BuildMI(BB, DL, TII->get(BNE))
1209 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1212 // sc success, newval, 0(ptr)
1213 // beq success, $0, loop1MBB
1215 BuildMI(BB, DL, TII->get(SC), Success)
1216 .addReg(NewVal).addReg(Ptr).addImm(0);
1217 BuildMI(BB, DL, TII->get(BEQ))
1218 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1220 MI->eraseFromParent(); // The instruction is gone now.
1226 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1227 MachineBasicBlock *BB,
1228 unsigned Size) const {
1229 assert((Size == 1 || Size == 2) &&
1230 "Unsupported size for EmitAtomicCmpSwapPartial.");
1232 MachineFunction *MF = BB->getParent();
1233 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1234 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1235 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1236 DebugLoc DL = MI->getDebugLoc();
1238 unsigned Dest = MI->getOperand(0).getReg();
1239 unsigned Ptr = MI->getOperand(1).getReg();
1240 unsigned CmpVal = MI->getOperand(2).getReg();
1241 unsigned NewVal = MI->getOperand(3).getReg();
1243 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1244 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1245 unsigned Mask = RegInfo.createVirtualRegister(RC);
1246 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1247 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1248 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1249 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1250 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1251 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1252 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1253 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1254 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1255 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1256 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1257 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1258 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1259 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1260 unsigned Success = RegInfo.createVirtualRegister(RC);
1262 // insert new blocks after the current block
1263 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1264 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1265 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1266 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1267 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1268 MachineFunction::iterator It = BB;
1270 MF->insert(It, loop1MBB);
1271 MF->insert(It, loop2MBB);
1272 MF->insert(It, sinkMBB);
1273 MF->insert(It, exitMBB);
1275 // Transfer the remainder of BB and its successor edges to exitMBB.
1276 exitMBB->splice(exitMBB->begin(), BB,
1277 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1278 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1280 BB->addSuccessor(loop1MBB);
1281 loop1MBB->addSuccessor(sinkMBB);
1282 loop1MBB->addSuccessor(loop2MBB);
1283 loop2MBB->addSuccessor(loop1MBB);
1284 loop2MBB->addSuccessor(sinkMBB);
1285 sinkMBB->addSuccessor(exitMBB);
1287 // FIXME: computation of newval2 can be moved to loop2MBB.
1289 // addiu masklsb2,$0,-4 # 0xfffffffc
1290 // and alignedaddr,ptr,masklsb2
1291 // andi ptrlsb2,ptr,3
1292 // sll shiftamt,ptrlsb2,3
1293 // ori maskupper,$0,255 # 0xff
1294 // sll mask,maskupper,shiftamt
1295 // nor mask2,$0,mask
1296 // andi maskedcmpval,cmpval,255
1297 // sll shiftedcmpval,maskedcmpval,shiftamt
1298 // andi maskednewval,newval,255
1299 // sll shiftednewval,maskednewval,shiftamt
1300 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1301 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1302 .addReg(Mips::ZERO).addImm(-4);
1303 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1304 .addReg(Ptr).addReg(MaskLSB2);
1305 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1306 if (Subtarget->isLittle()) {
1307 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1309 unsigned Off = RegInfo.createVirtualRegister(RC);
1310 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1311 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1312 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1314 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1315 .addReg(Mips::ZERO).addImm(MaskImm);
1316 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1317 .addReg(MaskUpper).addReg(ShiftAmt);
1318 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1319 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1320 .addReg(CmpVal).addImm(MaskImm);
1321 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1322 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1323 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1324 .addReg(NewVal).addImm(MaskImm);
1325 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1326 .addReg(MaskedNewVal).addReg(ShiftAmt);
1329 // ll oldval,0(alginedaddr)
1330 // and maskedoldval0,oldval,mask
1331 // bne maskedoldval0,shiftedcmpval,sinkMBB
1333 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1334 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1335 .addReg(OldVal).addReg(Mask);
1336 BuildMI(BB, DL, TII->get(Mips::BNE))
1337 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1340 // and maskedoldval1,oldval,mask2
1341 // or storeval,maskedoldval1,shiftednewval
1342 // sc success,storeval,0(alignedaddr)
1343 // beq success,$0,loop1MBB
1345 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1346 .addReg(OldVal).addReg(Mask2);
1347 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1348 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1349 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1350 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1351 BuildMI(BB, DL, TII->get(Mips::BEQ))
1352 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1355 // srl srlres,maskedoldval0,shiftamt
1356 // sll sllres,srlres,24
1357 // sra dest,sllres,24
1359 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1361 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1362 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1363 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1364 .addReg(SrlRes).addImm(ShiftImm);
1365 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1366 .addReg(SllRes).addImm(ShiftImm);
1368 MI->eraseFromParent(); // The instruction is gone now.
1373 //===----------------------------------------------------------------------===//
1374 // Misc Lower Operation implementation
1375 //===----------------------------------------------------------------------===//
1376 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1377 SDValue Chain = Op.getOperand(0);
1378 SDValue Table = Op.getOperand(1);
1379 SDValue Index = Op.getOperand(2);
1381 EVT PTy = getPointerTy();
1382 unsigned EntrySize =
1383 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1385 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1386 DAG.getConstant(EntrySize, PTy));
1387 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1389 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1390 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1391 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1393 Chain = Addr.getValue(1);
1395 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1396 // For PIC, the sequence is:
1397 // BRIND(load(Jumptable + index) + RelocBase)
1398 // RelocBase can be JumpTable, GOT or some sort of global base.
1399 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1400 getPICJumpTableRelocBase(Table, DAG));
1403 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1406 SDValue MipsTargetLowering::
1407 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1409 // The first operand is the chain, the second is the condition, the third is
1410 // the block to branch to if the condition is true.
1411 SDValue Chain = Op.getOperand(0);
1412 SDValue Dest = Op.getOperand(2);
1415 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1417 // Return if flag is not set by a floating point comparison.
1418 if (CondRes.getOpcode() != MipsISD::FPCmp)
1421 SDValue CCNode = CondRes.getOperand(2);
1423 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1424 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1425 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1426 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1427 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1428 FCC0, Dest, CondRes);
1431 SDValue MipsTargetLowering::
1432 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1434 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1436 // Return if flag is not set by a floating point comparison.
1437 if (Cond.getOpcode() != MipsISD::FPCmp)
1440 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1444 SDValue MipsTargetLowering::
1445 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1448 EVT Ty = Op.getOperand(0).getValueType();
1449 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1450 getSetCCResultType(*DAG.getContext(), Ty),
1451 Op.getOperand(0), Op.getOperand(1),
1454 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1458 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1459 SDValue Cond = createFPCmp(DAG, Op);
1461 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1462 "Floating point operand expected.");
1464 SDValue True = DAG.getConstant(1, MVT::i32);
1465 SDValue False = DAG.getConstant(0, MVT::i32);
1467 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1470 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1471 SelectionDAG &DAG) const {
1472 // FIXME there isn't actually debug info here
1474 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1476 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1477 const MipsTargetObjectFile &TLOF =
1478 (const MipsTargetObjectFile&)getObjFileLowering();
1480 // %gp_rel relocation
1481 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1482 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1484 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1485 DAG.getVTList(MVT::i32), &GA, 1);
1486 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1487 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1490 // %hi/%lo relocation
1491 return getAddrNonPIC(Op, DAG);
1494 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1495 return getAddrLocal(Op, DAG, HasMips64);
1498 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1499 MipsII::MO_GOT_LO16);
1501 return getAddrGlobal(Op, DAG,
1502 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1505 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1506 SelectionDAG &DAG) const {
1507 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1508 return getAddrNonPIC(Op, DAG);
1510 return getAddrLocal(Op, DAG, HasMips64);
1513 SDValue MipsTargetLowering::
1514 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1516 // If the relocation model is PIC, use the General Dynamic TLS Model or
1517 // Local Dynamic TLS model, otherwise use the Initial Exec or
1518 // Local Exec TLS Model.
1520 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1522 const GlobalValue *GV = GA->getGlobal();
1523 EVT PtrVT = getPointerTy();
1525 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1527 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1528 // General Dynamic and Local Dynamic TLS Model.
1529 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1532 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1533 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1534 getGlobalReg(DAG, PtrVT), TGA);
1535 unsigned PtrSize = PtrVT.getSizeInBits();
1536 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1538 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1542 Entry.Node = Argument;
1544 Args.push_back(Entry);
1546 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1547 false, false, false, false, 0, CallingConv::C,
1548 /*IsTailCall=*/false, /*doesNotRet=*/false,
1549 /*isReturnValueUsed=*/true,
1550 TlsGetAddr, Args, DAG, DL);
1551 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1553 SDValue Ret = CallResult.first;
1555 if (model != TLSModel::LocalDynamic)
1558 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1559 MipsII::MO_DTPREL_HI);
1560 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1561 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1562 MipsII::MO_DTPREL_LO);
1563 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1564 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1565 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1569 if (model == TLSModel::InitialExec) {
1570 // Initial Exec TLS Model
1571 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1572 MipsII::MO_GOTTPREL);
1573 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1575 Offset = DAG.getLoad(PtrVT, DL,
1576 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1577 false, false, false, 0);
1579 // Local Exec TLS Model
1580 assert(model == TLSModel::LocalExec);
1581 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1582 MipsII::MO_TPREL_HI);
1583 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1584 MipsII::MO_TPREL_LO);
1585 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1586 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1587 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1590 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1591 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1594 SDValue MipsTargetLowering::
1595 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1597 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1598 return getAddrNonPIC(Op, DAG);
1600 return getAddrLocal(Op, DAG, HasMips64);
1603 SDValue MipsTargetLowering::
1604 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1606 // gp_rel relocation
1607 // FIXME: we should reference the constant pool using small data sections,
1608 // but the asm printer currently doesn't support this feature without
1609 // hacking it. This feature should come soon so we can uncomment the
1611 //if (IsInSmallSection(C->getType())) {
1612 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1613 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1614 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1616 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1617 return getAddrNonPIC(Op, DAG);
1619 return getAddrLocal(Op, DAG, HasMips64);
1622 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1623 MachineFunction &MF = DAG.getMachineFunction();
1624 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1627 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1630 // vastart just stores the address of the VarArgsFrameIndex slot into the
1631 // memory location argument.
1632 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1633 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1634 MachinePointerInfo(SV), false, false, 0);
1637 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1638 EVT TyX = Op.getOperand(0).getValueType();
1639 EVT TyY = Op.getOperand(1).getValueType();
1640 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1641 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1645 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1647 SDValue X = (TyX == MVT::f32) ?
1648 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1649 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1651 SDValue Y = (TyY == MVT::f32) ?
1652 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1653 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1657 // ext E, Y, 31, 1 ; extract bit31 of Y
1658 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1659 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1660 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1663 // srl SrlX, SllX, 1
1665 // sll SllY, SrlX, 31
1666 // or Or, SrlX, SllY
1667 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1668 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1669 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1670 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1671 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1674 if (TyX == MVT::f32)
1675 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1677 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1678 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1679 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1682 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1683 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1684 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1685 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1686 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1689 // Bitcast to integer nodes.
1690 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1691 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1694 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1695 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1696 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1697 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1699 if (WidthX > WidthY)
1700 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1701 else if (WidthY > WidthX)
1702 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1704 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1705 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1706 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1709 // (d)sll SllX, X, 1
1710 // (d)srl SrlX, SllX, 1
1711 // (d)srl SrlY, Y, width(Y)-1
1712 // (d)sll SllY, SrlX, width(Y)-1
1713 // or Or, SrlX, SllY
1714 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1715 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1716 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1717 DAG.getConstant(WidthY - 1, MVT::i32));
1719 if (WidthX > WidthY)
1720 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1721 else if (WidthY > WidthX)
1722 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1724 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1725 DAG.getConstant(WidthX - 1, MVT::i32));
1726 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1727 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1731 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1732 if (Subtarget->hasMips64())
1733 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1735 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1738 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1739 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1742 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1744 SDValue X = (Op.getValueType() == MVT::f32) ?
1745 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1746 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1751 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1752 DAG.getRegister(Mips::ZERO, MVT::i32),
1753 DAG.getConstant(31, MVT::i32), Const1, X);
1755 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1756 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1759 if (Op.getValueType() == MVT::f32)
1760 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1762 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1763 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1764 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1767 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1768 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1771 // Bitcast to integer node.
1772 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1776 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1777 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1778 DAG.getConstant(63, MVT::i32), Const1, X);
1780 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1781 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1784 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1788 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1789 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1790 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1792 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1795 SDValue MipsTargetLowering::
1796 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1798 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1799 "Frame address can only be determined for current frame.");
1801 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1802 MFI->setFrameAddressIsTaken(true);
1803 EVT VT = Op.getValueType();
1805 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1806 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1810 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1811 SelectionDAG &DAG) const {
1813 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1814 "Return address can be determined only for current frame.");
1816 MachineFunction &MF = DAG.getMachineFunction();
1817 MachineFrameInfo *MFI = MF.getFrameInfo();
1818 MVT VT = Op.getSimpleValueType();
1819 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1820 MFI->setReturnAddressIsTaken(true);
1822 // Return RA, which contains the return address. Mark it an implicit live-in.
1823 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1824 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1827 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1828 // generated from __builtin_eh_return (offset, handler)
1829 // The effect of this is to adjust the stack pointer by "offset"
1830 // and then branch to "handler".
1831 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1833 MachineFunction &MF = DAG.getMachineFunction();
1834 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1836 MipsFI->setCallsEhReturn();
1837 SDValue Chain = Op.getOperand(0);
1838 SDValue Offset = Op.getOperand(1);
1839 SDValue Handler = Op.getOperand(2);
1841 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1843 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1844 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1845 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1846 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1847 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1848 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1849 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1850 DAG.getRegister(OffsetReg, Ty),
1851 DAG.getRegister(AddrReg, getPointerTy()),
1855 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1856 SelectionDAG &DAG) const {
1857 // FIXME: Need pseudo-fence for 'singlethread' fences
1858 // FIXME: Set SType for weaker fences where supported/appropriate.
1861 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1862 DAG.getConstant(SType, MVT::i32));
1865 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1866 SelectionDAG &DAG) const {
1868 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1869 SDValue Shamt = Op.getOperand(2);
1872 // lo = (shl lo, shamt)
1873 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1876 // hi = (shl lo, shamt[4:0])
1877 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1878 DAG.getConstant(-1, MVT::i32));
1879 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1880 DAG.getConstant(1, MVT::i32));
1881 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1883 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1884 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1885 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1886 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1887 DAG.getConstant(0x20, MVT::i32));
1888 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1889 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1890 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1892 SDValue Ops[2] = {Lo, Hi};
1893 return DAG.getMergeValues(Ops, 2, DL);
1896 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1899 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1900 SDValue Shamt = Op.getOperand(2);
1903 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1905 // hi = (sra hi, shamt)
1907 // hi = (srl hi, shamt)
1910 // lo = (sra hi, shamt[4:0])
1911 // hi = (sra hi, 31)
1913 // lo = (srl hi, shamt[4:0])
1915 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1916 DAG.getConstant(-1, MVT::i32));
1917 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1918 DAG.getConstant(1, MVT::i32));
1919 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1920 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1921 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1922 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1924 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1925 DAG.getConstant(0x20, MVT::i32));
1926 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1927 DAG.getConstant(31, MVT::i32));
1928 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1929 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1930 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1933 SDValue Ops[2] = {Lo, Hi};
1934 return DAG.getMergeValues(Ops, 2, DL);
1937 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1938 SDValue Chain, SDValue Src, unsigned Offset) {
1939 SDValue Ptr = LD->getBasePtr();
1940 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1941 EVT BasePtrVT = Ptr.getValueType();
1943 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1946 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1947 DAG.getConstant(Offset, BasePtrVT));
1949 SDValue Ops[] = { Chain, Ptr, Src };
1950 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1951 LD->getMemOperand());
1954 // Expand an unaligned 32 or 64-bit integer load node.
1955 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1956 LoadSDNode *LD = cast<LoadSDNode>(Op);
1957 EVT MemVT = LD->getMemoryVT();
1959 // Return if load is aligned or if MemVT is neither i32 nor i64.
1960 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1961 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1964 bool IsLittle = Subtarget->isLittle();
1965 EVT VT = Op.getValueType();
1966 ISD::LoadExtType ExtType = LD->getExtensionType();
1967 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1969 assert((VT == MVT::i32) || (VT == MVT::i64));
1972 // (set dst, (i64 (load baseptr)))
1974 // (set tmp, (ldl (add baseptr, 7), undef))
1975 // (set dst, (ldr baseptr, tmp))
1976 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1977 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1979 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1983 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1985 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1989 // (set dst, (i32 (load baseptr))) or
1990 // (set dst, (i64 (sextload baseptr))) or
1991 // (set dst, (i64 (extload baseptr)))
1993 // (set tmp, (lwl (add baseptr, 3), undef))
1994 // (set dst, (lwr baseptr, tmp))
1995 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1996 (ExtType == ISD::EXTLOAD))
1999 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2002 // (set dst, (i64 (zextload baseptr)))
2004 // (set tmp0, (lwl (add baseptr, 3), undef))
2005 // (set tmp1, (lwr baseptr, tmp0))
2006 // (set tmp2, (shl tmp1, 32))
2007 // (set dst, (srl tmp2, 32))
2009 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2010 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2011 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2012 SDValue Ops[] = { SRL, LWR.getValue(1) };
2013 return DAG.getMergeValues(Ops, 2, DL);
2016 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2017 SDValue Chain, unsigned Offset) {
2018 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2019 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2021 SDVTList VTList = DAG.getVTList(MVT::Other);
2024 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2025 DAG.getConstant(Offset, BasePtrVT));
2027 SDValue Ops[] = { Chain, Value, Ptr };
2028 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2029 SD->getMemOperand());
2032 // Expand an unaligned 32 or 64-bit integer store node.
2033 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2035 SDValue Value = SD->getValue(), Chain = SD->getChain();
2036 EVT VT = Value.getValueType();
2039 // (store val, baseptr) or
2040 // (truncstore val, baseptr)
2042 // (swl val, (add baseptr, 3))
2043 // (swr val, baseptr)
2044 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2045 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2047 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2050 assert(VT == MVT::i64);
2053 // (store val, baseptr)
2055 // (sdl val, (add baseptr, 7))
2056 // (sdr val, baseptr)
2057 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2058 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2061 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2062 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2063 SDValue Val = SD->getValue();
2065 if (Val.getOpcode() != ISD::FP_TO_SINT)
2068 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2069 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2072 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2073 SD->getPointerInfo(), SD->isVolatile(),
2074 SD->isNonTemporal(), SD->getAlignment());
2077 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2078 StoreSDNode *SD = cast<StoreSDNode>(Op);
2079 EVT MemVT = SD->getMemoryVT();
2081 // Lower unaligned integer stores.
2082 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2083 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2084 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2086 return lowerFP_TO_SINT_STORE(SD, DAG);
2089 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2090 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2091 || cast<ConstantSDNode>
2092 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2093 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2097 // (add (frameaddr 0), (frame_to_args_offset))
2098 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2099 // (add FrameObject, 0)
2100 // where FrameObject is a fixed StackObject with offset 0 which points to
2101 // the old stack pointer.
2102 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2103 EVT ValTy = Op->getValueType(0);
2104 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2105 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2106 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2107 DAG.getConstant(0, ValTy));
2110 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2111 SelectionDAG &DAG) const {
2112 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2113 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2115 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2118 //===----------------------------------------------------------------------===//
2119 // Calling Convention Implementation
2120 //===----------------------------------------------------------------------===//
2122 //===----------------------------------------------------------------------===//
2123 // TODO: Implement a generic logic using tblgen that can support this.
2124 // Mips O32 ABI rules:
2126 // i32 - Passed in A0, A1, A2, A3 and stack
2127 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2128 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2129 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2130 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2131 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2134 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2135 //===----------------------------------------------------------------------===//
2137 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2138 MVT LocVT, CCValAssign::LocInfo LocInfo,
2139 ISD::ArgFlagsTy ArgFlags, CCState &State,
2140 const uint16_t *F64Regs) {
2142 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2144 static const uint16_t IntRegs[] = {
2145 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2147 static const uint16_t F32Regs[] = {
2148 Mips::F12, Mips::F14
2151 // Do not process byval args here.
2152 if (ArgFlags.isByVal())
2155 // Promote i8 and i16
2156 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2158 if (ArgFlags.isSExt())
2159 LocInfo = CCValAssign::SExt;
2160 else if (ArgFlags.isZExt())
2161 LocInfo = CCValAssign::ZExt;
2163 LocInfo = CCValAssign::AExt;
2168 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2169 // is true: function is vararg, argument is 3rd or higher, there is previous
2170 // argument which is not f32 or f64.
2171 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2172 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2173 unsigned OrigAlign = ArgFlags.getOrigAlign();
2174 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2176 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2177 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2178 // If this is the first part of an i64 arg,
2179 // the allocated register must be either A0 or A2.
2180 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2181 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2183 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2184 // Allocate int register and shadow next int register. If first
2185 // available register is Mips::A1 or Mips::A3, shadow it too.
2186 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2187 if (Reg == Mips::A1 || Reg == Mips::A3)
2188 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2189 State.AllocateReg(IntRegs, IntRegsSize);
2191 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2192 // we are guaranteed to find an available float register
2193 if (ValVT == MVT::f32) {
2194 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2195 // Shadow int register
2196 State.AllocateReg(IntRegs, IntRegsSize);
2198 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2199 // Shadow int registers
2200 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2201 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2202 State.AllocateReg(IntRegs, IntRegsSize);
2203 State.AllocateReg(IntRegs, IntRegsSize);
2206 llvm_unreachable("Cannot handle this ValVT.");
2209 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2211 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2213 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2218 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2219 MVT LocVT, CCValAssign::LocInfo LocInfo,
2220 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2221 static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2223 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2226 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2227 MVT LocVT, CCValAssign::LocInfo LocInfo,
2228 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2229 static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D12_64 };
2231 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2234 #include "MipsGenCallingConv.inc"
2236 //===----------------------------------------------------------------------===//
2237 // Call Calling Convention Implementation
2238 //===----------------------------------------------------------------------===//
2240 // Return next O32 integer argument register.
2241 static unsigned getNextIntArgReg(unsigned Reg) {
2242 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2243 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2247 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2248 SDValue Chain, SDValue Arg, SDLoc DL,
2249 bool IsTailCall, SelectionDAG &DAG) const {
2251 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2252 DAG.getIntPtrConstant(Offset));
2253 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2257 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2258 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2259 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2260 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2261 /*isVolatile=*/ true, false, 0);
2264 void MipsTargetLowering::
2265 getOpndList(SmallVectorImpl<SDValue> &Ops,
2266 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2267 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2268 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2269 // Insert node "GP copy globalreg" before call to function.
2271 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2272 // in PIC mode) allow symbols to be resolved via lazy binding.
2273 // The lazy binding stub requires GP to point to the GOT.
2274 if (IsPICCall && !InternalLinkage) {
2275 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2276 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2277 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2280 // Build a sequence of copy-to-reg nodes chained together with token
2281 // chain and flag operands which copy the outgoing args into registers.
2282 // The InFlag in necessary since all emitted instructions must be
2286 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2287 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2288 RegsToPass[i].second, InFlag);
2289 InFlag = Chain.getValue(1);
2292 // Add argument registers to the end of the list so that they are
2293 // known live into the call.
2294 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2295 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2296 RegsToPass[i].second.getValueType()));
2298 // Add a register mask operand representing the call-preserved registers.
2299 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2300 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2301 assert(Mask && "Missing call preserved mask for calling convention");
2302 if (Subtarget->inMips16HardFloat()) {
2303 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2304 llvm::StringRef Sym = G->getGlobal()->getName();
2305 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2306 if (F->hasFnAttribute("__Mips16RetHelper")) {
2307 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2311 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2313 if (InFlag.getNode())
2314 Ops.push_back(InFlag);
2317 /// LowerCall - functions arguments are copied from virtual regs to
2318 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2320 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2321 SmallVectorImpl<SDValue> &InVals) const {
2322 SelectionDAG &DAG = CLI.DAG;
2324 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2325 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2326 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2327 SDValue Chain = CLI.Chain;
2328 SDValue Callee = CLI.Callee;
2329 bool &IsTailCall = CLI.IsTailCall;
2330 CallingConv::ID CallConv = CLI.CallConv;
2331 bool IsVarArg = CLI.IsVarArg;
2333 MachineFunction &MF = DAG.getMachineFunction();
2334 MachineFrameInfo *MFI = MF.getFrameInfo();
2335 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2336 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2338 // Analyze operands of the call, assigning locations to each operand.
2339 SmallVector<CCValAssign, 16> ArgLocs;
2340 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2341 getTargetMachine(), ArgLocs, *DAG.getContext());
2342 MipsCC::SpecialCallingConvType SpecialCallingConv =
2343 getSpecialCallingConv(Callee);
2344 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2345 SpecialCallingConv);
2347 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2348 Subtarget->mipsSEUsesSoftFloat(),
2349 Callee.getNode(), CLI.Args);
2351 // Get a count of how many bytes are to be pushed on the stack.
2352 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2354 // Check if it's really possible to do a tail call.
2357 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2358 *MF.getInfo<MipsFunctionInfo>());
2363 // Chain is the output chain of the last Load/Store or CopyToReg node.
2364 // ByValChain is the output chain of the last Memcpy node created for copying
2365 // byval arguments to the stack.
2366 unsigned StackAlignment = TFL->getStackAlignment();
2367 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2368 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2371 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2373 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2374 IsN64 ? Mips::SP_64 : Mips::SP,
2377 // With EABI is it possible to have 16 args on registers.
2378 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2379 SmallVector<SDValue, 8> MemOpChains;
2380 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2382 // Walk the register/memloc assignments, inserting copies/loads.
2383 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2384 SDValue Arg = OutVals[i];
2385 CCValAssign &VA = ArgLocs[i];
2386 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2387 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2390 if (Flags.isByVal()) {
2391 assert(Flags.getByValSize() &&
2392 "ByVal args of size 0 should have been ignored by front-end.");
2393 assert(ByValArg != MipsCCInfo.byval_end());
2394 assert(!IsTailCall &&
2395 "Do not tail-call optimize if there is a byval argument.");
2396 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2397 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2402 // Promote the value if needed.
2403 switch (VA.getLocInfo()) {
2404 default: llvm_unreachable("Unknown loc info!");
2405 case CCValAssign::Full:
2406 if (VA.isRegLoc()) {
2407 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2408 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2409 (ValVT == MVT::i64 && LocVT == MVT::f64))
2410 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2411 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2412 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2413 Arg, DAG.getConstant(0, MVT::i32));
2414 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2415 Arg, DAG.getConstant(1, MVT::i32));
2416 if (!Subtarget->isLittle())
2418 unsigned LocRegLo = VA.getLocReg();
2419 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2420 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2421 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2426 case CCValAssign::SExt:
2427 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2429 case CCValAssign::ZExt:
2430 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2432 case CCValAssign::AExt:
2433 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2437 // Arguments that can be passed on register must be kept at
2438 // RegsToPass vector
2439 if (VA.isRegLoc()) {
2440 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2444 // Register can't get to this point...
2445 assert(VA.isMemLoc());
2447 // emit ISD::STORE whichs stores the
2448 // parameter value to a stack Location
2449 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2450 Chain, Arg, DL, IsTailCall, DAG));
2453 // Transform all store nodes into one single node because all store
2454 // nodes are independent of each other.
2455 if (!MemOpChains.empty())
2456 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2457 &MemOpChains[0], MemOpChains.size());
2459 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2460 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2461 // node so that legalize doesn't hack it.
2462 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2463 bool GlobalOrExternal = false, InternalLinkage = false;
2466 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2468 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2470 if (InternalLinkage)
2471 Callee = getAddrLocal(Callee, DAG, HasMips64);
2473 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2474 MipsII::MO_CALL_LO16);
2476 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2478 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2479 MipsII::MO_NO_FLAG);
2480 GlobalOrExternal = true;
2482 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2483 if (!IsN64 && !IsPIC) // !N64 && static
2484 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2485 MipsII::MO_NO_FLAG);
2487 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2488 MipsII::MO_CALL_LO16);
2490 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2492 GlobalOrExternal = true;
2495 SmallVector<SDValue, 8> Ops(1, Chain);
2496 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2498 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2499 CLI, Callee, Chain);
2502 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2504 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2505 SDValue InFlag = Chain.getValue(1);
2507 // Create the CALLSEQ_END node.
2508 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2509 DAG.getIntPtrConstant(0, true), InFlag, DL);
2510 InFlag = Chain.getValue(1);
2512 // Handle result values, copying them out of physregs into vregs that we
2514 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2515 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2518 /// LowerCallResult - Lower the result values of a call into the
2519 /// appropriate copies out of appropriate physical registers.
2521 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2522 CallingConv::ID CallConv, bool IsVarArg,
2523 const SmallVectorImpl<ISD::InputArg> &Ins,
2524 SDLoc DL, SelectionDAG &DAG,
2525 SmallVectorImpl<SDValue> &InVals,
2526 const SDNode *CallNode,
2527 const Type *RetTy) const {
2528 // Assign locations to each value returned by this call.
2529 SmallVector<CCValAssign, 16> RVLocs;
2530 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2531 getTargetMachine(), RVLocs, *DAG.getContext());
2532 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2534 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2537 // Copy all of the result registers out of their specified physreg.
2538 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2539 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2540 RVLocs[i].getLocVT(), InFlag);
2541 Chain = Val.getValue(1);
2542 InFlag = Val.getValue(2);
2544 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2545 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2547 InVals.push_back(Val);
2553 //===----------------------------------------------------------------------===//
2554 // Formal Arguments Calling Convention Implementation
2555 //===----------------------------------------------------------------------===//
2556 /// LowerFormalArguments - transform physical registers into virtual registers
2557 /// and generate load operations for arguments places on the stack.
2559 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2560 CallingConv::ID CallConv,
2562 const SmallVectorImpl<ISD::InputArg> &Ins,
2563 SDLoc DL, SelectionDAG &DAG,
2564 SmallVectorImpl<SDValue> &InVals)
2566 MachineFunction &MF = DAG.getMachineFunction();
2567 MachineFrameInfo *MFI = MF.getFrameInfo();
2568 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2570 MipsFI->setVarArgsFrameIndex(0);
2572 // Used with vargs to acumulate store chains.
2573 std::vector<SDValue> OutChains;
2575 // Assign locations to all of the incoming arguments.
2576 SmallVector<CCValAssign, 16> ArgLocs;
2577 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2578 getTargetMachine(), ArgLocs, *DAG.getContext());
2579 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2580 Function::const_arg_iterator FuncArg =
2581 DAG.getMachineFunction().getFunction()->arg_begin();
2582 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2584 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2585 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2586 MipsCCInfo.hasByValArg());
2588 unsigned CurArgIdx = 0;
2589 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2591 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2592 CCValAssign &VA = ArgLocs[i];
2593 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2594 CurArgIdx = Ins[i].OrigArgIndex;
2595 EVT ValVT = VA.getValVT();
2596 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2597 bool IsRegLoc = VA.isRegLoc();
2599 if (Flags.isByVal()) {
2600 assert(Flags.getByValSize() &&
2601 "ByVal args of size 0 should have been ignored by front-end.");
2602 assert(ByValArg != MipsCCInfo.byval_end());
2603 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2604 MipsCCInfo, *ByValArg);
2609 // Arguments stored on registers
2611 EVT RegVT = VA.getLocVT();
2612 unsigned ArgReg = VA.getLocReg();
2613 const TargetRegisterClass *RC;
2615 if (RegVT == MVT::i32)
2616 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2617 &Mips::GPR32RegClass;
2618 else if (RegVT == MVT::i64)
2619 RC = &Mips::GPR64RegClass;
2620 else if (RegVT == MVT::f32)
2621 RC = &Mips::FGR32RegClass;
2622 else if (RegVT == MVT::f64)
2623 RC = Subtarget->isFP64bit() ? &Mips::FGR64RegClass :
2624 &Mips::AFGR64RegClass;
2626 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2628 // Transform the arguments stored on
2629 // physical registers into virtual ones
2630 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2631 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2633 // If this is an 8 or 16-bit value, it has been passed promoted
2634 // to 32 bits. Insert an assert[sz]ext to capture this, then
2635 // truncate to the right size.
2636 if (VA.getLocInfo() != CCValAssign::Full) {
2637 unsigned Opcode = 0;
2638 if (VA.getLocInfo() == CCValAssign::SExt)
2639 Opcode = ISD::AssertSext;
2640 else if (VA.getLocInfo() == CCValAssign::ZExt)
2641 Opcode = ISD::AssertZext;
2643 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2644 DAG.getValueType(ValVT));
2645 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2648 // Handle floating point arguments passed in integer registers and
2649 // long double arguments passed in floating point registers.
2650 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2651 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2652 (RegVT == MVT::f64 && ValVT == MVT::i64))
2653 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2654 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2655 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2656 getNextIntArgReg(ArgReg), RC);
2657 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2658 if (!Subtarget->isLittle())
2659 std::swap(ArgValue, ArgValue2);
2660 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2661 ArgValue, ArgValue2);
2664 InVals.push_back(ArgValue);
2665 } else { // VA.isRegLoc()
2668 assert(VA.isMemLoc());
2670 // The stack pointer offset is relative to the caller stack frame.
2671 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2672 VA.getLocMemOffset(), true);
2674 // Create load nodes to retrieve arguments from the stack
2675 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2676 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2677 MachinePointerInfo::getFixedStack(FI),
2678 false, false, false, 0));
2682 // The mips ABIs for returning structs by value requires that we copy
2683 // the sret argument into $v0 for the return. Save the argument into
2684 // a virtual register so that we can access it from the return points.
2685 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2686 unsigned Reg = MipsFI->getSRetReturnReg();
2688 Reg = MF.getRegInfo().
2689 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2690 MipsFI->setSRetReturnReg(Reg);
2692 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2693 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2697 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2699 // All stores are grouped in one node to allow the matching between
2700 // the size of Ins and InVals. This only happens when on varg functions
2701 if (!OutChains.empty()) {
2702 OutChains.push_back(Chain);
2703 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2704 &OutChains[0], OutChains.size());
2710 //===----------------------------------------------------------------------===//
2711 // Return Value Calling Convention Implementation
2712 //===----------------------------------------------------------------------===//
2715 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2716 MachineFunction &MF, bool IsVarArg,
2717 const SmallVectorImpl<ISD::OutputArg> &Outs,
2718 LLVMContext &Context) const {
2719 SmallVector<CCValAssign, 16> RVLocs;
2720 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2722 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2726 MipsTargetLowering::LowerReturn(SDValue Chain,
2727 CallingConv::ID CallConv, bool IsVarArg,
2728 const SmallVectorImpl<ISD::OutputArg> &Outs,
2729 const SmallVectorImpl<SDValue> &OutVals,
2730 SDLoc DL, SelectionDAG &DAG) const {
2731 // CCValAssign - represent the assignment of
2732 // the return value to a location
2733 SmallVector<CCValAssign, 16> RVLocs;
2734 MachineFunction &MF = DAG.getMachineFunction();
2736 // CCState - Info about the registers and stack slot.
2737 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2739 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2741 // Analyze return values.
2742 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2743 MF.getFunction()->getReturnType());
2746 SmallVector<SDValue, 4> RetOps(1, Chain);
2748 // Copy the result values into the output registers.
2749 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2750 SDValue Val = OutVals[i];
2751 CCValAssign &VA = RVLocs[i];
2752 assert(VA.isRegLoc() && "Can only return in registers!");
2754 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2755 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2757 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2759 // Guarantee that all emitted copies are stuck together with flags.
2760 Flag = Chain.getValue(1);
2761 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2764 // The mips ABIs for returning structs by value requires that we copy
2765 // the sret argument into $v0 for the return. We saved the argument into
2766 // a virtual register in the entry block, so now we copy the value out
2768 if (MF.getFunction()->hasStructRetAttr()) {
2769 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2770 unsigned Reg = MipsFI->getSRetReturnReg();
2773 llvm_unreachable("sret virtual register not created in the entry block");
2774 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2775 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2777 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2778 Flag = Chain.getValue(1);
2779 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2782 RetOps[0] = Chain; // Update chain.
2784 // Add the flag if we have it.
2786 RetOps.push_back(Flag);
2788 // Return on Mips is always a "jr $ra"
2789 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2792 //===----------------------------------------------------------------------===//
2793 // Mips Inline Assembly Support
2794 //===----------------------------------------------------------------------===//
2796 /// getConstraintType - Given a constraint letter, return the type of
2797 /// constraint it is for this target.
2798 MipsTargetLowering::ConstraintType MipsTargetLowering::
2799 getConstraintType(const std::string &Constraint) const
2801 // Mips specific constrainy
2802 // GCC config/mips/constraints.md
2804 // 'd' : An address register. Equivalent to r
2805 // unless generating MIPS16 code.
2806 // 'y' : Equivalent to r; retained for
2807 // backwards compatibility.
2808 // 'c' : A register suitable for use in an indirect
2809 // jump. This will always be $25 for -mabicalls.
2810 // 'l' : The lo register. 1 word storage.
2811 // 'x' : The hilo register pair. Double word storage.
2812 if (Constraint.size() == 1) {
2813 switch (Constraint[0]) {
2821 return C_RegisterClass;
2826 return TargetLowering::getConstraintType(Constraint);
2829 /// Examine constraint type and operand type and determine a weight value.
2830 /// This object must already have been set up with the operand type
2831 /// and the current alternative constraint selected.
2832 TargetLowering::ConstraintWeight
2833 MipsTargetLowering::getSingleConstraintMatchWeight(
2834 AsmOperandInfo &info, const char *constraint) const {
2835 ConstraintWeight weight = CW_Invalid;
2836 Value *CallOperandVal = info.CallOperandVal;
2837 // If we don't have a value, we can't do a match,
2838 // but allow it at the lowest weight.
2839 if (CallOperandVal == NULL)
2841 Type *type = CallOperandVal->getType();
2842 // Look at the constraint type.
2843 switch (*constraint) {
2845 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2849 if (type->isIntegerTy())
2850 weight = CW_Register;
2853 if (type->isFloatTy())
2854 weight = CW_Register;
2856 case 'c': // $25 for indirect jumps
2857 case 'l': // lo register
2858 case 'x': // hilo register pair
2859 if (type->isIntegerTy())
2860 weight = CW_SpecificReg;
2862 case 'I': // signed 16 bit immediate
2863 case 'J': // integer zero
2864 case 'K': // unsigned 16 bit immediate
2865 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2866 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2867 case 'O': // signed 15 bit immediate (+- 16383)
2868 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2869 if (isa<ConstantInt>(CallOperandVal))
2870 weight = CW_Constant;
2879 /// This is a helper function to parse a physical register string and split it
2880 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2881 /// that is returned indicates whether parsing was successful. The second flag
2882 /// is true if the numeric part exists.
2883 static std::pair<bool, bool>
2884 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2885 unsigned long long &Reg) {
2886 if (C.front() != '{' || C.back() != '}')
2887 return std::make_pair(false, false);
2889 // Search for the first numeric character.
2890 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2891 I = std::find_if(B, E, std::ptr_fun(isdigit));
2893 Prefix.assign(B, I - B);
2895 // The second flag is set to false if no numeric characters were found.
2897 return std::make_pair(true, false);
2899 // Parse the numeric characters.
2900 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2904 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2905 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2906 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2907 const TargetRegisterClass *RC;
2909 unsigned long long Reg;
2911 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2914 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2916 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2917 // No numeric characters follow "hi" or "lo".
2919 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2921 RC = TRI->getRegClass(Prefix == "hi" ?
2922 Mips::HI32RegClassID : Mips::LO32RegClassID);
2923 return std::make_pair(*(RC->begin()), RC);
2927 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2929 if (Prefix == "$f") { // Parse $f0-$f31.
2930 // If the size of FP registers is 64-bit or Reg is an even number, select
2931 // the 64-bit register class. Otherwise, select the 32-bit register class.
2932 if (VT == MVT::Other)
2933 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2935 RC= getRegClassFor(VT);
2937 if (RC == &Mips::AFGR64RegClass) {
2938 assert(Reg % 2 == 0);
2941 } else if (Prefix == "$fcc") { // Parse $fcc0-$fcc7.
2942 RC = TRI->getRegClass(Mips::FCCRegClassID);
2943 } else { // Parse $0-$31.
2944 assert(Prefix == "$");
2945 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2948 assert(Reg < RC->getNumRegs());
2949 return std::make_pair(*(RC->begin() + Reg), RC);
2952 /// Given a register class constraint, like 'r', if this corresponds directly
2953 /// to an LLVM register class, return a register of 0 and the register class
2955 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2956 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2958 if (Constraint.size() == 1) {
2959 switch (Constraint[0]) {
2960 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2961 case 'y': // Same as 'r'. Exists for compatibility.
2963 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2964 if (Subtarget->inMips16Mode())
2965 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2966 return std::make_pair(0U, &Mips::GPR32RegClass);
2968 if (VT == MVT::i64 && !HasMips64)
2969 return std::make_pair(0U, &Mips::GPR32RegClass);
2970 if (VT == MVT::i64 && HasMips64)
2971 return std::make_pair(0U, &Mips::GPR64RegClass);
2972 // This will generate an error message
2973 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2976 return std::make_pair(0U, &Mips::FGR32RegClass);
2977 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2978 if (Subtarget->isFP64bit())
2979 return std::make_pair(0U, &Mips::FGR64RegClass);
2980 return std::make_pair(0U, &Mips::AFGR64RegClass);
2983 case 'c': // register suitable for indirect jump
2985 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
2986 assert(VT == MVT::i64 && "Unexpected type.");
2987 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
2988 case 'l': // register suitable for indirect jump
2990 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
2991 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
2992 case 'x': // register suitable for indirect jump
2993 // Fixme: Not triggering the use of both hi and low
2994 // This will generate an error message
2995 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2999 std::pair<unsigned, const TargetRegisterClass *> R;
3000 R = parseRegForInlineAsmConstraint(Constraint, VT);
3005 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3008 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3009 /// vector. If it is invalid, don't add anything to Ops.
3010 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3011 std::string &Constraint,
3012 std::vector<SDValue>&Ops,
3013 SelectionDAG &DAG) const {
3014 SDValue Result(0, 0);
3016 // Only support length 1 constraints for now.
3017 if (Constraint.length() > 1) return;
3019 char ConstraintLetter = Constraint[0];
3020 switch (ConstraintLetter) {
3021 default: break; // This will fall through to the generic implementation
3022 case 'I': // Signed 16 bit constant
3023 // If this fails, the parent routine will give an error
3024 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3025 EVT Type = Op.getValueType();
3026 int64_t Val = C->getSExtValue();
3027 if (isInt<16>(Val)) {
3028 Result = DAG.getTargetConstant(Val, Type);
3033 case 'J': // integer zero
3034 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3035 EVT Type = Op.getValueType();
3036 int64_t Val = C->getZExtValue();
3038 Result = DAG.getTargetConstant(0, Type);
3043 case 'K': // unsigned 16 bit immediate
3044 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3045 EVT Type = Op.getValueType();
3046 uint64_t Val = (uint64_t)C->getZExtValue();
3047 if (isUInt<16>(Val)) {
3048 Result = DAG.getTargetConstant(Val, Type);
3053 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3054 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3055 EVT Type = Op.getValueType();
3056 int64_t Val = C->getSExtValue();
3057 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3058 Result = DAG.getTargetConstant(Val, Type);
3063 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3064 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3065 EVT Type = Op.getValueType();
3066 int64_t Val = C->getSExtValue();
3067 if ((Val >= -65535) && (Val <= -1)) {
3068 Result = DAG.getTargetConstant(Val, Type);
3073 case 'O': // signed 15 bit immediate
3074 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3075 EVT Type = Op.getValueType();
3076 int64_t Val = C->getSExtValue();
3077 if ((isInt<15>(Val))) {
3078 Result = DAG.getTargetConstant(Val, Type);
3083 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3084 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3085 EVT Type = Op.getValueType();
3086 int64_t Val = C->getSExtValue();
3087 if ((Val <= 65535) && (Val >= 1)) {
3088 Result = DAG.getTargetConstant(Val, Type);
3095 if (Result.getNode()) {
3096 Ops.push_back(Result);
3100 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3104 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3105 // No global is ever allowed as a base.
3110 case 0: // "r+i" or just "i", depending on HasBaseReg.
3113 if (!AM.HasBaseReg) // allow "r+i".
3115 return false; // disallow "r+r" or "r+r+i".
3124 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3125 // The Mips target isn't yet aware of offsets.
3129 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3131 bool IsMemset, bool ZeroMemset,
3133 MachineFunction &MF) const {
3134 if (Subtarget->hasMips64())
3140 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3141 if (VT != MVT::f32 && VT != MVT::f64)
3143 if (Imm.isNegZero())
3145 return Imm.isZero();
3148 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3150 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3152 return TargetLowering::getJumpTableEncoding();
3155 /// This function returns true if CallSym is a long double emulation routine.
3156 static bool isF128SoftLibCall(const char *CallSym) {
3157 const char *const LibCalls[] =
3158 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3159 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3160 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3161 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3162 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3163 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3164 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3165 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3168 const char * const *End = LibCalls + array_lengthof(LibCalls);
3170 // Check that LibCalls is sorted alphabetically.
3171 MipsTargetLowering::LTStr Comp;
3174 for (const char * const *I = LibCalls; I < End - 1; ++I)
3175 assert(Comp(*I, *(I + 1)));
3178 return std::binary_search(LibCalls, End, CallSym, Comp);
3181 /// This function returns true if Ty is fp128 or i128 which was originally a
3183 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3184 if (Ty->isFP128Ty())
3187 const ExternalSymbolSDNode *ES =
3188 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3190 // If the Ty is i128 and the function being called is a long double emulation
3191 // routine, then the original type is f128.
3192 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3195 MipsTargetLowering::MipsCC::SpecialCallingConvType
3196 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3197 MipsCC::SpecialCallingConvType SpecialCallingConv =
3198 MipsCC::NoSpecialCallingConv;;
3199 if (Subtarget->inMips16HardFloat()) {
3200 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3201 llvm::StringRef Sym = G->getGlobal()->getName();
3202 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3203 if (F->hasFnAttribute("__Mips16RetHelper")) {
3204 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3208 return SpecialCallingConv;
3211 MipsTargetLowering::MipsCC::MipsCC(
3212 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3213 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3214 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3215 SpecialCallingConv(SpecialCallingConv_){
3216 // Pre-allocate reserved argument area.
3217 CCInfo.AllocateStack(reservedArgArea(), 1);
3221 void MipsTargetLowering::MipsCC::
3222 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3223 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3224 std::vector<ArgListEntry> &FuncArgs) {
3225 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3226 "CallingConv::Fast shouldn't be used for vararg functions.");
3228 unsigned NumOpnds = Args.size();
3229 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3231 for (unsigned I = 0; I != NumOpnds; ++I) {
3232 MVT ArgVT = Args[I].VT;
3233 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3236 if (ArgFlags.isByVal()) {
3237 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3241 if (IsVarArg && !Args[I].IsFixed)
3242 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3244 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3246 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3251 dbgs() << "Call operand #" << I << " has unhandled type "
3252 << EVT(ArgVT).getEVTString();
3254 llvm_unreachable(0);
3259 void MipsTargetLowering::MipsCC::
3260 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3261 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3262 unsigned NumArgs = Args.size();
3263 llvm::CCAssignFn *FixedFn = fixedArgFn();
3264 unsigned CurArgIdx = 0;
3266 for (unsigned I = 0; I != NumArgs; ++I) {
3267 MVT ArgVT = Args[I].VT;
3268 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3269 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3270 CurArgIdx = Args[I].OrigArgIndex;
3272 if (ArgFlags.isByVal()) {
3273 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3277 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3279 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3283 dbgs() << "Formal Arg #" << I << " has unhandled type "
3284 << EVT(ArgVT).getEVTString();
3286 llvm_unreachable(0);
3290 template<typename Ty>
3291 void MipsTargetLowering::MipsCC::
3292 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3293 const SDNode *CallNode, const Type *RetTy) const {
3296 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3297 Fn = RetCC_F128Soft;
3301 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3302 MVT VT = RetVals[I].VT;
3303 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3304 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3306 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3308 dbgs() << "Call result #" << I << " has unhandled type "
3309 << EVT(VT).getEVTString() << '\n';
3311 llvm_unreachable(0);
3316 void MipsTargetLowering::MipsCC::
3317 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3318 const SDNode *CallNode, const Type *RetTy) const {
3319 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3322 void MipsTargetLowering::MipsCC::
3323 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3324 const Type *RetTy) const {
3325 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3329 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3331 CCValAssign::LocInfo LocInfo,
3332 ISD::ArgFlagsTy ArgFlags) {
3333 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3335 struct ByValArgInfo ByVal;
3336 unsigned RegSize = regSize();
3337 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3338 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3341 if (useRegsForByval())
3342 allocateRegs(ByVal, ByValSize, Align);
3344 // Allocate space on caller's stack.
3345 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3347 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3349 ByValArgs.push_back(ByVal);
3352 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3353 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3356 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3357 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3360 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3361 return IsO32 ? O32IntRegs : Mips64IntRegs;
3364 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3365 if (CallConv == CallingConv::Fast)
3366 return CC_Mips_FastCC;
3368 if (SpecialCallingConv == Mips16RetHelperConv)
3369 return CC_Mips16RetHelper;
3370 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3373 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3374 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3377 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3378 return IsO32 ? O32IntRegs : Mips64DPRegs;
3381 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3384 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3385 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3386 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3387 "Byval argument's size and alignment should be a multiple of"
3390 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3392 // If Align > RegSize, the first arg register must be even.
3393 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3394 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3398 // Mark the registers allocated.
3399 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3400 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3401 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3404 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3405 const SDNode *CallNode,
3406 bool IsSoftFloat) const {
3407 if (IsSoftFloat || IsO32)
3410 // Check if the original type was fp128.
3411 if (originalTypeIsF128(OrigTy, CallNode)) {
3412 assert(VT == MVT::i64);
3419 void MipsTargetLowering::
3420 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3421 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3422 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3423 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3424 MachineFunction &MF = DAG.getMachineFunction();
3425 MachineFrameInfo *MFI = MF.getFrameInfo();
3426 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3427 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3431 FrameObjOffset = (int)CC.reservedArgArea() -
3432 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3434 FrameObjOffset = ByVal.Address;
3436 // Create frame object.
3437 EVT PtrTy = getPointerTy();
3438 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3439 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3440 InVals.push_back(FIN);
3445 // Copy arg registers.
3446 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3447 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3449 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3450 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3451 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3452 unsigned Offset = I * CC.regSize();
3453 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3454 DAG.getConstant(Offset, PtrTy));
3455 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3456 StorePtr, MachinePointerInfo(FuncArg, Offset),
3458 OutChains.push_back(Store);
3462 // Copy byVal arg to registers and stack.
3463 void MipsTargetLowering::
3464 passByValArg(SDValue Chain, SDLoc DL,
3465 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3466 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3467 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3468 const MipsCC &CC, const ByValArgInfo &ByVal,
3469 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3470 unsigned ByValSize = Flags.getByValSize();
3471 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3472 unsigned RegSize = CC.regSize();
3473 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3474 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3476 if (ByVal.NumRegs) {
3477 const uint16_t *ArgRegs = CC.intArgRegs();
3478 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3481 // Copy words to registers.
3482 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3483 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3484 DAG.getConstant(Offset, PtrTy));
3485 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3486 MachinePointerInfo(), false, false, false,
3488 MemOpChains.push_back(LoadVal.getValue(1));
3489 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3490 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3493 // Return if the struct has been fully copied.
3494 if (ByValSize == Offset)
3497 // Copy the remainder of the byval argument with sub-word loads and shifts.
3498 if (LeftoverBytes) {
3499 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3500 "Size of the remainder should be smaller than RegSize.");
3503 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3504 Offset < ByValSize; LoadSize /= 2) {
3505 unsigned RemSize = ByValSize - Offset;
3507 if (RemSize < LoadSize)
3511 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3512 DAG.getConstant(Offset, PtrTy));
3514 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3515 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3516 false, false, Alignment);
3517 MemOpChains.push_back(LoadVal.getValue(1));
3519 // Shift the loaded value.
3523 Shamt = TotalSizeLoaded;
3525 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3527 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3528 DAG.getConstant(Shamt, MVT::i32));
3531 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3536 TotalSizeLoaded += LoadSize;
3537 Alignment = std::min(Alignment, LoadSize);
3540 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3541 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3546 // Copy remainder of byval arg to it with memcpy.
3547 unsigned MemCpySize = ByValSize - Offset;
3548 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3549 DAG.getConstant(Offset, PtrTy));
3550 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3551 DAG.getIntPtrConstant(ByVal.Address));
3552 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3553 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3554 /*isVolatile=*/false, /*AlwaysInline=*/false,
3555 MachinePointerInfo(0), MachinePointerInfo(0));
3556 MemOpChains.push_back(Chain);
3560 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3561 const MipsCC &CC, SDValue Chain,
3562 SDLoc DL, SelectionDAG &DAG) const {
3563 unsigned NumRegs = CC.numIntArgRegs();
3564 const uint16_t *ArgRegs = CC.intArgRegs();
3565 const CCState &CCInfo = CC.getCCInfo();
3566 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3567 unsigned RegSize = CC.regSize();
3568 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3569 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3570 MachineFunction &MF = DAG.getMachineFunction();
3571 MachineFrameInfo *MFI = MF.getFrameInfo();
3572 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3574 // Offset of the first variable argument from stack pointer.
3578 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3581 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3583 // Record the frame index of the first variable argument
3584 // which is a value necessary to VASTART.
3585 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3586 MipsFI->setVarArgsFrameIndex(FI);
3588 // Copy the integer registers that have not been used for argument passing
3589 // to the argument register save area. For O32, the save area is allocated
3590 // in the caller's stack frame, while for N32/64, it is allocated in the
3591 // callee's stack frame.
3592 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3593 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3594 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3595 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3596 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3597 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3598 MachinePointerInfo(), false, false, 0);
3599 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3600 OutChains.push_back(Store);