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::VSPLAT: return "MipsISD::VSPLAT";
216 case MipsISD::VSPLATD: return "MipsISD::VSPLATD";
217 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
218 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
219 case MipsISD::VNOR: return "MipsISD::VNOR";
220 default: return NULL;
225 MipsTargetLowering(MipsTargetMachine &TM)
226 : TargetLowering(TM, new MipsTargetObjectFile()),
227 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
228 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
229 IsO32(Subtarget->isABI_O32()) {
230 // Mips does not have i1 type, so use i32 for
231 // setcc operations results (slt, sgt, ...).
232 setBooleanContents(ZeroOrOneBooleanContent);
233 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
235 // Load extented operations for i1 types must be promoted
236 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
237 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
238 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
240 // MIPS doesn't have extending float->double load/store
241 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
242 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
244 // Used by legalize types to correctly generate the setcc result.
245 // Without this, every float setcc comes with a AND/OR with the result,
246 // we don't want this, since the fpcmp result goes to a flag register,
247 // which is used implicitly by brcond and select operations.
248 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
250 // Mips Custom Operations
251 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
252 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
253 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
254 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
255 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
256 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
257 setOperationAction(ISD::SELECT, MVT::f32, Custom);
258 setOperationAction(ISD::SELECT, MVT::f64, Custom);
259 setOperationAction(ISD::SELECT, MVT::i32, Custom);
260 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
261 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
262 setOperationAction(ISD::SETCC, MVT::f32, Custom);
263 setOperationAction(ISD::SETCC, MVT::f64, Custom);
264 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
265 setOperationAction(ISD::VASTART, MVT::Other, Custom);
266 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
267 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
268 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
270 if (!TM.Options.NoNaNsFPMath) {
271 setOperationAction(ISD::FABS, MVT::f32, Custom);
272 setOperationAction(ISD::FABS, MVT::f64, Custom);
276 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
277 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
278 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
279 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
280 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
281 setOperationAction(ISD::SELECT, MVT::i64, Custom);
282 setOperationAction(ISD::LOAD, MVT::i64, Custom);
283 setOperationAction(ISD::STORE, MVT::i64, Custom);
284 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
288 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
289 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
290 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
293 setOperationAction(ISD::ADD, MVT::i32, Custom);
295 setOperationAction(ISD::ADD, MVT::i64, Custom);
297 setOperationAction(ISD::SDIV, MVT::i32, Expand);
298 setOperationAction(ISD::SREM, MVT::i32, Expand);
299 setOperationAction(ISD::UDIV, MVT::i32, Expand);
300 setOperationAction(ISD::UREM, MVT::i32, Expand);
301 setOperationAction(ISD::SDIV, MVT::i64, Expand);
302 setOperationAction(ISD::SREM, MVT::i64, Expand);
303 setOperationAction(ISD::UDIV, MVT::i64, Expand);
304 setOperationAction(ISD::UREM, MVT::i64, Expand);
306 // Operations not directly supported by Mips.
307 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
308 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
309 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
310 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
311 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
312 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
313 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
314 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
315 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
316 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
317 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
318 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
319 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
320 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
321 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
322 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
323 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
324 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
325 setOperationAction(ISD::ROTL, MVT::i32, Expand);
326 setOperationAction(ISD::ROTL, MVT::i64, Expand);
327 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
328 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
330 if (!Subtarget->hasMips32r2())
331 setOperationAction(ISD::ROTR, MVT::i32, Expand);
333 if (!Subtarget->hasMips64r2())
334 setOperationAction(ISD::ROTR, MVT::i64, Expand);
336 setOperationAction(ISD::FSIN, MVT::f32, Expand);
337 setOperationAction(ISD::FSIN, MVT::f64, Expand);
338 setOperationAction(ISD::FCOS, MVT::f32, Expand);
339 setOperationAction(ISD::FCOS, MVT::f64, Expand);
340 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
341 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
342 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
343 setOperationAction(ISD::FPOW, MVT::f32, Expand);
344 setOperationAction(ISD::FPOW, MVT::f64, Expand);
345 setOperationAction(ISD::FLOG, MVT::f32, Expand);
346 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
347 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
348 setOperationAction(ISD::FEXP, MVT::f32, Expand);
349 setOperationAction(ISD::FMA, MVT::f32, Expand);
350 setOperationAction(ISD::FMA, MVT::f64, Expand);
351 setOperationAction(ISD::FREM, MVT::f32, Expand);
352 setOperationAction(ISD::FREM, MVT::f64, Expand);
354 if (!TM.Options.NoNaNsFPMath) {
355 setOperationAction(ISD::FNEG, MVT::f32, Expand);
356 setOperationAction(ISD::FNEG, MVT::f64, Expand);
359 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
361 setOperationAction(ISD::VAARG, MVT::Other, Expand);
362 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
363 setOperationAction(ISD::VAEND, MVT::Other, Expand);
365 // Use the default for now
366 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
367 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
369 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
370 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
371 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
372 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
374 setInsertFencesForAtomic(true);
376 if (!Subtarget->hasSEInReg()) {
377 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
378 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
381 if (!Subtarget->hasBitCount()) {
382 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
383 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
386 if (!Subtarget->hasSwap()) {
387 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
388 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
392 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
393 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
394 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
395 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
398 setOperationAction(ISD::TRAP, MVT::Other, Legal);
400 setTargetDAGCombine(ISD::SDIVREM);
401 setTargetDAGCombine(ISD::UDIVREM);
402 setTargetDAGCombine(ISD::SELECT);
403 setTargetDAGCombine(ISD::AND);
404 setTargetDAGCombine(ISD::OR);
405 setTargetDAGCombine(ISD::ADD);
407 setMinFunctionAlignment(HasMips64 ? 3 : 2);
409 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
411 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
412 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
414 MaxStoresPerMemcpy = 16;
417 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
418 if (TM.getSubtargetImpl()->inMips16Mode())
419 return llvm::createMips16TargetLowering(TM);
421 return llvm::createMipsSETargetLowering(TM);
424 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
427 return VT.changeVectorElementTypeToInteger();
430 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
431 TargetLowering::DAGCombinerInfo &DCI,
432 const MipsSubtarget *Subtarget) {
433 if (DCI.isBeforeLegalizeOps())
436 EVT Ty = N->getValueType(0);
437 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
438 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
439 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
443 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
444 N->getOperand(0), N->getOperand(1));
445 SDValue InChain = DAG.getEntryNode();
446 SDValue InGlue = DivRem;
449 if (N->hasAnyUseOfValue(0)) {
450 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
452 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
453 InChain = CopyFromLo.getValue(1);
454 InGlue = CopyFromLo.getValue(2);
458 if (N->hasAnyUseOfValue(1)) {
459 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
461 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
467 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
469 default: llvm_unreachable("Unknown fp condition code!");
471 case ISD::SETOEQ: return Mips::FCOND_OEQ;
472 case ISD::SETUNE: return Mips::FCOND_UNE;
474 case ISD::SETOLT: return Mips::FCOND_OLT;
476 case ISD::SETOGT: return Mips::FCOND_OGT;
478 case ISD::SETOLE: return Mips::FCOND_OLE;
480 case ISD::SETOGE: return Mips::FCOND_OGE;
481 case ISD::SETULT: return Mips::FCOND_ULT;
482 case ISD::SETULE: return Mips::FCOND_ULE;
483 case ISD::SETUGT: return Mips::FCOND_UGT;
484 case ISD::SETUGE: return Mips::FCOND_UGE;
485 case ISD::SETUO: return Mips::FCOND_UN;
486 case ISD::SETO: return Mips::FCOND_OR;
488 case ISD::SETONE: return Mips::FCOND_ONE;
489 case ISD::SETUEQ: return Mips::FCOND_UEQ;
494 /// This function returns true if the floating point conditional branches and
495 /// conditional moves which use condition code CC should be inverted.
496 static bool invertFPCondCodeUser(Mips::CondCode CC) {
497 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
500 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
501 "Illegal Condition Code");
506 // Creates and returns an FPCmp node from a setcc node.
507 // Returns Op if setcc is not a floating point comparison.
508 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
509 // must be a SETCC node
510 if (Op.getOpcode() != ISD::SETCC)
513 SDValue LHS = Op.getOperand(0);
515 if (!LHS.getValueType().isFloatingPoint())
518 SDValue RHS = Op.getOperand(1);
521 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
522 // node if necessary.
523 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
525 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
526 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
529 // Creates and returns a CMovFPT/F node.
530 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
531 SDValue False, SDLoc DL) {
532 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
533 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
534 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
536 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
537 True.getValueType(), True, FCC0, False, Cond);
540 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
541 TargetLowering::DAGCombinerInfo &DCI,
542 const MipsSubtarget *Subtarget) {
543 if (DCI.isBeforeLegalizeOps())
546 SDValue SetCC = N->getOperand(0);
548 if ((SetCC.getOpcode() != ISD::SETCC) ||
549 !SetCC.getOperand(0).getValueType().isInteger())
552 SDValue False = N->getOperand(2);
553 EVT FalseTy = False.getValueType();
555 if (!FalseTy.isInteger())
558 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
560 if (!CN || CN->getZExtValue())
564 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
565 SDValue True = N->getOperand(1);
567 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
568 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
570 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
573 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
574 TargetLowering::DAGCombinerInfo &DCI,
575 const MipsSubtarget *Subtarget) {
576 // Pattern match EXT.
577 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
578 // => ext $dst, $src, size, pos
579 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
582 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
583 unsigned ShiftRightOpc = ShiftRight.getOpcode();
585 // Op's first operand must be a shift right.
586 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
589 // The second operand of the shift must be an immediate.
591 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
594 uint64_t Pos = CN->getZExtValue();
595 uint64_t SMPos, SMSize;
597 // Op's second operand must be a shifted mask.
598 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
599 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
602 // Return if the shifted mask does not start at bit 0 or the sum of its size
603 // and Pos exceeds the word's size.
604 EVT ValTy = N->getValueType(0);
605 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
608 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
609 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
610 DAG.getConstant(SMSize, MVT::i32));
613 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
614 TargetLowering::DAGCombinerInfo &DCI,
615 const MipsSubtarget *Subtarget) {
616 // Pattern match INS.
617 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
618 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
619 // => ins $dst, $src, size, pos, $src1
620 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
623 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
624 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
627 // See if Op's first operand matches (and $src1 , mask0).
628 if (And0.getOpcode() != ISD::AND)
631 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
632 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
635 // See if Op's second operand matches (and (shl $src, pos), mask1).
636 if (And1.getOpcode() != ISD::AND)
639 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
640 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
643 // The shift masks must have the same position and size.
644 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
647 SDValue Shl = And1.getOperand(0);
648 if (Shl.getOpcode() != ISD::SHL)
651 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
654 unsigned Shamt = CN->getZExtValue();
656 // Return if the shift amount and the first bit position of mask are not the
658 EVT ValTy = N->getValueType(0);
659 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
662 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
663 DAG.getConstant(SMPos0, MVT::i32),
664 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
667 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
668 TargetLowering::DAGCombinerInfo &DCI,
669 const MipsSubtarget *Subtarget) {
670 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
672 if (DCI.isBeforeLegalizeOps())
675 SDValue Add = N->getOperand(1);
677 if (Add.getOpcode() != ISD::ADD)
680 SDValue Lo = Add.getOperand(1);
682 if ((Lo.getOpcode() != MipsISD::Lo) ||
683 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
686 EVT ValTy = N->getValueType(0);
689 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
691 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
694 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
696 SelectionDAG &DAG = DCI.DAG;
697 unsigned Opc = N->getOpcode();
703 return performDivRemCombine(N, DAG, DCI, Subtarget);
705 return performSELECTCombine(N, DAG, DCI, Subtarget);
707 return performANDCombine(N, DAG, DCI, Subtarget);
709 return performORCombine(N, DAG, DCI, Subtarget);
711 return performADDCombine(N, DAG, DCI, Subtarget);
718 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
719 SmallVectorImpl<SDValue> &Results,
720 SelectionDAG &DAG) const {
721 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
723 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
724 Results.push_back(Res.getValue(I));
728 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
729 SmallVectorImpl<SDValue> &Results,
730 SelectionDAG &DAG) const {
731 return LowerOperationWrapper(N, Results, DAG);
734 SDValue MipsTargetLowering::
735 LowerOperation(SDValue Op, SelectionDAG &DAG) const
737 switch (Op.getOpcode())
739 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
740 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
741 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
742 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
743 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
744 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
745 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
746 case ISD::SELECT: return lowerSELECT(Op, DAG);
747 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
748 case ISD::SETCC: return lowerSETCC(Op, DAG);
749 case ISD::VASTART: return lowerVASTART(Op, DAG);
750 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
751 case ISD::FABS: return lowerFABS(Op, DAG);
752 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
753 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
754 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
755 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
756 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
757 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
758 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
759 case ISD::LOAD: return lowerLOAD(Op, DAG);
760 case ISD::STORE: return lowerSTORE(Op, DAG);
761 case ISD::ADD: return lowerADD(Op, DAG);
762 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
767 //===----------------------------------------------------------------------===//
768 // Lower helper functions
769 //===----------------------------------------------------------------------===//
771 // addLiveIn - This helper function adds the specified physical register to the
772 // MachineFunction as a live in value. It also creates a corresponding
773 // virtual register for it.
775 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
777 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
778 MF.getRegInfo().addLiveIn(PReg, VReg);
782 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
783 MachineBasicBlock &MBB,
784 const TargetInstrInfo &TII,
789 // Insert instruction "teq $divisor_reg, $zero, 7".
790 MachineBasicBlock::iterator I(MI);
791 MachineInstrBuilder MIB;
792 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
793 .addOperand(MI->getOperand(2)).addReg(Mips::ZERO).addImm(7);
795 // Use the 32-bit sub-register if this is a 64-bit division.
797 MIB->getOperand(0).setSubReg(Mips::sub_32);
803 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
804 MachineBasicBlock *BB) const {
805 switch (MI->getOpcode()) {
807 llvm_unreachable("Unexpected instr type to insert");
808 case Mips::ATOMIC_LOAD_ADD_I8:
809 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
810 case Mips::ATOMIC_LOAD_ADD_I16:
811 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
812 case Mips::ATOMIC_LOAD_ADD_I32:
813 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
814 case Mips::ATOMIC_LOAD_ADD_I64:
815 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
817 case Mips::ATOMIC_LOAD_AND_I8:
818 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
819 case Mips::ATOMIC_LOAD_AND_I16:
820 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
821 case Mips::ATOMIC_LOAD_AND_I32:
822 return emitAtomicBinary(MI, BB, 4, Mips::AND);
823 case Mips::ATOMIC_LOAD_AND_I64:
824 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
826 case Mips::ATOMIC_LOAD_OR_I8:
827 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
828 case Mips::ATOMIC_LOAD_OR_I16:
829 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
830 case Mips::ATOMIC_LOAD_OR_I32:
831 return emitAtomicBinary(MI, BB, 4, Mips::OR);
832 case Mips::ATOMIC_LOAD_OR_I64:
833 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
835 case Mips::ATOMIC_LOAD_XOR_I8:
836 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
837 case Mips::ATOMIC_LOAD_XOR_I16:
838 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
839 case Mips::ATOMIC_LOAD_XOR_I32:
840 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
841 case Mips::ATOMIC_LOAD_XOR_I64:
842 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
844 case Mips::ATOMIC_LOAD_NAND_I8:
845 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
846 case Mips::ATOMIC_LOAD_NAND_I16:
847 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
848 case Mips::ATOMIC_LOAD_NAND_I32:
849 return emitAtomicBinary(MI, BB, 4, 0, true);
850 case Mips::ATOMIC_LOAD_NAND_I64:
851 return emitAtomicBinary(MI, BB, 8, 0, true);
853 case Mips::ATOMIC_LOAD_SUB_I8:
854 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
855 case Mips::ATOMIC_LOAD_SUB_I16:
856 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
857 case Mips::ATOMIC_LOAD_SUB_I32:
858 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
859 case Mips::ATOMIC_LOAD_SUB_I64:
860 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
862 case Mips::ATOMIC_SWAP_I8:
863 return emitAtomicBinaryPartword(MI, BB, 1, 0);
864 case Mips::ATOMIC_SWAP_I16:
865 return emitAtomicBinaryPartword(MI, BB, 2, 0);
866 case Mips::ATOMIC_SWAP_I32:
867 return emitAtomicBinary(MI, BB, 4, 0);
868 case Mips::ATOMIC_SWAP_I64:
869 return emitAtomicBinary(MI, BB, 8, 0);
871 case Mips::ATOMIC_CMP_SWAP_I8:
872 return emitAtomicCmpSwapPartword(MI, BB, 1);
873 case Mips::ATOMIC_CMP_SWAP_I16:
874 return emitAtomicCmpSwapPartword(MI, BB, 2);
875 case Mips::ATOMIC_CMP_SWAP_I32:
876 return emitAtomicCmpSwap(MI, BB, 4);
877 case Mips::ATOMIC_CMP_SWAP_I64:
878 return emitAtomicCmpSwap(MI, BB, 8);
879 case Mips::PseudoSDIV:
880 case Mips::PseudoUDIV:
881 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
882 case Mips::PseudoDSDIV:
883 case Mips::PseudoDUDIV:
884 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
888 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
889 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
891 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
892 unsigned Size, unsigned BinOpcode,
894 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
896 MachineFunction *MF = BB->getParent();
897 MachineRegisterInfo &RegInfo = MF->getRegInfo();
898 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
899 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
900 DebugLoc DL = MI->getDebugLoc();
901 unsigned LL, SC, AND, NOR, ZERO, BEQ;
916 ZERO = Mips::ZERO_64;
920 unsigned OldVal = MI->getOperand(0).getReg();
921 unsigned Ptr = MI->getOperand(1).getReg();
922 unsigned Incr = MI->getOperand(2).getReg();
924 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
925 unsigned AndRes = RegInfo.createVirtualRegister(RC);
926 unsigned Success = RegInfo.createVirtualRegister(RC);
928 // insert new blocks after the current block
929 const BasicBlock *LLVM_BB = BB->getBasicBlock();
930 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
931 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
932 MachineFunction::iterator It = BB;
934 MF->insert(It, loopMBB);
935 MF->insert(It, exitMBB);
937 // Transfer the remainder of BB and its successor edges to exitMBB.
938 exitMBB->splice(exitMBB->begin(), BB,
939 llvm::next(MachineBasicBlock::iterator(MI)),
941 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
945 // fallthrough --> loopMBB
946 BB->addSuccessor(loopMBB);
947 loopMBB->addSuccessor(loopMBB);
948 loopMBB->addSuccessor(exitMBB);
952 // <binop> storeval, oldval, incr
953 // sc success, storeval, 0(ptr)
954 // beq success, $0, loopMBB
956 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
958 // and andres, oldval, incr
959 // nor storeval, $0, andres
960 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
961 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
962 } else if (BinOpcode) {
963 // <binop> storeval, oldval, incr
964 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
968 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
969 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
971 MI->eraseFromParent(); // The instruction is gone now.
977 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
978 MachineBasicBlock *BB,
979 unsigned Size, unsigned BinOpcode,
981 assert((Size == 1 || Size == 2) &&
982 "Unsupported size for EmitAtomicBinaryPartial.");
984 MachineFunction *MF = BB->getParent();
985 MachineRegisterInfo &RegInfo = MF->getRegInfo();
986 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
987 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
988 DebugLoc DL = MI->getDebugLoc();
990 unsigned Dest = MI->getOperand(0).getReg();
991 unsigned Ptr = MI->getOperand(1).getReg();
992 unsigned Incr = MI->getOperand(2).getReg();
994 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
995 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
996 unsigned Mask = RegInfo.createVirtualRegister(RC);
997 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
998 unsigned NewVal = RegInfo.createVirtualRegister(RC);
999 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1000 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1001 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1002 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1003 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1004 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1005 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1006 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1007 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1008 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1009 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1010 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1011 unsigned Success = RegInfo.createVirtualRegister(RC);
1013 // insert new blocks after the current block
1014 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1015 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1016 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1017 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1018 MachineFunction::iterator It = BB;
1020 MF->insert(It, loopMBB);
1021 MF->insert(It, sinkMBB);
1022 MF->insert(It, exitMBB);
1024 // Transfer the remainder of BB and its successor edges to exitMBB.
1025 exitMBB->splice(exitMBB->begin(), BB,
1026 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1027 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1029 BB->addSuccessor(loopMBB);
1030 loopMBB->addSuccessor(loopMBB);
1031 loopMBB->addSuccessor(sinkMBB);
1032 sinkMBB->addSuccessor(exitMBB);
1035 // addiu masklsb2,$0,-4 # 0xfffffffc
1036 // and alignedaddr,ptr,masklsb2
1037 // andi ptrlsb2,ptr,3
1038 // sll shiftamt,ptrlsb2,3
1039 // ori maskupper,$0,255 # 0xff
1040 // sll mask,maskupper,shiftamt
1041 // nor mask2,$0,mask
1042 // sll incr2,incr,shiftamt
1044 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1045 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1046 .addReg(Mips::ZERO).addImm(-4);
1047 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1048 .addReg(Ptr).addReg(MaskLSB2);
1049 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1050 if (Subtarget->isLittle()) {
1051 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1053 unsigned Off = RegInfo.createVirtualRegister(RC);
1054 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1055 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1056 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1058 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1059 .addReg(Mips::ZERO).addImm(MaskImm);
1060 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1061 .addReg(MaskUpper).addReg(ShiftAmt);
1062 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1063 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1065 // atomic.load.binop
1067 // ll oldval,0(alignedaddr)
1068 // binop binopres,oldval,incr2
1069 // and newval,binopres,mask
1070 // and maskedoldval0,oldval,mask2
1071 // or storeval,maskedoldval0,newval
1072 // sc success,storeval,0(alignedaddr)
1073 // beq success,$0,loopMBB
1077 // ll oldval,0(alignedaddr)
1078 // and newval,incr2,mask
1079 // and maskedoldval0,oldval,mask2
1080 // or storeval,maskedoldval0,newval
1081 // sc success,storeval,0(alignedaddr)
1082 // beq success,$0,loopMBB
1085 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1087 // and andres, oldval, incr2
1088 // nor binopres, $0, andres
1089 // and newval, binopres, mask
1090 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1091 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1092 .addReg(Mips::ZERO).addReg(AndRes);
1093 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1094 } else if (BinOpcode) {
1095 // <binop> binopres, oldval, incr2
1096 // and newval, binopres, mask
1097 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1098 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1099 } else {// atomic.swap
1100 // and newval, incr2, mask
1101 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1104 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1105 .addReg(OldVal).addReg(Mask2);
1106 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1107 .addReg(MaskedOldVal0).addReg(NewVal);
1108 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1109 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1110 BuildMI(BB, DL, TII->get(Mips::BEQ))
1111 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1114 // and maskedoldval1,oldval,mask
1115 // srl srlres,maskedoldval1,shiftamt
1116 // sll sllres,srlres,24
1117 // sra dest,sllres,24
1119 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1121 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1122 .addReg(OldVal).addReg(Mask);
1123 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1124 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1125 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1126 .addReg(SrlRes).addImm(ShiftImm);
1127 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1128 .addReg(SllRes).addImm(ShiftImm);
1130 MI->eraseFromParent(); // The instruction is gone now.
1136 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1137 MachineBasicBlock *BB,
1138 unsigned Size) const {
1139 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1141 MachineFunction *MF = BB->getParent();
1142 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1143 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1144 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1145 DebugLoc DL = MI->getDebugLoc();
1146 unsigned LL, SC, ZERO, BNE, BEQ;
1158 ZERO = Mips::ZERO_64;
1163 unsigned Dest = MI->getOperand(0).getReg();
1164 unsigned Ptr = MI->getOperand(1).getReg();
1165 unsigned OldVal = MI->getOperand(2).getReg();
1166 unsigned NewVal = MI->getOperand(3).getReg();
1168 unsigned Success = RegInfo.createVirtualRegister(RC);
1170 // insert new blocks after the current block
1171 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1172 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1173 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1174 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1175 MachineFunction::iterator It = BB;
1177 MF->insert(It, loop1MBB);
1178 MF->insert(It, loop2MBB);
1179 MF->insert(It, exitMBB);
1181 // Transfer the remainder of BB and its successor edges to exitMBB.
1182 exitMBB->splice(exitMBB->begin(), BB,
1183 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1184 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1188 // fallthrough --> loop1MBB
1189 BB->addSuccessor(loop1MBB);
1190 loop1MBB->addSuccessor(exitMBB);
1191 loop1MBB->addSuccessor(loop2MBB);
1192 loop2MBB->addSuccessor(loop1MBB);
1193 loop2MBB->addSuccessor(exitMBB);
1197 // bne dest, oldval, exitMBB
1199 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1200 BuildMI(BB, DL, TII->get(BNE))
1201 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1204 // sc success, newval, 0(ptr)
1205 // beq success, $0, loop1MBB
1207 BuildMI(BB, DL, TII->get(SC), Success)
1208 .addReg(NewVal).addReg(Ptr).addImm(0);
1209 BuildMI(BB, DL, TII->get(BEQ))
1210 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1212 MI->eraseFromParent(); // The instruction is gone now.
1218 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1219 MachineBasicBlock *BB,
1220 unsigned Size) const {
1221 assert((Size == 1 || Size == 2) &&
1222 "Unsupported size for EmitAtomicCmpSwapPartial.");
1224 MachineFunction *MF = BB->getParent();
1225 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1226 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1227 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1228 DebugLoc DL = MI->getDebugLoc();
1230 unsigned Dest = MI->getOperand(0).getReg();
1231 unsigned Ptr = MI->getOperand(1).getReg();
1232 unsigned CmpVal = MI->getOperand(2).getReg();
1233 unsigned NewVal = MI->getOperand(3).getReg();
1235 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1236 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1237 unsigned Mask = RegInfo.createVirtualRegister(RC);
1238 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1239 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1240 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1241 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1242 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1243 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1244 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1245 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1246 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1247 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1248 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1249 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1250 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1251 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1252 unsigned Success = RegInfo.createVirtualRegister(RC);
1254 // insert new blocks after the current block
1255 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1256 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1257 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1258 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1259 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1260 MachineFunction::iterator It = BB;
1262 MF->insert(It, loop1MBB);
1263 MF->insert(It, loop2MBB);
1264 MF->insert(It, sinkMBB);
1265 MF->insert(It, exitMBB);
1267 // Transfer the remainder of BB and its successor edges to exitMBB.
1268 exitMBB->splice(exitMBB->begin(), BB,
1269 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1270 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1272 BB->addSuccessor(loop1MBB);
1273 loop1MBB->addSuccessor(sinkMBB);
1274 loop1MBB->addSuccessor(loop2MBB);
1275 loop2MBB->addSuccessor(loop1MBB);
1276 loop2MBB->addSuccessor(sinkMBB);
1277 sinkMBB->addSuccessor(exitMBB);
1279 // FIXME: computation of newval2 can be moved to loop2MBB.
1281 // addiu masklsb2,$0,-4 # 0xfffffffc
1282 // and alignedaddr,ptr,masklsb2
1283 // andi ptrlsb2,ptr,3
1284 // sll shiftamt,ptrlsb2,3
1285 // ori maskupper,$0,255 # 0xff
1286 // sll mask,maskupper,shiftamt
1287 // nor mask2,$0,mask
1288 // andi maskedcmpval,cmpval,255
1289 // sll shiftedcmpval,maskedcmpval,shiftamt
1290 // andi maskednewval,newval,255
1291 // sll shiftednewval,maskednewval,shiftamt
1292 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1293 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1294 .addReg(Mips::ZERO).addImm(-4);
1295 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1296 .addReg(Ptr).addReg(MaskLSB2);
1297 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1298 if (Subtarget->isLittle()) {
1299 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1301 unsigned Off = RegInfo.createVirtualRegister(RC);
1302 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1303 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1304 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1306 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1307 .addReg(Mips::ZERO).addImm(MaskImm);
1308 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1309 .addReg(MaskUpper).addReg(ShiftAmt);
1310 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1311 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1312 .addReg(CmpVal).addImm(MaskImm);
1313 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1314 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1315 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1316 .addReg(NewVal).addImm(MaskImm);
1317 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1318 .addReg(MaskedNewVal).addReg(ShiftAmt);
1321 // ll oldval,0(alginedaddr)
1322 // and maskedoldval0,oldval,mask
1323 // bne maskedoldval0,shiftedcmpval,sinkMBB
1325 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1326 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1327 .addReg(OldVal).addReg(Mask);
1328 BuildMI(BB, DL, TII->get(Mips::BNE))
1329 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1332 // and maskedoldval1,oldval,mask2
1333 // or storeval,maskedoldval1,shiftednewval
1334 // sc success,storeval,0(alignedaddr)
1335 // beq success,$0,loop1MBB
1337 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1338 .addReg(OldVal).addReg(Mask2);
1339 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1340 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1341 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1342 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1343 BuildMI(BB, DL, TII->get(Mips::BEQ))
1344 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1347 // srl srlres,maskedoldval0,shiftamt
1348 // sll sllres,srlres,24
1349 // sra dest,sllres,24
1351 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1353 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1354 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1355 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1356 .addReg(SrlRes).addImm(ShiftImm);
1357 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1358 .addReg(SllRes).addImm(ShiftImm);
1360 MI->eraseFromParent(); // The instruction is gone now.
1365 //===----------------------------------------------------------------------===//
1366 // Misc Lower Operation implementation
1367 //===----------------------------------------------------------------------===//
1368 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1369 SDValue Chain = Op.getOperand(0);
1370 SDValue Table = Op.getOperand(1);
1371 SDValue Index = Op.getOperand(2);
1373 EVT PTy = getPointerTy();
1374 unsigned EntrySize =
1375 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1377 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1378 DAG.getConstant(EntrySize, PTy));
1379 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1381 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1382 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1383 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1385 Chain = Addr.getValue(1);
1387 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1388 // For PIC, the sequence is:
1389 // BRIND(load(Jumptable + index) + RelocBase)
1390 // RelocBase can be JumpTable, GOT or some sort of global base.
1391 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1392 getPICJumpTableRelocBase(Table, DAG));
1395 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1398 SDValue MipsTargetLowering::
1399 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1401 // The first operand is the chain, the second is the condition, the third is
1402 // the block to branch to if the condition is true.
1403 SDValue Chain = Op.getOperand(0);
1404 SDValue Dest = Op.getOperand(2);
1407 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1409 // Return if flag is not set by a floating point comparison.
1410 if (CondRes.getOpcode() != MipsISD::FPCmp)
1413 SDValue CCNode = CondRes.getOperand(2);
1415 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1416 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1417 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1418 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1419 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1420 FCC0, Dest, CondRes);
1423 SDValue MipsTargetLowering::
1424 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1426 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1428 // Return if flag is not set by a floating point comparison.
1429 if (Cond.getOpcode() != MipsISD::FPCmp)
1432 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1436 SDValue MipsTargetLowering::
1437 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1440 EVT Ty = Op.getOperand(0).getValueType();
1441 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1442 getSetCCResultType(*DAG.getContext(), Ty),
1443 Op.getOperand(0), Op.getOperand(1),
1446 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1450 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1451 SDValue Cond = createFPCmp(DAG, Op);
1453 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1454 "Floating point operand expected.");
1456 SDValue True = DAG.getConstant(1, MVT::i32);
1457 SDValue False = DAG.getConstant(0, MVT::i32);
1459 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1462 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1463 SelectionDAG &DAG) const {
1464 // FIXME there isn't actually debug info here
1466 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1468 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1469 const MipsTargetObjectFile &TLOF =
1470 (const MipsTargetObjectFile&)getObjFileLowering();
1472 // %gp_rel relocation
1473 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1474 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1476 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1477 DAG.getVTList(MVT::i32), &GA, 1);
1478 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1479 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1482 // %hi/%lo relocation
1483 return getAddrNonPIC(Op, DAG);
1486 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1487 return getAddrLocal(Op, DAG, HasMips64);
1490 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1491 MipsII::MO_GOT_LO16);
1493 return getAddrGlobal(Op, DAG,
1494 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1497 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1498 SelectionDAG &DAG) const {
1499 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1500 return getAddrNonPIC(Op, DAG);
1502 return getAddrLocal(Op, DAG, HasMips64);
1505 SDValue MipsTargetLowering::
1506 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1508 // If the relocation model is PIC, use the General Dynamic TLS Model or
1509 // Local Dynamic TLS model, otherwise use the Initial Exec or
1510 // Local Exec TLS Model.
1512 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1514 const GlobalValue *GV = GA->getGlobal();
1515 EVT PtrVT = getPointerTy();
1517 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1519 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1520 // General Dynamic and Local Dynamic TLS Model.
1521 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1524 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1525 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1526 getGlobalReg(DAG, PtrVT), TGA);
1527 unsigned PtrSize = PtrVT.getSizeInBits();
1528 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1530 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1534 Entry.Node = Argument;
1536 Args.push_back(Entry);
1538 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1539 false, false, false, false, 0, CallingConv::C,
1540 /*IsTailCall=*/false, /*doesNotRet=*/false,
1541 /*isReturnValueUsed=*/true,
1542 TlsGetAddr, Args, DAG, DL);
1543 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1545 SDValue Ret = CallResult.first;
1547 if (model != TLSModel::LocalDynamic)
1550 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1551 MipsII::MO_DTPREL_HI);
1552 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1553 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1554 MipsII::MO_DTPREL_LO);
1555 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1556 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1557 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1561 if (model == TLSModel::InitialExec) {
1562 // Initial Exec TLS Model
1563 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1564 MipsII::MO_GOTTPREL);
1565 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1567 Offset = DAG.getLoad(PtrVT, DL,
1568 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1569 false, false, false, 0);
1571 // Local Exec TLS Model
1572 assert(model == TLSModel::LocalExec);
1573 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1574 MipsII::MO_TPREL_HI);
1575 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1576 MipsII::MO_TPREL_LO);
1577 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1578 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1579 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1582 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1583 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1586 SDValue MipsTargetLowering::
1587 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1589 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1590 return getAddrNonPIC(Op, DAG);
1592 return getAddrLocal(Op, DAG, HasMips64);
1595 SDValue MipsTargetLowering::
1596 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1598 // gp_rel relocation
1599 // FIXME: we should reference the constant pool using small data sections,
1600 // but the asm printer currently doesn't support this feature without
1601 // hacking it. This feature should come soon so we can uncomment the
1603 //if (IsInSmallSection(C->getType())) {
1604 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1605 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1606 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1608 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1609 return getAddrNonPIC(Op, DAG);
1611 return getAddrLocal(Op, DAG, HasMips64);
1614 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1615 MachineFunction &MF = DAG.getMachineFunction();
1616 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1619 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1622 // vastart just stores the address of the VarArgsFrameIndex slot into the
1623 // memory location argument.
1624 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1625 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1626 MachinePointerInfo(SV), false, false, 0);
1629 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1630 EVT TyX = Op.getOperand(0).getValueType();
1631 EVT TyY = Op.getOperand(1).getValueType();
1632 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1633 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1637 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1639 SDValue X = (TyX == MVT::f32) ?
1640 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1641 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1643 SDValue Y = (TyY == MVT::f32) ?
1644 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1645 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1649 // ext E, Y, 31, 1 ; extract bit31 of Y
1650 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1651 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1652 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1655 // srl SrlX, SllX, 1
1657 // sll SllY, SrlX, 31
1658 // or Or, SrlX, SllY
1659 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1660 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1661 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1662 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1663 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1666 if (TyX == MVT::f32)
1667 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1669 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1670 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1671 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1674 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1675 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1676 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1677 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1678 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1681 // Bitcast to integer nodes.
1682 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1683 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1686 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1687 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1688 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1689 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1691 if (WidthX > WidthY)
1692 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1693 else if (WidthY > WidthX)
1694 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1696 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1697 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1698 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1701 // (d)sll SllX, X, 1
1702 // (d)srl SrlX, SllX, 1
1703 // (d)srl SrlY, Y, width(Y)-1
1704 // (d)sll SllY, SrlX, width(Y)-1
1705 // or Or, SrlX, SllY
1706 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1707 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1708 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1709 DAG.getConstant(WidthY - 1, MVT::i32));
1711 if (WidthX > WidthY)
1712 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1713 else if (WidthY > WidthX)
1714 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1716 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1717 DAG.getConstant(WidthX - 1, MVT::i32));
1718 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1719 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1723 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1724 if (Subtarget->hasMips64())
1725 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1727 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1730 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1731 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1734 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1736 SDValue X = (Op.getValueType() == MVT::f32) ?
1737 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1738 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1743 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1744 DAG.getRegister(Mips::ZERO, MVT::i32),
1745 DAG.getConstant(31, MVT::i32), Const1, X);
1747 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1748 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1751 if (Op.getValueType() == MVT::f32)
1752 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1754 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1755 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1756 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1759 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1760 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1763 // Bitcast to integer node.
1764 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1768 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1769 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1770 DAG.getConstant(63, MVT::i32), Const1, X);
1772 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1773 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1776 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1780 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1781 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1782 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1784 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1787 SDValue MipsTargetLowering::
1788 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1790 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1791 "Frame address can only be determined for current frame.");
1793 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1794 MFI->setFrameAddressIsTaken(true);
1795 EVT VT = Op.getValueType();
1797 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1798 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1802 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1803 SelectionDAG &DAG) const {
1805 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1806 "Return address can be determined only for current frame.");
1808 MachineFunction &MF = DAG.getMachineFunction();
1809 MachineFrameInfo *MFI = MF.getFrameInfo();
1810 MVT VT = Op.getSimpleValueType();
1811 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1812 MFI->setReturnAddressIsTaken(true);
1814 // Return RA, which contains the return address. Mark it an implicit live-in.
1815 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1816 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1819 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1820 // generated from __builtin_eh_return (offset, handler)
1821 // The effect of this is to adjust the stack pointer by "offset"
1822 // and then branch to "handler".
1823 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1825 MachineFunction &MF = DAG.getMachineFunction();
1826 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1828 MipsFI->setCallsEhReturn();
1829 SDValue Chain = Op.getOperand(0);
1830 SDValue Offset = Op.getOperand(1);
1831 SDValue Handler = Op.getOperand(2);
1833 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1835 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1836 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1837 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1838 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1839 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1840 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1841 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1842 DAG.getRegister(OffsetReg, Ty),
1843 DAG.getRegister(AddrReg, getPointerTy()),
1847 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1848 SelectionDAG &DAG) const {
1849 // FIXME: Need pseudo-fence for 'singlethread' fences
1850 // FIXME: Set SType for weaker fences where supported/appropriate.
1853 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1854 DAG.getConstant(SType, MVT::i32));
1857 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1858 SelectionDAG &DAG) const {
1860 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1861 SDValue Shamt = Op.getOperand(2);
1864 // lo = (shl lo, shamt)
1865 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1868 // hi = (shl lo, shamt[4:0])
1869 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1870 DAG.getConstant(-1, MVT::i32));
1871 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1872 DAG.getConstant(1, MVT::i32));
1873 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1875 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1876 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1877 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1878 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1879 DAG.getConstant(0x20, MVT::i32));
1880 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1881 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1882 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1884 SDValue Ops[2] = {Lo, Hi};
1885 return DAG.getMergeValues(Ops, 2, DL);
1888 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1891 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1892 SDValue Shamt = Op.getOperand(2);
1895 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1897 // hi = (sra hi, shamt)
1899 // hi = (srl hi, shamt)
1902 // lo = (sra hi, shamt[4:0])
1903 // hi = (sra hi, 31)
1905 // lo = (srl hi, shamt[4:0])
1907 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1908 DAG.getConstant(-1, MVT::i32));
1909 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1910 DAG.getConstant(1, MVT::i32));
1911 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1912 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1913 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1914 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1916 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1917 DAG.getConstant(0x20, MVT::i32));
1918 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1919 DAG.getConstant(31, MVT::i32));
1920 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1921 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1922 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1925 SDValue Ops[2] = {Lo, Hi};
1926 return DAG.getMergeValues(Ops, 2, DL);
1929 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1930 SDValue Chain, SDValue Src, unsigned Offset) {
1931 SDValue Ptr = LD->getBasePtr();
1932 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1933 EVT BasePtrVT = Ptr.getValueType();
1935 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1938 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1939 DAG.getConstant(Offset, BasePtrVT));
1941 SDValue Ops[] = { Chain, Ptr, Src };
1942 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1943 LD->getMemOperand());
1946 // Expand an unaligned 32 or 64-bit integer load node.
1947 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1948 LoadSDNode *LD = cast<LoadSDNode>(Op);
1949 EVT MemVT = LD->getMemoryVT();
1951 // Return if load is aligned or if MemVT is neither i32 nor i64.
1952 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1953 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1956 bool IsLittle = Subtarget->isLittle();
1957 EVT VT = Op.getValueType();
1958 ISD::LoadExtType ExtType = LD->getExtensionType();
1959 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1961 assert((VT == MVT::i32) || (VT == MVT::i64));
1964 // (set dst, (i64 (load baseptr)))
1966 // (set tmp, (ldl (add baseptr, 7), undef))
1967 // (set dst, (ldr baseptr, tmp))
1968 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1969 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1971 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1975 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1977 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1981 // (set dst, (i32 (load baseptr))) or
1982 // (set dst, (i64 (sextload baseptr))) or
1983 // (set dst, (i64 (extload baseptr)))
1985 // (set tmp, (lwl (add baseptr, 3), undef))
1986 // (set dst, (lwr baseptr, tmp))
1987 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1988 (ExtType == ISD::EXTLOAD))
1991 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1994 // (set dst, (i64 (zextload baseptr)))
1996 // (set tmp0, (lwl (add baseptr, 3), undef))
1997 // (set tmp1, (lwr baseptr, tmp0))
1998 // (set tmp2, (shl tmp1, 32))
1999 // (set dst, (srl tmp2, 32))
2001 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2002 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2003 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2004 SDValue Ops[] = { SRL, LWR.getValue(1) };
2005 return DAG.getMergeValues(Ops, 2, DL);
2008 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2009 SDValue Chain, unsigned Offset) {
2010 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2011 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2013 SDVTList VTList = DAG.getVTList(MVT::Other);
2016 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2017 DAG.getConstant(Offset, BasePtrVT));
2019 SDValue Ops[] = { Chain, Value, Ptr };
2020 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2021 SD->getMemOperand());
2024 // Expand an unaligned 32 or 64-bit integer store node.
2025 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2027 SDValue Value = SD->getValue(), Chain = SD->getChain();
2028 EVT VT = Value.getValueType();
2031 // (store val, baseptr) or
2032 // (truncstore val, baseptr)
2034 // (swl val, (add baseptr, 3))
2035 // (swr val, baseptr)
2036 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2037 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2039 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2042 assert(VT == MVT::i64);
2045 // (store val, baseptr)
2047 // (sdl val, (add baseptr, 7))
2048 // (sdr val, baseptr)
2049 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2050 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2053 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2054 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2055 SDValue Val = SD->getValue();
2057 if (Val.getOpcode() != ISD::FP_TO_SINT)
2060 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2061 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2064 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2065 SD->getPointerInfo(), SD->isVolatile(),
2066 SD->isNonTemporal(), SD->getAlignment());
2069 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2070 StoreSDNode *SD = cast<StoreSDNode>(Op);
2071 EVT MemVT = SD->getMemoryVT();
2073 // Lower unaligned integer stores.
2074 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2075 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2076 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2078 return lowerFP_TO_SINT_STORE(SD, DAG);
2081 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2082 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2083 || cast<ConstantSDNode>
2084 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2085 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2089 // (add (frameaddr 0), (frame_to_args_offset))
2090 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2091 // (add FrameObject, 0)
2092 // where FrameObject is a fixed StackObject with offset 0 which points to
2093 // the old stack pointer.
2094 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2095 EVT ValTy = Op->getValueType(0);
2096 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2097 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2098 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2099 DAG.getConstant(0, ValTy));
2102 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2103 SelectionDAG &DAG) const {
2104 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2105 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2107 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2110 //===----------------------------------------------------------------------===//
2111 // Calling Convention Implementation
2112 //===----------------------------------------------------------------------===//
2114 //===----------------------------------------------------------------------===//
2115 // TODO: Implement a generic logic using tblgen that can support this.
2116 // Mips O32 ABI rules:
2118 // i32 - Passed in A0, A1, A2, A3 and stack
2119 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2120 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2121 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2122 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2123 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2126 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2127 //===----------------------------------------------------------------------===//
2129 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2130 MVT LocVT, CCValAssign::LocInfo LocInfo,
2131 ISD::ArgFlagsTy ArgFlags, CCState &State,
2132 const uint16_t *F64Regs) {
2134 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2136 static const uint16_t IntRegs[] = {
2137 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2139 static const uint16_t F32Regs[] = {
2140 Mips::F12, Mips::F14
2143 // Do not process byval args here.
2144 if (ArgFlags.isByVal())
2147 // Promote i8 and i16
2148 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2150 if (ArgFlags.isSExt())
2151 LocInfo = CCValAssign::SExt;
2152 else if (ArgFlags.isZExt())
2153 LocInfo = CCValAssign::ZExt;
2155 LocInfo = CCValAssign::AExt;
2160 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2161 // is true: function is vararg, argument is 3rd or higher, there is previous
2162 // argument which is not f32 or f64.
2163 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2164 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2165 unsigned OrigAlign = ArgFlags.getOrigAlign();
2166 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2168 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2169 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2170 // If this is the first part of an i64 arg,
2171 // the allocated register must be either A0 or A2.
2172 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2173 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2175 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2176 // Allocate int register and shadow next int register. If first
2177 // available register is Mips::A1 or Mips::A3, shadow it too.
2178 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2179 if (Reg == Mips::A1 || Reg == Mips::A3)
2180 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2181 State.AllocateReg(IntRegs, IntRegsSize);
2183 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2184 // we are guaranteed to find an available float register
2185 if (ValVT == MVT::f32) {
2186 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2187 // Shadow int register
2188 State.AllocateReg(IntRegs, IntRegsSize);
2190 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2191 // Shadow int registers
2192 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2193 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2194 State.AllocateReg(IntRegs, IntRegsSize);
2195 State.AllocateReg(IntRegs, IntRegsSize);
2198 llvm_unreachable("Cannot handle this ValVT.");
2201 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2203 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2205 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2210 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2211 MVT LocVT, CCValAssign::LocInfo LocInfo,
2212 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2213 static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2215 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2218 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2219 MVT LocVT, CCValAssign::LocInfo LocInfo,
2220 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2221 static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D12_64 };
2223 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2226 #include "MipsGenCallingConv.inc"
2228 //===----------------------------------------------------------------------===//
2229 // Call Calling Convention Implementation
2230 //===----------------------------------------------------------------------===//
2232 // Return next O32 integer argument register.
2233 static unsigned getNextIntArgReg(unsigned Reg) {
2234 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2235 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2239 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2240 SDValue Chain, SDValue Arg, SDLoc DL,
2241 bool IsTailCall, SelectionDAG &DAG) const {
2243 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2244 DAG.getIntPtrConstant(Offset));
2245 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2249 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2250 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2251 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2252 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2253 /*isVolatile=*/ true, false, 0);
2256 void MipsTargetLowering::
2257 getOpndList(SmallVectorImpl<SDValue> &Ops,
2258 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2259 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2260 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2261 // Insert node "GP copy globalreg" before call to function.
2263 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2264 // in PIC mode) allow symbols to be resolved via lazy binding.
2265 // The lazy binding stub requires GP to point to the GOT.
2266 if (IsPICCall && !InternalLinkage) {
2267 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2268 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2269 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2272 // Build a sequence of copy-to-reg nodes chained together with token
2273 // chain and flag operands which copy the outgoing args into registers.
2274 // The InFlag in necessary since all emitted instructions must be
2278 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2279 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2280 RegsToPass[i].second, InFlag);
2281 InFlag = Chain.getValue(1);
2284 // Add argument registers to the end of the list so that they are
2285 // known live into the call.
2286 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2287 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2288 RegsToPass[i].second.getValueType()));
2290 // Add a register mask operand representing the call-preserved registers.
2291 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2292 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2293 assert(Mask && "Missing call preserved mask for calling convention");
2294 if (Subtarget->inMips16HardFloat()) {
2295 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2296 llvm::StringRef Sym = G->getGlobal()->getName();
2297 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2298 if (F->hasFnAttribute("__Mips16RetHelper")) {
2299 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2303 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2305 if (InFlag.getNode())
2306 Ops.push_back(InFlag);
2309 /// LowerCall - functions arguments are copied from virtual regs to
2310 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2312 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2313 SmallVectorImpl<SDValue> &InVals) const {
2314 SelectionDAG &DAG = CLI.DAG;
2316 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2317 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2318 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2319 SDValue Chain = CLI.Chain;
2320 SDValue Callee = CLI.Callee;
2321 bool &IsTailCall = CLI.IsTailCall;
2322 CallingConv::ID CallConv = CLI.CallConv;
2323 bool IsVarArg = CLI.IsVarArg;
2325 MachineFunction &MF = DAG.getMachineFunction();
2326 MachineFrameInfo *MFI = MF.getFrameInfo();
2327 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2328 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2330 // Analyze operands of the call, assigning locations to each operand.
2331 SmallVector<CCValAssign, 16> ArgLocs;
2332 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2333 getTargetMachine(), ArgLocs, *DAG.getContext());
2334 MipsCC::SpecialCallingConvType SpecialCallingConv =
2335 getSpecialCallingConv(Callee);
2336 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2337 SpecialCallingConv);
2339 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2340 Subtarget->mipsSEUsesSoftFloat(),
2341 Callee.getNode(), CLI.Args);
2343 // Get a count of how many bytes are to be pushed on the stack.
2344 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2346 // Check if it's really possible to do a tail call.
2349 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2350 *MF.getInfo<MipsFunctionInfo>());
2355 // Chain is the output chain of the last Load/Store or CopyToReg node.
2356 // ByValChain is the output chain of the last Memcpy node created for copying
2357 // byval arguments to the stack.
2358 unsigned StackAlignment = TFL->getStackAlignment();
2359 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2360 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2363 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2365 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2366 IsN64 ? Mips::SP_64 : Mips::SP,
2369 // With EABI is it possible to have 16 args on registers.
2370 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2371 SmallVector<SDValue, 8> MemOpChains;
2372 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2374 // Walk the register/memloc assignments, inserting copies/loads.
2375 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2376 SDValue Arg = OutVals[i];
2377 CCValAssign &VA = ArgLocs[i];
2378 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2379 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2382 if (Flags.isByVal()) {
2383 assert(Flags.getByValSize() &&
2384 "ByVal args of size 0 should have been ignored by front-end.");
2385 assert(ByValArg != MipsCCInfo.byval_end());
2386 assert(!IsTailCall &&
2387 "Do not tail-call optimize if there is a byval argument.");
2388 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2389 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2394 // Promote the value if needed.
2395 switch (VA.getLocInfo()) {
2396 default: llvm_unreachable("Unknown loc info!");
2397 case CCValAssign::Full:
2398 if (VA.isRegLoc()) {
2399 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2400 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2401 (ValVT == MVT::i64 && LocVT == MVT::f64))
2402 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2403 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2404 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2405 Arg, DAG.getConstant(0, MVT::i32));
2406 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2407 Arg, DAG.getConstant(1, MVT::i32));
2408 if (!Subtarget->isLittle())
2410 unsigned LocRegLo = VA.getLocReg();
2411 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2412 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2413 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2418 case CCValAssign::SExt:
2419 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2421 case CCValAssign::ZExt:
2422 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2424 case CCValAssign::AExt:
2425 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2429 // Arguments that can be passed on register must be kept at
2430 // RegsToPass vector
2431 if (VA.isRegLoc()) {
2432 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2436 // Register can't get to this point...
2437 assert(VA.isMemLoc());
2439 // emit ISD::STORE whichs stores the
2440 // parameter value to a stack Location
2441 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2442 Chain, Arg, DL, IsTailCall, DAG));
2445 // Transform all store nodes into one single node because all store
2446 // nodes are independent of each other.
2447 if (!MemOpChains.empty())
2448 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2449 &MemOpChains[0], MemOpChains.size());
2451 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2452 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2453 // node so that legalize doesn't hack it.
2454 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2455 bool GlobalOrExternal = false, InternalLinkage = false;
2458 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2460 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2462 if (InternalLinkage)
2463 Callee = getAddrLocal(Callee, DAG, HasMips64);
2465 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2466 MipsII::MO_CALL_LO16);
2468 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2470 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2471 MipsII::MO_NO_FLAG);
2472 GlobalOrExternal = true;
2474 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2475 if (!IsN64 && !IsPIC) // !N64 && static
2476 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2477 MipsII::MO_NO_FLAG);
2479 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2480 MipsII::MO_CALL_LO16);
2482 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2484 GlobalOrExternal = true;
2487 SmallVector<SDValue, 8> Ops(1, Chain);
2488 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2490 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2491 CLI, Callee, Chain);
2494 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2496 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2497 SDValue InFlag = Chain.getValue(1);
2499 // Create the CALLSEQ_END node.
2500 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2501 DAG.getIntPtrConstant(0, true), InFlag, DL);
2502 InFlag = Chain.getValue(1);
2504 // Handle result values, copying them out of physregs into vregs that we
2506 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2507 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2510 /// LowerCallResult - Lower the result values of a call into the
2511 /// appropriate copies out of appropriate physical registers.
2513 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2514 CallingConv::ID CallConv, bool IsVarArg,
2515 const SmallVectorImpl<ISD::InputArg> &Ins,
2516 SDLoc DL, SelectionDAG &DAG,
2517 SmallVectorImpl<SDValue> &InVals,
2518 const SDNode *CallNode,
2519 const Type *RetTy) const {
2520 // Assign locations to each value returned by this call.
2521 SmallVector<CCValAssign, 16> RVLocs;
2522 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2523 getTargetMachine(), RVLocs, *DAG.getContext());
2524 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2526 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2529 // Copy all of the result registers out of their specified physreg.
2530 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2531 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2532 RVLocs[i].getLocVT(), InFlag);
2533 Chain = Val.getValue(1);
2534 InFlag = Val.getValue(2);
2536 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2537 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2539 InVals.push_back(Val);
2545 //===----------------------------------------------------------------------===//
2546 // Formal Arguments Calling Convention Implementation
2547 //===----------------------------------------------------------------------===//
2548 /// LowerFormalArguments - transform physical registers into virtual registers
2549 /// and generate load operations for arguments places on the stack.
2551 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2552 CallingConv::ID CallConv,
2554 const SmallVectorImpl<ISD::InputArg> &Ins,
2555 SDLoc DL, SelectionDAG &DAG,
2556 SmallVectorImpl<SDValue> &InVals)
2558 MachineFunction &MF = DAG.getMachineFunction();
2559 MachineFrameInfo *MFI = MF.getFrameInfo();
2560 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2562 MipsFI->setVarArgsFrameIndex(0);
2564 // Used with vargs to acumulate store chains.
2565 std::vector<SDValue> OutChains;
2567 // Assign locations to all of the incoming arguments.
2568 SmallVector<CCValAssign, 16> ArgLocs;
2569 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2570 getTargetMachine(), ArgLocs, *DAG.getContext());
2571 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2572 Function::const_arg_iterator FuncArg =
2573 DAG.getMachineFunction().getFunction()->arg_begin();
2574 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2576 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2577 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2578 MipsCCInfo.hasByValArg());
2580 unsigned CurArgIdx = 0;
2581 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2583 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2584 CCValAssign &VA = ArgLocs[i];
2585 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2586 CurArgIdx = Ins[i].OrigArgIndex;
2587 EVT ValVT = VA.getValVT();
2588 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2589 bool IsRegLoc = VA.isRegLoc();
2591 if (Flags.isByVal()) {
2592 assert(Flags.getByValSize() &&
2593 "ByVal args of size 0 should have been ignored by front-end.");
2594 assert(ByValArg != MipsCCInfo.byval_end());
2595 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2596 MipsCCInfo, *ByValArg);
2601 // Arguments stored on registers
2603 EVT RegVT = VA.getLocVT();
2604 unsigned ArgReg = VA.getLocReg();
2605 const TargetRegisterClass *RC;
2607 if (RegVT == MVT::i32)
2608 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2609 &Mips::GPR32RegClass;
2610 else if (RegVT == MVT::i64)
2611 RC = &Mips::GPR64RegClass;
2612 else if (RegVT == MVT::f32)
2613 RC = &Mips::FGR32RegClass;
2614 else if (RegVT == MVT::f64)
2615 RC = Subtarget->isFP64bit() ? &Mips::FGR64RegClass :
2616 &Mips::AFGR64RegClass;
2618 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2620 // Transform the arguments stored on
2621 // physical registers into virtual ones
2622 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2623 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2625 // If this is an 8 or 16-bit value, it has been passed promoted
2626 // to 32 bits. Insert an assert[sz]ext to capture this, then
2627 // truncate to the right size.
2628 if (VA.getLocInfo() != CCValAssign::Full) {
2629 unsigned Opcode = 0;
2630 if (VA.getLocInfo() == CCValAssign::SExt)
2631 Opcode = ISD::AssertSext;
2632 else if (VA.getLocInfo() == CCValAssign::ZExt)
2633 Opcode = ISD::AssertZext;
2635 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2636 DAG.getValueType(ValVT));
2637 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2640 // Handle floating point arguments passed in integer registers and
2641 // long double arguments passed in floating point registers.
2642 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2643 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2644 (RegVT == MVT::f64 && ValVT == MVT::i64))
2645 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2646 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2647 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2648 getNextIntArgReg(ArgReg), RC);
2649 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2650 if (!Subtarget->isLittle())
2651 std::swap(ArgValue, ArgValue2);
2652 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2653 ArgValue, ArgValue2);
2656 InVals.push_back(ArgValue);
2657 } else { // VA.isRegLoc()
2660 assert(VA.isMemLoc());
2662 // The stack pointer offset is relative to the caller stack frame.
2663 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2664 VA.getLocMemOffset(), true);
2666 // Create load nodes to retrieve arguments from the stack
2667 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2668 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2669 MachinePointerInfo::getFixedStack(FI),
2670 false, false, false, 0));
2674 // The mips ABIs for returning structs by value requires that we copy
2675 // the sret argument into $v0 for the return. Save the argument into
2676 // a virtual register so that we can access it from the return points.
2677 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2678 unsigned Reg = MipsFI->getSRetReturnReg();
2680 Reg = MF.getRegInfo().
2681 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2682 MipsFI->setSRetReturnReg(Reg);
2684 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2685 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2689 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2691 // All stores are grouped in one node to allow the matching between
2692 // the size of Ins and InVals. This only happens when on varg functions
2693 if (!OutChains.empty()) {
2694 OutChains.push_back(Chain);
2695 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2696 &OutChains[0], OutChains.size());
2702 //===----------------------------------------------------------------------===//
2703 // Return Value Calling Convention Implementation
2704 //===----------------------------------------------------------------------===//
2707 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2708 MachineFunction &MF, bool IsVarArg,
2709 const SmallVectorImpl<ISD::OutputArg> &Outs,
2710 LLVMContext &Context) const {
2711 SmallVector<CCValAssign, 16> RVLocs;
2712 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2714 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2718 MipsTargetLowering::LowerReturn(SDValue Chain,
2719 CallingConv::ID CallConv, bool IsVarArg,
2720 const SmallVectorImpl<ISD::OutputArg> &Outs,
2721 const SmallVectorImpl<SDValue> &OutVals,
2722 SDLoc DL, SelectionDAG &DAG) const {
2723 // CCValAssign - represent the assignment of
2724 // the return value to a location
2725 SmallVector<CCValAssign, 16> RVLocs;
2726 MachineFunction &MF = DAG.getMachineFunction();
2728 // CCState - Info about the registers and stack slot.
2729 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2731 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2733 // Analyze return values.
2734 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2735 MF.getFunction()->getReturnType());
2738 SmallVector<SDValue, 4> RetOps(1, Chain);
2740 // Copy the result values into the output registers.
2741 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2742 SDValue Val = OutVals[i];
2743 CCValAssign &VA = RVLocs[i];
2744 assert(VA.isRegLoc() && "Can only return in registers!");
2746 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2747 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2749 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2751 // Guarantee that all emitted copies are stuck together with flags.
2752 Flag = Chain.getValue(1);
2753 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2756 // The mips ABIs for returning structs by value requires that we copy
2757 // the sret argument into $v0 for the return. We saved the argument into
2758 // a virtual register in the entry block, so now we copy the value out
2760 if (MF.getFunction()->hasStructRetAttr()) {
2761 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2762 unsigned Reg = MipsFI->getSRetReturnReg();
2765 llvm_unreachable("sret virtual register not created in the entry block");
2766 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2767 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2769 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2770 Flag = Chain.getValue(1);
2771 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2774 RetOps[0] = Chain; // Update chain.
2776 // Add the flag if we have it.
2778 RetOps.push_back(Flag);
2780 // Return on Mips is always a "jr $ra"
2781 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2784 //===----------------------------------------------------------------------===//
2785 // Mips Inline Assembly Support
2786 //===----------------------------------------------------------------------===//
2788 /// getConstraintType - Given a constraint letter, return the type of
2789 /// constraint it is for this target.
2790 MipsTargetLowering::ConstraintType MipsTargetLowering::
2791 getConstraintType(const std::string &Constraint) const
2793 // Mips specific constrainy
2794 // GCC config/mips/constraints.md
2796 // 'd' : An address register. Equivalent to r
2797 // unless generating MIPS16 code.
2798 // 'y' : Equivalent to r; retained for
2799 // backwards compatibility.
2800 // 'c' : A register suitable for use in an indirect
2801 // jump. This will always be $25 for -mabicalls.
2802 // 'l' : The lo register. 1 word storage.
2803 // 'x' : The hilo register pair. Double word storage.
2804 if (Constraint.size() == 1) {
2805 switch (Constraint[0]) {
2813 return C_RegisterClass;
2818 return TargetLowering::getConstraintType(Constraint);
2821 /// Examine constraint type and operand type and determine a weight value.
2822 /// This object must already have been set up with the operand type
2823 /// and the current alternative constraint selected.
2824 TargetLowering::ConstraintWeight
2825 MipsTargetLowering::getSingleConstraintMatchWeight(
2826 AsmOperandInfo &info, const char *constraint) const {
2827 ConstraintWeight weight = CW_Invalid;
2828 Value *CallOperandVal = info.CallOperandVal;
2829 // If we don't have a value, we can't do a match,
2830 // but allow it at the lowest weight.
2831 if (CallOperandVal == NULL)
2833 Type *type = CallOperandVal->getType();
2834 // Look at the constraint type.
2835 switch (*constraint) {
2837 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2841 if (type->isIntegerTy())
2842 weight = CW_Register;
2845 if (type->isFloatTy())
2846 weight = CW_Register;
2848 case 'c': // $25 for indirect jumps
2849 case 'l': // lo register
2850 case 'x': // hilo register pair
2851 if (type->isIntegerTy())
2852 weight = CW_SpecificReg;
2854 case 'I': // signed 16 bit immediate
2855 case 'J': // integer zero
2856 case 'K': // unsigned 16 bit immediate
2857 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2858 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2859 case 'O': // signed 15 bit immediate (+- 16383)
2860 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2861 if (isa<ConstantInt>(CallOperandVal))
2862 weight = CW_Constant;
2871 /// This is a helper function to parse a physical register string and split it
2872 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2873 /// that is returned indicates whether parsing was successful. The second flag
2874 /// is true if the numeric part exists.
2875 static std::pair<bool, bool>
2876 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2877 unsigned long long &Reg) {
2878 if (C.front() != '{' || C.back() != '}')
2879 return std::make_pair(false, false);
2881 // Search for the first numeric character.
2882 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2883 I = std::find_if(B, E, std::ptr_fun(isdigit));
2885 Prefix.assign(B, I - B);
2887 // The second flag is set to false if no numeric characters were found.
2889 return std::make_pair(true, false);
2891 // Parse the numeric characters.
2892 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2896 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2897 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2898 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2899 const TargetRegisterClass *RC;
2901 unsigned long long Reg;
2903 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2906 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2908 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2909 // No numeric characters follow "hi" or "lo".
2911 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2913 RC = TRI->getRegClass(Prefix == "hi" ?
2914 Mips::HI32RegClassID : Mips::LO32RegClassID);
2915 return std::make_pair(*(RC->begin()), RC);
2919 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2921 if (Prefix == "$f") { // Parse $f0-$f31.
2922 // If the size of FP registers is 64-bit or Reg is an even number, select
2923 // the 64-bit register class. Otherwise, select the 32-bit register class.
2924 if (VT == MVT::Other)
2925 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2927 RC= getRegClassFor(VT);
2929 if (RC == &Mips::AFGR64RegClass) {
2930 assert(Reg % 2 == 0);
2933 } else if (Prefix == "$fcc") { // Parse $fcc0-$fcc7.
2934 RC = TRI->getRegClass(Mips::FCCRegClassID);
2935 } else { // Parse $0-$31.
2936 assert(Prefix == "$");
2937 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2940 assert(Reg < RC->getNumRegs());
2941 return std::make_pair(*(RC->begin() + Reg), RC);
2944 /// Given a register class constraint, like 'r', if this corresponds directly
2945 /// to an LLVM register class, return a register of 0 and the register class
2947 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2948 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2950 if (Constraint.size() == 1) {
2951 switch (Constraint[0]) {
2952 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2953 case 'y': // Same as 'r'. Exists for compatibility.
2955 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2956 if (Subtarget->inMips16Mode())
2957 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2958 return std::make_pair(0U, &Mips::GPR32RegClass);
2960 if (VT == MVT::i64 && !HasMips64)
2961 return std::make_pair(0U, &Mips::GPR32RegClass);
2962 if (VT == MVT::i64 && HasMips64)
2963 return std::make_pair(0U, &Mips::GPR64RegClass);
2964 // This will generate an error message
2965 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2968 return std::make_pair(0U, &Mips::FGR32RegClass);
2969 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2970 if (Subtarget->isFP64bit())
2971 return std::make_pair(0U, &Mips::FGR64RegClass);
2972 return std::make_pair(0U, &Mips::AFGR64RegClass);
2975 case 'c': // register suitable for indirect jump
2977 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
2978 assert(VT == MVT::i64 && "Unexpected type.");
2979 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
2980 case 'l': // register suitable for indirect jump
2982 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
2983 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
2984 case 'x': // register suitable for indirect jump
2985 // Fixme: Not triggering the use of both hi and low
2986 // This will generate an error message
2987 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2991 std::pair<unsigned, const TargetRegisterClass *> R;
2992 R = parseRegForInlineAsmConstraint(Constraint, VT);
2997 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3000 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3001 /// vector. If it is invalid, don't add anything to Ops.
3002 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3003 std::string &Constraint,
3004 std::vector<SDValue>&Ops,
3005 SelectionDAG &DAG) const {
3006 SDValue Result(0, 0);
3008 // Only support length 1 constraints for now.
3009 if (Constraint.length() > 1) return;
3011 char ConstraintLetter = Constraint[0];
3012 switch (ConstraintLetter) {
3013 default: break; // This will fall through to the generic implementation
3014 case 'I': // Signed 16 bit constant
3015 // If this fails, the parent routine will give an error
3016 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3017 EVT Type = Op.getValueType();
3018 int64_t Val = C->getSExtValue();
3019 if (isInt<16>(Val)) {
3020 Result = DAG.getTargetConstant(Val, Type);
3025 case 'J': // integer zero
3026 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3027 EVT Type = Op.getValueType();
3028 int64_t Val = C->getZExtValue();
3030 Result = DAG.getTargetConstant(0, Type);
3035 case 'K': // unsigned 16 bit immediate
3036 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3037 EVT Type = Op.getValueType();
3038 uint64_t Val = (uint64_t)C->getZExtValue();
3039 if (isUInt<16>(Val)) {
3040 Result = DAG.getTargetConstant(Val, Type);
3045 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3046 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3047 EVT Type = Op.getValueType();
3048 int64_t Val = C->getSExtValue();
3049 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3050 Result = DAG.getTargetConstant(Val, Type);
3055 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3056 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3057 EVT Type = Op.getValueType();
3058 int64_t Val = C->getSExtValue();
3059 if ((Val >= -65535) && (Val <= -1)) {
3060 Result = DAG.getTargetConstant(Val, Type);
3065 case 'O': // signed 15 bit immediate
3066 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3067 EVT Type = Op.getValueType();
3068 int64_t Val = C->getSExtValue();
3069 if ((isInt<15>(Val))) {
3070 Result = DAG.getTargetConstant(Val, Type);
3075 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3076 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3077 EVT Type = Op.getValueType();
3078 int64_t Val = C->getSExtValue();
3079 if ((Val <= 65535) && (Val >= 1)) {
3080 Result = DAG.getTargetConstant(Val, Type);
3087 if (Result.getNode()) {
3088 Ops.push_back(Result);
3092 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3096 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
3097 // No global is ever allowed as a base.
3102 case 0: // "r+i" or just "i", depending on HasBaseReg.
3105 if (!AM.HasBaseReg) // allow "r+i".
3107 return false; // disallow "r+r" or "r+r+i".
3116 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3117 // The Mips target isn't yet aware of offsets.
3121 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3123 bool IsMemset, bool ZeroMemset,
3125 MachineFunction &MF) const {
3126 if (Subtarget->hasMips64())
3132 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3133 if (VT != MVT::f32 && VT != MVT::f64)
3135 if (Imm.isNegZero())
3137 return Imm.isZero();
3140 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3142 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3144 return TargetLowering::getJumpTableEncoding();
3147 /// This function returns true if CallSym is a long double emulation routine.
3148 static bool isF128SoftLibCall(const char *CallSym) {
3149 const char *const LibCalls[] =
3150 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3151 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3152 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3153 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3154 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3155 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3156 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3157 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3160 const char * const *End = LibCalls + array_lengthof(LibCalls);
3162 // Check that LibCalls is sorted alphabetically.
3163 MipsTargetLowering::LTStr Comp;
3166 for (const char * const *I = LibCalls; I < End - 1; ++I)
3167 assert(Comp(*I, *(I + 1)));
3170 return std::binary_search(LibCalls, End, CallSym, Comp);
3173 /// This function returns true if Ty is fp128 or i128 which was originally a
3175 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3176 if (Ty->isFP128Ty())
3179 const ExternalSymbolSDNode *ES =
3180 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3182 // If the Ty is i128 and the function being called is a long double emulation
3183 // routine, then the original type is f128.
3184 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3187 MipsTargetLowering::MipsCC::SpecialCallingConvType
3188 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3189 MipsCC::SpecialCallingConvType SpecialCallingConv =
3190 MipsCC::NoSpecialCallingConv;;
3191 if (Subtarget->inMips16HardFloat()) {
3192 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3193 llvm::StringRef Sym = G->getGlobal()->getName();
3194 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3195 if (F->hasFnAttribute("__Mips16RetHelper")) {
3196 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3200 return SpecialCallingConv;
3203 MipsTargetLowering::MipsCC::MipsCC(
3204 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3205 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3206 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3207 SpecialCallingConv(SpecialCallingConv_){
3208 // Pre-allocate reserved argument area.
3209 CCInfo.AllocateStack(reservedArgArea(), 1);
3213 void MipsTargetLowering::MipsCC::
3214 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3215 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3216 std::vector<ArgListEntry> &FuncArgs) {
3217 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3218 "CallingConv::Fast shouldn't be used for vararg functions.");
3220 unsigned NumOpnds = Args.size();
3221 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3223 for (unsigned I = 0; I != NumOpnds; ++I) {
3224 MVT ArgVT = Args[I].VT;
3225 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3228 if (ArgFlags.isByVal()) {
3229 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3233 if (IsVarArg && !Args[I].IsFixed)
3234 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3236 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3238 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3243 dbgs() << "Call operand #" << I << " has unhandled type "
3244 << EVT(ArgVT).getEVTString();
3246 llvm_unreachable(0);
3251 void MipsTargetLowering::MipsCC::
3252 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3253 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3254 unsigned NumArgs = Args.size();
3255 llvm::CCAssignFn *FixedFn = fixedArgFn();
3256 unsigned CurArgIdx = 0;
3258 for (unsigned I = 0; I != NumArgs; ++I) {
3259 MVT ArgVT = Args[I].VT;
3260 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3261 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3262 CurArgIdx = Args[I].OrigArgIndex;
3264 if (ArgFlags.isByVal()) {
3265 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3269 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3271 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3275 dbgs() << "Formal Arg #" << I << " has unhandled type "
3276 << EVT(ArgVT).getEVTString();
3278 llvm_unreachable(0);
3282 template<typename Ty>
3283 void MipsTargetLowering::MipsCC::
3284 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3285 const SDNode *CallNode, const Type *RetTy) const {
3288 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3289 Fn = RetCC_F128Soft;
3293 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3294 MVT VT = RetVals[I].VT;
3295 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3296 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3298 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3300 dbgs() << "Call result #" << I << " has unhandled type "
3301 << EVT(VT).getEVTString() << '\n';
3303 llvm_unreachable(0);
3308 void MipsTargetLowering::MipsCC::
3309 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3310 const SDNode *CallNode, const Type *RetTy) const {
3311 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3314 void MipsTargetLowering::MipsCC::
3315 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3316 const Type *RetTy) const {
3317 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3321 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3323 CCValAssign::LocInfo LocInfo,
3324 ISD::ArgFlagsTy ArgFlags) {
3325 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3327 struct ByValArgInfo ByVal;
3328 unsigned RegSize = regSize();
3329 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3330 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3333 if (useRegsForByval())
3334 allocateRegs(ByVal, ByValSize, Align);
3336 // Allocate space on caller's stack.
3337 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3339 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3341 ByValArgs.push_back(ByVal);
3344 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3345 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3348 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3349 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3352 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3353 return IsO32 ? O32IntRegs : Mips64IntRegs;
3356 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3357 if (CallConv == CallingConv::Fast)
3358 return CC_Mips_FastCC;
3360 if (SpecialCallingConv == Mips16RetHelperConv)
3361 return CC_Mips16RetHelper;
3362 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3365 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3366 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3369 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3370 return IsO32 ? O32IntRegs : Mips64DPRegs;
3373 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3376 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3377 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3378 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3379 "Byval argument's size and alignment should be a multiple of"
3382 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3384 // If Align > RegSize, the first arg register must be even.
3385 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3386 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3390 // Mark the registers allocated.
3391 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3392 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3393 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3396 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3397 const SDNode *CallNode,
3398 bool IsSoftFloat) const {
3399 if (IsSoftFloat || IsO32)
3402 // Check if the original type was fp128.
3403 if (originalTypeIsF128(OrigTy, CallNode)) {
3404 assert(VT == MVT::i64);
3411 void MipsTargetLowering::
3412 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3413 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3414 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3415 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3416 MachineFunction &MF = DAG.getMachineFunction();
3417 MachineFrameInfo *MFI = MF.getFrameInfo();
3418 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3419 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3423 FrameObjOffset = (int)CC.reservedArgArea() -
3424 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3426 FrameObjOffset = ByVal.Address;
3428 // Create frame object.
3429 EVT PtrTy = getPointerTy();
3430 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3431 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3432 InVals.push_back(FIN);
3437 // Copy arg registers.
3438 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3439 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3441 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3442 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3443 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3444 unsigned Offset = I * CC.regSize();
3445 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3446 DAG.getConstant(Offset, PtrTy));
3447 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3448 StorePtr, MachinePointerInfo(FuncArg, Offset),
3450 OutChains.push_back(Store);
3454 // Copy byVal arg to registers and stack.
3455 void MipsTargetLowering::
3456 passByValArg(SDValue Chain, SDLoc DL,
3457 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3458 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3459 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3460 const MipsCC &CC, const ByValArgInfo &ByVal,
3461 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3462 unsigned ByValSize = Flags.getByValSize();
3463 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3464 unsigned RegSize = CC.regSize();
3465 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3466 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3468 if (ByVal.NumRegs) {
3469 const uint16_t *ArgRegs = CC.intArgRegs();
3470 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3473 // Copy words to registers.
3474 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3475 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3476 DAG.getConstant(Offset, PtrTy));
3477 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3478 MachinePointerInfo(), false, false, false,
3480 MemOpChains.push_back(LoadVal.getValue(1));
3481 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3482 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3485 // Return if the struct has been fully copied.
3486 if (ByValSize == Offset)
3489 // Copy the remainder of the byval argument with sub-word loads and shifts.
3490 if (LeftoverBytes) {
3491 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3492 "Size of the remainder should be smaller than RegSize.");
3495 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3496 Offset < ByValSize; LoadSize /= 2) {
3497 unsigned RemSize = ByValSize - Offset;
3499 if (RemSize < LoadSize)
3503 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3504 DAG.getConstant(Offset, PtrTy));
3506 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3507 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3508 false, false, Alignment);
3509 MemOpChains.push_back(LoadVal.getValue(1));
3511 // Shift the loaded value.
3515 Shamt = TotalSizeLoaded;
3517 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3519 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3520 DAG.getConstant(Shamt, MVT::i32));
3523 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3528 TotalSizeLoaded += LoadSize;
3529 Alignment = std::min(Alignment, LoadSize);
3532 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3533 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3538 // Copy remainder of byval arg to it with memcpy.
3539 unsigned MemCpySize = ByValSize - Offset;
3540 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3541 DAG.getConstant(Offset, PtrTy));
3542 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3543 DAG.getIntPtrConstant(ByVal.Address));
3544 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3545 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3546 /*isVolatile=*/false, /*AlwaysInline=*/false,
3547 MachinePointerInfo(0), MachinePointerInfo(0));
3548 MemOpChains.push_back(Chain);
3552 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3553 const MipsCC &CC, SDValue Chain,
3554 SDLoc DL, SelectionDAG &DAG) const {
3555 unsigned NumRegs = CC.numIntArgRegs();
3556 const uint16_t *ArgRegs = CC.intArgRegs();
3557 const CCState &CCInfo = CC.getCCInfo();
3558 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3559 unsigned RegSize = CC.regSize();
3560 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3561 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3562 MachineFunction &MF = DAG.getMachineFunction();
3563 MachineFrameInfo *MFI = MF.getFrameInfo();
3564 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3566 // Offset of the first variable argument from stack pointer.
3570 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3573 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3575 // Record the frame index of the first variable argument
3576 // which is a value necessary to VASTART.
3577 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3578 MipsFI->setVarArgsFrameIndex(FI);
3580 // Copy the integer registers that have not been used for argument passing
3581 // to the argument register save area. For O32, the save area is allocated
3582 // in the caller's stack frame, while for N32/64, it is allocated in the
3583 // callee's stack frame.
3584 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3585 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3586 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3587 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3588 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3589 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3590 MachinePointerInfo(), false, false, 0);
3591 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3592 OutChains.push_back(Store);