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) {
2124 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2126 static const uint16_t IntRegs[] = {
2127 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2129 static const uint16_t F32Regs[] = {
2130 Mips::F12, Mips::F14
2132 static const uint16_t F64Regs[] = {
2136 // Do not process byval args here.
2137 if (ArgFlags.isByVal())
2140 // Promote i8 and i16
2141 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2143 if (ArgFlags.isSExt())
2144 LocInfo = CCValAssign::SExt;
2145 else if (ArgFlags.isZExt())
2146 LocInfo = CCValAssign::ZExt;
2148 LocInfo = CCValAssign::AExt;
2153 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2154 // is true: function is vararg, argument is 3rd or higher, there is previous
2155 // argument which is not f32 or f64.
2156 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2157 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2158 unsigned OrigAlign = ArgFlags.getOrigAlign();
2159 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2161 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2162 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2163 // If this is the first part of an i64 arg,
2164 // the allocated register must be either A0 or A2.
2165 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2166 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2168 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2169 // Allocate int register and shadow next int register. If first
2170 // available register is Mips::A1 or Mips::A3, shadow it too.
2171 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2172 if (Reg == Mips::A1 || Reg == Mips::A3)
2173 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2174 State.AllocateReg(IntRegs, IntRegsSize);
2176 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2177 // we are guaranteed to find an available float register
2178 if (ValVT == MVT::f32) {
2179 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2180 // Shadow int register
2181 State.AllocateReg(IntRegs, IntRegsSize);
2183 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2184 // Shadow int registers
2185 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2186 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2187 State.AllocateReg(IntRegs, IntRegsSize);
2188 State.AllocateReg(IntRegs, IntRegsSize);
2191 llvm_unreachable("Cannot handle this ValVT.");
2194 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2196 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2198 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2203 #include "MipsGenCallingConv.inc"
2205 //===----------------------------------------------------------------------===//
2206 // Call Calling Convention Implementation
2207 //===----------------------------------------------------------------------===//
2209 static const unsigned O32IntRegsSize = 4;
2211 // Return next O32 integer argument register.
2212 static unsigned getNextIntArgReg(unsigned Reg) {
2213 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2214 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2218 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2219 SDValue Chain, SDValue Arg, SDLoc DL,
2220 bool IsTailCall, SelectionDAG &DAG) const {
2222 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2223 DAG.getIntPtrConstant(Offset));
2224 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2228 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2229 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2230 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2231 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2232 /*isVolatile=*/ true, false, 0);
2235 void MipsTargetLowering::
2236 getOpndList(SmallVectorImpl<SDValue> &Ops,
2237 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2238 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2239 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2240 // Insert node "GP copy globalreg" before call to function.
2242 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2243 // in PIC mode) allow symbols to be resolved via lazy binding.
2244 // The lazy binding stub requires GP to point to the GOT.
2245 if (IsPICCall && !InternalLinkage) {
2246 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2247 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2248 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2251 // Build a sequence of copy-to-reg nodes chained together with token
2252 // chain and flag operands which copy the outgoing args into registers.
2253 // The InFlag in necessary since all emitted instructions must be
2257 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2258 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2259 RegsToPass[i].second, InFlag);
2260 InFlag = Chain.getValue(1);
2263 // Add argument registers to the end of the list so that they are
2264 // known live into the call.
2265 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2266 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2267 RegsToPass[i].second.getValueType()));
2269 // Add a register mask operand representing the call-preserved registers.
2270 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2271 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2272 assert(Mask && "Missing call preserved mask for calling convention");
2273 if (Subtarget->inMips16HardFloat()) {
2274 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2275 llvm::StringRef Sym = G->getGlobal()->getName();
2276 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2277 if (F->hasFnAttribute("__Mips16RetHelper")) {
2278 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2282 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2284 if (InFlag.getNode())
2285 Ops.push_back(InFlag);
2288 /// LowerCall - functions arguments are copied from virtual regs to
2289 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2291 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2292 SmallVectorImpl<SDValue> &InVals) const {
2293 SelectionDAG &DAG = CLI.DAG;
2295 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2296 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2297 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2298 SDValue Chain = CLI.Chain;
2299 SDValue Callee = CLI.Callee;
2300 bool &IsTailCall = CLI.IsTailCall;
2301 CallingConv::ID CallConv = CLI.CallConv;
2302 bool IsVarArg = CLI.IsVarArg;
2304 MachineFunction &MF = DAG.getMachineFunction();
2305 MachineFrameInfo *MFI = MF.getFrameInfo();
2306 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2307 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2309 // Analyze operands of the call, assigning locations to each operand.
2310 SmallVector<CCValAssign, 16> ArgLocs;
2311 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2312 getTargetMachine(), ArgLocs, *DAG.getContext());
2313 MipsCC::SpecialCallingConvType SpecialCallingConv =
2314 getSpecialCallingConv(Callee);
2315 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo, SpecialCallingConv);
2317 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2318 getTargetMachine().Options.UseSoftFloat,
2319 Callee.getNode(), CLI.Args);
2321 // Get a count of how many bytes are to be pushed on the stack.
2322 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2324 // Check if it's really possible to do a tail call.
2327 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2328 *MF.getInfo<MipsFunctionInfo>());
2333 // Chain is the output chain of the last Load/Store or CopyToReg node.
2334 // ByValChain is the output chain of the last Memcpy node created for copying
2335 // byval arguments to the stack.
2336 unsigned StackAlignment = TFL->getStackAlignment();
2337 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2338 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2341 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2343 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2344 IsN64 ? Mips::SP_64 : Mips::SP,
2347 // With EABI is it possible to have 16 args on registers.
2348 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2349 SmallVector<SDValue, 8> MemOpChains;
2350 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2352 // Walk the register/memloc assignments, inserting copies/loads.
2353 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2354 SDValue Arg = OutVals[i];
2355 CCValAssign &VA = ArgLocs[i];
2356 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2357 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2360 if (Flags.isByVal()) {
2361 assert(Flags.getByValSize() &&
2362 "ByVal args of size 0 should have been ignored by front-end.");
2363 assert(ByValArg != MipsCCInfo.byval_end());
2364 assert(!IsTailCall &&
2365 "Do not tail-call optimize if there is a byval argument.");
2366 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2367 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2372 // Promote the value if needed.
2373 switch (VA.getLocInfo()) {
2374 default: llvm_unreachable("Unknown loc info!");
2375 case CCValAssign::Full:
2376 if (VA.isRegLoc()) {
2377 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2378 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2379 (ValVT == MVT::i64 && LocVT == MVT::f64))
2380 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2381 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2382 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2383 Arg, DAG.getConstant(0, MVT::i32));
2384 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2385 Arg, DAG.getConstant(1, MVT::i32));
2386 if (!Subtarget->isLittle())
2388 unsigned LocRegLo = VA.getLocReg();
2389 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2390 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2391 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2396 case CCValAssign::SExt:
2397 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2399 case CCValAssign::ZExt:
2400 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2402 case CCValAssign::AExt:
2403 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2407 // Arguments that can be passed on register must be kept at
2408 // RegsToPass vector
2409 if (VA.isRegLoc()) {
2410 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2414 // Register can't get to this point...
2415 assert(VA.isMemLoc());
2417 // emit ISD::STORE whichs stores the
2418 // parameter value to a stack Location
2419 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2420 Chain, Arg, DL, IsTailCall, DAG));
2423 // Transform all store nodes into one single node because all store
2424 // nodes are independent of each other.
2425 if (!MemOpChains.empty())
2426 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2427 &MemOpChains[0], MemOpChains.size());
2429 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2430 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2431 // node so that legalize doesn't hack it.
2432 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2433 bool GlobalOrExternal = false, InternalLinkage = false;
2436 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2438 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2440 if (InternalLinkage)
2441 Callee = getAddrLocal(Callee, DAG, HasMips64);
2443 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2444 MipsII::MO_CALL_LO16);
2446 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2448 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2449 MipsII::MO_NO_FLAG);
2450 GlobalOrExternal = true;
2452 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2453 if (!IsN64 && !IsPIC) // !N64 && static
2454 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2455 MipsII::MO_NO_FLAG);
2457 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2458 MipsII::MO_CALL_LO16);
2460 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2462 GlobalOrExternal = true;
2465 SmallVector<SDValue, 8> Ops(1, Chain);
2466 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2468 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2469 CLI, Callee, Chain);
2472 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2474 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2475 SDValue InFlag = Chain.getValue(1);
2477 // Create the CALLSEQ_END node.
2478 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2479 DAG.getIntPtrConstant(0, true), InFlag, DL);
2480 InFlag = Chain.getValue(1);
2482 // Handle result values, copying them out of physregs into vregs that we
2484 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2485 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2488 /// LowerCallResult - Lower the result values of a call into the
2489 /// appropriate copies out of appropriate physical registers.
2491 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2492 CallingConv::ID CallConv, bool IsVarArg,
2493 const SmallVectorImpl<ISD::InputArg> &Ins,
2494 SDLoc DL, SelectionDAG &DAG,
2495 SmallVectorImpl<SDValue> &InVals,
2496 const SDNode *CallNode,
2497 const Type *RetTy) const {
2498 // Assign locations to each value returned by this call.
2499 SmallVector<CCValAssign, 16> RVLocs;
2500 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2501 getTargetMachine(), RVLocs, *DAG.getContext());
2502 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2504 MipsCCInfo.analyzeCallResult(Ins, getTargetMachine().Options.UseSoftFloat,
2507 // Copy all of the result registers out of their specified physreg.
2508 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2509 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2510 RVLocs[i].getLocVT(), InFlag);
2511 Chain = Val.getValue(1);
2512 InFlag = Val.getValue(2);
2514 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2515 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2517 InVals.push_back(Val);
2523 //===----------------------------------------------------------------------===//
2524 // Formal Arguments Calling Convention Implementation
2525 //===----------------------------------------------------------------------===//
2526 /// LowerFormalArguments - transform physical registers into virtual registers
2527 /// and generate load operations for arguments places on the stack.
2529 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2530 CallingConv::ID CallConv,
2532 const SmallVectorImpl<ISD::InputArg> &Ins,
2533 SDLoc DL, SelectionDAG &DAG,
2534 SmallVectorImpl<SDValue> &InVals)
2536 MachineFunction &MF = DAG.getMachineFunction();
2537 MachineFrameInfo *MFI = MF.getFrameInfo();
2538 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2540 MipsFI->setVarArgsFrameIndex(0);
2542 // Used with vargs to acumulate store chains.
2543 std::vector<SDValue> OutChains;
2545 // Assign locations to all of the incoming arguments.
2546 SmallVector<CCValAssign, 16> ArgLocs;
2547 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2548 getTargetMachine(), ArgLocs, *DAG.getContext());
2549 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2550 Function::const_arg_iterator FuncArg =
2551 DAG.getMachineFunction().getFunction()->arg_begin();
2552 bool UseSoftFloat = getTargetMachine().Options.UseSoftFloat;
2554 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2555 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2556 MipsCCInfo.hasByValArg());
2558 unsigned CurArgIdx = 0;
2559 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2561 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2562 CCValAssign &VA = ArgLocs[i];
2563 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2564 CurArgIdx = Ins[i].OrigArgIndex;
2565 EVT ValVT = VA.getValVT();
2566 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2567 bool IsRegLoc = VA.isRegLoc();
2569 if (Flags.isByVal()) {
2570 assert(Flags.getByValSize() &&
2571 "ByVal args of size 0 should have been ignored by front-end.");
2572 assert(ByValArg != MipsCCInfo.byval_end());
2573 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2574 MipsCCInfo, *ByValArg);
2579 // Arguments stored on registers
2581 EVT RegVT = VA.getLocVT();
2582 unsigned ArgReg = VA.getLocReg();
2583 const TargetRegisterClass *RC;
2585 if (RegVT == MVT::i32)
2586 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2587 &Mips::GPR32RegClass;
2588 else if (RegVT == MVT::i64)
2589 RC = &Mips::GPR64RegClass;
2590 else if (RegVT == MVT::f32)
2591 RC = &Mips::FGR32RegClass;
2592 else if (RegVT == MVT::f64)
2593 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
2595 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2597 // Transform the arguments stored on
2598 // physical registers into virtual ones
2599 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2600 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2602 // If this is an 8 or 16-bit value, it has been passed promoted
2603 // to 32 bits. Insert an assert[sz]ext to capture this, then
2604 // truncate to the right size.
2605 if (VA.getLocInfo() != CCValAssign::Full) {
2606 unsigned Opcode = 0;
2607 if (VA.getLocInfo() == CCValAssign::SExt)
2608 Opcode = ISD::AssertSext;
2609 else if (VA.getLocInfo() == CCValAssign::ZExt)
2610 Opcode = ISD::AssertZext;
2612 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2613 DAG.getValueType(ValVT));
2614 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2617 // Handle floating point arguments passed in integer registers and
2618 // long double arguments passed in floating point registers.
2619 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2620 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2621 (RegVT == MVT::f64 && ValVT == MVT::i64))
2622 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2623 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2624 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2625 getNextIntArgReg(ArgReg), RC);
2626 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2627 if (!Subtarget->isLittle())
2628 std::swap(ArgValue, ArgValue2);
2629 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2630 ArgValue, ArgValue2);
2633 InVals.push_back(ArgValue);
2634 } else { // VA.isRegLoc()
2637 assert(VA.isMemLoc());
2639 // The stack pointer offset is relative to the caller stack frame.
2640 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2641 VA.getLocMemOffset(), true);
2643 // Create load nodes to retrieve arguments from the stack
2644 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2645 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2646 MachinePointerInfo::getFixedStack(FI),
2647 false, false, false, 0));
2651 // The mips ABIs for returning structs by value requires that we copy
2652 // the sret argument into $v0 for the return. Save the argument into
2653 // a virtual register so that we can access it from the return points.
2654 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2655 unsigned Reg = MipsFI->getSRetReturnReg();
2657 Reg = MF.getRegInfo().
2658 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2659 MipsFI->setSRetReturnReg(Reg);
2661 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2662 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2666 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2668 // All stores are grouped in one node to allow the matching between
2669 // the size of Ins and InVals. This only happens when on varg functions
2670 if (!OutChains.empty()) {
2671 OutChains.push_back(Chain);
2672 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2673 &OutChains[0], OutChains.size());
2679 //===----------------------------------------------------------------------===//
2680 // Return Value Calling Convention Implementation
2681 //===----------------------------------------------------------------------===//
2684 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2685 MachineFunction &MF, bool IsVarArg,
2686 const SmallVectorImpl<ISD::OutputArg> &Outs,
2687 LLVMContext &Context) const {
2688 SmallVector<CCValAssign, 16> RVLocs;
2689 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2691 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2695 MipsTargetLowering::LowerReturn(SDValue Chain,
2696 CallingConv::ID CallConv, bool IsVarArg,
2697 const SmallVectorImpl<ISD::OutputArg> &Outs,
2698 const SmallVectorImpl<SDValue> &OutVals,
2699 SDLoc DL, SelectionDAG &DAG) const {
2700 // CCValAssign - represent the assignment of
2701 // the return value to a location
2702 SmallVector<CCValAssign, 16> RVLocs;
2703 MachineFunction &MF = DAG.getMachineFunction();
2705 // CCState - Info about the registers and stack slot.
2706 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2708 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2710 // Analyze return values.
2711 MipsCCInfo.analyzeReturn(Outs, getTargetMachine().Options.UseSoftFloat,
2712 MF.getFunction()->getReturnType());
2715 SmallVector<SDValue, 4> RetOps(1, Chain);
2717 // Copy the result values into the output registers.
2718 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2719 SDValue Val = OutVals[i];
2720 CCValAssign &VA = RVLocs[i];
2721 assert(VA.isRegLoc() && "Can only return in registers!");
2723 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2724 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2726 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2728 // Guarantee that all emitted copies are stuck together with flags.
2729 Flag = Chain.getValue(1);
2730 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2733 // The mips ABIs for returning structs by value requires that we copy
2734 // the sret argument into $v0 for the return. We saved the argument into
2735 // a virtual register in the entry block, so now we copy the value out
2737 if (MF.getFunction()->hasStructRetAttr()) {
2738 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2739 unsigned Reg = MipsFI->getSRetReturnReg();
2742 llvm_unreachable("sret virtual register not created in the entry block");
2743 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2744 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2746 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2747 Flag = Chain.getValue(1);
2748 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2751 RetOps[0] = Chain; // Update chain.
2753 // Add the flag if we have it.
2755 RetOps.push_back(Flag);
2757 // Return on Mips is always a "jr $ra"
2758 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2761 //===----------------------------------------------------------------------===//
2762 // Mips Inline Assembly Support
2763 //===----------------------------------------------------------------------===//
2765 /// getConstraintType - Given a constraint letter, return the type of
2766 /// constraint it is for this target.
2767 MipsTargetLowering::ConstraintType MipsTargetLowering::
2768 getConstraintType(const std::string &Constraint) const
2770 // Mips specific constrainy
2771 // GCC config/mips/constraints.md
2773 // 'd' : An address register. Equivalent to r
2774 // unless generating MIPS16 code.
2775 // 'y' : Equivalent to r; retained for
2776 // backwards compatibility.
2777 // 'c' : A register suitable for use in an indirect
2778 // jump. This will always be $25 for -mabicalls.
2779 // 'l' : The lo register. 1 word storage.
2780 // 'x' : The hilo register pair. Double word storage.
2781 if (Constraint.size() == 1) {
2782 switch (Constraint[0]) {
2790 return C_RegisterClass;
2795 return TargetLowering::getConstraintType(Constraint);
2798 /// Examine constraint type and operand type and determine a weight value.
2799 /// This object must already have been set up with the operand type
2800 /// and the current alternative constraint selected.
2801 TargetLowering::ConstraintWeight
2802 MipsTargetLowering::getSingleConstraintMatchWeight(
2803 AsmOperandInfo &info, const char *constraint) const {
2804 ConstraintWeight weight = CW_Invalid;
2805 Value *CallOperandVal = info.CallOperandVal;
2806 // If we don't have a value, we can't do a match,
2807 // but allow it at the lowest weight.
2808 if (CallOperandVal == NULL)
2810 Type *type = CallOperandVal->getType();
2811 // Look at the constraint type.
2812 switch (*constraint) {
2814 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2818 if (type->isIntegerTy())
2819 weight = CW_Register;
2822 if (type->isFloatTy())
2823 weight = CW_Register;
2825 case 'c': // $25 for indirect jumps
2826 case 'l': // lo register
2827 case 'x': // hilo register pair
2828 if (type->isIntegerTy())
2829 weight = CW_SpecificReg;
2831 case 'I': // signed 16 bit immediate
2832 case 'J': // integer zero
2833 case 'K': // unsigned 16 bit immediate
2834 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2835 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2836 case 'O': // signed 15 bit immediate (+- 16383)
2837 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2838 if (isa<ConstantInt>(CallOperandVal))
2839 weight = CW_Constant;
2848 /// This is a helper function to parse a physical register string and split it
2849 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2850 /// that is returned indicates whether parsing was successful. The second flag
2851 /// is true if the numeric part exists.
2852 static std::pair<bool, bool>
2853 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2854 unsigned long long &Reg) {
2855 if (C.front() != '{' || C.back() != '}')
2856 return std::make_pair(false, false);
2858 // Search for the first numeric character.
2859 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2860 I = std::find_if(B, E, std::ptr_fun(isdigit));
2862 Prefix.assign(B, I - B);
2864 // The second flag is set to false if no numeric characters were found.
2866 return std::make_pair(true, false);
2868 // Parse the numeric characters.
2869 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2873 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2874 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2875 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2876 const TargetRegisterClass *RC;
2878 unsigned long long Reg;
2880 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2883 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2885 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2886 // No numeric characters follow "hi" or "lo".
2888 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2890 RC = TRI->getRegClass(Prefix == "hi" ?
2891 Mips::HI32RegClassID : Mips::LO32RegClassID);
2892 return std::make_pair(*(RC->begin()), RC);
2896 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2898 if (Prefix == "$f") { // Parse $f0-$f31.
2899 // If the size of FP registers is 64-bit or Reg is an even number, select
2900 // the 64-bit register class. Otherwise, select the 32-bit register class.
2901 if (VT == MVT::Other)
2902 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2904 RC= getRegClassFor(VT);
2906 if (RC == &Mips::AFGR64RegClass) {
2907 assert(Reg % 2 == 0);
2910 } else if (Prefix == "$fcc") { // Parse $fcc0-$fcc7.
2911 RC = TRI->getRegClass(Mips::FCCRegClassID);
2912 } else { // Parse $0-$31.
2913 assert(Prefix == "$");
2914 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2917 assert(Reg < RC->getNumRegs());
2918 return std::make_pair(*(RC->begin() + Reg), RC);
2921 /// Given a register class constraint, like 'r', if this corresponds directly
2922 /// to an LLVM register class, return a register of 0 and the register class
2924 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2925 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2927 if (Constraint.size() == 1) {
2928 switch (Constraint[0]) {
2929 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2930 case 'y': // Same as 'r'. Exists for compatibility.
2932 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2933 if (Subtarget->inMips16Mode())
2934 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2935 return std::make_pair(0U, &Mips::GPR32RegClass);
2937 if (VT == MVT::i64 && !HasMips64)
2938 return std::make_pair(0U, &Mips::GPR32RegClass);
2939 if (VT == MVT::i64 && HasMips64)
2940 return std::make_pair(0U, &Mips::GPR64RegClass);
2941 // This will generate an error message
2942 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2945 return std::make_pair(0U, &Mips::FGR32RegClass);
2946 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2947 if (Subtarget->isFP64bit())
2948 return std::make_pair(0U, &Mips::FGR64RegClass);
2949 return std::make_pair(0U, &Mips::AFGR64RegClass);
2952 case 'c': // register suitable for indirect jump
2954 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
2955 assert(VT == MVT::i64 && "Unexpected type.");
2956 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
2957 case 'l': // register suitable for indirect jump
2959 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
2960 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
2961 case 'x': // register suitable for indirect jump
2962 // Fixme: Not triggering the use of both hi and low
2963 // This will generate an error message
2964 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2968 std::pair<unsigned, const TargetRegisterClass *> R;
2969 R = parseRegForInlineAsmConstraint(Constraint, VT);
2974 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2977 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2978 /// vector. If it is invalid, don't add anything to Ops.
2979 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2980 std::string &Constraint,
2981 std::vector<SDValue>&Ops,
2982 SelectionDAG &DAG) const {
2983 SDValue Result(0, 0);
2985 // Only support length 1 constraints for now.
2986 if (Constraint.length() > 1) return;
2988 char ConstraintLetter = Constraint[0];
2989 switch (ConstraintLetter) {
2990 default: break; // This will fall through to the generic implementation
2991 case 'I': // Signed 16 bit constant
2992 // If this fails, the parent routine will give an error
2993 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2994 EVT Type = Op.getValueType();
2995 int64_t Val = C->getSExtValue();
2996 if (isInt<16>(Val)) {
2997 Result = DAG.getTargetConstant(Val, Type);
3002 case 'J': // integer zero
3003 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3004 EVT Type = Op.getValueType();
3005 int64_t Val = C->getZExtValue();
3007 Result = DAG.getTargetConstant(0, Type);
3012 case 'K': // unsigned 16 bit immediate
3013 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3014 EVT Type = Op.getValueType();
3015 uint64_t Val = (uint64_t)C->getZExtValue();
3016 if (isUInt<16>(Val)) {
3017 Result = DAG.getTargetConstant(Val, Type);
3022 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3023 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3024 EVT Type = Op.getValueType();
3025 int64_t Val = C->getSExtValue();
3026 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3027 Result = DAG.getTargetConstant(Val, Type);
3032 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3033 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3034 EVT Type = Op.getValueType();
3035 int64_t Val = C->getSExtValue();
3036 if ((Val >= -65535) && (Val <= -1)) {
3037 Result = DAG.getTargetConstant(Val, Type);
3042 case 'O': // signed 15 bit immediate
3043 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3044 EVT Type = Op.getValueType();
3045 int64_t Val = C->getSExtValue();
3046 if ((isInt<15>(Val))) {
3047 Result = DAG.getTargetConstant(Val, Type);
3052 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3053 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3054 EVT Type = Op.getValueType();
3055 int64_t Val = C->getSExtValue();
3056 if ((Val <= 65535) && (Val >= 1)) {
3057 Result = DAG.getTargetConstant(Val, Type);
3064 if (Result.getNode()) {
3065 Ops.push_back(Result);
3069 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3073 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3074 // No global is ever allowed as a base.
3079 case 0: // "r+i" or just "i", depending on HasBaseReg.
3082 if (!AM.HasBaseReg) // allow "r+i".
3084 return false; // disallow "r+r" or "r+r+i".
3093 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3094 // The Mips target isn't yet aware of offsets.
3098 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3100 bool IsMemset, bool ZeroMemset,
3102 MachineFunction &MF) const {
3103 if (Subtarget->hasMips64())
3109 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3110 if (VT != MVT::f32 && VT != MVT::f64)
3112 if (Imm.isNegZero())
3114 return Imm.isZero();
3117 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3119 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3121 return TargetLowering::getJumpTableEncoding();
3124 /// This function returns true if CallSym is a long double emulation routine.
3125 static bool isF128SoftLibCall(const char *CallSym) {
3126 const char *const LibCalls[] =
3127 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3128 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3129 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3130 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3131 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3132 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3133 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3134 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3137 const char * const *End = LibCalls + array_lengthof(LibCalls);
3139 // Check that LibCalls is sorted alphabetically.
3140 MipsTargetLowering::LTStr Comp;
3143 for (const char * const *I = LibCalls; I < End - 1; ++I)
3144 assert(Comp(*I, *(I + 1)));
3147 return std::binary_search(LibCalls, End, CallSym, Comp);
3150 /// This function returns true if Ty is fp128 or i128 which was originally a
3152 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3153 if (Ty->isFP128Ty())
3156 const ExternalSymbolSDNode *ES =
3157 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3159 // If the Ty is i128 and the function being called is a long double emulation
3160 // routine, then the original type is f128.
3161 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3164 MipsTargetLowering::MipsCC::SpecialCallingConvType
3165 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3166 MipsCC::SpecialCallingConvType SpecialCallingConv =
3167 MipsCC::NoSpecialCallingConv;;
3168 if (Subtarget->inMips16HardFloat()) {
3169 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3170 llvm::StringRef Sym = G->getGlobal()->getName();
3171 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3172 if (F->hasFnAttribute("__Mips16RetHelper")) {
3173 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3177 return SpecialCallingConv;
3180 MipsTargetLowering::MipsCC::MipsCC(
3181 CallingConv::ID CC, bool IsO32_, CCState &Info,
3182 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3183 : CCInfo(Info), CallConv(CC), IsO32(IsO32_),
3184 SpecialCallingConv(SpecialCallingConv_){
3185 // Pre-allocate reserved argument area.
3186 CCInfo.AllocateStack(reservedArgArea(), 1);
3190 void MipsTargetLowering::MipsCC::
3191 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3192 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3193 std::vector<ArgListEntry> &FuncArgs) {
3194 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3195 "CallingConv::Fast shouldn't be used for vararg functions.");
3197 unsigned NumOpnds = Args.size();
3198 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3200 for (unsigned I = 0; I != NumOpnds; ++I) {
3201 MVT ArgVT = Args[I].VT;
3202 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3205 if (ArgFlags.isByVal()) {
3206 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3210 if (IsVarArg && !Args[I].IsFixed)
3211 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3213 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3215 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3220 dbgs() << "Call operand #" << I << " has unhandled type "
3221 << EVT(ArgVT).getEVTString();
3223 llvm_unreachable(0);
3228 void MipsTargetLowering::MipsCC::
3229 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3230 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3231 unsigned NumArgs = Args.size();
3232 llvm::CCAssignFn *FixedFn = fixedArgFn();
3233 unsigned CurArgIdx = 0;
3235 for (unsigned I = 0; I != NumArgs; ++I) {
3236 MVT ArgVT = Args[I].VT;
3237 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3238 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3239 CurArgIdx = Args[I].OrigArgIndex;
3241 if (ArgFlags.isByVal()) {
3242 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3246 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3248 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3252 dbgs() << "Formal Arg #" << I << " has unhandled type "
3253 << EVT(ArgVT).getEVTString();
3255 llvm_unreachable(0);
3259 template<typename Ty>
3260 void MipsTargetLowering::MipsCC::
3261 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3262 const SDNode *CallNode, const Type *RetTy) const {
3265 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3266 Fn = RetCC_F128Soft;
3270 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3271 MVT VT = RetVals[I].VT;
3272 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3273 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3275 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3277 dbgs() << "Call result #" << I << " has unhandled type "
3278 << EVT(VT).getEVTString() << '\n';
3280 llvm_unreachable(0);
3285 void MipsTargetLowering::MipsCC::
3286 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3287 const SDNode *CallNode, const Type *RetTy) const {
3288 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3291 void MipsTargetLowering::MipsCC::
3292 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3293 const Type *RetTy) const {
3294 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3298 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3300 CCValAssign::LocInfo LocInfo,
3301 ISD::ArgFlagsTy ArgFlags) {
3302 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3304 struct ByValArgInfo ByVal;
3305 unsigned RegSize = regSize();
3306 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3307 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3310 if (useRegsForByval())
3311 allocateRegs(ByVal, ByValSize, Align);
3313 // Allocate space on caller's stack.
3314 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3316 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3318 ByValArgs.push_back(ByVal);
3321 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3322 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3325 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3326 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3329 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3330 return IsO32 ? O32IntRegs : Mips64IntRegs;
3333 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3334 if (CallConv == CallingConv::Fast)
3335 return CC_Mips_FastCC;
3337 if (SpecialCallingConv == Mips16RetHelperConv)
3338 return CC_Mips16RetHelper;
3339 return IsO32 ? CC_MipsO32 : CC_MipsN;
3342 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3343 return IsO32 ? CC_MipsO32 : CC_MipsN_VarArg;
3346 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3347 return IsO32 ? O32IntRegs : Mips64DPRegs;
3350 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3353 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3354 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3355 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3356 "Byval argument's size and alignment should be a multiple of"
3359 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3361 // If Align > RegSize, the first arg register must be even.
3362 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3363 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3367 // Mark the registers allocated.
3368 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3369 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3370 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3373 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3374 const SDNode *CallNode,
3375 bool IsSoftFloat) const {
3376 if (IsSoftFloat || IsO32)
3379 // Check if the original type was fp128.
3380 if (originalTypeIsF128(OrigTy, CallNode)) {
3381 assert(VT == MVT::i64);
3388 void MipsTargetLowering::
3389 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3390 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3391 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3392 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3393 MachineFunction &MF = DAG.getMachineFunction();
3394 MachineFrameInfo *MFI = MF.getFrameInfo();
3395 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3396 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3400 FrameObjOffset = (int)CC.reservedArgArea() -
3401 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3403 FrameObjOffset = ByVal.Address;
3405 // Create frame object.
3406 EVT PtrTy = getPointerTy();
3407 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3408 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3409 InVals.push_back(FIN);
3414 // Copy arg registers.
3415 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3416 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3418 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3419 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3420 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3421 unsigned Offset = I * CC.regSize();
3422 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3423 DAG.getConstant(Offset, PtrTy));
3424 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3425 StorePtr, MachinePointerInfo(FuncArg, Offset),
3427 OutChains.push_back(Store);
3431 // Copy byVal arg to registers and stack.
3432 void MipsTargetLowering::
3433 passByValArg(SDValue Chain, SDLoc DL,
3434 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3435 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3436 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3437 const MipsCC &CC, const ByValArgInfo &ByVal,
3438 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3439 unsigned ByValSize = Flags.getByValSize();
3440 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3441 unsigned RegSize = CC.regSize();
3442 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3443 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3445 if (ByVal.NumRegs) {
3446 const uint16_t *ArgRegs = CC.intArgRegs();
3447 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3450 // Copy words to registers.
3451 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3452 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3453 DAG.getConstant(Offset, PtrTy));
3454 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3455 MachinePointerInfo(), false, false, false,
3457 MemOpChains.push_back(LoadVal.getValue(1));
3458 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3459 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3462 // Return if the struct has been fully copied.
3463 if (ByValSize == Offset)
3466 // Copy the remainder of the byval argument with sub-word loads and shifts.
3467 if (LeftoverBytes) {
3468 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3469 "Size of the remainder should be smaller than RegSize.");
3472 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3473 Offset < ByValSize; LoadSize /= 2) {
3474 unsigned RemSize = ByValSize - Offset;
3476 if (RemSize < LoadSize)
3480 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3481 DAG.getConstant(Offset, PtrTy));
3483 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3484 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3485 false, false, Alignment);
3486 MemOpChains.push_back(LoadVal.getValue(1));
3488 // Shift the loaded value.
3492 Shamt = TotalSizeLoaded;
3494 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3496 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3497 DAG.getConstant(Shamt, MVT::i32));
3500 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3505 TotalSizeLoaded += LoadSize;
3506 Alignment = std::min(Alignment, LoadSize);
3509 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3510 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3515 // Copy remainder of byval arg to it with memcpy.
3516 unsigned MemCpySize = ByValSize - Offset;
3517 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3518 DAG.getConstant(Offset, PtrTy));
3519 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3520 DAG.getIntPtrConstant(ByVal.Address));
3521 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3522 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3523 /*isVolatile=*/false, /*AlwaysInline=*/false,
3524 MachinePointerInfo(0), MachinePointerInfo(0));
3525 MemOpChains.push_back(Chain);
3529 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3530 const MipsCC &CC, SDValue Chain,
3531 SDLoc DL, SelectionDAG &DAG) const {
3532 unsigned NumRegs = CC.numIntArgRegs();
3533 const uint16_t *ArgRegs = CC.intArgRegs();
3534 const CCState &CCInfo = CC.getCCInfo();
3535 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3536 unsigned RegSize = CC.regSize();
3537 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3538 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3539 MachineFunction &MF = DAG.getMachineFunction();
3540 MachineFrameInfo *MFI = MF.getFrameInfo();
3541 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3543 // Offset of the first variable argument from stack pointer.
3547 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3550 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3552 // Record the frame index of the first variable argument
3553 // which is a value necessary to VASTART.
3554 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3555 MipsFI->setVarArgsFrameIndex(FI);
3557 // Copy the integer registers that have not been used for argument passing
3558 // to the argument register save area. For O32, the save area is allocated
3559 // in the caller's stack frame, while for N32/64, it is allocated in the
3560 // callee's stack frame.
3561 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3562 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3563 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3564 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3565 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3566 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3567 MachinePointerInfo(), false, false, 0);
3568 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3569 OutChains.push_back(Store);