1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "mips-lower"
15 #include "MipsISelLowering.h"
16 #include "InstPrinter/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsBaseInfo.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
41 STATISTIC(NumTailCalls, "Number of tail calls");
44 LargeGOT("mxgot", cl::Hidden,
45 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
48 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
49 cl::desc("MIPS: Don't trap on integer division by zero."),
52 static const uint16_t O32IntRegs[4] = {
53 Mips::A0, Mips::A1, Mips::A2, Mips::A3
56 static const uint16_t Mips64IntRegs[8] = {
57 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
58 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
61 static const uint16_t Mips64DPRegs[8] = {
62 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
63 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
66 // If I is a shifted mask, set the size (Size) and the first bit of the
67 // mask (Pos), and return true.
68 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
69 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
70 if (!isShiftedMask_64(I))
73 Size = CountPopulation_64(I);
74 Pos = countTrailingZeros(I);
78 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
79 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
80 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
83 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
84 EVT Ty = Op.getValueType();
86 if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
87 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(Op), Ty, 0,
89 if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
90 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
91 if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
92 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
93 if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
94 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
95 if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
96 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
97 N->getOffset(), Flag);
99 llvm_unreachable("Unexpected node type.");
103 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
105 EVT Ty = Op.getValueType();
106 SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
107 SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
108 return DAG.getNode(ISD::ADD, DL, Ty,
109 DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
110 DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
113 SDValue MipsTargetLowering::getAddrLocal(SDValue Op, SelectionDAG &DAG,
114 bool HasMips64) const {
116 EVT Ty = Op.getValueType();
117 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
118 SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
119 getTargetNode(Op, DAG, GOTFlag));
120 SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
121 MachinePointerInfo::getGOT(), false, false, false,
123 unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
124 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
125 return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
128 SDValue MipsTargetLowering::getAddrGlobal(SDValue Op, SelectionDAG &DAG,
129 unsigned Flag) const {
131 EVT Ty = Op.getValueType();
132 SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
133 getTargetNode(Op, DAG, Flag));
134 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
135 MachinePointerInfo::getGOT(), false, false, false, 0);
138 SDValue MipsTargetLowering::getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
140 unsigned LoFlag) const {
142 EVT Ty = Op.getValueType();
143 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
144 Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, getGlobalReg(DAG, Ty));
145 SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
146 getTargetNode(Op, DAG, LoFlag));
147 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
148 MachinePointerInfo::getGOT(), false, false, false, 0);
151 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
153 case MipsISD::JmpLink: return "MipsISD::JmpLink";
154 case MipsISD::TailCall: return "MipsISD::TailCall";
155 case MipsISD::Hi: return "MipsISD::Hi";
156 case MipsISD::Lo: return "MipsISD::Lo";
157 case MipsISD::GPRel: return "MipsISD::GPRel";
158 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
159 case MipsISD::Ret: return "MipsISD::Ret";
160 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
161 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
162 case MipsISD::FPCmp: return "MipsISD::FPCmp";
163 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
164 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
165 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
166 case MipsISD::ExtractLOHI: return "MipsISD::ExtractLOHI";
167 case MipsISD::InsertLOHI: return "MipsISD::InsertLOHI";
168 case MipsISD::Mult: return "MipsISD::Mult";
169 case MipsISD::Multu: return "MipsISD::Multu";
170 case MipsISD::MAdd: return "MipsISD::MAdd";
171 case MipsISD::MAddu: return "MipsISD::MAddu";
172 case MipsISD::MSub: return "MipsISD::MSub";
173 case MipsISD::MSubu: return "MipsISD::MSubu";
174 case MipsISD::DivRem: return "MipsISD::DivRem";
175 case MipsISD::DivRemU: return "MipsISD::DivRemU";
176 case MipsISD::DivRem16: return "MipsISD::DivRem16";
177 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
178 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
179 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
180 case MipsISD::Wrapper: return "MipsISD::Wrapper";
181 case MipsISD::Sync: return "MipsISD::Sync";
182 case MipsISD::Ext: return "MipsISD::Ext";
183 case MipsISD::Ins: return "MipsISD::Ins";
184 case MipsISD::LWL: return "MipsISD::LWL";
185 case MipsISD::LWR: return "MipsISD::LWR";
186 case MipsISD::SWL: return "MipsISD::SWL";
187 case MipsISD::SWR: return "MipsISD::SWR";
188 case MipsISD::LDL: return "MipsISD::LDL";
189 case MipsISD::LDR: return "MipsISD::LDR";
190 case MipsISD::SDL: return "MipsISD::SDL";
191 case MipsISD::SDR: return "MipsISD::SDR";
192 case MipsISD::EXTP: return "MipsISD::EXTP";
193 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
194 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
195 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
196 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
197 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
198 case MipsISD::SHILO: return "MipsISD::SHILO";
199 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
200 case MipsISD::MULT: return "MipsISD::MULT";
201 case MipsISD::MULTU: return "MipsISD::MULTU";
202 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
203 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
204 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
205 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
206 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
207 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
208 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
209 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
210 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
211 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
212 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
213 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
214 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
215 case MipsISD::VCEQ: return "MipsISD::VCEQ";
216 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
217 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
218 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
219 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
220 case MipsISD::VSMAX: return "MipsISD::VSMAX";
221 case MipsISD::VSMIN: return "MipsISD::VSMIN";
222 case MipsISD::VUMAX: return "MipsISD::VUMAX";
223 case MipsISD::VUMIN: return "MipsISD::VUMIN";
224 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
225 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
226 case MipsISD::VNOR: return "MipsISD::VNOR";
227 default: return NULL;
232 MipsTargetLowering(MipsTargetMachine &TM)
233 : TargetLowering(TM, new MipsTargetObjectFile()),
234 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
235 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
236 IsO32(Subtarget->isABI_O32()) {
237 // Mips does not have i1 type, so use i32 for
238 // setcc operations results (slt, sgt, ...).
239 setBooleanContents(ZeroOrOneBooleanContent);
240 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
242 // Load extented operations for i1 types must be promoted
243 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
244 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
245 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
247 // MIPS doesn't have extending float->double load/store
248 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
249 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
251 // Used by legalize types to correctly generate the setcc result.
252 // Without this, every float setcc comes with a AND/OR with the result,
253 // we don't want this, since the fpcmp result goes to a flag register,
254 // which is used implicitly by brcond and select operations.
255 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
257 // Mips Custom Operations
258 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
259 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
260 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
261 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
262 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
263 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
264 setOperationAction(ISD::SELECT, MVT::f32, Custom);
265 setOperationAction(ISD::SELECT, MVT::f64, Custom);
266 setOperationAction(ISD::SELECT, MVT::i32, Custom);
267 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
268 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
269 setOperationAction(ISD::SETCC, MVT::f32, Custom);
270 setOperationAction(ISD::SETCC, MVT::f64, Custom);
271 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
272 setOperationAction(ISD::VASTART, MVT::Other, Custom);
273 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
274 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
275 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
277 if (!TM.Options.NoNaNsFPMath) {
278 setOperationAction(ISD::FABS, MVT::f32, Custom);
279 setOperationAction(ISD::FABS, MVT::f64, Custom);
283 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
284 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
285 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
286 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
287 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
288 setOperationAction(ISD::SELECT, MVT::i64, Custom);
289 setOperationAction(ISD::LOAD, MVT::i64, Custom);
290 setOperationAction(ISD::STORE, MVT::i64, Custom);
291 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
295 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
296 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
297 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
300 setOperationAction(ISD::ADD, MVT::i32, Custom);
302 setOperationAction(ISD::ADD, MVT::i64, Custom);
304 setOperationAction(ISD::SDIV, MVT::i32, Expand);
305 setOperationAction(ISD::SREM, MVT::i32, Expand);
306 setOperationAction(ISD::UDIV, MVT::i32, Expand);
307 setOperationAction(ISD::UREM, MVT::i32, Expand);
308 setOperationAction(ISD::SDIV, MVT::i64, Expand);
309 setOperationAction(ISD::SREM, MVT::i64, Expand);
310 setOperationAction(ISD::UDIV, MVT::i64, Expand);
311 setOperationAction(ISD::UREM, MVT::i64, Expand);
313 // Operations not directly supported by Mips.
314 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
315 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
316 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
317 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
318 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
319 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
320 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
321 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
322 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
323 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
324 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
325 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
326 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
327 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
328 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
329 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
330 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
331 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
332 setOperationAction(ISD::ROTL, MVT::i32, Expand);
333 setOperationAction(ISD::ROTL, MVT::i64, Expand);
334 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
335 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
337 if (!Subtarget->hasMips32r2())
338 setOperationAction(ISD::ROTR, MVT::i32, Expand);
340 if (!Subtarget->hasMips64r2())
341 setOperationAction(ISD::ROTR, MVT::i64, Expand);
343 setOperationAction(ISD::FSIN, MVT::f32, Expand);
344 setOperationAction(ISD::FSIN, MVT::f64, Expand);
345 setOperationAction(ISD::FCOS, MVT::f32, Expand);
346 setOperationAction(ISD::FCOS, MVT::f64, Expand);
347 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
348 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
349 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
350 setOperationAction(ISD::FPOW, MVT::f32, Expand);
351 setOperationAction(ISD::FPOW, MVT::f64, Expand);
352 setOperationAction(ISD::FLOG, MVT::f32, Expand);
353 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
354 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
355 setOperationAction(ISD::FEXP, MVT::f32, Expand);
356 setOperationAction(ISD::FMA, MVT::f32, Expand);
357 setOperationAction(ISD::FMA, MVT::f64, Expand);
358 setOperationAction(ISD::FREM, MVT::f32, Expand);
359 setOperationAction(ISD::FREM, MVT::f64, Expand);
361 if (!TM.Options.NoNaNsFPMath) {
362 setOperationAction(ISD::FNEG, MVT::f32, Expand);
363 setOperationAction(ISD::FNEG, MVT::f64, Expand);
366 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
368 setOperationAction(ISD::VAARG, MVT::Other, Expand);
369 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
370 setOperationAction(ISD::VAEND, MVT::Other, Expand);
372 // Use the default for now
373 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
374 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
376 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
377 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
378 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
379 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
381 setInsertFencesForAtomic(true);
383 if (!Subtarget->hasSEInReg()) {
384 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
385 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
388 if (!Subtarget->hasBitCount()) {
389 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
390 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
393 if (!Subtarget->hasSwap()) {
394 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
395 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
399 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
400 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
401 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
402 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
405 setOperationAction(ISD::TRAP, MVT::Other, Legal);
407 setTargetDAGCombine(ISD::SDIVREM);
408 setTargetDAGCombine(ISD::UDIVREM);
409 setTargetDAGCombine(ISD::SELECT);
410 setTargetDAGCombine(ISD::AND);
411 setTargetDAGCombine(ISD::OR);
412 setTargetDAGCombine(ISD::ADD);
414 setMinFunctionAlignment(HasMips64 ? 3 : 2);
416 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
418 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
419 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
421 MaxStoresPerMemcpy = 16;
424 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
425 if (TM.getSubtargetImpl()->inMips16Mode())
426 return llvm::createMips16TargetLowering(TM);
428 return llvm::createMipsSETargetLowering(TM);
431 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
434 return VT.changeVectorElementTypeToInteger();
437 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
438 TargetLowering::DAGCombinerInfo &DCI,
439 const MipsSubtarget *Subtarget) {
440 if (DCI.isBeforeLegalizeOps())
443 EVT Ty = N->getValueType(0);
444 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
445 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
446 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
450 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
451 N->getOperand(0), N->getOperand(1));
452 SDValue InChain = DAG.getEntryNode();
453 SDValue InGlue = DivRem;
456 if (N->hasAnyUseOfValue(0)) {
457 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
459 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
460 InChain = CopyFromLo.getValue(1);
461 InGlue = CopyFromLo.getValue(2);
465 if (N->hasAnyUseOfValue(1)) {
466 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
468 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
474 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
476 default: llvm_unreachable("Unknown fp condition code!");
478 case ISD::SETOEQ: return Mips::FCOND_OEQ;
479 case ISD::SETUNE: return Mips::FCOND_UNE;
481 case ISD::SETOLT: return Mips::FCOND_OLT;
483 case ISD::SETOGT: return Mips::FCOND_OGT;
485 case ISD::SETOLE: return Mips::FCOND_OLE;
487 case ISD::SETOGE: return Mips::FCOND_OGE;
488 case ISD::SETULT: return Mips::FCOND_ULT;
489 case ISD::SETULE: return Mips::FCOND_ULE;
490 case ISD::SETUGT: return Mips::FCOND_UGT;
491 case ISD::SETUGE: return Mips::FCOND_UGE;
492 case ISD::SETUO: return Mips::FCOND_UN;
493 case ISD::SETO: return Mips::FCOND_OR;
495 case ISD::SETONE: return Mips::FCOND_ONE;
496 case ISD::SETUEQ: return Mips::FCOND_UEQ;
501 /// This function returns true if the floating point conditional branches and
502 /// conditional moves which use condition code CC should be inverted.
503 static bool invertFPCondCodeUser(Mips::CondCode CC) {
504 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
507 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
508 "Illegal Condition Code");
513 // Creates and returns an FPCmp node from a setcc node.
514 // Returns Op if setcc is not a floating point comparison.
515 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
516 // must be a SETCC node
517 if (Op.getOpcode() != ISD::SETCC)
520 SDValue LHS = Op.getOperand(0);
522 if (!LHS.getValueType().isFloatingPoint())
525 SDValue RHS = Op.getOperand(1);
528 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
529 // node if necessary.
530 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
532 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
533 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
536 // Creates and returns a CMovFPT/F node.
537 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
538 SDValue False, SDLoc DL) {
539 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
540 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
541 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
543 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
544 True.getValueType(), True, FCC0, False, Cond);
547 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
548 TargetLowering::DAGCombinerInfo &DCI,
549 const MipsSubtarget *Subtarget) {
550 if (DCI.isBeforeLegalizeOps())
553 SDValue SetCC = N->getOperand(0);
555 if ((SetCC.getOpcode() != ISD::SETCC) ||
556 !SetCC.getOperand(0).getValueType().isInteger())
559 SDValue False = N->getOperand(2);
560 EVT FalseTy = False.getValueType();
562 if (!FalseTy.isInteger())
565 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
567 if (!CN || CN->getZExtValue())
571 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
572 SDValue True = N->getOperand(1);
574 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
575 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
577 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
580 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
581 TargetLowering::DAGCombinerInfo &DCI,
582 const MipsSubtarget *Subtarget) {
583 // Pattern match EXT.
584 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
585 // => ext $dst, $src, size, pos
586 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
589 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
590 unsigned ShiftRightOpc = ShiftRight.getOpcode();
592 // Op's first operand must be a shift right.
593 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
596 // The second operand of the shift must be an immediate.
598 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
601 uint64_t Pos = CN->getZExtValue();
602 uint64_t SMPos, SMSize;
604 // Op's second operand must be a shifted mask.
605 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
606 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
609 // Return if the shifted mask does not start at bit 0 or the sum of its size
610 // and Pos exceeds the word's size.
611 EVT ValTy = N->getValueType(0);
612 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
615 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
616 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
617 DAG.getConstant(SMSize, MVT::i32));
620 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
621 TargetLowering::DAGCombinerInfo &DCI,
622 const MipsSubtarget *Subtarget) {
623 // Pattern match INS.
624 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
625 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
626 // => ins $dst, $src, size, pos, $src1
627 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
630 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
631 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
634 // See if Op's first operand matches (and $src1 , mask0).
635 if (And0.getOpcode() != ISD::AND)
638 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
639 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
642 // See if Op's second operand matches (and (shl $src, pos), mask1).
643 if (And1.getOpcode() != ISD::AND)
646 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
647 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
650 // The shift masks must have the same position and size.
651 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
654 SDValue Shl = And1.getOperand(0);
655 if (Shl.getOpcode() != ISD::SHL)
658 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
661 unsigned Shamt = CN->getZExtValue();
663 // Return if the shift amount and the first bit position of mask are not the
665 EVT ValTy = N->getValueType(0);
666 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
669 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
670 DAG.getConstant(SMPos0, MVT::i32),
671 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
674 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
675 TargetLowering::DAGCombinerInfo &DCI,
676 const MipsSubtarget *Subtarget) {
677 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
679 if (DCI.isBeforeLegalizeOps())
682 SDValue Add = N->getOperand(1);
684 if (Add.getOpcode() != ISD::ADD)
687 SDValue Lo = Add.getOperand(1);
689 if ((Lo.getOpcode() != MipsISD::Lo) ||
690 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
693 EVT ValTy = N->getValueType(0);
696 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
698 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
701 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
703 SelectionDAG &DAG = DCI.DAG;
704 unsigned Opc = N->getOpcode();
710 return performDivRemCombine(N, DAG, DCI, Subtarget);
712 return performSELECTCombine(N, DAG, DCI, Subtarget);
714 return performANDCombine(N, DAG, DCI, Subtarget);
716 return performORCombine(N, DAG, DCI, Subtarget);
718 return performADDCombine(N, DAG, DCI, Subtarget);
725 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
726 SmallVectorImpl<SDValue> &Results,
727 SelectionDAG &DAG) const {
728 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
730 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
731 Results.push_back(Res.getValue(I));
735 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
736 SmallVectorImpl<SDValue> &Results,
737 SelectionDAG &DAG) const {
738 return LowerOperationWrapper(N, Results, DAG);
741 SDValue MipsTargetLowering::
742 LowerOperation(SDValue Op, SelectionDAG &DAG) const
744 switch (Op.getOpcode())
746 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
747 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
748 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
749 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
750 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
751 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
752 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
753 case ISD::SELECT: return lowerSELECT(Op, DAG);
754 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
755 case ISD::SETCC: return lowerSETCC(Op, DAG);
756 case ISD::VASTART: return lowerVASTART(Op, DAG);
757 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
758 case ISD::FABS: return lowerFABS(Op, DAG);
759 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
760 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
761 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
762 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
763 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
764 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
765 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
766 case ISD::LOAD: return lowerLOAD(Op, DAG);
767 case ISD::STORE: return lowerSTORE(Op, DAG);
768 case ISD::ADD: return lowerADD(Op, DAG);
769 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
774 //===----------------------------------------------------------------------===//
775 // Lower helper functions
776 //===----------------------------------------------------------------------===//
778 // addLiveIn - This helper function adds the specified physical register to the
779 // MachineFunction as a live in value. It also creates a corresponding
780 // virtual register for it.
782 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
784 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
785 MF.getRegInfo().addLiveIn(PReg, VReg);
789 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
790 MachineBasicBlock &MBB,
791 const TargetInstrInfo &TII,
796 // Insert instruction "teq $divisor_reg, $zero, 7".
797 MachineBasicBlock::iterator I(MI);
798 MachineInstrBuilder MIB;
799 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
800 .addOperand(MI->getOperand(2)).addReg(Mips::ZERO).addImm(7);
802 // Use the 32-bit sub-register if this is a 64-bit division.
804 MIB->getOperand(0).setSubReg(Mips::sub_32);
810 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
811 MachineBasicBlock *BB) const {
812 switch (MI->getOpcode()) {
814 llvm_unreachable("Unexpected instr type to insert");
815 case Mips::ATOMIC_LOAD_ADD_I8:
816 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
817 case Mips::ATOMIC_LOAD_ADD_I16:
818 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
819 case Mips::ATOMIC_LOAD_ADD_I32:
820 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
821 case Mips::ATOMIC_LOAD_ADD_I64:
822 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
824 case Mips::ATOMIC_LOAD_AND_I8:
825 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
826 case Mips::ATOMIC_LOAD_AND_I16:
827 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
828 case Mips::ATOMIC_LOAD_AND_I32:
829 return emitAtomicBinary(MI, BB, 4, Mips::AND);
830 case Mips::ATOMIC_LOAD_AND_I64:
831 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
833 case Mips::ATOMIC_LOAD_OR_I8:
834 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
835 case Mips::ATOMIC_LOAD_OR_I16:
836 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
837 case Mips::ATOMIC_LOAD_OR_I32:
838 return emitAtomicBinary(MI, BB, 4, Mips::OR);
839 case Mips::ATOMIC_LOAD_OR_I64:
840 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
842 case Mips::ATOMIC_LOAD_XOR_I8:
843 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
844 case Mips::ATOMIC_LOAD_XOR_I16:
845 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
846 case Mips::ATOMIC_LOAD_XOR_I32:
847 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
848 case Mips::ATOMIC_LOAD_XOR_I64:
849 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
851 case Mips::ATOMIC_LOAD_NAND_I8:
852 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
853 case Mips::ATOMIC_LOAD_NAND_I16:
854 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
855 case Mips::ATOMIC_LOAD_NAND_I32:
856 return emitAtomicBinary(MI, BB, 4, 0, true);
857 case Mips::ATOMIC_LOAD_NAND_I64:
858 return emitAtomicBinary(MI, BB, 8, 0, true);
860 case Mips::ATOMIC_LOAD_SUB_I8:
861 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
862 case Mips::ATOMIC_LOAD_SUB_I16:
863 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
864 case Mips::ATOMIC_LOAD_SUB_I32:
865 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
866 case Mips::ATOMIC_LOAD_SUB_I64:
867 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
869 case Mips::ATOMIC_SWAP_I8:
870 return emitAtomicBinaryPartword(MI, BB, 1, 0);
871 case Mips::ATOMIC_SWAP_I16:
872 return emitAtomicBinaryPartword(MI, BB, 2, 0);
873 case Mips::ATOMIC_SWAP_I32:
874 return emitAtomicBinary(MI, BB, 4, 0);
875 case Mips::ATOMIC_SWAP_I64:
876 return emitAtomicBinary(MI, BB, 8, 0);
878 case Mips::ATOMIC_CMP_SWAP_I8:
879 return emitAtomicCmpSwapPartword(MI, BB, 1);
880 case Mips::ATOMIC_CMP_SWAP_I16:
881 return emitAtomicCmpSwapPartword(MI, BB, 2);
882 case Mips::ATOMIC_CMP_SWAP_I32:
883 return emitAtomicCmpSwap(MI, BB, 4);
884 case Mips::ATOMIC_CMP_SWAP_I64:
885 return emitAtomicCmpSwap(MI, BB, 8);
886 case Mips::PseudoSDIV:
887 case Mips::PseudoUDIV:
888 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
889 case Mips::PseudoDSDIV:
890 case Mips::PseudoDUDIV:
891 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
895 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
896 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
898 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
899 unsigned Size, unsigned BinOpcode,
901 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
903 MachineFunction *MF = BB->getParent();
904 MachineRegisterInfo &RegInfo = MF->getRegInfo();
905 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
906 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
907 DebugLoc DL = MI->getDebugLoc();
908 unsigned LL, SC, AND, NOR, ZERO, BEQ;
923 ZERO = Mips::ZERO_64;
927 unsigned OldVal = MI->getOperand(0).getReg();
928 unsigned Ptr = MI->getOperand(1).getReg();
929 unsigned Incr = MI->getOperand(2).getReg();
931 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
932 unsigned AndRes = RegInfo.createVirtualRegister(RC);
933 unsigned Success = RegInfo.createVirtualRegister(RC);
935 // insert new blocks after the current block
936 const BasicBlock *LLVM_BB = BB->getBasicBlock();
937 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
938 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
939 MachineFunction::iterator It = BB;
941 MF->insert(It, loopMBB);
942 MF->insert(It, exitMBB);
944 // Transfer the remainder of BB and its successor edges to exitMBB.
945 exitMBB->splice(exitMBB->begin(), BB,
946 llvm::next(MachineBasicBlock::iterator(MI)),
948 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
952 // fallthrough --> loopMBB
953 BB->addSuccessor(loopMBB);
954 loopMBB->addSuccessor(loopMBB);
955 loopMBB->addSuccessor(exitMBB);
959 // <binop> storeval, oldval, incr
960 // sc success, storeval, 0(ptr)
961 // beq success, $0, loopMBB
963 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
965 // and andres, oldval, incr
966 // nor storeval, $0, andres
967 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
968 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
969 } else if (BinOpcode) {
970 // <binop> storeval, oldval, incr
971 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
975 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
976 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
978 MI->eraseFromParent(); // The instruction is gone now.
984 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
985 MachineBasicBlock *BB,
986 unsigned Size, unsigned BinOpcode,
988 assert((Size == 1 || Size == 2) &&
989 "Unsupported size for EmitAtomicBinaryPartial.");
991 MachineFunction *MF = BB->getParent();
992 MachineRegisterInfo &RegInfo = MF->getRegInfo();
993 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
994 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
995 DebugLoc DL = MI->getDebugLoc();
997 unsigned Dest = MI->getOperand(0).getReg();
998 unsigned Ptr = MI->getOperand(1).getReg();
999 unsigned Incr = MI->getOperand(2).getReg();
1001 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1002 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1003 unsigned Mask = RegInfo.createVirtualRegister(RC);
1004 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1005 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1006 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1007 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1008 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1009 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1010 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1011 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1012 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1013 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1014 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1015 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1016 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1017 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1018 unsigned Success = RegInfo.createVirtualRegister(RC);
1020 // insert new blocks after the current block
1021 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1022 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1023 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1024 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1025 MachineFunction::iterator It = BB;
1027 MF->insert(It, loopMBB);
1028 MF->insert(It, sinkMBB);
1029 MF->insert(It, exitMBB);
1031 // Transfer the remainder of BB and its successor edges to exitMBB.
1032 exitMBB->splice(exitMBB->begin(), BB,
1033 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1034 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1036 BB->addSuccessor(loopMBB);
1037 loopMBB->addSuccessor(loopMBB);
1038 loopMBB->addSuccessor(sinkMBB);
1039 sinkMBB->addSuccessor(exitMBB);
1042 // addiu masklsb2,$0,-4 # 0xfffffffc
1043 // and alignedaddr,ptr,masklsb2
1044 // andi ptrlsb2,ptr,3
1045 // sll shiftamt,ptrlsb2,3
1046 // ori maskupper,$0,255 # 0xff
1047 // sll mask,maskupper,shiftamt
1048 // nor mask2,$0,mask
1049 // sll incr2,incr,shiftamt
1051 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1052 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1053 .addReg(Mips::ZERO).addImm(-4);
1054 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1055 .addReg(Ptr).addReg(MaskLSB2);
1056 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1057 if (Subtarget->isLittle()) {
1058 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1060 unsigned Off = RegInfo.createVirtualRegister(RC);
1061 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1062 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1063 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1065 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1066 .addReg(Mips::ZERO).addImm(MaskImm);
1067 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1068 .addReg(MaskUpper).addReg(ShiftAmt);
1069 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1070 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1072 // atomic.load.binop
1074 // ll oldval,0(alignedaddr)
1075 // binop binopres,oldval,incr2
1076 // and newval,binopres,mask
1077 // and maskedoldval0,oldval,mask2
1078 // or storeval,maskedoldval0,newval
1079 // sc success,storeval,0(alignedaddr)
1080 // beq success,$0,loopMBB
1084 // ll oldval,0(alignedaddr)
1085 // and newval,incr2,mask
1086 // and maskedoldval0,oldval,mask2
1087 // or storeval,maskedoldval0,newval
1088 // sc success,storeval,0(alignedaddr)
1089 // beq success,$0,loopMBB
1092 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1094 // and andres, oldval, incr2
1095 // nor binopres, $0, andres
1096 // and newval, binopres, mask
1097 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1098 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1099 .addReg(Mips::ZERO).addReg(AndRes);
1100 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1101 } else if (BinOpcode) {
1102 // <binop> binopres, oldval, incr2
1103 // and newval, binopres, mask
1104 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1105 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1106 } else {// atomic.swap
1107 // and newval, incr2, mask
1108 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1111 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1112 .addReg(OldVal).addReg(Mask2);
1113 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1114 .addReg(MaskedOldVal0).addReg(NewVal);
1115 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1116 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1117 BuildMI(BB, DL, TII->get(Mips::BEQ))
1118 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1121 // and maskedoldval1,oldval,mask
1122 // srl srlres,maskedoldval1,shiftamt
1123 // sll sllres,srlres,24
1124 // sra dest,sllres,24
1126 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1128 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1129 .addReg(OldVal).addReg(Mask);
1130 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1131 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1132 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1133 .addReg(SrlRes).addImm(ShiftImm);
1134 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1135 .addReg(SllRes).addImm(ShiftImm);
1137 MI->eraseFromParent(); // The instruction is gone now.
1143 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1144 MachineBasicBlock *BB,
1145 unsigned Size) const {
1146 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1148 MachineFunction *MF = BB->getParent();
1149 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1150 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1151 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1152 DebugLoc DL = MI->getDebugLoc();
1153 unsigned LL, SC, ZERO, BNE, BEQ;
1165 ZERO = Mips::ZERO_64;
1170 unsigned Dest = MI->getOperand(0).getReg();
1171 unsigned Ptr = MI->getOperand(1).getReg();
1172 unsigned OldVal = MI->getOperand(2).getReg();
1173 unsigned NewVal = MI->getOperand(3).getReg();
1175 unsigned Success = RegInfo.createVirtualRegister(RC);
1177 // insert new blocks after the current block
1178 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1179 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1180 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1181 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1182 MachineFunction::iterator It = BB;
1184 MF->insert(It, loop1MBB);
1185 MF->insert(It, loop2MBB);
1186 MF->insert(It, exitMBB);
1188 // Transfer the remainder of BB and its successor edges to exitMBB.
1189 exitMBB->splice(exitMBB->begin(), BB,
1190 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1191 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1195 // fallthrough --> loop1MBB
1196 BB->addSuccessor(loop1MBB);
1197 loop1MBB->addSuccessor(exitMBB);
1198 loop1MBB->addSuccessor(loop2MBB);
1199 loop2MBB->addSuccessor(loop1MBB);
1200 loop2MBB->addSuccessor(exitMBB);
1204 // bne dest, oldval, exitMBB
1206 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1207 BuildMI(BB, DL, TII->get(BNE))
1208 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1211 // sc success, newval, 0(ptr)
1212 // beq success, $0, loop1MBB
1214 BuildMI(BB, DL, TII->get(SC), Success)
1215 .addReg(NewVal).addReg(Ptr).addImm(0);
1216 BuildMI(BB, DL, TII->get(BEQ))
1217 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1219 MI->eraseFromParent(); // The instruction is gone now.
1225 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1226 MachineBasicBlock *BB,
1227 unsigned Size) const {
1228 assert((Size == 1 || Size == 2) &&
1229 "Unsupported size for EmitAtomicCmpSwapPartial.");
1231 MachineFunction *MF = BB->getParent();
1232 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1233 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1234 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1235 DebugLoc DL = MI->getDebugLoc();
1237 unsigned Dest = MI->getOperand(0).getReg();
1238 unsigned Ptr = MI->getOperand(1).getReg();
1239 unsigned CmpVal = MI->getOperand(2).getReg();
1240 unsigned NewVal = MI->getOperand(3).getReg();
1242 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1243 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1244 unsigned Mask = RegInfo.createVirtualRegister(RC);
1245 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1246 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1247 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1248 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1249 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1250 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1251 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1252 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1253 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1254 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1255 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1256 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1257 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1258 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1259 unsigned Success = RegInfo.createVirtualRegister(RC);
1261 // insert new blocks after the current block
1262 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1263 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1264 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1265 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1266 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1267 MachineFunction::iterator It = BB;
1269 MF->insert(It, loop1MBB);
1270 MF->insert(It, loop2MBB);
1271 MF->insert(It, sinkMBB);
1272 MF->insert(It, exitMBB);
1274 // Transfer the remainder of BB and its successor edges to exitMBB.
1275 exitMBB->splice(exitMBB->begin(), BB,
1276 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1277 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1279 BB->addSuccessor(loop1MBB);
1280 loop1MBB->addSuccessor(sinkMBB);
1281 loop1MBB->addSuccessor(loop2MBB);
1282 loop2MBB->addSuccessor(loop1MBB);
1283 loop2MBB->addSuccessor(sinkMBB);
1284 sinkMBB->addSuccessor(exitMBB);
1286 // FIXME: computation of newval2 can be moved to loop2MBB.
1288 // addiu masklsb2,$0,-4 # 0xfffffffc
1289 // and alignedaddr,ptr,masklsb2
1290 // andi ptrlsb2,ptr,3
1291 // sll shiftamt,ptrlsb2,3
1292 // ori maskupper,$0,255 # 0xff
1293 // sll mask,maskupper,shiftamt
1294 // nor mask2,$0,mask
1295 // andi maskedcmpval,cmpval,255
1296 // sll shiftedcmpval,maskedcmpval,shiftamt
1297 // andi maskednewval,newval,255
1298 // sll shiftednewval,maskednewval,shiftamt
1299 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1300 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1301 .addReg(Mips::ZERO).addImm(-4);
1302 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1303 .addReg(Ptr).addReg(MaskLSB2);
1304 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1305 if (Subtarget->isLittle()) {
1306 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1308 unsigned Off = RegInfo.createVirtualRegister(RC);
1309 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1310 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1311 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1313 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1314 .addReg(Mips::ZERO).addImm(MaskImm);
1315 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1316 .addReg(MaskUpper).addReg(ShiftAmt);
1317 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1318 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1319 .addReg(CmpVal).addImm(MaskImm);
1320 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1321 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1322 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1323 .addReg(NewVal).addImm(MaskImm);
1324 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1325 .addReg(MaskedNewVal).addReg(ShiftAmt);
1328 // ll oldval,0(alginedaddr)
1329 // and maskedoldval0,oldval,mask
1330 // bne maskedoldval0,shiftedcmpval,sinkMBB
1332 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1333 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1334 .addReg(OldVal).addReg(Mask);
1335 BuildMI(BB, DL, TII->get(Mips::BNE))
1336 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1339 // and maskedoldval1,oldval,mask2
1340 // or storeval,maskedoldval1,shiftednewval
1341 // sc success,storeval,0(alignedaddr)
1342 // beq success,$0,loop1MBB
1344 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1345 .addReg(OldVal).addReg(Mask2);
1346 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1347 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1348 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1349 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1350 BuildMI(BB, DL, TII->get(Mips::BEQ))
1351 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1354 // srl srlres,maskedoldval0,shiftamt
1355 // sll sllres,srlres,24
1356 // sra dest,sllres,24
1358 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1360 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1361 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1362 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1363 .addReg(SrlRes).addImm(ShiftImm);
1364 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1365 .addReg(SllRes).addImm(ShiftImm);
1367 MI->eraseFromParent(); // The instruction is gone now.
1372 //===----------------------------------------------------------------------===//
1373 // Misc Lower Operation implementation
1374 //===----------------------------------------------------------------------===//
1375 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1376 SDValue Chain = Op.getOperand(0);
1377 SDValue Table = Op.getOperand(1);
1378 SDValue Index = Op.getOperand(2);
1380 EVT PTy = getPointerTy();
1381 unsigned EntrySize =
1382 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1384 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1385 DAG.getConstant(EntrySize, PTy));
1386 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1388 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1389 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1390 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1392 Chain = Addr.getValue(1);
1394 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1395 // For PIC, the sequence is:
1396 // BRIND(load(Jumptable + index) + RelocBase)
1397 // RelocBase can be JumpTable, GOT or some sort of global base.
1398 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1399 getPICJumpTableRelocBase(Table, DAG));
1402 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1405 SDValue MipsTargetLowering::
1406 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1408 // The first operand is the chain, the second is the condition, the third is
1409 // the block to branch to if the condition is true.
1410 SDValue Chain = Op.getOperand(0);
1411 SDValue Dest = Op.getOperand(2);
1414 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1416 // Return if flag is not set by a floating point comparison.
1417 if (CondRes.getOpcode() != MipsISD::FPCmp)
1420 SDValue CCNode = CondRes.getOperand(2);
1422 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1423 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1424 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1425 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1426 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1427 FCC0, Dest, CondRes);
1430 SDValue MipsTargetLowering::
1431 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1433 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1435 // Return if flag is not set by a floating point comparison.
1436 if (Cond.getOpcode() != MipsISD::FPCmp)
1439 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1443 SDValue MipsTargetLowering::
1444 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1447 EVT Ty = Op.getOperand(0).getValueType();
1448 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1449 getSetCCResultType(*DAG.getContext(), Ty),
1450 Op.getOperand(0), Op.getOperand(1),
1453 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1457 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1458 SDValue Cond = createFPCmp(DAG, Op);
1460 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1461 "Floating point operand expected.");
1463 SDValue True = DAG.getConstant(1, MVT::i32);
1464 SDValue False = DAG.getConstant(0, MVT::i32);
1466 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1469 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1470 SelectionDAG &DAG) const {
1471 // FIXME there isn't actually debug info here
1473 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1475 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1476 const MipsTargetObjectFile &TLOF =
1477 (const MipsTargetObjectFile&)getObjFileLowering();
1479 // %gp_rel relocation
1480 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1481 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1483 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1484 DAG.getVTList(MVT::i32), &GA, 1);
1485 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1486 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1489 // %hi/%lo relocation
1490 return getAddrNonPIC(Op, DAG);
1493 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1494 return getAddrLocal(Op, DAG, HasMips64);
1497 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1498 MipsII::MO_GOT_LO16);
1500 return getAddrGlobal(Op, DAG,
1501 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1504 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1505 SelectionDAG &DAG) const {
1506 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1507 return getAddrNonPIC(Op, DAG);
1509 return getAddrLocal(Op, DAG, HasMips64);
1512 SDValue MipsTargetLowering::
1513 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1515 // If the relocation model is PIC, use the General Dynamic TLS Model or
1516 // Local Dynamic TLS model, otherwise use the Initial Exec or
1517 // Local Exec TLS Model.
1519 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1521 const GlobalValue *GV = GA->getGlobal();
1522 EVT PtrVT = getPointerTy();
1524 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1526 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1527 // General Dynamic and Local Dynamic TLS Model.
1528 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1531 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1532 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1533 getGlobalReg(DAG, PtrVT), TGA);
1534 unsigned PtrSize = PtrVT.getSizeInBits();
1535 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1537 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1541 Entry.Node = Argument;
1543 Args.push_back(Entry);
1545 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1546 false, false, false, false, 0, CallingConv::C,
1547 /*IsTailCall=*/false, /*doesNotRet=*/false,
1548 /*isReturnValueUsed=*/true,
1549 TlsGetAddr, Args, DAG, DL);
1550 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1552 SDValue Ret = CallResult.first;
1554 if (model != TLSModel::LocalDynamic)
1557 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1558 MipsII::MO_DTPREL_HI);
1559 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1560 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1561 MipsII::MO_DTPREL_LO);
1562 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1563 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1564 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1568 if (model == TLSModel::InitialExec) {
1569 // Initial Exec TLS Model
1570 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1571 MipsII::MO_GOTTPREL);
1572 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1574 Offset = DAG.getLoad(PtrVT, DL,
1575 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1576 false, false, false, 0);
1578 // Local Exec TLS Model
1579 assert(model == TLSModel::LocalExec);
1580 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1581 MipsII::MO_TPREL_HI);
1582 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1583 MipsII::MO_TPREL_LO);
1584 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1585 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1586 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1589 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1590 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1593 SDValue MipsTargetLowering::
1594 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1596 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1597 return getAddrNonPIC(Op, DAG);
1599 return getAddrLocal(Op, DAG, HasMips64);
1602 SDValue MipsTargetLowering::
1603 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1605 // gp_rel relocation
1606 // FIXME: we should reference the constant pool using small data sections,
1607 // but the asm printer currently doesn't support this feature without
1608 // hacking it. This feature should come soon so we can uncomment the
1610 //if (IsInSmallSection(C->getType())) {
1611 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1612 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1613 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1615 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1616 return getAddrNonPIC(Op, DAG);
1618 return getAddrLocal(Op, DAG, HasMips64);
1621 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1622 MachineFunction &MF = DAG.getMachineFunction();
1623 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1626 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1629 // vastart just stores the address of the VarArgsFrameIndex slot into the
1630 // memory location argument.
1631 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1632 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1633 MachinePointerInfo(SV), false, false, 0);
1636 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1637 EVT TyX = Op.getOperand(0).getValueType();
1638 EVT TyY = Op.getOperand(1).getValueType();
1639 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1640 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1644 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1646 SDValue X = (TyX == MVT::f32) ?
1647 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1648 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1650 SDValue Y = (TyY == MVT::f32) ?
1651 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1652 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1656 // ext E, Y, 31, 1 ; extract bit31 of Y
1657 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1658 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1659 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1662 // srl SrlX, SllX, 1
1664 // sll SllY, SrlX, 31
1665 // or Or, SrlX, SllY
1666 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1667 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1668 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1669 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1670 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1673 if (TyX == MVT::f32)
1674 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1676 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1677 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1678 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1681 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1682 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1683 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1684 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1685 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1688 // Bitcast to integer nodes.
1689 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1690 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1693 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1694 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1695 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1696 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1698 if (WidthX > WidthY)
1699 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1700 else if (WidthY > WidthX)
1701 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1703 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1704 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1705 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1708 // (d)sll SllX, X, 1
1709 // (d)srl SrlX, SllX, 1
1710 // (d)srl SrlY, Y, width(Y)-1
1711 // (d)sll SllY, SrlX, width(Y)-1
1712 // or Or, SrlX, SllY
1713 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1714 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1715 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1716 DAG.getConstant(WidthY - 1, MVT::i32));
1718 if (WidthX > WidthY)
1719 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1720 else if (WidthY > WidthX)
1721 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1723 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1724 DAG.getConstant(WidthX - 1, MVT::i32));
1725 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1726 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1730 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1731 if (Subtarget->hasMips64())
1732 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1734 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1737 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1738 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1741 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1743 SDValue X = (Op.getValueType() == MVT::f32) ?
1744 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1745 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1750 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1751 DAG.getRegister(Mips::ZERO, MVT::i32),
1752 DAG.getConstant(31, MVT::i32), Const1, X);
1754 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1755 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1758 if (Op.getValueType() == MVT::f32)
1759 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1761 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1762 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1763 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1766 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1767 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1770 // Bitcast to integer node.
1771 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1775 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1776 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1777 DAG.getConstant(63, MVT::i32), Const1, X);
1779 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1780 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1783 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1787 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1788 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1789 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1791 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1794 SDValue MipsTargetLowering::
1795 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1797 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1798 "Frame address can only be determined for current frame.");
1800 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1801 MFI->setFrameAddressIsTaken(true);
1802 EVT VT = Op.getValueType();
1804 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1805 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1809 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1810 SelectionDAG &DAG) const {
1812 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1813 "Return address can be determined only for current frame.");
1815 MachineFunction &MF = DAG.getMachineFunction();
1816 MachineFrameInfo *MFI = MF.getFrameInfo();
1817 MVT VT = Op.getSimpleValueType();
1818 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1819 MFI->setReturnAddressIsTaken(true);
1821 // Return RA, which contains the return address. Mark it an implicit live-in.
1822 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1823 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1826 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1827 // generated from __builtin_eh_return (offset, handler)
1828 // The effect of this is to adjust the stack pointer by "offset"
1829 // and then branch to "handler".
1830 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1832 MachineFunction &MF = DAG.getMachineFunction();
1833 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1835 MipsFI->setCallsEhReturn();
1836 SDValue Chain = Op.getOperand(0);
1837 SDValue Offset = Op.getOperand(1);
1838 SDValue Handler = Op.getOperand(2);
1840 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1842 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1843 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1844 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1845 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1846 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1847 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1848 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1849 DAG.getRegister(OffsetReg, Ty),
1850 DAG.getRegister(AddrReg, getPointerTy()),
1854 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1855 SelectionDAG &DAG) const {
1856 // FIXME: Need pseudo-fence for 'singlethread' fences
1857 // FIXME: Set SType for weaker fences where supported/appropriate.
1860 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1861 DAG.getConstant(SType, MVT::i32));
1864 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1865 SelectionDAG &DAG) const {
1867 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1868 SDValue Shamt = Op.getOperand(2);
1871 // lo = (shl lo, shamt)
1872 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1875 // hi = (shl lo, shamt[4:0])
1876 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1877 DAG.getConstant(-1, MVT::i32));
1878 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1879 DAG.getConstant(1, MVT::i32));
1880 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1882 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1883 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1884 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1885 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1886 DAG.getConstant(0x20, MVT::i32));
1887 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1888 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1889 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1891 SDValue Ops[2] = {Lo, Hi};
1892 return DAG.getMergeValues(Ops, 2, DL);
1895 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1898 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1899 SDValue Shamt = Op.getOperand(2);
1902 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1904 // hi = (sra hi, shamt)
1906 // hi = (srl hi, shamt)
1909 // lo = (sra hi, shamt[4:0])
1910 // hi = (sra hi, 31)
1912 // lo = (srl hi, shamt[4:0])
1914 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1915 DAG.getConstant(-1, MVT::i32));
1916 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1917 DAG.getConstant(1, MVT::i32));
1918 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1919 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1920 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1921 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1923 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1924 DAG.getConstant(0x20, MVT::i32));
1925 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1926 DAG.getConstant(31, MVT::i32));
1927 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1928 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1929 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1932 SDValue Ops[2] = {Lo, Hi};
1933 return DAG.getMergeValues(Ops, 2, DL);
1936 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1937 SDValue Chain, SDValue Src, unsigned Offset) {
1938 SDValue Ptr = LD->getBasePtr();
1939 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1940 EVT BasePtrVT = Ptr.getValueType();
1942 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1945 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1946 DAG.getConstant(Offset, BasePtrVT));
1948 SDValue Ops[] = { Chain, Ptr, Src };
1949 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1950 LD->getMemOperand());
1953 // Expand an unaligned 32 or 64-bit integer load node.
1954 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1955 LoadSDNode *LD = cast<LoadSDNode>(Op);
1956 EVT MemVT = LD->getMemoryVT();
1958 // Return if load is aligned or if MemVT is neither i32 nor i64.
1959 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1960 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1963 bool IsLittle = Subtarget->isLittle();
1964 EVT VT = Op.getValueType();
1965 ISD::LoadExtType ExtType = LD->getExtensionType();
1966 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1968 assert((VT == MVT::i32) || (VT == MVT::i64));
1971 // (set dst, (i64 (load baseptr)))
1973 // (set tmp, (ldl (add baseptr, 7), undef))
1974 // (set dst, (ldr baseptr, tmp))
1975 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1976 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1978 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1982 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1984 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1988 // (set dst, (i32 (load baseptr))) or
1989 // (set dst, (i64 (sextload baseptr))) or
1990 // (set dst, (i64 (extload baseptr)))
1992 // (set tmp, (lwl (add baseptr, 3), undef))
1993 // (set dst, (lwr baseptr, tmp))
1994 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1995 (ExtType == ISD::EXTLOAD))
1998 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2001 // (set dst, (i64 (zextload baseptr)))
2003 // (set tmp0, (lwl (add baseptr, 3), undef))
2004 // (set tmp1, (lwr baseptr, tmp0))
2005 // (set tmp2, (shl tmp1, 32))
2006 // (set dst, (srl tmp2, 32))
2008 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2009 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2010 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2011 SDValue Ops[] = { SRL, LWR.getValue(1) };
2012 return DAG.getMergeValues(Ops, 2, DL);
2015 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2016 SDValue Chain, unsigned Offset) {
2017 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2018 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2020 SDVTList VTList = DAG.getVTList(MVT::Other);
2023 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2024 DAG.getConstant(Offset, BasePtrVT));
2026 SDValue Ops[] = { Chain, Value, Ptr };
2027 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2028 SD->getMemOperand());
2031 // Expand an unaligned 32 or 64-bit integer store node.
2032 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2034 SDValue Value = SD->getValue(), Chain = SD->getChain();
2035 EVT VT = Value.getValueType();
2038 // (store val, baseptr) or
2039 // (truncstore val, baseptr)
2041 // (swl val, (add baseptr, 3))
2042 // (swr val, baseptr)
2043 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2044 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2046 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2049 assert(VT == MVT::i64);
2052 // (store val, baseptr)
2054 // (sdl val, (add baseptr, 7))
2055 // (sdr val, baseptr)
2056 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2057 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2060 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2061 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2062 SDValue Val = SD->getValue();
2064 if (Val.getOpcode() != ISD::FP_TO_SINT)
2067 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2068 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2071 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2072 SD->getPointerInfo(), SD->isVolatile(),
2073 SD->isNonTemporal(), SD->getAlignment());
2076 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2077 StoreSDNode *SD = cast<StoreSDNode>(Op);
2078 EVT MemVT = SD->getMemoryVT();
2080 // Lower unaligned integer stores.
2081 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2082 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2083 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2085 return lowerFP_TO_SINT_STORE(SD, DAG);
2088 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2089 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2090 || cast<ConstantSDNode>
2091 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2092 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2096 // (add (frameaddr 0), (frame_to_args_offset))
2097 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2098 // (add FrameObject, 0)
2099 // where FrameObject is a fixed StackObject with offset 0 which points to
2100 // the old stack pointer.
2101 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2102 EVT ValTy = Op->getValueType(0);
2103 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2104 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2105 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2106 DAG.getConstant(0, ValTy));
2109 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2110 SelectionDAG &DAG) const {
2111 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2112 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2114 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2117 //===----------------------------------------------------------------------===//
2118 // Calling Convention Implementation
2119 //===----------------------------------------------------------------------===//
2121 //===----------------------------------------------------------------------===//
2122 // TODO: Implement a generic logic using tblgen that can support this.
2123 // Mips O32 ABI rules:
2125 // i32 - Passed in A0, A1, A2, A3 and stack
2126 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2127 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2128 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2129 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2130 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2133 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2134 //===----------------------------------------------------------------------===//
2136 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2137 MVT LocVT, CCValAssign::LocInfo LocInfo,
2138 ISD::ArgFlagsTy ArgFlags, CCState &State,
2139 const uint16_t *F64Regs) {
2141 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2143 static const uint16_t IntRegs[] = {
2144 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2146 static const uint16_t F32Regs[] = {
2147 Mips::F12, Mips::F14
2150 // Do not process byval args here.
2151 if (ArgFlags.isByVal())
2154 // Promote i8 and i16
2155 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2157 if (ArgFlags.isSExt())
2158 LocInfo = CCValAssign::SExt;
2159 else if (ArgFlags.isZExt())
2160 LocInfo = CCValAssign::ZExt;
2162 LocInfo = CCValAssign::AExt;
2167 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2168 // is true: function is vararg, argument is 3rd or higher, there is previous
2169 // argument which is not f32 or f64.
2170 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2171 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2172 unsigned OrigAlign = ArgFlags.getOrigAlign();
2173 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2175 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2176 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2177 // If this is the first part of an i64 arg,
2178 // the allocated register must be either A0 or A2.
2179 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2180 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2182 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2183 // Allocate int register and shadow next int register. If first
2184 // available register is Mips::A1 or Mips::A3, shadow it too.
2185 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2186 if (Reg == Mips::A1 || Reg == Mips::A3)
2187 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2188 State.AllocateReg(IntRegs, IntRegsSize);
2190 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2191 // we are guaranteed to find an available float register
2192 if (ValVT == MVT::f32) {
2193 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2194 // Shadow int register
2195 State.AllocateReg(IntRegs, IntRegsSize);
2197 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2198 // Shadow int registers
2199 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2200 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2201 State.AllocateReg(IntRegs, IntRegsSize);
2202 State.AllocateReg(IntRegs, IntRegsSize);
2205 llvm_unreachable("Cannot handle this ValVT.");
2208 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2210 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2212 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2217 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2218 MVT LocVT, CCValAssign::LocInfo LocInfo,
2219 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2220 static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2222 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2225 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2226 MVT LocVT, CCValAssign::LocInfo LocInfo,
2227 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2228 static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D12_64 };
2230 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2233 #include "MipsGenCallingConv.inc"
2235 //===----------------------------------------------------------------------===//
2236 // Call Calling Convention Implementation
2237 //===----------------------------------------------------------------------===//
2239 // Return next O32 integer argument register.
2240 static unsigned getNextIntArgReg(unsigned Reg) {
2241 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2242 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2246 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2247 SDValue Chain, SDValue Arg, SDLoc DL,
2248 bool IsTailCall, SelectionDAG &DAG) const {
2250 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2251 DAG.getIntPtrConstant(Offset));
2252 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2256 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2257 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2258 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2259 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2260 /*isVolatile=*/ true, false, 0);
2263 void MipsTargetLowering::
2264 getOpndList(SmallVectorImpl<SDValue> &Ops,
2265 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2266 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2267 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2268 // Insert node "GP copy globalreg" before call to function.
2270 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2271 // in PIC mode) allow symbols to be resolved via lazy binding.
2272 // The lazy binding stub requires GP to point to the GOT.
2273 if (IsPICCall && !InternalLinkage) {
2274 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2275 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2276 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2279 // Build a sequence of copy-to-reg nodes chained together with token
2280 // chain and flag operands which copy the outgoing args into registers.
2281 // The InFlag in necessary since all emitted instructions must be
2285 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2286 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2287 RegsToPass[i].second, InFlag);
2288 InFlag = Chain.getValue(1);
2291 // Add argument registers to the end of the list so that they are
2292 // known live into the call.
2293 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2294 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2295 RegsToPass[i].second.getValueType()));
2297 // Add a register mask operand representing the call-preserved registers.
2298 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2299 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2300 assert(Mask && "Missing call preserved mask for calling convention");
2301 if (Subtarget->inMips16HardFloat()) {
2302 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2303 llvm::StringRef Sym = G->getGlobal()->getName();
2304 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2305 if (F->hasFnAttribute("__Mips16RetHelper")) {
2306 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2310 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2312 if (InFlag.getNode())
2313 Ops.push_back(InFlag);
2316 /// LowerCall - functions arguments are copied from virtual regs to
2317 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2319 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2320 SmallVectorImpl<SDValue> &InVals) const {
2321 SelectionDAG &DAG = CLI.DAG;
2323 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2324 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2325 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2326 SDValue Chain = CLI.Chain;
2327 SDValue Callee = CLI.Callee;
2328 bool &IsTailCall = CLI.IsTailCall;
2329 CallingConv::ID CallConv = CLI.CallConv;
2330 bool IsVarArg = CLI.IsVarArg;
2332 MachineFunction &MF = DAG.getMachineFunction();
2333 MachineFrameInfo *MFI = MF.getFrameInfo();
2334 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2335 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2337 // Analyze operands of the call, assigning locations to each operand.
2338 SmallVector<CCValAssign, 16> ArgLocs;
2339 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2340 getTargetMachine(), ArgLocs, *DAG.getContext());
2341 MipsCC::SpecialCallingConvType SpecialCallingConv =
2342 getSpecialCallingConv(Callee);
2343 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2344 SpecialCallingConv);
2346 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2347 Subtarget->mipsSEUsesSoftFloat(),
2348 Callee.getNode(), CLI.Args);
2350 // Get a count of how many bytes are to be pushed on the stack.
2351 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2353 // Check if it's really possible to do a tail call.
2356 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2357 *MF.getInfo<MipsFunctionInfo>());
2362 // Chain is the output chain of the last Load/Store or CopyToReg node.
2363 // ByValChain is the output chain of the last Memcpy node created for copying
2364 // byval arguments to the stack.
2365 unsigned StackAlignment = TFL->getStackAlignment();
2366 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2367 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2370 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2372 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2373 IsN64 ? Mips::SP_64 : Mips::SP,
2376 // With EABI is it possible to have 16 args on registers.
2377 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2378 SmallVector<SDValue, 8> MemOpChains;
2379 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2381 // Walk the register/memloc assignments, inserting copies/loads.
2382 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2383 SDValue Arg = OutVals[i];
2384 CCValAssign &VA = ArgLocs[i];
2385 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2386 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2389 if (Flags.isByVal()) {
2390 assert(Flags.getByValSize() &&
2391 "ByVal args of size 0 should have been ignored by front-end.");
2392 assert(ByValArg != MipsCCInfo.byval_end());
2393 assert(!IsTailCall &&
2394 "Do not tail-call optimize if there is a byval argument.");
2395 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2396 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2401 // Promote the value if needed.
2402 switch (VA.getLocInfo()) {
2403 default: llvm_unreachable("Unknown loc info!");
2404 case CCValAssign::Full:
2405 if (VA.isRegLoc()) {
2406 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2407 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2408 (ValVT == MVT::i64 && LocVT == MVT::f64))
2409 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2410 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2411 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2412 Arg, DAG.getConstant(0, MVT::i32));
2413 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2414 Arg, DAG.getConstant(1, MVT::i32));
2415 if (!Subtarget->isLittle())
2417 unsigned LocRegLo = VA.getLocReg();
2418 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2419 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2420 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2425 case CCValAssign::SExt:
2426 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2428 case CCValAssign::ZExt:
2429 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2431 case CCValAssign::AExt:
2432 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2436 // Arguments that can be passed on register must be kept at
2437 // RegsToPass vector
2438 if (VA.isRegLoc()) {
2439 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2443 // Register can't get to this point...
2444 assert(VA.isMemLoc());
2446 // emit ISD::STORE whichs stores the
2447 // parameter value to a stack Location
2448 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2449 Chain, Arg, DL, IsTailCall, DAG));
2452 // Transform all store nodes into one single node because all store
2453 // nodes are independent of each other.
2454 if (!MemOpChains.empty())
2455 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2456 &MemOpChains[0], MemOpChains.size());
2458 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2459 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2460 // node so that legalize doesn't hack it.
2461 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2462 bool GlobalOrExternal = false, InternalLinkage = false;
2465 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2467 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2469 if (InternalLinkage)
2470 Callee = getAddrLocal(Callee, DAG, HasMips64);
2472 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2473 MipsII::MO_CALL_LO16);
2475 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2477 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2478 MipsII::MO_NO_FLAG);
2479 GlobalOrExternal = true;
2481 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2482 if (!IsN64 && !IsPIC) // !N64 && static
2483 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2484 MipsII::MO_NO_FLAG);
2486 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2487 MipsII::MO_CALL_LO16);
2489 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2491 GlobalOrExternal = true;
2494 SmallVector<SDValue, 8> Ops(1, Chain);
2495 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2497 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2498 CLI, Callee, Chain);
2501 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2503 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2504 SDValue InFlag = Chain.getValue(1);
2506 // Create the CALLSEQ_END node.
2507 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2508 DAG.getIntPtrConstant(0, true), InFlag, DL);
2509 InFlag = Chain.getValue(1);
2511 // Handle result values, copying them out of physregs into vregs that we
2513 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2514 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2517 /// LowerCallResult - Lower the result values of a call into the
2518 /// appropriate copies out of appropriate physical registers.
2520 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2521 CallingConv::ID CallConv, bool IsVarArg,
2522 const SmallVectorImpl<ISD::InputArg> &Ins,
2523 SDLoc DL, SelectionDAG &DAG,
2524 SmallVectorImpl<SDValue> &InVals,
2525 const SDNode *CallNode,
2526 const Type *RetTy) const {
2527 // Assign locations to each value returned by this call.
2528 SmallVector<CCValAssign, 16> RVLocs;
2529 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2530 getTargetMachine(), RVLocs, *DAG.getContext());
2531 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2533 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2536 // Copy all of the result registers out of their specified physreg.
2537 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2538 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2539 RVLocs[i].getLocVT(), InFlag);
2540 Chain = Val.getValue(1);
2541 InFlag = Val.getValue(2);
2543 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2544 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2546 InVals.push_back(Val);
2552 //===----------------------------------------------------------------------===//
2553 // Formal Arguments Calling Convention Implementation
2554 //===----------------------------------------------------------------------===//
2555 /// LowerFormalArguments - transform physical registers into virtual registers
2556 /// and generate load operations for arguments places on the stack.
2558 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2559 CallingConv::ID CallConv,
2561 const SmallVectorImpl<ISD::InputArg> &Ins,
2562 SDLoc DL, SelectionDAG &DAG,
2563 SmallVectorImpl<SDValue> &InVals)
2565 MachineFunction &MF = DAG.getMachineFunction();
2566 MachineFrameInfo *MFI = MF.getFrameInfo();
2567 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2569 MipsFI->setVarArgsFrameIndex(0);
2571 // Used with vargs to acumulate store chains.
2572 std::vector<SDValue> OutChains;
2574 // Assign locations to all of the incoming arguments.
2575 SmallVector<CCValAssign, 16> ArgLocs;
2576 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2577 getTargetMachine(), ArgLocs, *DAG.getContext());
2578 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2579 Function::const_arg_iterator FuncArg =
2580 DAG.getMachineFunction().getFunction()->arg_begin();
2581 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2583 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2584 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2585 MipsCCInfo.hasByValArg());
2587 unsigned CurArgIdx = 0;
2588 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2590 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2591 CCValAssign &VA = ArgLocs[i];
2592 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2593 CurArgIdx = Ins[i].OrigArgIndex;
2594 EVT ValVT = VA.getValVT();
2595 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2596 bool IsRegLoc = VA.isRegLoc();
2598 if (Flags.isByVal()) {
2599 assert(Flags.getByValSize() &&
2600 "ByVal args of size 0 should have been ignored by front-end.");
2601 assert(ByValArg != MipsCCInfo.byval_end());
2602 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2603 MipsCCInfo, *ByValArg);
2608 // Arguments stored on registers
2610 EVT RegVT = VA.getLocVT();
2611 unsigned ArgReg = VA.getLocReg();
2612 const TargetRegisterClass *RC;
2614 if (RegVT == MVT::i32)
2615 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2616 &Mips::GPR32RegClass;
2617 else if (RegVT == MVT::i64)
2618 RC = &Mips::GPR64RegClass;
2619 else if (RegVT == MVT::f32)
2620 RC = &Mips::FGR32RegClass;
2621 else if (RegVT == MVT::f64)
2622 RC = Subtarget->isFP64bit() ? &Mips::FGR64RegClass :
2623 &Mips::AFGR64RegClass;
2625 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2627 // Transform the arguments stored on
2628 // physical registers into virtual ones
2629 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2630 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2632 // If this is an 8 or 16-bit value, it has been passed promoted
2633 // to 32 bits. Insert an assert[sz]ext to capture this, then
2634 // truncate to the right size.
2635 if (VA.getLocInfo() != CCValAssign::Full) {
2636 unsigned Opcode = 0;
2637 if (VA.getLocInfo() == CCValAssign::SExt)
2638 Opcode = ISD::AssertSext;
2639 else if (VA.getLocInfo() == CCValAssign::ZExt)
2640 Opcode = ISD::AssertZext;
2642 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2643 DAG.getValueType(ValVT));
2644 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2647 // Handle floating point arguments passed in integer registers and
2648 // long double arguments passed in floating point registers.
2649 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2650 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2651 (RegVT == MVT::f64 && ValVT == MVT::i64))
2652 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2653 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2654 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2655 getNextIntArgReg(ArgReg), RC);
2656 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2657 if (!Subtarget->isLittle())
2658 std::swap(ArgValue, ArgValue2);
2659 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2660 ArgValue, ArgValue2);
2663 InVals.push_back(ArgValue);
2664 } else { // VA.isRegLoc()
2667 assert(VA.isMemLoc());
2669 // The stack pointer offset is relative to the caller stack frame.
2670 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2671 VA.getLocMemOffset(), true);
2673 // Create load nodes to retrieve arguments from the stack
2674 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2675 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2676 MachinePointerInfo::getFixedStack(FI),
2677 false, false, false, 0));
2681 // The mips ABIs for returning structs by value requires that we copy
2682 // the sret argument into $v0 for the return. Save the argument into
2683 // a virtual register so that we can access it from the return points.
2684 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2685 unsigned Reg = MipsFI->getSRetReturnReg();
2687 Reg = MF.getRegInfo().
2688 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2689 MipsFI->setSRetReturnReg(Reg);
2691 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2692 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2696 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2698 // All stores are grouped in one node to allow the matching between
2699 // the size of Ins and InVals. This only happens when on varg functions
2700 if (!OutChains.empty()) {
2701 OutChains.push_back(Chain);
2702 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2703 &OutChains[0], OutChains.size());
2709 //===----------------------------------------------------------------------===//
2710 // Return Value Calling Convention Implementation
2711 //===----------------------------------------------------------------------===//
2714 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2715 MachineFunction &MF, bool IsVarArg,
2716 const SmallVectorImpl<ISD::OutputArg> &Outs,
2717 LLVMContext &Context) const {
2718 SmallVector<CCValAssign, 16> RVLocs;
2719 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2721 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2725 MipsTargetLowering::LowerReturn(SDValue Chain,
2726 CallingConv::ID CallConv, bool IsVarArg,
2727 const SmallVectorImpl<ISD::OutputArg> &Outs,
2728 const SmallVectorImpl<SDValue> &OutVals,
2729 SDLoc DL, SelectionDAG &DAG) const {
2730 // CCValAssign - represent the assignment of
2731 // the return value to a location
2732 SmallVector<CCValAssign, 16> RVLocs;
2733 MachineFunction &MF = DAG.getMachineFunction();
2735 // CCState - Info about the registers and stack slot.
2736 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2738 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2740 // Analyze return values.
2741 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2742 MF.getFunction()->getReturnType());
2745 SmallVector<SDValue, 4> RetOps(1, Chain);
2747 // Copy the result values into the output registers.
2748 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2749 SDValue Val = OutVals[i];
2750 CCValAssign &VA = RVLocs[i];
2751 assert(VA.isRegLoc() && "Can only return in registers!");
2753 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2754 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2756 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2758 // Guarantee that all emitted copies are stuck together with flags.
2759 Flag = Chain.getValue(1);
2760 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2763 // The mips ABIs for returning structs by value requires that we copy
2764 // the sret argument into $v0 for the return. We saved the argument into
2765 // a virtual register in the entry block, so now we copy the value out
2767 if (MF.getFunction()->hasStructRetAttr()) {
2768 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2769 unsigned Reg = MipsFI->getSRetReturnReg();
2772 llvm_unreachable("sret virtual register not created in the entry block");
2773 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2774 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2776 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2777 Flag = Chain.getValue(1);
2778 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2781 RetOps[0] = Chain; // Update chain.
2783 // Add the flag if we have it.
2785 RetOps.push_back(Flag);
2787 // Return on Mips is always a "jr $ra"
2788 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2791 //===----------------------------------------------------------------------===//
2792 // Mips Inline Assembly Support
2793 //===----------------------------------------------------------------------===//
2795 /// getConstraintType - Given a constraint letter, return the type of
2796 /// constraint it is for this target.
2797 MipsTargetLowering::ConstraintType MipsTargetLowering::
2798 getConstraintType(const std::string &Constraint) const
2800 // Mips specific constrainy
2801 // GCC config/mips/constraints.md
2803 // 'd' : An address register. Equivalent to r
2804 // unless generating MIPS16 code.
2805 // 'y' : Equivalent to r; retained for
2806 // backwards compatibility.
2807 // 'c' : A register suitable for use in an indirect
2808 // jump. This will always be $25 for -mabicalls.
2809 // 'l' : The lo register. 1 word storage.
2810 // 'x' : The hilo register pair. Double word storage.
2811 if (Constraint.size() == 1) {
2812 switch (Constraint[0]) {
2820 return C_RegisterClass;
2825 return TargetLowering::getConstraintType(Constraint);
2828 /// Examine constraint type and operand type and determine a weight value.
2829 /// This object must already have been set up with the operand type
2830 /// and the current alternative constraint selected.
2831 TargetLowering::ConstraintWeight
2832 MipsTargetLowering::getSingleConstraintMatchWeight(
2833 AsmOperandInfo &info, const char *constraint) const {
2834 ConstraintWeight weight = CW_Invalid;
2835 Value *CallOperandVal = info.CallOperandVal;
2836 // If we don't have a value, we can't do a match,
2837 // but allow it at the lowest weight.
2838 if (CallOperandVal == NULL)
2840 Type *type = CallOperandVal->getType();
2841 // Look at the constraint type.
2842 switch (*constraint) {
2844 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2848 if (type->isIntegerTy())
2849 weight = CW_Register;
2852 if (type->isFloatTy())
2853 weight = CW_Register;
2855 case 'c': // $25 for indirect jumps
2856 case 'l': // lo register
2857 case 'x': // hilo register pair
2858 if (type->isIntegerTy())
2859 weight = CW_SpecificReg;
2861 case 'I': // signed 16 bit immediate
2862 case 'J': // integer zero
2863 case 'K': // unsigned 16 bit immediate
2864 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2865 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2866 case 'O': // signed 15 bit immediate (+- 16383)
2867 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2868 if (isa<ConstantInt>(CallOperandVal))
2869 weight = CW_Constant;
2878 /// This is a helper function to parse a physical register string and split it
2879 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2880 /// that is returned indicates whether parsing was successful. The second flag
2881 /// is true if the numeric part exists.
2882 static std::pair<bool, bool>
2883 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2884 unsigned long long &Reg) {
2885 if (C.front() != '{' || C.back() != '}')
2886 return std::make_pair(false, false);
2888 // Search for the first numeric character.
2889 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2890 I = std::find_if(B, E, std::ptr_fun(isdigit));
2892 Prefix.assign(B, I - B);
2894 // The second flag is set to false if no numeric characters were found.
2896 return std::make_pair(true, false);
2898 // Parse the numeric characters.
2899 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2903 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2904 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2905 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2906 const TargetRegisterClass *RC;
2908 unsigned long long Reg;
2910 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2913 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2915 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2916 // No numeric characters follow "hi" or "lo".
2918 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2920 RC = TRI->getRegClass(Prefix == "hi" ?
2921 Mips::HI32RegClassID : Mips::LO32RegClassID);
2922 return std::make_pair(*(RC->begin()), RC);
2926 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2928 if (Prefix == "$f") { // Parse $f0-$f31.
2929 // If the size of FP registers is 64-bit or Reg is an even number, select
2930 // the 64-bit register class. Otherwise, select the 32-bit register class.
2931 if (VT == MVT::Other)
2932 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2934 RC= getRegClassFor(VT);
2936 if (RC == &Mips::AFGR64RegClass) {
2937 assert(Reg % 2 == 0);
2940 } else if (Prefix == "$fcc") { // Parse $fcc0-$fcc7.
2941 RC = TRI->getRegClass(Mips::FCCRegClassID);
2942 } else { // Parse $0-$31.
2943 assert(Prefix == "$");
2944 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2947 assert(Reg < RC->getNumRegs());
2948 return std::make_pair(*(RC->begin() + Reg), RC);
2951 /// Given a register class constraint, like 'r', if this corresponds directly
2952 /// to an LLVM register class, return a register of 0 and the register class
2954 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2955 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2957 if (Constraint.size() == 1) {
2958 switch (Constraint[0]) {
2959 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2960 case 'y': // Same as 'r'. Exists for compatibility.
2962 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2963 if (Subtarget->inMips16Mode())
2964 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2965 return std::make_pair(0U, &Mips::GPR32RegClass);
2967 if (VT == MVT::i64 && !HasMips64)
2968 return std::make_pair(0U, &Mips::GPR32RegClass);
2969 if (VT == MVT::i64 && HasMips64)
2970 return std::make_pair(0U, &Mips::GPR64RegClass);
2971 // This will generate an error message
2972 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2975 return std::make_pair(0U, &Mips::FGR32RegClass);
2976 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2977 if (Subtarget->isFP64bit())
2978 return std::make_pair(0U, &Mips::FGR64RegClass);
2979 return std::make_pair(0U, &Mips::AFGR64RegClass);
2982 case 'c': // register suitable for indirect jump
2984 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
2985 assert(VT == MVT::i64 && "Unexpected type.");
2986 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
2987 case 'l': // register suitable for indirect jump
2989 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
2990 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
2991 case 'x': // register suitable for indirect jump
2992 // Fixme: Not triggering the use of both hi and low
2993 // This will generate an error message
2994 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2998 std::pair<unsigned, const TargetRegisterClass *> R;
2999 R = parseRegForInlineAsmConstraint(Constraint, VT);
3004 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3007 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3008 /// vector. If it is invalid, don't add anything to Ops.
3009 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3010 std::string &Constraint,
3011 std::vector<SDValue>&Ops,
3012 SelectionDAG &DAG) const {
3013 SDValue Result(0, 0);
3015 // Only support length 1 constraints for now.
3016 if (Constraint.length() > 1) return;
3018 char ConstraintLetter = Constraint[0];
3019 switch (ConstraintLetter) {
3020 default: break; // This will fall through to the generic implementation
3021 case 'I': // Signed 16 bit constant
3022 // If this fails, the parent routine will give an error
3023 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3024 EVT Type = Op.getValueType();
3025 int64_t Val = C->getSExtValue();
3026 if (isInt<16>(Val)) {
3027 Result = DAG.getTargetConstant(Val, Type);
3032 case 'J': // integer zero
3033 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3034 EVT Type = Op.getValueType();
3035 int64_t Val = C->getZExtValue();
3037 Result = DAG.getTargetConstant(0, Type);
3042 case 'K': // unsigned 16 bit immediate
3043 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3044 EVT Type = Op.getValueType();
3045 uint64_t Val = (uint64_t)C->getZExtValue();
3046 if (isUInt<16>(Val)) {
3047 Result = DAG.getTargetConstant(Val, Type);
3052 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3053 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3054 EVT Type = Op.getValueType();
3055 int64_t Val = C->getSExtValue();
3056 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3057 Result = DAG.getTargetConstant(Val, Type);
3062 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3063 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3064 EVT Type = Op.getValueType();
3065 int64_t Val = C->getSExtValue();
3066 if ((Val >= -65535) && (Val <= -1)) {
3067 Result = DAG.getTargetConstant(Val, Type);
3072 case 'O': // signed 15 bit immediate
3073 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3074 EVT Type = Op.getValueType();
3075 int64_t Val = C->getSExtValue();
3076 if ((isInt<15>(Val))) {
3077 Result = DAG.getTargetConstant(Val, Type);
3082 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3083 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3084 EVT Type = Op.getValueType();
3085 int64_t Val = C->getSExtValue();
3086 if ((Val <= 65535) && (Val >= 1)) {
3087 Result = DAG.getTargetConstant(Val, Type);
3094 if (Result.getNode()) {
3095 Ops.push_back(Result);
3099 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3103 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3104 // No global is ever allowed as a base.
3109 case 0: // "r+i" or just "i", depending on HasBaseReg.
3112 if (!AM.HasBaseReg) // allow "r+i".
3114 return false; // disallow "r+r" or "r+r+i".
3123 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3124 // The Mips target isn't yet aware of offsets.
3128 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3130 bool IsMemset, bool ZeroMemset,
3132 MachineFunction &MF) const {
3133 if (Subtarget->hasMips64())
3139 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3140 if (VT != MVT::f32 && VT != MVT::f64)
3142 if (Imm.isNegZero())
3144 return Imm.isZero();
3147 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3149 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3151 return TargetLowering::getJumpTableEncoding();
3154 /// This function returns true if CallSym is a long double emulation routine.
3155 static bool isF128SoftLibCall(const char *CallSym) {
3156 const char *const LibCalls[] =
3157 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3158 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3159 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3160 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3161 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3162 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3163 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3164 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3167 const char * const *End = LibCalls + array_lengthof(LibCalls);
3169 // Check that LibCalls is sorted alphabetically.
3170 MipsTargetLowering::LTStr Comp;
3173 for (const char * const *I = LibCalls; I < End - 1; ++I)
3174 assert(Comp(*I, *(I + 1)));
3177 return std::binary_search(LibCalls, End, CallSym, Comp);
3180 /// This function returns true if Ty is fp128 or i128 which was originally a
3182 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3183 if (Ty->isFP128Ty())
3186 const ExternalSymbolSDNode *ES =
3187 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3189 // If the Ty is i128 and the function being called is a long double emulation
3190 // routine, then the original type is f128.
3191 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3194 MipsTargetLowering::MipsCC::SpecialCallingConvType
3195 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3196 MipsCC::SpecialCallingConvType SpecialCallingConv =
3197 MipsCC::NoSpecialCallingConv;;
3198 if (Subtarget->inMips16HardFloat()) {
3199 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3200 llvm::StringRef Sym = G->getGlobal()->getName();
3201 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3202 if (F->hasFnAttribute("__Mips16RetHelper")) {
3203 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3207 return SpecialCallingConv;
3210 MipsTargetLowering::MipsCC::MipsCC(
3211 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3212 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3213 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3214 SpecialCallingConv(SpecialCallingConv_){
3215 // Pre-allocate reserved argument area.
3216 CCInfo.AllocateStack(reservedArgArea(), 1);
3220 void MipsTargetLowering::MipsCC::
3221 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3222 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3223 std::vector<ArgListEntry> &FuncArgs) {
3224 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3225 "CallingConv::Fast shouldn't be used for vararg functions.");
3227 unsigned NumOpnds = Args.size();
3228 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3230 for (unsigned I = 0; I != NumOpnds; ++I) {
3231 MVT ArgVT = Args[I].VT;
3232 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3235 if (ArgFlags.isByVal()) {
3236 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3240 if (IsVarArg && !Args[I].IsFixed)
3241 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3243 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3245 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3250 dbgs() << "Call operand #" << I << " has unhandled type "
3251 << EVT(ArgVT).getEVTString();
3253 llvm_unreachable(0);
3258 void MipsTargetLowering::MipsCC::
3259 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3260 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3261 unsigned NumArgs = Args.size();
3262 llvm::CCAssignFn *FixedFn = fixedArgFn();
3263 unsigned CurArgIdx = 0;
3265 for (unsigned I = 0; I != NumArgs; ++I) {
3266 MVT ArgVT = Args[I].VT;
3267 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3268 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3269 CurArgIdx = Args[I].OrigArgIndex;
3271 if (ArgFlags.isByVal()) {
3272 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3276 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3278 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3282 dbgs() << "Formal Arg #" << I << " has unhandled type "
3283 << EVT(ArgVT).getEVTString();
3285 llvm_unreachable(0);
3289 template<typename Ty>
3290 void MipsTargetLowering::MipsCC::
3291 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3292 const SDNode *CallNode, const Type *RetTy) const {
3295 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3296 Fn = RetCC_F128Soft;
3300 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3301 MVT VT = RetVals[I].VT;
3302 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3303 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3305 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3307 dbgs() << "Call result #" << I << " has unhandled type "
3308 << EVT(VT).getEVTString() << '\n';
3310 llvm_unreachable(0);
3315 void MipsTargetLowering::MipsCC::
3316 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3317 const SDNode *CallNode, const Type *RetTy) const {
3318 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3321 void MipsTargetLowering::MipsCC::
3322 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3323 const Type *RetTy) const {
3324 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3328 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3330 CCValAssign::LocInfo LocInfo,
3331 ISD::ArgFlagsTy ArgFlags) {
3332 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3334 struct ByValArgInfo ByVal;
3335 unsigned RegSize = regSize();
3336 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3337 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3340 if (useRegsForByval())
3341 allocateRegs(ByVal, ByValSize, Align);
3343 // Allocate space on caller's stack.
3344 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3346 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3348 ByValArgs.push_back(ByVal);
3351 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3352 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3355 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3356 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3359 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3360 return IsO32 ? O32IntRegs : Mips64IntRegs;
3363 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3364 if (CallConv == CallingConv::Fast)
3365 return CC_Mips_FastCC;
3367 if (SpecialCallingConv == Mips16RetHelperConv)
3368 return CC_Mips16RetHelper;
3369 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3372 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3373 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3376 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3377 return IsO32 ? O32IntRegs : Mips64DPRegs;
3380 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3383 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3384 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3385 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3386 "Byval argument's size and alignment should be a multiple of"
3389 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3391 // If Align > RegSize, the first arg register must be even.
3392 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3393 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3397 // Mark the registers allocated.
3398 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3399 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3400 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3403 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3404 const SDNode *CallNode,
3405 bool IsSoftFloat) const {
3406 if (IsSoftFloat || IsO32)
3409 // Check if the original type was fp128.
3410 if (originalTypeIsF128(OrigTy, CallNode)) {
3411 assert(VT == MVT::i64);
3418 void MipsTargetLowering::
3419 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3420 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3421 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3422 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3423 MachineFunction &MF = DAG.getMachineFunction();
3424 MachineFrameInfo *MFI = MF.getFrameInfo();
3425 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3426 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3430 FrameObjOffset = (int)CC.reservedArgArea() -
3431 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3433 FrameObjOffset = ByVal.Address;
3435 // Create frame object.
3436 EVT PtrTy = getPointerTy();
3437 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3438 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3439 InVals.push_back(FIN);
3444 // Copy arg registers.
3445 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3446 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3448 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3449 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3450 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3451 unsigned Offset = I * CC.regSize();
3452 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3453 DAG.getConstant(Offset, PtrTy));
3454 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3455 StorePtr, MachinePointerInfo(FuncArg, Offset),
3457 OutChains.push_back(Store);
3461 // Copy byVal arg to registers and stack.
3462 void MipsTargetLowering::
3463 passByValArg(SDValue Chain, SDLoc DL,
3464 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3465 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3466 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3467 const MipsCC &CC, const ByValArgInfo &ByVal,
3468 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3469 unsigned ByValSize = Flags.getByValSize();
3470 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3471 unsigned RegSize = CC.regSize();
3472 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3473 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3475 if (ByVal.NumRegs) {
3476 const uint16_t *ArgRegs = CC.intArgRegs();
3477 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3480 // Copy words to registers.
3481 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3482 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3483 DAG.getConstant(Offset, PtrTy));
3484 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3485 MachinePointerInfo(), false, false, false,
3487 MemOpChains.push_back(LoadVal.getValue(1));
3488 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3489 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3492 // Return if the struct has been fully copied.
3493 if (ByValSize == Offset)
3496 // Copy the remainder of the byval argument with sub-word loads and shifts.
3497 if (LeftoverBytes) {
3498 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3499 "Size of the remainder should be smaller than RegSize.");
3502 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3503 Offset < ByValSize; LoadSize /= 2) {
3504 unsigned RemSize = ByValSize - Offset;
3506 if (RemSize < LoadSize)
3510 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3511 DAG.getConstant(Offset, PtrTy));
3513 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3514 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3515 false, false, Alignment);
3516 MemOpChains.push_back(LoadVal.getValue(1));
3518 // Shift the loaded value.
3522 Shamt = TotalSizeLoaded;
3524 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3526 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3527 DAG.getConstant(Shamt, MVT::i32));
3530 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3535 TotalSizeLoaded += LoadSize;
3536 Alignment = std::min(Alignment, LoadSize);
3539 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3540 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3545 // Copy remainder of byval arg to it with memcpy.
3546 unsigned MemCpySize = ByValSize - Offset;
3547 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3548 DAG.getConstant(Offset, PtrTy));
3549 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3550 DAG.getIntPtrConstant(ByVal.Address));
3551 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3552 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3553 /*isVolatile=*/false, /*AlwaysInline=*/false,
3554 MachinePointerInfo(0), MachinePointerInfo(0));
3555 MemOpChains.push_back(Chain);
3559 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3560 const MipsCC &CC, SDValue Chain,
3561 SDLoc DL, SelectionDAG &DAG) const {
3562 unsigned NumRegs = CC.numIntArgRegs();
3563 const uint16_t *ArgRegs = CC.intArgRegs();
3564 const CCState &CCInfo = CC.getCCInfo();
3565 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3566 unsigned RegSize = CC.regSize();
3567 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3568 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3569 MachineFunction &MF = DAG.getMachineFunction();
3570 MachineFrameInfo *MFI = MF.getFrameInfo();
3571 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3573 // Offset of the first variable argument from stack pointer.
3577 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3580 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3582 // Record the frame index of the first variable argument
3583 // which is a value necessary to VASTART.
3584 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3585 MipsFI->setVarArgsFrameIndex(FI);
3587 // Copy the integer registers that have not been used for argument passing
3588 // to the argument register save area. For O32, the save area is allocated
3589 // in the caller's stack frame, while for N32/64, it is allocated in the
3590 // callee's stack frame.
3591 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3592 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3593 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3594 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3595 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3596 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3597 MachinePointerInfo(), false, false, 0);
3598 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3599 OutChains.push_back(Store);