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 default: return NULL;
216 MipsTargetLowering(MipsTargetMachine &TM)
217 : TargetLowering(TM, new MipsTargetObjectFile()),
218 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
219 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
220 IsO32(Subtarget->isABI_O32()) {
221 // Mips does not have i1 type, so use i32 for
222 // setcc operations results (slt, sgt, ...).
223 setBooleanContents(ZeroOrOneBooleanContent);
224 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
226 // Load extented operations for i1 types must be promoted
227 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
228 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
229 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
231 // MIPS doesn't have extending float->double load/store
232 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
233 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
235 // Used by legalize types to correctly generate the setcc result.
236 // Without this, every float setcc comes with a AND/OR with the result,
237 // we don't want this, since the fpcmp result goes to a flag register,
238 // which is used implicitly by brcond and select operations.
239 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
241 // Mips Custom Operations
242 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
243 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
244 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
245 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
246 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
247 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
248 setOperationAction(ISD::SELECT, MVT::f32, Custom);
249 setOperationAction(ISD::SELECT, MVT::f64, Custom);
250 setOperationAction(ISD::SELECT, MVT::i32, Custom);
251 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
252 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
253 setOperationAction(ISD::SETCC, MVT::f32, Custom);
254 setOperationAction(ISD::SETCC, MVT::f64, Custom);
255 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
256 setOperationAction(ISD::VASTART, MVT::Other, Custom);
257 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
258 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
259 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
261 if (!TM.Options.NoNaNsFPMath) {
262 setOperationAction(ISD::FABS, MVT::f32, Custom);
263 setOperationAction(ISD::FABS, MVT::f64, Custom);
267 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
268 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
269 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
270 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
271 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
272 setOperationAction(ISD::SELECT, MVT::i64, Custom);
273 setOperationAction(ISD::LOAD, MVT::i64, Custom);
274 setOperationAction(ISD::STORE, MVT::i64, Custom);
275 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
279 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
280 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
281 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
284 setOperationAction(ISD::ADD, MVT::i32, Custom);
286 setOperationAction(ISD::ADD, MVT::i64, Custom);
288 setOperationAction(ISD::SDIV, MVT::i32, Expand);
289 setOperationAction(ISD::SREM, MVT::i32, Expand);
290 setOperationAction(ISD::UDIV, MVT::i32, Expand);
291 setOperationAction(ISD::UREM, MVT::i32, Expand);
292 setOperationAction(ISD::SDIV, MVT::i64, Expand);
293 setOperationAction(ISD::SREM, MVT::i64, Expand);
294 setOperationAction(ISD::UDIV, MVT::i64, Expand);
295 setOperationAction(ISD::UREM, MVT::i64, Expand);
297 // Operations not directly supported by Mips.
298 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
299 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
300 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
301 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
302 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
303 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
304 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
305 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
306 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
307 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
308 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
309 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
310 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
311 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
312 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
313 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
314 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
315 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
316 setOperationAction(ISD::ROTL, MVT::i32, Expand);
317 setOperationAction(ISD::ROTL, MVT::i64, Expand);
318 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
319 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
321 if (!Subtarget->hasMips32r2())
322 setOperationAction(ISD::ROTR, MVT::i32, Expand);
324 if (!Subtarget->hasMips64r2())
325 setOperationAction(ISD::ROTR, MVT::i64, Expand);
327 setOperationAction(ISD::FSIN, MVT::f32, Expand);
328 setOperationAction(ISD::FSIN, MVT::f64, Expand);
329 setOperationAction(ISD::FCOS, MVT::f32, Expand);
330 setOperationAction(ISD::FCOS, MVT::f64, Expand);
331 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
332 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
333 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
334 setOperationAction(ISD::FPOW, MVT::f32, Expand);
335 setOperationAction(ISD::FPOW, MVT::f64, Expand);
336 setOperationAction(ISD::FLOG, MVT::f32, Expand);
337 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
338 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
339 setOperationAction(ISD::FEXP, MVT::f32, Expand);
340 setOperationAction(ISD::FMA, MVT::f32, Expand);
341 setOperationAction(ISD::FMA, MVT::f64, Expand);
342 setOperationAction(ISD::FREM, MVT::f32, Expand);
343 setOperationAction(ISD::FREM, MVT::f64, Expand);
345 if (!TM.Options.NoNaNsFPMath) {
346 setOperationAction(ISD::FNEG, MVT::f32, Expand);
347 setOperationAction(ISD::FNEG, MVT::f64, Expand);
350 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
352 setOperationAction(ISD::VAARG, MVT::Other, Expand);
353 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
354 setOperationAction(ISD::VAEND, MVT::Other, Expand);
356 // Use the default for now
357 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
358 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
360 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
361 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
362 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
363 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
365 setInsertFencesForAtomic(true);
367 if (!Subtarget->hasSEInReg()) {
368 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
369 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
372 if (!Subtarget->hasBitCount()) {
373 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
374 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
377 if (!Subtarget->hasSwap()) {
378 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
379 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
383 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
384 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
385 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
386 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
389 setOperationAction(ISD::TRAP, MVT::Other, Legal);
391 setTargetDAGCombine(ISD::SDIVREM);
392 setTargetDAGCombine(ISD::UDIVREM);
393 setTargetDAGCombine(ISD::SELECT);
394 setTargetDAGCombine(ISD::AND);
395 setTargetDAGCombine(ISD::OR);
396 setTargetDAGCombine(ISD::ADD);
398 setMinFunctionAlignment(HasMips64 ? 3 : 2);
400 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
402 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
403 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
405 MaxStoresPerMemcpy = 16;
408 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
409 if (TM.getSubtargetImpl()->inMips16Mode())
410 return llvm::createMips16TargetLowering(TM);
412 return llvm::createMipsSETargetLowering(TM);
415 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
418 return VT.changeVectorElementTypeToInteger();
421 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
422 TargetLowering::DAGCombinerInfo &DCI,
423 const MipsSubtarget *Subtarget) {
424 if (DCI.isBeforeLegalizeOps())
427 EVT Ty = N->getValueType(0);
428 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
429 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
430 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
434 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
435 N->getOperand(0), N->getOperand(1));
436 SDValue InChain = DAG.getEntryNode();
437 SDValue InGlue = DivRem;
440 if (N->hasAnyUseOfValue(0)) {
441 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
443 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
444 InChain = CopyFromLo.getValue(1);
445 InGlue = CopyFromLo.getValue(2);
449 if (N->hasAnyUseOfValue(1)) {
450 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
452 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
458 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
460 default: llvm_unreachable("Unknown fp condition code!");
462 case ISD::SETOEQ: return Mips::FCOND_OEQ;
463 case ISD::SETUNE: return Mips::FCOND_UNE;
465 case ISD::SETOLT: return Mips::FCOND_OLT;
467 case ISD::SETOGT: return Mips::FCOND_OGT;
469 case ISD::SETOLE: return Mips::FCOND_OLE;
471 case ISD::SETOGE: return Mips::FCOND_OGE;
472 case ISD::SETULT: return Mips::FCOND_ULT;
473 case ISD::SETULE: return Mips::FCOND_ULE;
474 case ISD::SETUGT: return Mips::FCOND_UGT;
475 case ISD::SETUGE: return Mips::FCOND_UGE;
476 case ISD::SETUO: return Mips::FCOND_UN;
477 case ISD::SETO: return Mips::FCOND_OR;
479 case ISD::SETONE: return Mips::FCOND_ONE;
480 case ISD::SETUEQ: return Mips::FCOND_UEQ;
485 /// This function returns true if the floating point conditional branches and
486 /// conditional moves which use condition code CC should be inverted.
487 static bool invertFPCondCodeUser(Mips::CondCode CC) {
488 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
491 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
492 "Illegal Condition Code");
497 // Creates and returns an FPCmp node from a setcc node.
498 // Returns Op if setcc is not a floating point comparison.
499 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
500 // must be a SETCC node
501 if (Op.getOpcode() != ISD::SETCC)
504 SDValue LHS = Op.getOperand(0);
506 if (!LHS.getValueType().isFloatingPoint())
509 SDValue RHS = Op.getOperand(1);
512 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
513 // node if necessary.
514 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
516 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
517 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
520 // Creates and returns a CMovFPT/F node.
521 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
522 SDValue False, SDLoc DL) {
523 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
524 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
525 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
527 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
528 True.getValueType(), True, FCC0, False, Cond);
531 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
532 TargetLowering::DAGCombinerInfo &DCI,
533 const MipsSubtarget *Subtarget) {
534 if (DCI.isBeforeLegalizeOps())
537 SDValue SetCC = N->getOperand(0);
539 if ((SetCC.getOpcode() != ISD::SETCC) ||
540 !SetCC.getOperand(0).getValueType().isInteger())
543 SDValue False = N->getOperand(2);
544 EVT FalseTy = False.getValueType();
546 if (!FalseTy.isInteger())
549 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
551 if (!CN || CN->getZExtValue())
555 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
556 SDValue True = N->getOperand(1);
558 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
559 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
561 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
564 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
565 TargetLowering::DAGCombinerInfo &DCI,
566 const MipsSubtarget *Subtarget) {
567 // Pattern match EXT.
568 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
569 // => ext $dst, $src, size, pos
570 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
573 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
574 unsigned ShiftRightOpc = ShiftRight.getOpcode();
576 // Op's first operand must be a shift right.
577 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
580 // The second operand of the shift must be an immediate.
582 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
585 uint64_t Pos = CN->getZExtValue();
586 uint64_t SMPos, SMSize;
588 // Op's second operand must be a shifted mask.
589 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
590 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
593 // Return if the shifted mask does not start at bit 0 or the sum of its size
594 // and Pos exceeds the word's size.
595 EVT ValTy = N->getValueType(0);
596 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
599 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
600 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
601 DAG.getConstant(SMSize, MVT::i32));
604 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
605 TargetLowering::DAGCombinerInfo &DCI,
606 const MipsSubtarget *Subtarget) {
607 // Pattern match INS.
608 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
609 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
610 // => ins $dst, $src, size, pos, $src1
611 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
614 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
615 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
618 // See if Op's first operand matches (and $src1 , mask0).
619 if (And0.getOpcode() != ISD::AND)
622 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
623 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
626 // See if Op's second operand matches (and (shl $src, pos), mask1).
627 if (And1.getOpcode() != ISD::AND)
630 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
631 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
634 // The shift masks must have the same position and size.
635 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
638 SDValue Shl = And1.getOperand(0);
639 if (Shl.getOpcode() != ISD::SHL)
642 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
645 unsigned Shamt = CN->getZExtValue();
647 // Return if the shift amount and the first bit position of mask are not the
649 EVT ValTy = N->getValueType(0);
650 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
653 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
654 DAG.getConstant(SMPos0, MVT::i32),
655 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
658 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
659 TargetLowering::DAGCombinerInfo &DCI,
660 const MipsSubtarget *Subtarget) {
661 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
663 if (DCI.isBeforeLegalizeOps())
666 SDValue Add = N->getOperand(1);
668 if (Add.getOpcode() != ISD::ADD)
671 SDValue Lo = Add.getOperand(1);
673 if ((Lo.getOpcode() != MipsISD::Lo) ||
674 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
677 EVT ValTy = N->getValueType(0);
680 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
682 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
685 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
687 SelectionDAG &DAG = DCI.DAG;
688 unsigned Opc = N->getOpcode();
694 return performDivRemCombine(N, DAG, DCI, Subtarget);
696 return performSELECTCombine(N, DAG, DCI, Subtarget);
698 return performANDCombine(N, DAG, DCI, Subtarget);
700 return performORCombine(N, DAG, DCI, Subtarget);
702 return performADDCombine(N, DAG, DCI, Subtarget);
709 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
710 SmallVectorImpl<SDValue> &Results,
711 SelectionDAG &DAG) const {
712 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
714 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
715 Results.push_back(Res.getValue(I));
719 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
720 SmallVectorImpl<SDValue> &Results,
721 SelectionDAG &DAG) const {
722 return LowerOperationWrapper(N, Results, DAG);
725 SDValue MipsTargetLowering::
726 LowerOperation(SDValue Op, SelectionDAG &DAG) const
728 switch (Op.getOpcode())
730 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
731 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
732 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
733 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
734 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
735 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
736 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
737 case ISD::SELECT: return lowerSELECT(Op, DAG);
738 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
739 case ISD::SETCC: return lowerSETCC(Op, DAG);
740 case ISD::VASTART: return lowerVASTART(Op, DAG);
741 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
742 case ISD::FABS: return lowerFABS(Op, DAG);
743 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
744 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
745 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
746 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
747 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
748 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
749 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
750 case ISD::LOAD: return lowerLOAD(Op, DAG);
751 case ISD::STORE: return lowerSTORE(Op, DAG);
752 case ISD::ADD: return lowerADD(Op, DAG);
753 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
758 //===----------------------------------------------------------------------===//
759 // Lower helper functions
760 //===----------------------------------------------------------------------===//
762 // addLiveIn - This helper function adds the specified physical register to the
763 // MachineFunction as a live in value. It also creates a corresponding
764 // virtual register for it.
766 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
768 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
769 MF.getRegInfo().addLiveIn(PReg, VReg);
773 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
774 MachineBasicBlock &MBB,
775 const TargetInstrInfo &TII,
780 // Insert instruction "teq $divisor_reg, $zero, 7".
781 MachineBasicBlock::iterator I(MI);
782 MachineInstrBuilder MIB;
783 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
784 .addOperand(MI->getOperand(2)).addReg(Mips::ZERO).addImm(7);
786 // Use the 32-bit sub-register if this is a 64-bit division.
788 MIB->getOperand(0).setSubReg(Mips::sub_32);
794 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
795 MachineBasicBlock *BB) const {
796 switch (MI->getOpcode()) {
798 llvm_unreachable("Unexpected instr type to insert");
799 case Mips::ATOMIC_LOAD_ADD_I8:
800 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
801 case Mips::ATOMIC_LOAD_ADD_I16:
802 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
803 case Mips::ATOMIC_LOAD_ADD_I32:
804 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
805 case Mips::ATOMIC_LOAD_ADD_I64:
806 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
808 case Mips::ATOMIC_LOAD_AND_I8:
809 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
810 case Mips::ATOMIC_LOAD_AND_I16:
811 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
812 case Mips::ATOMIC_LOAD_AND_I32:
813 return emitAtomicBinary(MI, BB, 4, Mips::AND);
814 case Mips::ATOMIC_LOAD_AND_I64:
815 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
817 case Mips::ATOMIC_LOAD_OR_I8:
818 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
819 case Mips::ATOMIC_LOAD_OR_I16:
820 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
821 case Mips::ATOMIC_LOAD_OR_I32:
822 return emitAtomicBinary(MI, BB, 4, Mips::OR);
823 case Mips::ATOMIC_LOAD_OR_I64:
824 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
826 case Mips::ATOMIC_LOAD_XOR_I8:
827 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
828 case Mips::ATOMIC_LOAD_XOR_I16:
829 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
830 case Mips::ATOMIC_LOAD_XOR_I32:
831 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
832 case Mips::ATOMIC_LOAD_XOR_I64:
833 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
835 case Mips::ATOMIC_LOAD_NAND_I8:
836 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
837 case Mips::ATOMIC_LOAD_NAND_I16:
838 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
839 case Mips::ATOMIC_LOAD_NAND_I32:
840 return emitAtomicBinary(MI, BB, 4, 0, true);
841 case Mips::ATOMIC_LOAD_NAND_I64:
842 return emitAtomicBinary(MI, BB, 8, 0, true);
844 case Mips::ATOMIC_LOAD_SUB_I8:
845 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
846 case Mips::ATOMIC_LOAD_SUB_I16:
847 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
848 case Mips::ATOMIC_LOAD_SUB_I32:
849 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
850 case Mips::ATOMIC_LOAD_SUB_I64:
851 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
853 case Mips::ATOMIC_SWAP_I8:
854 return emitAtomicBinaryPartword(MI, BB, 1, 0);
855 case Mips::ATOMIC_SWAP_I16:
856 return emitAtomicBinaryPartword(MI, BB, 2, 0);
857 case Mips::ATOMIC_SWAP_I32:
858 return emitAtomicBinary(MI, BB, 4, 0);
859 case Mips::ATOMIC_SWAP_I64:
860 return emitAtomicBinary(MI, BB, 8, 0);
862 case Mips::ATOMIC_CMP_SWAP_I8:
863 return emitAtomicCmpSwapPartword(MI, BB, 1);
864 case Mips::ATOMIC_CMP_SWAP_I16:
865 return emitAtomicCmpSwapPartword(MI, BB, 2);
866 case Mips::ATOMIC_CMP_SWAP_I32:
867 return emitAtomicCmpSwap(MI, BB, 4);
868 case Mips::ATOMIC_CMP_SWAP_I64:
869 return emitAtomicCmpSwap(MI, BB, 8);
870 case Mips::PseudoSDIV:
871 case Mips::PseudoUDIV:
872 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
873 case Mips::PseudoDSDIV:
874 case Mips::PseudoDUDIV:
875 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
879 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
880 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
882 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
883 unsigned Size, unsigned BinOpcode,
885 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
887 MachineFunction *MF = BB->getParent();
888 MachineRegisterInfo &RegInfo = MF->getRegInfo();
889 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
890 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
891 DebugLoc DL = MI->getDebugLoc();
892 unsigned LL, SC, AND, NOR, ZERO, BEQ;
907 ZERO = Mips::ZERO_64;
911 unsigned OldVal = MI->getOperand(0).getReg();
912 unsigned Ptr = MI->getOperand(1).getReg();
913 unsigned Incr = MI->getOperand(2).getReg();
915 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
916 unsigned AndRes = RegInfo.createVirtualRegister(RC);
917 unsigned Success = RegInfo.createVirtualRegister(RC);
919 // insert new blocks after the current block
920 const BasicBlock *LLVM_BB = BB->getBasicBlock();
921 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
922 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
923 MachineFunction::iterator It = BB;
925 MF->insert(It, loopMBB);
926 MF->insert(It, exitMBB);
928 // Transfer the remainder of BB and its successor edges to exitMBB.
929 exitMBB->splice(exitMBB->begin(), BB,
930 llvm::next(MachineBasicBlock::iterator(MI)),
932 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
936 // fallthrough --> loopMBB
937 BB->addSuccessor(loopMBB);
938 loopMBB->addSuccessor(loopMBB);
939 loopMBB->addSuccessor(exitMBB);
943 // <binop> storeval, oldval, incr
944 // sc success, storeval, 0(ptr)
945 // beq success, $0, loopMBB
947 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
949 // and andres, oldval, incr
950 // nor storeval, $0, andres
951 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
952 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
953 } else if (BinOpcode) {
954 // <binop> storeval, oldval, incr
955 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
959 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
960 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
962 MI->eraseFromParent(); // The instruction is gone now.
968 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
969 MachineBasicBlock *BB,
970 unsigned Size, unsigned BinOpcode,
972 assert((Size == 1 || Size == 2) &&
973 "Unsupported size for EmitAtomicBinaryPartial.");
975 MachineFunction *MF = BB->getParent();
976 MachineRegisterInfo &RegInfo = MF->getRegInfo();
977 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
978 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
979 DebugLoc DL = MI->getDebugLoc();
981 unsigned Dest = MI->getOperand(0).getReg();
982 unsigned Ptr = MI->getOperand(1).getReg();
983 unsigned Incr = MI->getOperand(2).getReg();
985 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
986 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
987 unsigned Mask = RegInfo.createVirtualRegister(RC);
988 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
989 unsigned NewVal = RegInfo.createVirtualRegister(RC);
990 unsigned OldVal = RegInfo.createVirtualRegister(RC);
991 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
992 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
993 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
994 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
995 unsigned AndRes = RegInfo.createVirtualRegister(RC);
996 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
997 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
998 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
999 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1000 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1001 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1002 unsigned Success = RegInfo.createVirtualRegister(RC);
1004 // insert new blocks after the current block
1005 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1006 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1007 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1008 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1009 MachineFunction::iterator It = BB;
1011 MF->insert(It, loopMBB);
1012 MF->insert(It, sinkMBB);
1013 MF->insert(It, exitMBB);
1015 // Transfer the remainder of BB and its successor edges to exitMBB.
1016 exitMBB->splice(exitMBB->begin(), BB,
1017 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1018 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1020 BB->addSuccessor(loopMBB);
1021 loopMBB->addSuccessor(loopMBB);
1022 loopMBB->addSuccessor(sinkMBB);
1023 sinkMBB->addSuccessor(exitMBB);
1026 // addiu masklsb2,$0,-4 # 0xfffffffc
1027 // and alignedaddr,ptr,masklsb2
1028 // andi ptrlsb2,ptr,3
1029 // sll shiftamt,ptrlsb2,3
1030 // ori maskupper,$0,255 # 0xff
1031 // sll mask,maskupper,shiftamt
1032 // nor mask2,$0,mask
1033 // sll incr2,incr,shiftamt
1035 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1036 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1037 .addReg(Mips::ZERO).addImm(-4);
1038 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1039 .addReg(Ptr).addReg(MaskLSB2);
1040 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1041 if (Subtarget->isLittle()) {
1042 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1044 unsigned Off = RegInfo.createVirtualRegister(RC);
1045 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1046 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1047 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1049 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1050 .addReg(Mips::ZERO).addImm(MaskImm);
1051 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1052 .addReg(MaskUpper).addReg(ShiftAmt);
1053 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1054 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1056 // atomic.load.binop
1058 // ll oldval,0(alignedaddr)
1059 // binop binopres,oldval,incr2
1060 // and newval,binopres,mask
1061 // and maskedoldval0,oldval,mask2
1062 // or storeval,maskedoldval0,newval
1063 // sc success,storeval,0(alignedaddr)
1064 // beq success,$0,loopMBB
1068 // ll oldval,0(alignedaddr)
1069 // and newval,incr2,mask
1070 // and maskedoldval0,oldval,mask2
1071 // or storeval,maskedoldval0,newval
1072 // sc success,storeval,0(alignedaddr)
1073 // beq success,$0,loopMBB
1076 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1078 // and andres, oldval, incr2
1079 // nor binopres, $0, andres
1080 // and newval, binopres, mask
1081 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1082 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1083 .addReg(Mips::ZERO).addReg(AndRes);
1084 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1085 } else if (BinOpcode) {
1086 // <binop> binopres, oldval, incr2
1087 // and newval, binopres, mask
1088 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1089 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1090 } else {// atomic.swap
1091 // and newval, incr2, mask
1092 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1095 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1096 .addReg(OldVal).addReg(Mask2);
1097 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1098 .addReg(MaskedOldVal0).addReg(NewVal);
1099 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1100 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1101 BuildMI(BB, DL, TII->get(Mips::BEQ))
1102 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1105 // and maskedoldval1,oldval,mask
1106 // srl srlres,maskedoldval1,shiftamt
1107 // sll sllres,srlres,24
1108 // sra dest,sllres,24
1110 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1112 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1113 .addReg(OldVal).addReg(Mask);
1114 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1115 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1116 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1117 .addReg(SrlRes).addImm(ShiftImm);
1118 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1119 .addReg(SllRes).addImm(ShiftImm);
1121 MI->eraseFromParent(); // The instruction is gone now.
1127 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1128 MachineBasicBlock *BB,
1129 unsigned Size) const {
1130 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1132 MachineFunction *MF = BB->getParent();
1133 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1134 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1135 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1136 DebugLoc DL = MI->getDebugLoc();
1137 unsigned LL, SC, ZERO, BNE, BEQ;
1149 ZERO = Mips::ZERO_64;
1154 unsigned Dest = MI->getOperand(0).getReg();
1155 unsigned Ptr = MI->getOperand(1).getReg();
1156 unsigned OldVal = MI->getOperand(2).getReg();
1157 unsigned NewVal = MI->getOperand(3).getReg();
1159 unsigned Success = RegInfo.createVirtualRegister(RC);
1161 // insert new blocks after the current block
1162 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1163 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1164 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1165 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1166 MachineFunction::iterator It = BB;
1168 MF->insert(It, loop1MBB);
1169 MF->insert(It, loop2MBB);
1170 MF->insert(It, exitMBB);
1172 // Transfer the remainder of BB and its successor edges to exitMBB.
1173 exitMBB->splice(exitMBB->begin(), BB,
1174 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1175 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1179 // fallthrough --> loop1MBB
1180 BB->addSuccessor(loop1MBB);
1181 loop1MBB->addSuccessor(exitMBB);
1182 loop1MBB->addSuccessor(loop2MBB);
1183 loop2MBB->addSuccessor(loop1MBB);
1184 loop2MBB->addSuccessor(exitMBB);
1188 // bne dest, oldval, exitMBB
1190 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1191 BuildMI(BB, DL, TII->get(BNE))
1192 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1195 // sc success, newval, 0(ptr)
1196 // beq success, $0, loop1MBB
1198 BuildMI(BB, DL, TII->get(SC), Success)
1199 .addReg(NewVal).addReg(Ptr).addImm(0);
1200 BuildMI(BB, DL, TII->get(BEQ))
1201 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1203 MI->eraseFromParent(); // The instruction is gone now.
1209 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1210 MachineBasicBlock *BB,
1211 unsigned Size) const {
1212 assert((Size == 1 || Size == 2) &&
1213 "Unsupported size for EmitAtomicCmpSwapPartial.");
1215 MachineFunction *MF = BB->getParent();
1216 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1217 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1218 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1219 DebugLoc DL = MI->getDebugLoc();
1221 unsigned Dest = MI->getOperand(0).getReg();
1222 unsigned Ptr = MI->getOperand(1).getReg();
1223 unsigned CmpVal = MI->getOperand(2).getReg();
1224 unsigned NewVal = MI->getOperand(3).getReg();
1226 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1227 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1228 unsigned Mask = RegInfo.createVirtualRegister(RC);
1229 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1230 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1231 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1232 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1233 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1234 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1235 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1236 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1237 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1238 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1239 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1240 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1241 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1242 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1243 unsigned Success = RegInfo.createVirtualRegister(RC);
1245 // insert new blocks after the current block
1246 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1247 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1248 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1249 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1250 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1251 MachineFunction::iterator It = BB;
1253 MF->insert(It, loop1MBB);
1254 MF->insert(It, loop2MBB);
1255 MF->insert(It, sinkMBB);
1256 MF->insert(It, exitMBB);
1258 // Transfer the remainder of BB and its successor edges to exitMBB.
1259 exitMBB->splice(exitMBB->begin(), BB,
1260 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1261 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1263 BB->addSuccessor(loop1MBB);
1264 loop1MBB->addSuccessor(sinkMBB);
1265 loop1MBB->addSuccessor(loop2MBB);
1266 loop2MBB->addSuccessor(loop1MBB);
1267 loop2MBB->addSuccessor(sinkMBB);
1268 sinkMBB->addSuccessor(exitMBB);
1270 // FIXME: computation of newval2 can be moved to loop2MBB.
1272 // addiu masklsb2,$0,-4 # 0xfffffffc
1273 // and alignedaddr,ptr,masklsb2
1274 // andi ptrlsb2,ptr,3
1275 // sll shiftamt,ptrlsb2,3
1276 // ori maskupper,$0,255 # 0xff
1277 // sll mask,maskupper,shiftamt
1278 // nor mask2,$0,mask
1279 // andi maskedcmpval,cmpval,255
1280 // sll shiftedcmpval,maskedcmpval,shiftamt
1281 // andi maskednewval,newval,255
1282 // sll shiftednewval,maskednewval,shiftamt
1283 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1284 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1285 .addReg(Mips::ZERO).addImm(-4);
1286 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1287 .addReg(Ptr).addReg(MaskLSB2);
1288 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1289 if (Subtarget->isLittle()) {
1290 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1292 unsigned Off = RegInfo.createVirtualRegister(RC);
1293 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1294 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1295 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1297 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1298 .addReg(Mips::ZERO).addImm(MaskImm);
1299 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1300 .addReg(MaskUpper).addReg(ShiftAmt);
1301 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1302 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1303 .addReg(CmpVal).addImm(MaskImm);
1304 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1305 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1306 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1307 .addReg(NewVal).addImm(MaskImm);
1308 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1309 .addReg(MaskedNewVal).addReg(ShiftAmt);
1312 // ll oldval,0(alginedaddr)
1313 // and maskedoldval0,oldval,mask
1314 // bne maskedoldval0,shiftedcmpval,sinkMBB
1316 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1317 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1318 .addReg(OldVal).addReg(Mask);
1319 BuildMI(BB, DL, TII->get(Mips::BNE))
1320 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1323 // and maskedoldval1,oldval,mask2
1324 // or storeval,maskedoldval1,shiftednewval
1325 // sc success,storeval,0(alignedaddr)
1326 // beq success,$0,loop1MBB
1328 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1329 .addReg(OldVal).addReg(Mask2);
1330 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1331 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1332 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1333 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1334 BuildMI(BB, DL, TII->get(Mips::BEQ))
1335 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1338 // srl srlres,maskedoldval0,shiftamt
1339 // sll sllres,srlres,24
1340 // sra dest,sllres,24
1342 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1344 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1345 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1346 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1347 .addReg(SrlRes).addImm(ShiftImm);
1348 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1349 .addReg(SllRes).addImm(ShiftImm);
1351 MI->eraseFromParent(); // The instruction is gone now.
1356 //===----------------------------------------------------------------------===//
1357 // Misc Lower Operation implementation
1358 //===----------------------------------------------------------------------===//
1359 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1360 SDValue Chain = Op.getOperand(0);
1361 SDValue Table = Op.getOperand(1);
1362 SDValue Index = Op.getOperand(2);
1364 EVT PTy = getPointerTy();
1365 unsigned EntrySize =
1366 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1368 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1369 DAG.getConstant(EntrySize, PTy));
1370 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1372 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1373 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1374 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1376 Chain = Addr.getValue(1);
1378 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1379 // For PIC, the sequence is:
1380 // BRIND(load(Jumptable + index) + RelocBase)
1381 // RelocBase can be JumpTable, GOT or some sort of global base.
1382 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1383 getPICJumpTableRelocBase(Table, DAG));
1386 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1389 SDValue MipsTargetLowering::
1390 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1392 // The first operand is the chain, the second is the condition, the third is
1393 // the block to branch to if the condition is true.
1394 SDValue Chain = Op.getOperand(0);
1395 SDValue Dest = Op.getOperand(2);
1398 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1400 // Return if flag is not set by a floating point comparison.
1401 if (CondRes.getOpcode() != MipsISD::FPCmp)
1404 SDValue CCNode = CondRes.getOperand(2);
1406 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1407 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1408 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1409 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1410 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1411 FCC0, Dest, CondRes);
1414 SDValue MipsTargetLowering::
1415 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1417 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1419 // Return if flag is not set by a floating point comparison.
1420 if (Cond.getOpcode() != MipsISD::FPCmp)
1423 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1427 SDValue MipsTargetLowering::
1428 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1431 EVT Ty = Op.getOperand(0).getValueType();
1432 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1433 getSetCCResultType(*DAG.getContext(), Ty),
1434 Op.getOperand(0), Op.getOperand(1),
1437 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1441 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1442 SDValue Cond = createFPCmp(DAG, Op);
1444 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1445 "Floating point operand expected.");
1447 SDValue True = DAG.getConstant(1, MVT::i32);
1448 SDValue False = DAG.getConstant(0, MVT::i32);
1450 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1453 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1454 SelectionDAG &DAG) const {
1455 // FIXME there isn't actually debug info here
1457 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1459 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1460 const MipsTargetObjectFile &TLOF =
1461 (const MipsTargetObjectFile&)getObjFileLowering();
1463 // %gp_rel relocation
1464 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1465 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1467 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1468 DAG.getVTList(MVT::i32), &GA, 1);
1469 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1470 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1473 // %hi/%lo relocation
1474 return getAddrNonPIC(Op, DAG);
1477 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1478 return getAddrLocal(Op, DAG, HasMips64);
1481 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1482 MipsII::MO_GOT_LO16);
1484 return getAddrGlobal(Op, DAG,
1485 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1488 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1489 SelectionDAG &DAG) const {
1490 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1491 return getAddrNonPIC(Op, DAG);
1493 return getAddrLocal(Op, DAG, HasMips64);
1496 SDValue MipsTargetLowering::
1497 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1499 // If the relocation model is PIC, use the General Dynamic TLS Model or
1500 // Local Dynamic TLS model, otherwise use the Initial Exec or
1501 // Local Exec TLS Model.
1503 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1505 const GlobalValue *GV = GA->getGlobal();
1506 EVT PtrVT = getPointerTy();
1508 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1510 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1511 // General Dynamic and Local Dynamic TLS Model.
1512 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1515 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1516 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1517 getGlobalReg(DAG, PtrVT), TGA);
1518 unsigned PtrSize = PtrVT.getSizeInBits();
1519 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1521 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1525 Entry.Node = Argument;
1527 Args.push_back(Entry);
1529 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1530 false, false, false, false, 0, CallingConv::C,
1531 /*IsTailCall=*/false, /*doesNotRet=*/false,
1532 /*isReturnValueUsed=*/true,
1533 TlsGetAddr, Args, DAG, DL);
1534 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1536 SDValue Ret = CallResult.first;
1538 if (model != TLSModel::LocalDynamic)
1541 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1542 MipsII::MO_DTPREL_HI);
1543 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1544 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1545 MipsII::MO_DTPREL_LO);
1546 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1547 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1548 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1552 if (model == TLSModel::InitialExec) {
1553 // Initial Exec TLS Model
1554 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1555 MipsII::MO_GOTTPREL);
1556 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1558 Offset = DAG.getLoad(PtrVT, DL,
1559 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1560 false, false, false, 0);
1562 // Local Exec TLS Model
1563 assert(model == TLSModel::LocalExec);
1564 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1565 MipsII::MO_TPREL_HI);
1566 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1567 MipsII::MO_TPREL_LO);
1568 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1569 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1570 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1573 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1574 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1577 SDValue MipsTargetLowering::
1578 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1580 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1581 return getAddrNonPIC(Op, DAG);
1583 return getAddrLocal(Op, DAG, HasMips64);
1586 SDValue MipsTargetLowering::
1587 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1589 // gp_rel relocation
1590 // FIXME: we should reference the constant pool using small data sections,
1591 // but the asm printer currently doesn't support this feature without
1592 // hacking it. This feature should come soon so we can uncomment the
1594 //if (IsInSmallSection(C->getType())) {
1595 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1596 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1597 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1599 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1600 return getAddrNonPIC(Op, DAG);
1602 return getAddrLocal(Op, DAG, HasMips64);
1605 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1606 MachineFunction &MF = DAG.getMachineFunction();
1607 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1610 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1613 // vastart just stores the address of the VarArgsFrameIndex slot into the
1614 // memory location argument.
1615 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1616 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1617 MachinePointerInfo(SV), false, false, 0);
1620 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1621 EVT TyX = Op.getOperand(0).getValueType();
1622 EVT TyY = Op.getOperand(1).getValueType();
1623 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1624 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1628 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1630 SDValue X = (TyX == MVT::f32) ?
1631 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1632 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1634 SDValue Y = (TyY == MVT::f32) ?
1635 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1636 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1640 // ext E, Y, 31, 1 ; extract bit31 of Y
1641 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1642 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1643 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1646 // srl SrlX, SllX, 1
1648 // sll SllY, SrlX, 31
1649 // or Or, SrlX, SllY
1650 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1651 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1652 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1653 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1654 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1657 if (TyX == MVT::f32)
1658 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1660 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1661 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1662 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1665 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1666 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1667 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1668 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1669 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1672 // Bitcast to integer nodes.
1673 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1674 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1677 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1678 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1679 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1680 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1682 if (WidthX > WidthY)
1683 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1684 else if (WidthY > WidthX)
1685 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1687 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1688 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1689 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1692 // (d)sll SllX, X, 1
1693 // (d)srl SrlX, SllX, 1
1694 // (d)srl SrlY, Y, width(Y)-1
1695 // (d)sll SllY, SrlX, width(Y)-1
1696 // or Or, SrlX, SllY
1697 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1698 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1699 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1700 DAG.getConstant(WidthY - 1, MVT::i32));
1702 if (WidthX > WidthY)
1703 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1704 else if (WidthY > WidthX)
1705 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1707 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1708 DAG.getConstant(WidthX - 1, MVT::i32));
1709 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1710 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1714 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1715 if (Subtarget->hasMips64())
1716 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1718 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1721 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1722 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1725 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1727 SDValue X = (Op.getValueType() == MVT::f32) ?
1728 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1729 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1734 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1735 DAG.getRegister(Mips::ZERO, MVT::i32),
1736 DAG.getConstant(31, MVT::i32), Const1, X);
1738 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1739 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1742 if (Op.getValueType() == MVT::f32)
1743 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1745 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1746 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1747 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1750 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1751 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1754 // Bitcast to integer node.
1755 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1759 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1760 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1761 DAG.getConstant(63, MVT::i32), Const1, X);
1763 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1764 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1767 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1771 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1772 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1773 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1775 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1778 SDValue MipsTargetLowering::
1779 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1781 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1782 "Frame address can only be determined for current frame.");
1784 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1785 MFI->setFrameAddressIsTaken(true);
1786 EVT VT = Op.getValueType();
1788 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1789 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1793 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1794 SelectionDAG &DAG) const {
1796 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1797 "Return address can be determined only for current frame.");
1799 MachineFunction &MF = DAG.getMachineFunction();
1800 MachineFrameInfo *MFI = MF.getFrameInfo();
1801 MVT VT = Op.getSimpleValueType();
1802 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1803 MFI->setReturnAddressIsTaken(true);
1805 // Return RA, which contains the return address. Mark it an implicit live-in.
1806 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1807 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1810 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1811 // generated from __builtin_eh_return (offset, handler)
1812 // The effect of this is to adjust the stack pointer by "offset"
1813 // and then branch to "handler".
1814 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1816 MachineFunction &MF = DAG.getMachineFunction();
1817 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1819 MipsFI->setCallsEhReturn();
1820 SDValue Chain = Op.getOperand(0);
1821 SDValue Offset = Op.getOperand(1);
1822 SDValue Handler = Op.getOperand(2);
1824 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1826 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1827 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1828 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1829 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1830 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1831 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1832 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1833 DAG.getRegister(OffsetReg, Ty),
1834 DAG.getRegister(AddrReg, getPointerTy()),
1838 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1839 SelectionDAG &DAG) const {
1840 // FIXME: Need pseudo-fence for 'singlethread' fences
1841 // FIXME: Set SType for weaker fences where supported/appropriate.
1844 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1845 DAG.getConstant(SType, MVT::i32));
1848 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1849 SelectionDAG &DAG) const {
1851 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1852 SDValue Shamt = Op.getOperand(2);
1855 // lo = (shl lo, shamt)
1856 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1859 // hi = (shl lo, shamt[4:0])
1860 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1861 DAG.getConstant(-1, MVT::i32));
1862 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1863 DAG.getConstant(1, MVT::i32));
1864 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1866 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1867 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1868 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1869 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1870 DAG.getConstant(0x20, MVT::i32));
1871 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1872 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1873 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1875 SDValue Ops[2] = {Lo, Hi};
1876 return DAG.getMergeValues(Ops, 2, DL);
1879 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1882 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1883 SDValue Shamt = Op.getOperand(2);
1886 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1888 // hi = (sra hi, shamt)
1890 // hi = (srl hi, shamt)
1893 // lo = (sra hi, shamt[4:0])
1894 // hi = (sra hi, 31)
1896 // lo = (srl hi, shamt[4:0])
1898 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1899 DAG.getConstant(-1, MVT::i32));
1900 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1901 DAG.getConstant(1, MVT::i32));
1902 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1903 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1904 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1905 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1907 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1908 DAG.getConstant(0x20, MVT::i32));
1909 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1910 DAG.getConstant(31, MVT::i32));
1911 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1912 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1913 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1916 SDValue Ops[2] = {Lo, Hi};
1917 return DAG.getMergeValues(Ops, 2, DL);
1920 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1921 SDValue Chain, SDValue Src, unsigned Offset) {
1922 SDValue Ptr = LD->getBasePtr();
1923 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1924 EVT BasePtrVT = Ptr.getValueType();
1926 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1929 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1930 DAG.getConstant(Offset, BasePtrVT));
1932 SDValue Ops[] = { Chain, Ptr, Src };
1933 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1934 LD->getMemOperand());
1937 // Expand an unaligned 32 or 64-bit integer load node.
1938 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1939 LoadSDNode *LD = cast<LoadSDNode>(Op);
1940 EVT MemVT = LD->getMemoryVT();
1942 // Return if load is aligned or if MemVT is neither i32 nor i64.
1943 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1944 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1947 bool IsLittle = Subtarget->isLittle();
1948 EVT VT = Op.getValueType();
1949 ISD::LoadExtType ExtType = LD->getExtensionType();
1950 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1952 assert((VT == MVT::i32) || (VT == MVT::i64));
1955 // (set dst, (i64 (load baseptr)))
1957 // (set tmp, (ldl (add baseptr, 7), undef))
1958 // (set dst, (ldr baseptr, tmp))
1959 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1960 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1962 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1966 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1968 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1972 // (set dst, (i32 (load baseptr))) or
1973 // (set dst, (i64 (sextload baseptr))) or
1974 // (set dst, (i64 (extload baseptr)))
1976 // (set tmp, (lwl (add baseptr, 3), undef))
1977 // (set dst, (lwr baseptr, tmp))
1978 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1979 (ExtType == ISD::EXTLOAD))
1982 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1985 // (set dst, (i64 (zextload baseptr)))
1987 // (set tmp0, (lwl (add baseptr, 3), undef))
1988 // (set tmp1, (lwr baseptr, tmp0))
1989 // (set tmp2, (shl tmp1, 32))
1990 // (set dst, (srl tmp2, 32))
1992 SDValue Const32 = DAG.getConstant(32, MVT::i32);
1993 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1994 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
1995 SDValue Ops[] = { SRL, LWR.getValue(1) };
1996 return DAG.getMergeValues(Ops, 2, DL);
1999 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2000 SDValue Chain, unsigned Offset) {
2001 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2002 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2004 SDVTList VTList = DAG.getVTList(MVT::Other);
2007 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2008 DAG.getConstant(Offset, BasePtrVT));
2010 SDValue Ops[] = { Chain, Value, Ptr };
2011 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2012 SD->getMemOperand());
2015 // Expand an unaligned 32 or 64-bit integer store node.
2016 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2018 SDValue Value = SD->getValue(), Chain = SD->getChain();
2019 EVT VT = Value.getValueType();
2022 // (store val, baseptr) or
2023 // (truncstore val, baseptr)
2025 // (swl val, (add baseptr, 3))
2026 // (swr val, baseptr)
2027 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2028 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2030 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2033 assert(VT == MVT::i64);
2036 // (store val, baseptr)
2038 // (sdl val, (add baseptr, 7))
2039 // (sdr val, baseptr)
2040 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2041 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2044 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2045 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2046 SDValue Val = SD->getValue();
2048 if (Val.getOpcode() != ISD::FP_TO_SINT)
2051 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2052 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2055 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2056 SD->getPointerInfo(), SD->isVolatile(),
2057 SD->isNonTemporal(), SD->getAlignment());
2060 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2061 StoreSDNode *SD = cast<StoreSDNode>(Op);
2062 EVT MemVT = SD->getMemoryVT();
2064 // Lower unaligned integer stores.
2065 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2066 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2067 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2069 return lowerFP_TO_SINT_STORE(SD, DAG);
2072 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2073 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2074 || cast<ConstantSDNode>
2075 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2076 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2080 // (add (frameaddr 0), (frame_to_args_offset))
2081 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2082 // (add FrameObject, 0)
2083 // where FrameObject is a fixed StackObject with offset 0 which points to
2084 // the old stack pointer.
2085 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2086 EVT ValTy = Op->getValueType(0);
2087 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2088 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2089 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2090 DAG.getConstant(0, ValTy));
2093 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2094 SelectionDAG &DAG) const {
2095 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2096 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2098 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2101 //===----------------------------------------------------------------------===//
2102 // Calling Convention Implementation
2103 //===----------------------------------------------------------------------===//
2105 //===----------------------------------------------------------------------===//
2106 // TODO: Implement a generic logic using tblgen that can support this.
2107 // Mips O32 ABI rules:
2109 // i32 - Passed in A0, A1, A2, A3 and stack
2110 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2111 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2112 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2113 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2114 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2117 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2118 //===----------------------------------------------------------------------===//
2120 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2121 MVT LocVT, CCValAssign::LocInfo LocInfo,
2122 ISD::ArgFlagsTy ArgFlags, CCState &State,
2123 const uint16_t *F64Regs) {
2125 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2127 static const uint16_t IntRegs[] = {
2128 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2130 static const uint16_t F32Regs[] = {
2131 Mips::F12, Mips::F14
2134 // Do not process byval args here.
2135 if (ArgFlags.isByVal())
2138 // Promote i8 and i16
2139 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2141 if (ArgFlags.isSExt())
2142 LocInfo = CCValAssign::SExt;
2143 else if (ArgFlags.isZExt())
2144 LocInfo = CCValAssign::ZExt;
2146 LocInfo = CCValAssign::AExt;
2151 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2152 // is true: function is vararg, argument is 3rd or higher, there is previous
2153 // argument which is not f32 or f64.
2154 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2155 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2156 unsigned OrigAlign = ArgFlags.getOrigAlign();
2157 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2159 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2160 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2161 // If this is the first part of an i64 arg,
2162 // the allocated register must be either A0 or A2.
2163 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2164 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2166 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2167 // Allocate int register and shadow next int register. If first
2168 // available register is Mips::A1 or Mips::A3, shadow it too.
2169 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2170 if (Reg == Mips::A1 || Reg == Mips::A3)
2171 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2172 State.AllocateReg(IntRegs, IntRegsSize);
2174 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2175 // we are guaranteed to find an available float register
2176 if (ValVT == MVT::f32) {
2177 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2178 // Shadow int register
2179 State.AllocateReg(IntRegs, IntRegsSize);
2181 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2182 // Shadow int registers
2183 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2184 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2185 State.AllocateReg(IntRegs, IntRegsSize);
2186 State.AllocateReg(IntRegs, IntRegsSize);
2189 llvm_unreachable("Cannot handle this ValVT.");
2192 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2194 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2196 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2201 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2202 MVT LocVT, CCValAssign::LocInfo LocInfo,
2203 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2204 static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2206 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2209 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2210 MVT LocVT, CCValAssign::LocInfo LocInfo,
2211 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2212 static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D12_64 };
2214 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2217 #include "MipsGenCallingConv.inc"
2219 //===----------------------------------------------------------------------===//
2220 // Call Calling Convention Implementation
2221 //===----------------------------------------------------------------------===//
2223 static const unsigned O32IntRegsSize = 4;
2225 // Return next O32 integer argument register.
2226 static unsigned getNextIntArgReg(unsigned Reg) {
2227 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2228 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2232 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2233 SDValue Chain, SDValue Arg, SDLoc DL,
2234 bool IsTailCall, SelectionDAG &DAG) const {
2236 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2237 DAG.getIntPtrConstant(Offset));
2238 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2242 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2243 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2244 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2245 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2246 /*isVolatile=*/ true, false, 0);
2249 void MipsTargetLowering::
2250 getOpndList(SmallVectorImpl<SDValue> &Ops,
2251 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2252 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2253 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2254 // Insert node "GP copy globalreg" before call to function.
2256 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2257 // in PIC mode) allow symbols to be resolved via lazy binding.
2258 // The lazy binding stub requires GP to point to the GOT.
2259 if (IsPICCall && !InternalLinkage) {
2260 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2261 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2262 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2265 // Build a sequence of copy-to-reg nodes chained together with token
2266 // chain and flag operands which copy the outgoing args into registers.
2267 // The InFlag in necessary since all emitted instructions must be
2271 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2272 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2273 RegsToPass[i].second, InFlag);
2274 InFlag = Chain.getValue(1);
2277 // Add argument registers to the end of the list so that they are
2278 // known live into the call.
2279 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2280 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2281 RegsToPass[i].second.getValueType()));
2283 // Add a register mask operand representing the call-preserved registers.
2284 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2285 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2286 assert(Mask && "Missing call preserved mask for calling convention");
2287 if (Subtarget->inMips16HardFloat()) {
2288 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2289 llvm::StringRef Sym = G->getGlobal()->getName();
2290 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2291 if (F->hasFnAttribute("__Mips16RetHelper")) {
2292 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2296 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2298 if (InFlag.getNode())
2299 Ops.push_back(InFlag);
2302 /// LowerCall - functions arguments are copied from virtual regs to
2303 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2305 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2306 SmallVectorImpl<SDValue> &InVals) const {
2307 SelectionDAG &DAG = CLI.DAG;
2309 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2310 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2311 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2312 SDValue Chain = CLI.Chain;
2313 SDValue Callee = CLI.Callee;
2314 bool &IsTailCall = CLI.IsTailCall;
2315 CallingConv::ID CallConv = CLI.CallConv;
2316 bool IsVarArg = CLI.IsVarArg;
2318 MachineFunction &MF = DAG.getMachineFunction();
2319 MachineFrameInfo *MFI = MF.getFrameInfo();
2320 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2321 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2323 // Analyze operands of the call, assigning locations to each operand.
2324 SmallVector<CCValAssign, 16> ArgLocs;
2325 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2326 getTargetMachine(), ArgLocs, *DAG.getContext());
2327 MipsCC::SpecialCallingConvType SpecialCallingConv =
2328 getSpecialCallingConv(Callee);
2329 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2330 SpecialCallingConv);
2332 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2333 getTargetMachine().Options.UseSoftFloat,
2334 Callee.getNode(), CLI.Args);
2336 // Get a count of how many bytes are to be pushed on the stack.
2337 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2339 // Check if it's really possible to do a tail call.
2342 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2343 *MF.getInfo<MipsFunctionInfo>());
2348 // Chain is the output chain of the last Load/Store or CopyToReg node.
2349 // ByValChain is the output chain of the last Memcpy node created for copying
2350 // byval arguments to the stack.
2351 unsigned StackAlignment = TFL->getStackAlignment();
2352 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2353 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2356 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2358 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2359 IsN64 ? Mips::SP_64 : Mips::SP,
2362 // With EABI is it possible to have 16 args on registers.
2363 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2364 SmallVector<SDValue, 8> MemOpChains;
2365 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2367 // Walk the register/memloc assignments, inserting copies/loads.
2368 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2369 SDValue Arg = OutVals[i];
2370 CCValAssign &VA = ArgLocs[i];
2371 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2372 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2375 if (Flags.isByVal()) {
2376 assert(Flags.getByValSize() &&
2377 "ByVal args of size 0 should have been ignored by front-end.");
2378 assert(ByValArg != MipsCCInfo.byval_end());
2379 assert(!IsTailCall &&
2380 "Do not tail-call optimize if there is a byval argument.");
2381 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2382 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2387 // Promote the value if needed.
2388 switch (VA.getLocInfo()) {
2389 default: llvm_unreachable("Unknown loc info!");
2390 case CCValAssign::Full:
2391 if (VA.isRegLoc()) {
2392 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2393 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2394 (ValVT == MVT::i64 && LocVT == MVT::f64))
2395 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2396 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2397 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2398 Arg, DAG.getConstant(0, MVT::i32));
2399 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2400 Arg, DAG.getConstant(1, MVT::i32));
2401 if (!Subtarget->isLittle())
2403 unsigned LocRegLo = VA.getLocReg();
2404 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2405 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2406 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2411 case CCValAssign::SExt:
2412 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2414 case CCValAssign::ZExt:
2415 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2417 case CCValAssign::AExt:
2418 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2422 // Arguments that can be passed on register must be kept at
2423 // RegsToPass vector
2424 if (VA.isRegLoc()) {
2425 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2429 // Register can't get to this point...
2430 assert(VA.isMemLoc());
2432 // emit ISD::STORE whichs stores the
2433 // parameter value to a stack Location
2434 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2435 Chain, Arg, DL, IsTailCall, DAG));
2438 // Transform all store nodes into one single node because all store
2439 // nodes are independent of each other.
2440 if (!MemOpChains.empty())
2441 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2442 &MemOpChains[0], MemOpChains.size());
2444 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2445 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2446 // node so that legalize doesn't hack it.
2447 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2448 bool GlobalOrExternal = false, InternalLinkage = false;
2451 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2453 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2455 if (InternalLinkage)
2456 Callee = getAddrLocal(Callee, DAG, HasMips64);
2458 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2459 MipsII::MO_CALL_LO16);
2461 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2463 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2464 MipsII::MO_NO_FLAG);
2465 GlobalOrExternal = true;
2467 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2468 if (!IsN64 && !IsPIC) // !N64 && static
2469 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2470 MipsII::MO_NO_FLAG);
2472 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2473 MipsII::MO_CALL_LO16);
2475 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2477 GlobalOrExternal = true;
2480 SmallVector<SDValue, 8> Ops(1, Chain);
2481 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2483 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2484 CLI, Callee, Chain);
2487 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2489 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2490 SDValue InFlag = Chain.getValue(1);
2492 // Create the CALLSEQ_END node.
2493 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2494 DAG.getIntPtrConstant(0, true), InFlag, DL);
2495 InFlag = Chain.getValue(1);
2497 // Handle result values, copying them out of physregs into vregs that we
2499 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2500 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2503 /// LowerCallResult - Lower the result values of a call into the
2504 /// appropriate copies out of appropriate physical registers.
2506 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2507 CallingConv::ID CallConv, bool IsVarArg,
2508 const SmallVectorImpl<ISD::InputArg> &Ins,
2509 SDLoc DL, SelectionDAG &DAG,
2510 SmallVectorImpl<SDValue> &InVals,
2511 const SDNode *CallNode,
2512 const Type *RetTy) const {
2513 // Assign locations to each value returned by this call.
2514 SmallVector<CCValAssign, 16> RVLocs;
2515 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2516 getTargetMachine(), RVLocs, *DAG.getContext());
2517 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2519 MipsCCInfo.analyzeCallResult(Ins, getTargetMachine().Options.UseSoftFloat,
2522 // Copy all of the result registers out of their specified physreg.
2523 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2524 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2525 RVLocs[i].getLocVT(), InFlag);
2526 Chain = Val.getValue(1);
2527 InFlag = Val.getValue(2);
2529 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2530 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2532 InVals.push_back(Val);
2538 //===----------------------------------------------------------------------===//
2539 // Formal Arguments Calling Convention Implementation
2540 //===----------------------------------------------------------------------===//
2541 /// LowerFormalArguments - transform physical registers into virtual registers
2542 /// and generate load operations for arguments places on the stack.
2544 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2545 CallingConv::ID CallConv,
2547 const SmallVectorImpl<ISD::InputArg> &Ins,
2548 SDLoc DL, SelectionDAG &DAG,
2549 SmallVectorImpl<SDValue> &InVals)
2551 MachineFunction &MF = DAG.getMachineFunction();
2552 MachineFrameInfo *MFI = MF.getFrameInfo();
2553 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2555 MipsFI->setVarArgsFrameIndex(0);
2557 // Used with vargs to acumulate store chains.
2558 std::vector<SDValue> OutChains;
2560 // Assign locations to all of the incoming arguments.
2561 SmallVector<CCValAssign, 16> ArgLocs;
2562 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2563 getTargetMachine(), ArgLocs, *DAG.getContext());
2564 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2565 Function::const_arg_iterator FuncArg =
2566 DAG.getMachineFunction().getFunction()->arg_begin();
2567 bool UseSoftFloat = getTargetMachine().Options.UseSoftFloat;
2569 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2570 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2571 MipsCCInfo.hasByValArg());
2573 unsigned CurArgIdx = 0;
2574 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2576 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2577 CCValAssign &VA = ArgLocs[i];
2578 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2579 CurArgIdx = Ins[i].OrigArgIndex;
2580 EVT ValVT = VA.getValVT();
2581 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2582 bool IsRegLoc = VA.isRegLoc();
2584 if (Flags.isByVal()) {
2585 assert(Flags.getByValSize() &&
2586 "ByVal args of size 0 should have been ignored by front-end.");
2587 assert(ByValArg != MipsCCInfo.byval_end());
2588 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2589 MipsCCInfo, *ByValArg);
2594 // Arguments stored on registers
2596 EVT RegVT = VA.getLocVT();
2597 unsigned ArgReg = VA.getLocReg();
2598 const TargetRegisterClass *RC;
2600 if (RegVT == MVT::i32)
2601 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2602 &Mips::GPR32RegClass;
2603 else if (RegVT == MVT::i64)
2604 RC = &Mips::GPR64RegClass;
2605 else if (RegVT == MVT::f32)
2606 RC = &Mips::FGR32RegClass;
2607 else if (RegVT == MVT::f64)
2608 RC = Subtarget->isFP64bit() ? &Mips::FGR64RegClass :
2609 &Mips::AFGR64RegClass;
2611 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2613 // Transform the arguments stored on
2614 // physical registers into virtual ones
2615 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2616 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2618 // If this is an 8 or 16-bit value, it has been passed promoted
2619 // to 32 bits. Insert an assert[sz]ext to capture this, then
2620 // truncate to the right size.
2621 if (VA.getLocInfo() != CCValAssign::Full) {
2622 unsigned Opcode = 0;
2623 if (VA.getLocInfo() == CCValAssign::SExt)
2624 Opcode = ISD::AssertSext;
2625 else if (VA.getLocInfo() == CCValAssign::ZExt)
2626 Opcode = ISD::AssertZext;
2628 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2629 DAG.getValueType(ValVT));
2630 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2633 // Handle floating point arguments passed in integer registers and
2634 // long double arguments passed in floating point registers.
2635 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2636 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2637 (RegVT == MVT::f64 && ValVT == MVT::i64))
2638 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2639 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2640 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2641 getNextIntArgReg(ArgReg), RC);
2642 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2643 if (!Subtarget->isLittle())
2644 std::swap(ArgValue, ArgValue2);
2645 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2646 ArgValue, ArgValue2);
2649 InVals.push_back(ArgValue);
2650 } else { // VA.isRegLoc()
2653 assert(VA.isMemLoc());
2655 // The stack pointer offset is relative to the caller stack frame.
2656 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2657 VA.getLocMemOffset(), true);
2659 // Create load nodes to retrieve arguments from the stack
2660 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2661 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2662 MachinePointerInfo::getFixedStack(FI),
2663 false, false, false, 0));
2667 // The mips ABIs for returning structs by value requires that we copy
2668 // the sret argument into $v0 for the return. Save the argument into
2669 // a virtual register so that we can access it from the return points.
2670 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2671 unsigned Reg = MipsFI->getSRetReturnReg();
2673 Reg = MF.getRegInfo().
2674 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2675 MipsFI->setSRetReturnReg(Reg);
2677 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2678 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2682 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2684 // All stores are grouped in one node to allow the matching between
2685 // the size of Ins and InVals. This only happens when on varg functions
2686 if (!OutChains.empty()) {
2687 OutChains.push_back(Chain);
2688 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2689 &OutChains[0], OutChains.size());
2695 //===----------------------------------------------------------------------===//
2696 // Return Value Calling Convention Implementation
2697 //===----------------------------------------------------------------------===//
2700 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2701 MachineFunction &MF, bool IsVarArg,
2702 const SmallVectorImpl<ISD::OutputArg> &Outs,
2703 LLVMContext &Context) const {
2704 SmallVector<CCValAssign, 16> RVLocs;
2705 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2707 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2711 MipsTargetLowering::LowerReturn(SDValue Chain,
2712 CallingConv::ID CallConv, bool IsVarArg,
2713 const SmallVectorImpl<ISD::OutputArg> &Outs,
2714 const SmallVectorImpl<SDValue> &OutVals,
2715 SDLoc DL, SelectionDAG &DAG) const {
2716 // CCValAssign - represent the assignment of
2717 // the return value to a location
2718 SmallVector<CCValAssign, 16> RVLocs;
2719 MachineFunction &MF = DAG.getMachineFunction();
2721 // CCState - Info about the registers and stack slot.
2722 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2724 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2726 // Analyze return values.
2727 MipsCCInfo.analyzeReturn(Outs, getTargetMachine().Options.UseSoftFloat,
2728 MF.getFunction()->getReturnType());
2731 SmallVector<SDValue, 4> RetOps(1, Chain);
2733 // Copy the result values into the output registers.
2734 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2735 SDValue Val = OutVals[i];
2736 CCValAssign &VA = RVLocs[i];
2737 assert(VA.isRegLoc() && "Can only return in registers!");
2739 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2740 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2742 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2744 // Guarantee that all emitted copies are stuck together with flags.
2745 Flag = Chain.getValue(1);
2746 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2749 // The mips ABIs for returning structs by value requires that we copy
2750 // the sret argument into $v0 for the return. We saved the argument into
2751 // a virtual register in the entry block, so now we copy the value out
2753 if (MF.getFunction()->hasStructRetAttr()) {
2754 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2755 unsigned Reg = MipsFI->getSRetReturnReg();
2758 llvm_unreachable("sret virtual register not created in the entry block");
2759 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2760 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2762 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2763 Flag = Chain.getValue(1);
2764 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2767 RetOps[0] = Chain; // Update chain.
2769 // Add the flag if we have it.
2771 RetOps.push_back(Flag);
2773 // Return on Mips is always a "jr $ra"
2774 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2777 //===----------------------------------------------------------------------===//
2778 // Mips Inline Assembly Support
2779 //===----------------------------------------------------------------------===//
2781 /// getConstraintType - Given a constraint letter, return the type of
2782 /// constraint it is for this target.
2783 MipsTargetLowering::ConstraintType MipsTargetLowering::
2784 getConstraintType(const std::string &Constraint) const
2786 // Mips specific constrainy
2787 // GCC config/mips/constraints.md
2789 // 'd' : An address register. Equivalent to r
2790 // unless generating MIPS16 code.
2791 // 'y' : Equivalent to r; retained for
2792 // backwards compatibility.
2793 // 'c' : A register suitable for use in an indirect
2794 // jump. This will always be $25 for -mabicalls.
2795 // 'l' : The lo register. 1 word storage.
2796 // 'x' : The hilo register pair. Double word storage.
2797 if (Constraint.size() == 1) {
2798 switch (Constraint[0]) {
2806 return C_RegisterClass;
2811 return TargetLowering::getConstraintType(Constraint);
2814 /// Examine constraint type and operand type and determine a weight value.
2815 /// This object must already have been set up with the operand type
2816 /// and the current alternative constraint selected.
2817 TargetLowering::ConstraintWeight
2818 MipsTargetLowering::getSingleConstraintMatchWeight(
2819 AsmOperandInfo &info, const char *constraint) const {
2820 ConstraintWeight weight = CW_Invalid;
2821 Value *CallOperandVal = info.CallOperandVal;
2822 // If we don't have a value, we can't do a match,
2823 // but allow it at the lowest weight.
2824 if (CallOperandVal == NULL)
2826 Type *type = CallOperandVal->getType();
2827 // Look at the constraint type.
2828 switch (*constraint) {
2830 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2834 if (type->isIntegerTy())
2835 weight = CW_Register;
2838 if (type->isFloatTy())
2839 weight = CW_Register;
2841 case 'c': // $25 for indirect jumps
2842 case 'l': // lo register
2843 case 'x': // hilo register pair
2844 if (type->isIntegerTy())
2845 weight = CW_SpecificReg;
2847 case 'I': // signed 16 bit immediate
2848 case 'J': // integer zero
2849 case 'K': // unsigned 16 bit immediate
2850 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2851 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2852 case 'O': // signed 15 bit immediate (+- 16383)
2853 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2854 if (isa<ConstantInt>(CallOperandVal))
2855 weight = CW_Constant;
2864 /// This is a helper function to parse a physical register string and split it
2865 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2866 /// that is returned indicates whether parsing was successful. The second flag
2867 /// is true if the numeric part exists.
2868 static std::pair<bool, bool>
2869 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2870 unsigned long long &Reg) {
2871 if (C.front() != '{' || C.back() != '}')
2872 return std::make_pair(false, false);
2874 // Search for the first numeric character.
2875 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2876 I = std::find_if(B, E, std::ptr_fun(isdigit));
2878 Prefix.assign(B, I - B);
2880 // The second flag is set to false if no numeric characters were found.
2882 return std::make_pair(true, false);
2884 // Parse the numeric characters.
2885 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2889 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2890 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2891 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2892 const TargetRegisterClass *RC;
2894 unsigned long long Reg;
2896 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2899 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2901 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2902 // No numeric characters follow "hi" or "lo".
2904 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2906 RC = TRI->getRegClass(Prefix == "hi" ?
2907 Mips::HI32RegClassID : Mips::LO32RegClassID);
2908 return std::make_pair(*(RC->begin()), RC);
2912 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2914 if (Prefix == "$f") { // Parse $f0-$f31.
2915 // If the size of FP registers is 64-bit or Reg is an even number, select
2916 // the 64-bit register class. Otherwise, select the 32-bit register class.
2917 if (VT == MVT::Other)
2918 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2920 RC= getRegClassFor(VT);
2922 if (RC == &Mips::AFGR64RegClass) {
2923 assert(Reg % 2 == 0);
2926 } else if (Prefix == "$fcc") { // Parse $fcc0-$fcc7.
2927 RC = TRI->getRegClass(Mips::FCCRegClassID);
2928 } else { // Parse $0-$31.
2929 assert(Prefix == "$");
2930 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2933 assert(Reg < RC->getNumRegs());
2934 return std::make_pair(*(RC->begin() + Reg), RC);
2937 /// Given a register class constraint, like 'r', if this corresponds directly
2938 /// to an LLVM register class, return a register of 0 and the register class
2940 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2941 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2943 if (Constraint.size() == 1) {
2944 switch (Constraint[0]) {
2945 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2946 case 'y': // Same as 'r'. Exists for compatibility.
2948 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2949 if (Subtarget->inMips16Mode())
2950 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2951 return std::make_pair(0U, &Mips::GPR32RegClass);
2953 if (VT == MVT::i64 && !HasMips64)
2954 return std::make_pair(0U, &Mips::GPR32RegClass);
2955 if (VT == MVT::i64 && HasMips64)
2956 return std::make_pair(0U, &Mips::GPR64RegClass);
2957 // This will generate an error message
2958 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2961 return std::make_pair(0U, &Mips::FGR32RegClass);
2962 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2963 if (Subtarget->isFP64bit())
2964 return std::make_pair(0U, &Mips::FGR64RegClass);
2965 return std::make_pair(0U, &Mips::AFGR64RegClass);
2968 case 'c': // register suitable for indirect jump
2970 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
2971 assert(VT == MVT::i64 && "Unexpected type.");
2972 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
2973 case 'l': // register suitable for indirect jump
2975 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
2976 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
2977 case 'x': // register suitable for indirect jump
2978 // Fixme: Not triggering the use of both hi and low
2979 // This will generate an error message
2980 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2984 std::pair<unsigned, const TargetRegisterClass *> R;
2985 R = parseRegForInlineAsmConstraint(Constraint, VT);
2990 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2993 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2994 /// vector. If it is invalid, don't add anything to Ops.
2995 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2996 std::string &Constraint,
2997 std::vector<SDValue>&Ops,
2998 SelectionDAG &DAG) const {
2999 SDValue Result(0, 0);
3001 // Only support length 1 constraints for now.
3002 if (Constraint.length() > 1) return;
3004 char ConstraintLetter = Constraint[0];
3005 switch (ConstraintLetter) {
3006 default: break; // This will fall through to the generic implementation
3007 case 'I': // Signed 16 bit constant
3008 // If this fails, the parent routine will give an error
3009 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3010 EVT Type = Op.getValueType();
3011 int64_t Val = C->getSExtValue();
3012 if (isInt<16>(Val)) {
3013 Result = DAG.getTargetConstant(Val, Type);
3018 case 'J': // integer zero
3019 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3020 EVT Type = Op.getValueType();
3021 int64_t Val = C->getZExtValue();
3023 Result = DAG.getTargetConstant(0, Type);
3028 case 'K': // unsigned 16 bit immediate
3029 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3030 EVT Type = Op.getValueType();
3031 uint64_t Val = (uint64_t)C->getZExtValue();
3032 if (isUInt<16>(Val)) {
3033 Result = DAG.getTargetConstant(Val, Type);
3038 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3039 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3040 EVT Type = Op.getValueType();
3041 int64_t Val = C->getSExtValue();
3042 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3043 Result = DAG.getTargetConstant(Val, Type);
3048 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3049 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3050 EVT Type = Op.getValueType();
3051 int64_t Val = C->getSExtValue();
3052 if ((Val >= -65535) && (Val <= -1)) {
3053 Result = DAG.getTargetConstant(Val, Type);
3058 case 'O': // signed 15 bit immediate
3059 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3060 EVT Type = Op.getValueType();
3061 int64_t Val = C->getSExtValue();
3062 if ((isInt<15>(Val))) {
3063 Result = DAG.getTargetConstant(Val, Type);
3068 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3069 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3070 EVT Type = Op.getValueType();
3071 int64_t Val = C->getSExtValue();
3072 if ((Val <= 65535) && (Val >= 1)) {
3073 Result = DAG.getTargetConstant(Val, Type);
3080 if (Result.getNode()) {
3081 Ops.push_back(Result);
3085 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3089 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3090 // No global is ever allowed as a base.
3095 case 0: // "r+i" or just "i", depending on HasBaseReg.
3098 if (!AM.HasBaseReg) // allow "r+i".
3100 return false; // disallow "r+r" or "r+r+i".
3109 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3110 // The Mips target isn't yet aware of offsets.
3114 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3116 bool IsMemset, bool ZeroMemset,
3118 MachineFunction &MF) const {
3119 if (Subtarget->hasMips64())
3125 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3126 if (VT != MVT::f32 && VT != MVT::f64)
3128 if (Imm.isNegZero())
3130 return Imm.isZero();
3133 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3135 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3137 return TargetLowering::getJumpTableEncoding();
3140 /// This function returns true if CallSym is a long double emulation routine.
3141 static bool isF128SoftLibCall(const char *CallSym) {
3142 const char *const LibCalls[] =
3143 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3144 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3145 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3146 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3147 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3148 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3149 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3150 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3153 const char * const *End = LibCalls + array_lengthof(LibCalls);
3155 // Check that LibCalls is sorted alphabetically.
3156 MipsTargetLowering::LTStr Comp;
3159 for (const char * const *I = LibCalls; I < End - 1; ++I)
3160 assert(Comp(*I, *(I + 1)));
3163 return std::binary_search(LibCalls, End, CallSym, Comp);
3166 /// This function returns true if Ty is fp128 or i128 which was originally a
3168 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3169 if (Ty->isFP128Ty())
3172 const ExternalSymbolSDNode *ES =
3173 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3175 // If the Ty is i128 and the function being called is a long double emulation
3176 // routine, then the original type is f128.
3177 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3180 MipsTargetLowering::MipsCC::SpecialCallingConvType
3181 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3182 MipsCC::SpecialCallingConvType SpecialCallingConv =
3183 MipsCC::NoSpecialCallingConv;;
3184 if (Subtarget->inMips16HardFloat()) {
3185 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3186 llvm::StringRef Sym = G->getGlobal()->getName();
3187 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3188 if (F->hasFnAttribute("__Mips16RetHelper")) {
3189 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3193 return SpecialCallingConv;
3196 MipsTargetLowering::MipsCC::MipsCC(
3197 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3198 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3199 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3200 SpecialCallingConv(SpecialCallingConv_){
3201 // Pre-allocate reserved argument area.
3202 CCInfo.AllocateStack(reservedArgArea(), 1);
3206 void MipsTargetLowering::MipsCC::
3207 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3208 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3209 std::vector<ArgListEntry> &FuncArgs) {
3210 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3211 "CallingConv::Fast shouldn't be used for vararg functions.");
3213 unsigned NumOpnds = Args.size();
3214 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3216 for (unsigned I = 0; I != NumOpnds; ++I) {
3217 MVT ArgVT = Args[I].VT;
3218 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3221 if (ArgFlags.isByVal()) {
3222 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3226 if (IsVarArg && !Args[I].IsFixed)
3227 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3229 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3231 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3236 dbgs() << "Call operand #" << I << " has unhandled type "
3237 << EVT(ArgVT).getEVTString();
3239 llvm_unreachable(0);
3244 void MipsTargetLowering::MipsCC::
3245 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3246 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3247 unsigned NumArgs = Args.size();
3248 llvm::CCAssignFn *FixedFn = fixedArgFn();
3249 unsigned CurArgIdx = 0;
3251 for (unsigned I = 0; I != NumArgs; ++I) {
3252 MVT ArgVT = Args[I].VT;
3253 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3254 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3255 CurArgIdx = Args[I].OrigArgIndex;
3257 if (ArgFlags.isByVal()) {
3258 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3262 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3264 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3268 dbgs() << "Formal Arg #" << I << " has unhandled type "
3269 << EVT(ArgVT).getEVTString();
3271 llvm_unreachable(0);
3275 template<typename Ty>
3276 void MipsTargetLowering::MipsCC::
3277 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3278 const SDNode *CallNode, const Type *RetTy) const {
3281 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3282 Fn = RetCC_F128Soft;
3286 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3287 MVT VT = RetVals[I].VT;
3288 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3289 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3291 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3293 dbgs() << "Call result #" << I << " has unhandled type "
3294 << EVT(VT).getEVTString() << '\n';
3296 llvm_unreachable(0);
3301 void MipsTargetLowering::MipsCC::
3302 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3303 const SDNode *CallNode, const Type *RetTy) const {
3304 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3307 void MipsTargetLowering::MipsCC::
3308 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3309 const Type *RetTy) const {
3310 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3314 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3316 CCValAssign::LocInfo LocInfo,
3317 ISD::ArgFlagsTy ArgFlags) {
3318 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3320 struct ByValArgInfo ByVal;
3321 unsigned RegSize = regSize();
3322 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3323 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3326 if (useRegsForByval())
3327 allocateRegs(ByVal, ByValSize, Align);
3329 // Allocate space on caller's stack.
3330 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3332 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3334 ByValArgs.push_back(ByVal);
3337 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3338 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3341 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3342 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3345 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3346 return IsO32 ? O32IntRegs : Mips64IntRegs;
3349 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3350 if (CallConv == CallingConv::Fast)
3351 return CC_Mips_FastCC;
3353 if (SpecialCallingConv == Mips16RetHelperConv)
3354 return CC_Mips16RetHelper;
3355 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3358 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3359 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3362 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3363 return IsO32 ? O32IntRegs : Mips64DPRegs;
3366 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3369 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3370 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3371 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3372 "Byval argument's size and alignment should be a multiple of"
3375 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3377 // If Align > RegSize, the first arg register must be even.
3378 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3379 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3383 // Mark the registers allocated.
3384 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3385 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3386 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3389 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3390 const SDNode *CallNode,
3391 bool IsSoftFloat) const {
3392 if (IsSoftFloat || IsO32)
3395 // Check if the original type was fp128.
3396 if (originalTypeIsF128(OrigTy, CallNode)) {
3397 assert(VT == MVT::i64);
3404 void MipsTargetLowering::
3405 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3406 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3407 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3408 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3409 MachineFunction &MF = DAG.getMachineFunction();
3410 MachineFrameInfo *MFI = MF.getFrameInfo();
3411 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3412 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3416 FrameObjOffset = (int)CC.reservedArgArea() -
3417 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3419 FrameObjOffset = ByVal.Address;
3421 // Create frame object.
3422 EVT PtrTy = getPointerTy();
3423 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3424 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3425 InVals.push_back(FIN);
3430 // Copy arg registers.
3431 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3432 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3434 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3435 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3436 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3437 unsigned Offset = I * CC.regSize();
3438 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3439 DAG.getConstant(Offset, PtrTy));
3440 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3441 StorePtr, MachinePointerInfo(FuncArg, Offset),
3443 OutChains.push_back(Store);
3447 // Copy byVal arg to registers and stack.
3448 void MipsTargetLowering::
3449 passByValArg(SDValue Chain, SDLoc DL,
3450 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3451 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3452 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3453 const MipsCC &CC, const ByValArgInfo &ByVal,
3454 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3455 unsigned ByValSize = Flags.getByValSize();
3456 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3457 unsigned RegSize = CC.regSize();
3458 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3459 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3461 if (ByVal.NumRegs) {
3462 const uint16_t *ArgRegs = CC.intArgRegs();
3463 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3466 // Copy words to registers.
3467 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3468 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3469 DAG.getConstant(Offset, PtrTy));
3470 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3471 MachinePointerInfo(), false, false, false,
3473 MemOpChains.push_back(LoadVal.getValue(1));
3474 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3475 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3478 // Return if the struct has been fully copied.
3479 if (ByValSize == Offset)
3482 // Copy the remainder of the byval argument with sub-word loads and shifts.
3483 if (LeftoverBytes) {
3484 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3485 "Size of the remainder should be smaller than RegSize.");
3488 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3489 Offset < ByValSize; LoadSize /= 2) {
3490 unsigned RemSize = ByValSize - Offset;
3492 if (RemSize < LoadSize)
3496 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3497 DAG.getConstant(Offset, PtrTy));
3499 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3500 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3501 false, false, Alignment);
3502 MemOpChains.push_back(LoadVal.getValue(1));
3504 // Shift the loaded value.
3508 Shamt = TotalSizeLoaded;
3510 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3512 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3513 DAG.getConstant(Shamt, MVT::i32));
3516 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3521 TotalSizeLoaded += LoadSize;
3522 Alignment = std::min(Alignment, LoadSize);
3525 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3526 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3531 // Copy remainder of byval arg to it with memcpy.
3532 unsigned MemCpySize = ByValSize - Offset;
3533 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3534 DAG.getConstant(Offset, PtrTy));
3535 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3536 DAG.getIntPtrConstant(ByVal.Address));
3537 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3538 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3539 /*isVolatile=*/false, /*AlwaysInline=*/false,
3540 MachinePointerInfo(0), MachinePointerInfo(0));
3541 MemOpChains.push_back(Chain);
3545 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3546 const MipsCC &CC, SDValue Chain,
3547 SDLoc DL, SelectionDAG &DAG) const {
3548 unsigned NumRegs = CC.numIntArgRegs();
3549 const uint16_t *ArgRegs = CC.intArgRegs();
3550 const CCState &CCInfo = CC.getCCInfo();
3551 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3552 unsigned RegSize = CC.regSize();
3553 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3554 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3555 MachineFunction &MF = DAG.getMachineFunction();
3556 MachineFrameInfo *MFI = MF.getFrameInfo();
3557 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3559 // Offset of the first variable argument from stack pointer.
3563 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3566 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3568 // Record the frame index of the first variable argument
3569 // which is a value necessary to VASTART.
3570 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3571 MipsFI->setVarArgsFrameIndex(FI);
3573 // Copy the integer registers that have not been used for argument passing
3574 // to the argument register save area. For O32, the save area is allocated
3575 // in the caller's stack frame, while for N32/64, it is allocated in the
3576 // callee's stack frame.
3577 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3578 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3579 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3580 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3581 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3582 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3583 MachinePointerInfo(), false, false, 0);
3584 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3585 OutChains.push_back(Store);