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 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
85 unsigned Flag) const {
86 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
89 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
91 unsigned Flag) const {
92 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
95 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
97 unsigned Flag) const {
98 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
101 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
103 unsigned Flag) const {
104 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
107 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
109 unsigned Flag) const {
110 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
111 N->getOffset(), Flag);
114 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
116 case MipsISD::JmpLink: return "MipsISD::JmpLink";
117 case MipsISD::TailCall: return "MipsISD::TailCall";
118 case MipsISD::Hi: return "MipsISD::Hi";
119 case MipsISD::Lo: return "MipsISD::Lo";
120 case MipsISD::GPRel: return "MipsISD::GPRel";
121 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
122 case MipsISD::Ret: return "MipsISD::Ret";
123 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
124 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
125 case MipsISD::FPCmp: return "MipsISD::FPCmp";
126 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
127 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
128 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
129 case MipsISD::ExtractHI: return "MipsISD::ExtractHI";
130 case MipsISD::ExtractLO: return "MipsISD::ExtractLO";
131 case MipsISD::InsertLOHI: return "MipsISD::InsertLOHI";
132 case MipsISD::Mult: return "MipsISD::Mult";
133 case MipsISD::Multu: return "MipsISD::Multu";
134 case MipsISD::MAdd: return "MipsISD::MAdd";
135 case MipsISD::MAddu: return "MipsISD::MAddu";
136 case MipsISD::MSub: return "MipsISD::MSub";
137 case MipsISD::MSubu: return "MipsISD::MSubu";
138 case MipsISD::DivRem: return "MipsISD::DivRem";
139 case MipsISD::DivRemU: return "MipsISD::DivRemU";
140 case MipsISD::DivRem16: return "MipsISD::DivRem16";
141 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
142 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
143 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
144 case MipsISD::Wrapper: return "MipsISD::Wrapper";
145 case MipsISD::Sync: return "MipsISD::Sync";
146 case MipsISD::Ext: return "MipsISD::Ext";
147 case MipsISD::Ins: return "MipsISD::Ins";
148 case MipsISD::LWL: return "MipsISD::LWL";
149 case MipsISD::LWR: return "MipsISD::LWR";
150 case MipsISD::SWL: return "MipsISD::SWL";
151 case MipsISD::SWR: return "MipsISD::SWR";
152 case MipsISD::LDL: return "MipsISD::LDL";
153 case MipsISD::LDR: return "MipsISD::LDR";
154 case MipsISD::SDL: return "MipsISD::SDL";
155 case MipsISD::SDR: return "MipsISD::SDR";
156 case MipsISD::EXTP: return "MipsISD::EXTP";
157 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
158 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
159 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
160 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
161 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
162 case MipsISD::SHILO: return "MipsISD::SHILO";
163 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
164 case MipsISD::MULT: return "MipsISD::MULT";
165 case MipsISD::MULTU: return "MipsISD::MULTU";
166 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
167 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
168 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
169 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
170 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
171 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
172 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
173 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
174 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
175 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
176 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
177 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
178 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
179 case MipsISD::VCEQ: return "MipsISD::VCEQ";
180 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
181 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
182 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
183 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
184 case MipsISD::VSMAX: return "MipsISD::VSMAX";
185 case MipsISD::VSMIN: return "MipsISD::VSMIN";
186 case MipsISD::VUMAX: return "MipsISD::VUMAX";
187 case MipsISD::VUMIN: return "MipsISD::VUMIN";
188 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
189 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
190 case MipsISD::VNOR: return "MipsISD::VNOR";
191 case MipsISD::VSHF: return "MipsISD::VSHF";
192 case MipsISD::SHF: return "MipsISD::SHF";
193 case MipsISD::ILVEV: return "MipsISD::ILVEV";
194 case MipsISD::ILVOD: return "MipsISD::ILVOD";
195 case MipsISD::ILVL: return "MipsISD::ILVL";
196 case MipsISD::ILVR: return "MipsISD::ILVR";
197 case MipsISD::PCKEV: return "MipsISD::PCKEV";
198 case MipsISD::PCKOD: return "MipsISD::PCKOD";
199 default: return NULL;
204 MipsTargetLowering(MipsTargetMachine &TM)
205 : TargetLowering(TM, new MipsTargetObjectFile()),
206 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
207 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
208 IsO32(Subtarget->isABI_O32()) {
209 // Mips does not have i1 type, so use i32 for
210 // setcc operations results (slt, sgt, ...).
211 setBooleanContents(ZeroOrOneBooleanContent);
212 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
214 // Load extented operations for i1 types must be promoted
215 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
216 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
217 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
219 // MIPS doesn't have extending float->double load/store
220 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
221 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
223 // Used by legalize types to correctly generate the setcc result.
224 // Without this, every float setcc comes with a AND/OR with the result,
225 // we don't want this, since the fpcmp result goes to a flag register,
226 // which is used implicitly by brcond and select operations.
227 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
229 // Mips Custom Operations
230 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
231 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
232 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
233 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
234 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
235 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
236 setOperationAction(ISD::SELECT, MVT::f32, Custom);
237 setOperationAction(ISD::SELECT, MVT::f64, Custom);
238 setOperationAction(ISD::SELECT, MVT::i32, Custom);
239 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
241 setOperationAction(ISD::SETCC, MVT::f32, Custom);
242 setOperationAction(ISD::SETCC, MVT::f64, Custom);
243 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
244 setOperationAction(ISD::VASTART, MVT::Other, Custom);
245 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
246 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
247 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
249 if (!TM.Options.NoNaNsFPMath) {
250 setOperationAction(ISD::FABS, MVT::f32, Custom);
251 setOperationAction(ISD::FABS, MVT::f64, Custom);
255 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
256 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
257 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
258 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
259 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
260 setOperationAction(ISD::SELECT, MVT::i64, Custom);
261 setOperationAction(ISD::LOAD, MVT::i64, Custom);
262 setOperationAction(ISD::STORE, MVT::i64, Custom);
263 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
267 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
268 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
269 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
272 setOperationAction(ISD::ADD, MVT::i32, Custom);
274 setOperationAction(ISD::ADD, MVT::i64, Custom);
276 setOperationAction(ISD::SDIV, MVT::i32, Expand);
277 setOperationAction(ISD::SREM, MVT::i32, Expand);
278 setOperationAction(ISD::UDIV, MVT::i32, Expand);
279 setOperationAction(ISD::UREM, MVT::i32, Expand);
280 setOperationAction(ISD::SDIV, MVT::i64, Expand);
281 setOperationAction(ISD::SREM, MVT::i64, Expand);
282 setOperationAction(ISD::UDIV, MVT::i64, Expand);
283 setOperationAction(ISD::UREM, MVT::i64, Expand);
285 // Operations not directly supported by Mips.
286 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
287 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
288 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
289 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
290 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
291 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
292 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
293 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
294 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
295 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
296 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
297 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
298 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
299 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
300 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
301 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
302 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
303 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
304 setOperationAction(ISD::ROTL, MVT::i32, Expand);
305 setOperationAction(ISD::ROTL, MVT::i64, Expand);
306 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
307 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
309 if (!Subtarget->hasMips32r2())
310 setOperationAction(ISD::ROTR, MVT::i32, Expand);
312 if (!Subtarget->hasMips64r2())
313 setOperationAction(ISD::ROTR, MVT::i64, Expand);
315 setOperationAction(ISD::FSIN, MVT::f32, Expand);
316 setOperationAction(ISD::FSIN, MVT::f64, Expand);
317 setOperationAction(ISD::FCOS, MVT::f32, Expand);
318 setOperationAction(ISD::FCOS, MVT::f64, Expand);
319 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
320 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
321 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
322 setOperationAction(ISD::FPOW, MVT::f32, Expand);
323 setOperationAction(ISD::FPOW, MVT::f64, Expand);
324 setOperationAction(ISD::FLOG, MVT::f32, Expand);
325 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
326 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
327 setOperationAction(ISD::FEXP, MVT::f32, Expand);
328 setOperationAction(ISD::FMA, MVT::f32, Expand);
329 setOperationAction(ISD::FMA, MVT::f64, Expand);
330 setOperationAction(ISD::FREM, MVT::f32, Expand);
331 setOperationAction(ISD::FREM, MVT::f64, Expand);
333 if (!TM.Options.NoNaNsFPMath) {
334 setOperationAction(ISD::FNEG, MVT::f32, Expand);
335 setOperationAction(ISD::FNEG, MVT::f64, Expand);
338 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
340 setOperationAction(ISD::VAARG, MVT::Other, Expand);
341 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
342 setOperationAction(ISD::VAEND, MVT::Other, Expand);
344 // Use the default for now
345 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
346 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
348 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
349 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
350 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
351 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
353 setInsertFencesForAtomic(true);
355 if (!Subtarget->hasSEInReg()) {
356 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
357 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
360 if (!Subtarget->hasBitCount()) {
361 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
362 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
365 if (!Subtarget->hasSwap()) {
366 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
367 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
371 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
372 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
373 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
374 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
377 setOperationAction(ISD::TRAP, MVT::Other, Legal);
379 setTargetDAGCombine(ISD::SDIVREM);
380 setTargetDAGCombine(ISD::UDIVREM);
381 setTargetDAGCombine(ISD::SELECT);
382 setTargetDAGCombine(ISD::AND);
383 setTargetDAGCombine(ISD::OR);
384 setTargetDAGCombine(ISD::ADD);
386 setMinFunctionAlignment(HasMips64 ? 3 : 2);
388 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
390 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
391 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
393 MaxStoresPerMemcpy = 16;
396 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
397 if (TM.getSubtargetImpl()->inMips16Mode())
398 return llvm::createMips16TargetLowering(TM);
400 return llvm::createMipsSETargetLowering(TM);
403 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
406 return VT.changeVectorElementTypeToInteger();
409 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
410 TargetLowering::DAGCombinerInfo &DCI,
411 const MipsSubtarget *Subtarget) {
412 if (DCI.isBeforeLegalizeOps())
415 EVT Ty = N->getValueType(0);
416 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
417 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
418 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
422 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
423 N->getOperand(0), N->getOperand(1));
424 SDValue InChain = DAG.getEntryNode();
425 SDValue InGlue = DivRem;
428 if (N->hasAnyUseOfValue(0)) {
429 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
431 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
432 InChain = CopyFromLo.getValue(1);
433 InGlue = CopyFromLo.getValue(2);
437 if (N->hasAnyUseOfValue(1)) {
438 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
440 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
446 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
448 default: llvm_unreachable("Unknown fp condition code!");
450 case ISD::SETOEQ: return Mips::FCOND_OEQ;
451 case ISD::SETUNE: return Mips::FCOND_UNE;
453 case ISD::SETOLT: return Mips::FCOND_OLT;
455 case ISD::SETOGT: return Mips::FCOND_OGT;
457 case ISD::SETOLE: return Mips::FCOND_OLE;
459 case ISD::SETOGE: return Mips::FCOND_OGE;
460 case ISD::SETULT: return Mips::FCOND_ULT;
461 case ISD::SETULE: return Mips::FCOND_ULE;
462 case ISD::SETUGT: return Mips::FCOND_UGT;
463 case ISD::SETUGE: return Mips::FCOND_UGE;
464 case ISD::SETUO: return Mips::FCOND_UN;
465 case ISD::SETO: return Mips::FCOND_OR;
467 case ISD::SETONE: return Mips::FCOND_ONE;
468 case ISD::SETUEQ: return Mips::FCOND_UEQ;
473 /// This function returns true if the floating point conditional branches and
474 /// conditional moves which use condition code CC should be inverted.
475 static bool invertFPCondCodeUser(Mips::CondCode CC) {
476 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
479 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
480 "Illegal Condition Code");
485 // Creates and returns an FPCmp node from a setcc node.
486 // Returns Op if setcc is not a floating point comparison.
487 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
488 // must be a SETCC node
489 if (Op.getOpcode() != ISD::SETCC)
492 SDValue LHS = Op.getOperand(0);
494 if (!LHS.getValueType().isFloatingPoint())
497 SDValue RHS = Op.getOperand(1);
500 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
501 // node if necessary.
502 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
504 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
505 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
508 // Creates and returns a CMovFPT/F node.
509 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
510 SDValue False, SDLoc DL) {
511 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
512 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
513 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
515 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
516 True.getValueType(), True, FCC0, False, Cond);
519 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
520 TargetLowering::DAGCombinerInfo &DCI,
521 const MipsSubtarget *Subtarget) {
522 if (DCI.isBeforeLegalizeOps())
525 SDValue SetCC = N->getOperand(0);
527 if ((SetCC.getOpcode() != ISD::SETCC) ||
528 !SetCC.getOperand(0).getValueType().isInteger())
531 SDValue False = N->getOperand(2);
532 EVT FalseTy = False.getValueType();
534 if (!FalseTy.isInteger())
537 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
539 if (!CN || CN->getZExtValue())
543 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
544 SDValue True = N->getOperand(1);
546 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
547 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
549 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
552 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
553 TargetLowering::DAGCombinerInfo &DCI,
554 const MipsSubtarget *Subtarget) {
555 // Pattern match EXT.
556 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
557 // => ext $dst, $src, size, pos
558 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
561 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
562 unsigned ShiftRightOpc = ShiftRight.getOpcode();
564 // Op's first operand must be a shift right.
565 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
568 // The second operand of the shift must be an immediate.
570 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
573 uint64_t Pos = CN->getZExtValue();
574 uint64_t SMPos, SMSize;
576 // Op's second operand must be a shifted mask.
577 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
578 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
581 // Return if the shifted mask does not start at bit 0 or the sum of its size
582 // and Pos exceeds the word's size.
583 EVT ValTy = N->getValueType(0);
584 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
587 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
588 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
589 DAG.getConstant(SMSize, MVT::i32));
592 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
593 TargetLowering::DAGCombinerInfo &DCI,
594 const MipsSubtarget *Subtarget) {
595 // Pattern match INS.
596 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
597 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
598 // => ins $dst, $src, size, pos, $src1
599 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
602 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
603 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
606 // See if Op's first operand matches (and $src1 , mask0).
607 if (And0.getOpcode() != ISD::AND)
610 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
611 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
614 // See if Op's second operand matches (and (shl $src, pos), mask1).
615 if (And1.getOpcode() != ISD::AND)
618 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
619 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
622 // The shift masks must have the same position and size.
623 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
626 SDValue Shl = And1.getOperand(0);
627 if (Shl.getOpcode() != ISD::SHL)
630 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
633 unsigned Shamt = CN->getZExtValue();
635 // Return if the shift amount and the first bit position of mask are not the
637 EVT ValTy = N->getValueType(0);
638 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
641 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
642 DAG.getConstant(SMPos0, MVT::i32),
643 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
646 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
647 TargetLowering::DAGCombinerInfo &DCI,
648 const MipsSubtarget *Subtarget) {
649 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
651 if (DCI.isBeforeLegalizeOps())
654 SDValue Add = N->getOperand(1);
656 if (Add.getOpcode() != ISD::ADD)
659 SDValue Lo = Add.getOperand(1);
661 if ((Lo.getOpcode() != MipsISD::Lo) ||
662 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
665 EVT ValTy = N->getValueType(0);
668 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
670 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
673 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
675 SelectionDAG &DAG = DCI.DAG;
676 unsigned Opc = N->getOpcode();
682 return performDivRemCombine(N, DAG, DCI, Subtarget);
684 return performSELECTCombine(N, DAG, DCI, Subtarget);
686 return performANDCombine(N, DAG, DCI, Subtarget);
688 return performORCombine(N, DAG, DCI, Subtarget);
690 return performADDCombine(N, DAG, DCI, Subtarget);
697 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
698 SmallVectorImpl<SDValue> &Results,
699 SelectionDAG &DAG) const {
700 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
702 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
703 Results.push_back(Res.getValue(I));
707 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
708 SmallVectorImpl<SDValue> &Results,
709 SelectionDAG &DAG) const {
710 return LowerOperationWrapper(N, Results, DAG);
713 SDValue MipsTargetLowering::
714 LowerOperation(SDValue Op, SelectionDAG &DAG) const
716 switch (Op.getOpcode())
718 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
719 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
720 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
721 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
722 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
723 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
724 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
725 case ISD::SELECT: return lowerSELECT(Op, DAG);
726 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
727 case ISD::SETCC: return lowerSETCC(Op, DAG);
728 case ISD::VASTART: return lowerVASTART(Op, DAG);
729 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
730 case ISD::FABS: return lowerFABS(Op, DAG);
731 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
732 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
733 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
734 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
735 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
736 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
737 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
738 case ISD::LOAD: return lowerLOAD(Op, DAG);
739 case ISD::STORE: return lowerSTORE(Op, DAG);
740 case ISD::ADD: return lowerADD(Op, DAG);
741 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
746 //===----------------------------------------------------------------------===//
747 // Lower helper functions
748 //===----------------------------------------------------------------------===//
750 // addLiveIn - This helper function adds the specified physical register to the
751 // MachineFunction as a live in value. It also creates a corresponding
752 // virtual register for it.
754 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
756 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
757 MF.getRegInfo().addLiveIn(PReg, VReg);
761 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
762 MachineBasicBlock &MBB,
763 const TargetInstrInfo &TII,
768 // Insert instruction "teq $divisor_reg, $zero, 7".
769 MachineBasicBlock::iterator I(MI);
770 MachineInstrBuilder MIB;
771 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
772 .addOperand(MI->getOperand(2)).addReg(Mips::ZERO).addImm(7);
774 // Use the 32-bit sub-register if this is a 64-bit division.
776 MIB->getOperand(0).setSubReg(Mips::sub_32);
782 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
783 MachineBasicBlock *BB) const {
784 switch (MI->getOpcode()) {
786 llvm_unreachable("Unexpected instr type to insert");
787 case Mips::ATOMIC_LOAD_ADD_I8:
788 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
789 case Mips::ATOMIC_LOAD_ADD_I16:
790 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
791 case Mips::ATOMIC_LOAD_ADD_I32:
792 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
793 case Mips::ATOMIC_LOAD_ADD_I64:
794 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
796 case Mips::ATOMIC_LOAD_AND_I8:
797 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
798 case Mips::ATOMIC_LOAD_AND_I16:
799 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
800 case Mips::ATOMIC_LOAD_AND_I32:
801 return emitAtomicBinary(MI, BB, 4, Mips::AND);
802 case Mips::ATOMIC_LOAD_AND_I64:
803 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
805 case Mips::ATOMIC_LOAD_OR_I8:
806 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
807 case Mips::ATOMIC_LOAD_OR_I16:
808 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
809 case Mips::ATOMIC_LOAD_OR_I32:
810 return emitAtomicBinary(MI, BB, 4, Mips::OR);
811 case Mips::ATOMIC_LOAD_OR_I64:
812 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
814 case Mips::ATOMIC_LOAD_XOR_I8:
815 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
816 case Mips::ATOMIC_LOAD_XOR_I16:
817 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
818 case Mips::ATOMIC_LOAD_XOR_I32:
819 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
820 case Mips::ATOMIC_LOAD_XOR_I64:
821 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
823 case Mips::ATOMIC_LOAD_NAND_I8:
824 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
825 case Mips::ATOMIC_LOAD_NAND_I16:
826 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
827 case Mips::ATOMIC_LOAD_NAND_I32:
828 return emitAtomicBinary(MI, BB, 4, 0, true);
829 case Mips::ATOMIC_LOAD_NAND_I64:
830 return emitAtomicBinary(MI, BB, 8, 0, true);
832 case Mips::ATOMIC_LOAD_SUB_I8:
833 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
834 case Mips::ATOMIC_LOAD_SUB_I16:
835 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
836 case Mips::ATOMIC_LOAD_SUB_I32:
837 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
838 case Mips::ATOMIC_LOAD_SUB_I64:
839 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
841 case Mips::ATOMIC_SWAP_I8:
842 return emitAtomicBinaryPartword(MI, BB, 1, 0);
843 case Mips::ATOMIC_SWAP_I16:
844 return emitAtomicBinaryPartword(MI, BB, 2, 0);
845 case Mips::ATOMIC_SWAP_I32:
846 return emitAtomicBinary(MI, BB, 4, 0);
847 case Mips::ATOMIC_SWAP_I64:
848 return emitAtomicBinary(MI, BB, 8, 0);
850 case Mips::ATOMIC_CMP_SWAP_I8:
851 return emitAtomicCmpSwapPartword(MI, BB, 1);
852 case Mips::ATOMIC_CMP_SWAP_I16:
853 return emitAtomicCmpSwapPartword(MI, BB, 2);
854 case Mips::ATOMIC_CMP_SWAP_I32:
855 return emitAtomicCmpSwap(MI, BB, 4);
856 case Mips::ATOMIC_CMP_SWAP_I64:
857 return emitAtomicCmpSwap(MI, BB, 8);
858 case Mips::PseudoSDIV:
859 case Mips::PseudoUDIV:
860 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
861 case Mips::PseudoDSDIV:
862 case Mips::PseudoDUDIV:
863 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
867 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
868 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
870 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
871 unsigned Size, unsigned BinOpcode,
873 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
875 MachineFunction *MF = BB->getParent();
876 MachineRegisterInfo &RegInfo = MF->getRegInfo();
877 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
878 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
879 DebugLoc DL = MI->getDebugLoc();
880 unsigned LL, SC, AND, NOR, ZERO, BEQ;
895 ZERO = Mips::ZERO_64;
899 unsigned OldVal = MI->getOperand(0).getReg();
900 unsigned Ptr = MI->getOperand(1).getReg();
901 unsigned Incr = MI->getOperand(2).getReg();
903 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
904 unsigned AndRes = RegInfo.createVirtualRegister(RC);
905 unsigned Success = RegInfo.createVirtualRegister(RC);
907 // insert new blocks after the current block
908 const BasicBlock *LLVM_BB = BB->getBasicBlock();
909 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
910 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
911 MachineFunction::iterator It = BB;
913 MF->insert(It, loopMBB);
914 MF->insert(It, exitMBB);
916 // Transfer the remainder of BB and its successor edges to exitMBB.
917 exitMBB->splice(exitMBB->begin(), BB,
918 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
919 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
923 // fallthrough --> loopMBB
924 BB->addSuccessor(loopMBB);
925 loopMBB->addSuccessor(loopMBB);
926 loopMBB->addSuccessor(exitMBB);
930 // <binop> storeval, oldval, incr
931 // sc success, storeval, 0(ptr)
932 // beq success, $0, loopMBB
934 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
936 // and andres, oldval, incr
937 // nor storeval, $0, andres
938 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
939 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
940 } else if (BinOpcode) {
941 // <binop> storeval, oldval, incr
942 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
946 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
947 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
949 MI->eraseFromParent(); // The instruction is gone now.
955 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
956 MachineBasicBlock *BB,
957 unsigned Size, unsigned BinOpcode,
959 assert((Size == 1 || Size == 2) &&
960 "Unsupported size for EmitAtomicBinaryPartial.");
962 MachineFunction *MF = BB->getParent();
963 MachineRegisterInfo &RegInfo = MF->getRegInfo();
964 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
965 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
966 DebugLoc DL = MI->getDebugLoc();
968 unsigned Dest = MI->getOperand(0).getReg();
969 unsigned Ptr = MI->getOperand(1).getReg();
970 unsigned Incr = MI->getOperand(2).getReg();
972 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
973 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
974 unsigned Mask = RegInfo.createVirtualRegister(RC);
975 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
976 unsigned NewVal = RegInfo.createVirtualRegister(RC);
977 unsigned OldVal = RegInfo.createVirtualRegister(RC);
978 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
979 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
980 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
981 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
982 unsigned AndRes = RegInfo.createVirtualRegister(RC);
983 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
984 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
985 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
986 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
987 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
988 unsigned SllRes = RegInfo.createVirtualRegister(RC);
989 unsigned Success = RegInfo.createVirtualRegister(RC);
991 // insert new blocks after the current block
992 const BasicBlock *LLVM_BB = BB->getBasicBlock();
993 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
994 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
995 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
996 MachineFunction::iterator It = BB;
998 MF->insert(It, loopMBB);
999 MF->insert(It, sinkMBB);
1000 MF->insert(It, exitMBB);
1002 // Transfer the remainder of BB and its successor edges to exitMBB.
1003 exitMBB->splice(exitMBB->begin(), BB,
1004 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1005 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1007 BB->addSuccessor(loopMBB);
1008 loopMBB->addSuccessor(loopMBB);
1009 loopMBB->addSuccessor(sinkMBB);
1010 sinkMBB->addSuccessor(exitMBB);
1013 // addiu masklsb2,$0,-4 # 0xfffffffc
1014 // and alignedaddr,ptr,masklsb2
1015 // andi ptrlsb2,ptr,3
1016 // sll shiftamt,ptrlsb2,3
1017 // ori maskupper,$0,255 # 0xff
1018 // sll mask,maskupper,shiftamt
1019 // nor mask2,$0,mask
1020 // sll incr2,incr,shiftamt
1022 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1023 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1024 .addReg(Mips::ZERO).addImm(-4);
1025 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1026 .addReg(Ptr).addReg(MaskLSB2);
1027 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1028 if (Subtarget->isLittle()) {
1029 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1031 unsigned Off = RegInfo.createVirtualRegister(RC);
1032 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1033 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1034 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1036 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1037 .addReg(Mips::ZERO).addImm(MaskImm);
1038 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1039 .addReg(MaskUpper).addReg(ShiftAmt);
1040 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1041 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1043 // atomic.load.binop
1045 // ll oldval,0(alignedaddr)
1046 // binop binopres,oldval,incr2
1047 // and newval,binopres,mask
1048 // and maskedoldval0,oldval,mask2
1049 // or storeval,maskedoldval0,newval
1050 // sc success,storeval,0(alignedaddr)
1051 // beq success,$0,loopMBB
1055 // ll oldval,0(alignedaddr)
1056 // and newval,incr2,mask
1057 // and maskedoldval0,oldval,mask2
1058 // or storeval,maskedoldval0,newval
1059 // sc success,storeval,0(alignedaddr)
1060 // beq success,$0,loopMBB
1063 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1065 // and andres, oldval, incr2
1066 // nor binopres, $0, andres
1067 // and newval, binopres, mask
1068 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1069 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1070 .addReg(Mips::ZERO).addReg(AndRes);
1071 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1072 } else if (BinOpcode) {
1073 // <binop> binopres, oldval, incr2
1074 // and newval, binopres, mask
1075 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1076 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1077 } else { // atomic.swap
1078 // and newval, incr2, mask
1079 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1082 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1083 .addReg(OldVal).addReg(Mask2);
1084 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1085 .addReg(MaskedOldVal0).addReg(NewVal);
1086 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1087 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1088 BuildMI(BB, DL, TII->get(Mips::BEQ))
1089 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1092 // and maskedoldval1,oldval,mask
1093 // srl srlres,maskedoldval1,shiftamt
1094 // sll sllres,srlres,24
1095 // sra dest,sllres,24
1097 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1099 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1100 .addReg(OldVal).addReg(Mask);
1101 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1102 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1103 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1104 .addReg(SrlRes).addImm(ShiftImm);
1105 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1106 .addReg(SllRes).addImm(ShiftImm);
1108 MI->eraseFromParent(); // The instruction is gone now.
1113 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1114 MachineBasicBlock *BB,
1115 unsigned Size) const {
1116 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1118 MachineFunction *MF = BB->getParent();
1119 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1120 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1121 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1122 DebugLoc DL = MI->getDebugLoc();
1123 unsigned LL, SC, ZERO, BNE, BEQ;
1134 ZERO = Mips::ZERO_64;
1139 unsigned Dest = MI->getOperand(0).getReg();
1140 unsigned Ptr = MI->getOperand(1).getReg();
1141 unsigned OldVal = MI->getOperand(2).getReg();
1142 unsigned NewVal = MI->getOperand(3).getReg();
1144 unsigned Success = RegInfo.createVirtualRegister(RC);
1146 // insert new blocks after the current block
1147 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1148 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1149 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1150 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1151 MachineFunction::iterator It = BB;
1153 MF->insert(It, loop1MBB);
1154 MF->insert(It, loop2MBB);
1155 MF->insert(It, exitMBB);
1157 // Transfer the remainder of BB and its successor edges to exitMBB.
1158 exitMBB->splice(exitMBB->begin(), BB,
1159 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1160 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1164 // fallthrough --> loop1MBB
1165 BB->addSuccessor(loop1MBB);
1166 loop1MBB->addSuccessor(exitMBB);
1167 loop1MBB->addSuccessor(loop2MBB);
1168 loop2MBB->addSuccessor(loop1MBB);
1169 loop2MBB->addSuccessor(exitMBB);
1173 // bne dest, oldval, exitMBB
1175 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1176 BuildMI(BB, DL, TII->get(BNE))
1177 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1180 // sc success, newval, 0(ptr)
1181 // beq success, $0, loop1MBB
1183 BuildMI(BB, DL, TII->get(SC), Success)
1184 .addReg(NewVal).addReg(Ptr).addImm(0);
1185 BuildMI(BB, DL, TII->get(BEQ))
1186 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1188 MI->eraseFromParent(); // The instruction is gone now.
1194 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1195 MachineBasicBlock *BB,
1196 unsigned Size) const {
1197 assert((Size == 1 || Size == 2) &&
1198 "Unsupported size for EmitAtomicCmpSwapPartial.");
1200 MachineFunction *MF = BB->getParent();
1201 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1202 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1203 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1204 DebugLoc DL = MI->getDebugLoc();
1206 unsigned Dest = MI->getOperand(0).getReg();
1207 unsigned Ptr = MI->getOperand(1).getReg();
1208 unsigned CmpVal = MI->getOperand(2).getReg();
1209 unsigned NewVal = MI->getOperand(3).getReg();
1211 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1212 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1213 unsigned Mask = RegInfo.createVirtualRegister(RC);
1214 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1215 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1216 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1217 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1218 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1219 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1220 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1221 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1222 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1223 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1224 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1225 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1226 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1227 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1228 unsigned Success = RegInfo.createVirtualRegister(RC);
1230 // insert new blocks after the current block
1231 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1232 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1233 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1234 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1235 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1236 MachineFunction::iterator It = BB;
1238 MF->insert(It, loop1MBB);
1239 MF->insert(It, loop2MBB);
1240 MF->insert(It, sinkMBB);
1241 MF->insert(It, exitMBB);
1243 // Transfer the remainder of BB and its successor edges to exitMBB.
1244 exitMBB->splice(exitMBB->begin(), BB,
1245 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1246 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1248 BB->addSuccessor(loop1MBB);
1249 loop1MBB->addSuccessor(sinkMBB);
1250 loop1MBB->addSuccessor(loop2MBB);
1251 loop2MBB->addSuccessor(loop1MBB);
1252 loop2MBB->addSuccessor(sinkMBB);
1253 sinkMBB->addSuccessor(exitMBB);
1255 // FIXME: computation of newval2 can be moved to loop2MBB.
1257 // addiu masklsb2,$0,-4 # 0xfffffffc
1258 // and alignedaddr,ptr,masklsb2
1259 // andi ptrlsb2,ptr,3
1260 // sll shiftamt,ptrlsb2,3
1261 // ori maskupper,$0,255 # 0xff
1262 // sll mask,maskupper,shiftamt
1263 // nor mask2,$0,mask
1264 // andi maskedcmpval,cmpval,255
1265 // sll shiftedcmpval,maskedcmpval,shiftamt
1266 // andi maskednewval,newval,255
1267 // sll shiftednewval,maskednewval,shiftamt
1268 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1269 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1270 .addReg(Mips::ZERO).addImm(-4);
1271 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1272 .addReg(Ptr).addReg(MaskLSB2);
1273 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1274 if (Subtarget->isLittle()) {
1275 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1277 unsigned Off = RegInfo.createVirtualRegister(RC);
1278 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1279 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1280 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1282 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1283 .addReg(Mips::ZERO).addImm(MaskImm);
1284 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1285 .addReg(MaskUpper).addReg(ShiftAmt);
1286 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1287 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1288 .addReg(CmpVal).addImm(MaskImm);
1289 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1290 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1291 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1292 .addReg(NewVal).addImm(MaskImm);
1293 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1294 .addReg(MaskedNewVal).addReg(ShiftAmt);
1297 // ll oldval,0(alginedaddr)
1298 // and maskedoldval0,oldval,mask
1299 // bne maskedoldval0,shiftedcmpval,sinkMBB
1301 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1302 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1303 .addReg(OldVal).addReg(Mask);
1304 BuildMI(BB, DL, TII->get(Mips::BNE))
1305 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1308 // and maskedoldval1,oldval,mask2
1309 // or storeval,maskedoldval1,shiftednewval
1310 // sc success,storeval,0(alignedaddr)
1311 // beq success,$0,loop1MBB
1313 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1314 .addReg(OldVal).addReg(Mask2);
1315 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1316 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1317 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1318 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1319 BuildMI(BB, DL, TII->get(Mips::BEQ))
1320 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1323 // srl srlres,maskedoldval0,shiftamt
1324 // sll sllres,srlres,24
1325 // sra dest,sllres,24
1327 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1329 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1330 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1331 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1332 .addReg(SrlRes).addImm(ShiftImm);
1333 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1334 .addReg(SllRes).addImm(ShiftImm);
1336 MI->eraseFromParent(); // The instruction is gone now.
1341 //===----------------------------------------------------------------------===//
1342 // Misc Lower Operation implementation
1343 //===----------------------------------------------------------------------===//
1344 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1345 SDValue Chain = Op.getOperand(0);
1346 SDValue Table = Op.getOperand(1);
1347 SDValue Index = Op.getOperand(2);
1349 EVT PTy = getPointerTy();
1350 unsigned EntrySize =
1351 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1353 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1354 DAG.getConstant(EntrySize, PTy));
1355 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1357 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1358 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1359 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1361 Chain = Addr.getValue(1);
1363 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1364 // For PIC, the sequence is:
1365 // BRIND(load(Jumptable + index) + RelocBase)
1366 // RelocBase can be JumpTable, GOT or some sort of global base.
1367 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1368 getPICJumpTableRelocBase(Table, DAG));
1371 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1374 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1375 // The first operand is the chain, the second is the condition, the third is
1376 // the block to branch to if the condition is true.
1377 SDValue Chain = Op.getOperand(0);
1378 SDValue Dest = Op.getOperand(2);
1381 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1383 // Return if flag is not set by a floating point comparison.
1384 if (CondRes.getOpcode() != MipsISD::FPCmp)
1387 SDValue CCNode = CondRes.getOperand(2);
1389 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1390 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1391 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1392 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1393 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1394 FCC0, Dest, CondRes);
1397 SDValue MipsTargetLowering::
1398 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1400 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1402 // Return if flag is not set by a floating point comparison.
1403 if (Cond.getOpcode() != MipsISD::FPCmp)
1406 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1410 SDValue MipsTargetLowering::
1411 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1414 EVT Ty = Op.getOperand(0).getValueType();
1415 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1416 getSetCCResultType(*DAG.getContext(), Ty),
1417 Op.getOperand(0), Op.getOperand(1),
1420 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1424 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1425 SDValue Cond = createFPCmp(DAG, Op);
1427 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1428 "Floating point operand expected.");
1430 SDValue True = DAG.getConstant(1, MVT::i32);
1431 SDValue False = DAG.getConstant(0, MVT::i32);
1433 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1436 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1437 SelectionDAG &DAG) const {
1438 // FIXME there isn't actually debug info here
1440 EVT Ty = Op.getValueType();
1441 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1442 const GlobalValue *GV = N->getGlobal();
1444 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1445 const MipsTargetObjectFile &TLOF =
1446 (const MipsTargetObjectFile&)getObjFileLowering();
1448 // %gp_rel relocation
1449 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1450 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1452 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1453 DAG.getVTList(MVT::i32), &GA, 1);
1454 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1455 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1458 // %hi/%lo relocation
1459 return getAddrNonPIC(N, Ty, DAG);
1462 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1463 return getAddrLocal(N, Ty, DAG, HasMips64);
1466 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1467 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1468 MachinePointerInfo::getGOT());
1470 return getAddrGlobal(N, Ty, DAG,
1471 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16,
1472 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1475 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1476 SelectionDAG &DAG) const {
1477 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1478 EVT Ty = Op.getValueType();
1480 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1481 return getAddrNonPIC(N, Ty, DAG);
1483 return getAddrLocal(N, Ty, DAG, HasMips64);
1486 SDValue MipsTargetLowering::
1487 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1489 // If the relocation model is PIC, use the General Dynamic TLS Model or
1490 // Local Dynamic TLS model, otherwise use the Initial Exec or
1491 // Local Exec TLS Model.
1493 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1495 const GlobalValue *GV = GA->getGlobal();
1496 EVT PtrVT = getPointerTy();
1498 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1500 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1501 // General Dynamic and Local Dynamic TLS Model.
1502 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1505 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1506 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1507 getGlobalReg(DAG, PtrVT), TGA);
1508 unsigned PtrSize = PtrVT.getSizeInBits();
1509 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1511 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1515 Entry.Node = Argument;
1517 Args.push_back(Entry);
1519 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1520 false, false, false, false, 0, CallingConv::C,
1521 /*IsTailCall=*/false, /*doesNotRet=*/false,
1522 /*isReturnValueUsed=*/true,
1523 TlsGetAddr, Args, DAG, DL);
1524 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1526 SDValue Ret = CallResult.first;
1528 if (model != TLSModel::LocalDynamic)
1531 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1532 MipsII::MO_DTPREL_HI);
1533 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1534 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1535 MipsII::MO_DTPREL_LO);
1536 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1537 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1538 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1542 if (model == TLSModel::InitialExec) {
1543 // Initial Exec TLS Model
1544 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1545 MipsII::MO_GOTTPREL);
1546 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1548 Offset = DAG.getLoad(PtrVT, DL,
1549 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1550 false, false, false, 0);
1552 // Local Exec TLS Model
1553 assert(model == TLSModel::LocalExec);
1554 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1555 MipsII::MO_TPREL_HI);
1556 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1557 MipsII::MO_TPREL_LO);
1558 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1559 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1560 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1563 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1564 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1567 SDValue MipsTargetLowering::
1568 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1570 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1571 EVT Ty = Op.getValueType();
1573 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1574 return getAddrNonPIC(N, Ty, DAG);
1576 return getAddrLocal(N, Ty, DAG, HasMips64);
1579 SDValue MipsTargetLowering::
1580 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1582 // gp_rel relocation
1583 // FIXME: we should reference the constant pool using small data sections,
1584 // but the asm printer currently doesn't support this feature without
1585 // hacking it. This feature should come soon so we can uncomment the
1587 //if (IsInSmallSection(C->getType())) {
1588 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1589 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1590 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1591 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1592 EVT Ty = Op.getValueType();
1594 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1595 return getAddrNonPIC(N, Ty, DAG);
1597 return getAddrLocal(N, Ty, DAG, HasMips64);
1600 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1601 MachineFunction &MF = DAG.getMachineFunction();
1602 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1605 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1608 // vastart just stores the address of the VarArgsFrameIndex slot into the
1609 // memory location argument.
1610 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1611 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1612 MachinePointerInfo(SV), false, false, 0);
1615 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1616 EVT TyX = Op.getOperand(0).getValueType();
1617 EVT TyY = Op.getOperand(1).getValueType();
1618 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1619 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1623 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1625 SDValue X = (TyX == MVT::f32) ?
1626 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1627 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1629 SDValue Y = (TyY == MVT::f32) ?
1630 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1631 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1635 // ext E, Y, 31, 1 ; extract bit31 of Y
1636 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1637 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1638 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1641 // srl SrlX, SllX, 1
1643 // sll SllY, SrlX, 31
1644 // or Or, SrlX, SllY
1645 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1646 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1647 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1648 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1649 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1652 if (TyX == MVT::f32)
1653 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1655 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1656 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1657 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1660 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1661 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1662 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1663 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1664 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1667 // Bitcast to integer nodes.
1668 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1669 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1672 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1673 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1674 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1675 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1677 if (WidthX > WidthY)
1678 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1679 else if (WidthY > WidthX)
1680 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1682 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1683 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1684 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1687 // (d)sll SllX, X, 1
1688 // (d)srl SrlX, SllX, 1
1689 // (d)srl SrlY, Y, width(Y)-1
1690 // (d)sll SllY, SrlX, width(Y)-1
1691 // or Or, SrlX, SllY
1692 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1693 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1694 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1695 DAG.getConstant(WidthY - 1, MVT::i32));
1697 if (WidthX > WidthY)
1698 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1699 else if (WidthY > WidthX)
1700 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1702 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1703 DAG.getConstant(WidthX - 1, MVT::i32));
1704 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1705 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1709 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1710 if (Subtarget->hasMips64())
1711 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1713 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1716 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1717 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1720 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1722 SDValue X = (Op.getValueType() == MVT::f32) ?
1723 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1724 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1729 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1730 DAG.getRegister(Mips::ZERO, MVT::i32),
1731 DAG.getConstant(31, MVT::i32), Const1, X);
1733 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1734 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1737 if (Op.getValueType() == MVT::f32)
1738 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1740 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1741 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1742 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1745 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1746 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1749 // Bitcast to integer node.
1750 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1754 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1755 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1756 DAG.getConstant(63, MVT::i32), Const1, X);
1758 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1759 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1762 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1766 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1767 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1768 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1770 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1773 SDValue MipsTargetLowering::
1774 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1776 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1777 "Frame address can only be determined for current frame.");
1779 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1780 MFI->setFrameAddressIsTaken(true);
1781 EVT VT = Op.getValueType();
1783 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1784 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1788 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1789 SelectionDAG &DAG) const {
1791 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1792 "Return address can be determined only for current frame.");
1794 MachineFunction &MF = DAG.getMachineFunction();
1795 MachineFrameInfo *MFI = MF.getFrameInfo();
1796 MVT VT = Op.getSimpleValueType();
1797 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1798 MFI->setReturnAddressIsTaken(true);
1800 // Return RA, which contains the return address. Mark it an implicit live-in.
1801 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1802 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1805 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1806 // generated from __builtin_eh_return (offset, handler)
1807 // The effect of this is to adjust the stack pointer by "offset"
1808 // and then branch to "handler".
1809 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1811 MachineFunction &MF = DAG.getMachineFunction();
1812 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1814 MipsFI->setCallsEhReturn();
1815 SDValue Chain = Op.getOperand(0);
1816 SDValue Offset = Op.getOperand(1);
1817 SDValue Handler = Op.getOperand(2);
1819 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1821 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1822 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1823 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1824 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1825 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1826 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1827 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1828 DAG.getRegister(OffsetReg, Ty),
1829 DAG.getRegister(AddrReg, getPointerTy()),
1833 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1834 SelectionDAG &DAG) const {
1835 // FIXME: Need pseudo-fence for 'singlethread' fences
1836 // FIXME: Set SType for weaker fences where supported/appropriate.
1839 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1840 DAG.getConstant(SType, MVT::i32));
1843 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1844 SelectionDAG &DAG) const {
1846 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1847 SDValue Shamt = Op.getOperand(2);
1850 // lo = (shl lo, shamt)
1851 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1854 // hi = (shl lo, shamt[4:0])
1855 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1856 DAG.getConstant(-1, MVT::i32));
1857 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1858 DAG.getConstant(1, MVT::i32));
1859 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1861 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1862 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1863 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1864 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1865 DAG.getConstant(0x20, MVT::i32));
1866 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1867 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1868 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1870 SDValue Ops[2] = {Lo, Hi};
1871 return DAG.getMergeValues(Ops, 2, DL);
1874 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1877 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1878 SDValue Shamt = Op.getOperand(2);
1881 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1883 // hi = (sra hi, shamt)
1885 // hi = (srl hi, shamt)
1888 // lo = (sra hi, shamt[4:0])
1889 // hi = (sra hi, 31)
1891 // lo = (srl hi, shamt[4:0])
1893 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1894 DAG.getConstant(-1, MVT::i32));
1895 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1896 DAG.getConstant(1, MVT::i32));
1897 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1898 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1899 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1900 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1902 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1903 DAG.getConstant(0x20, MVT::i32));
1904 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1905 DAG.getConstant(31, MVT::i32));
1906 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1907 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1908 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1911 SDValue Ops[2] = {Lo, Hi};
1912 return DAG.getMergeValues(Ops, 2, DL);
1915 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1916 SDValue Chain, SDValue Src, unsigned Offset) {
1917 SDValue Ptr = LD->getBasePtr();
1918 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1919 EVT BasePtrVT = Ptr.getValueType();
1921 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1924 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1925 DAG.getConstant(Offset, BasePtrVT));
1927 SDValue Ops[] = { Chain, Ptr, Src };
1928 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1929 LD->getMemOperand());
1932 // Expand an unaligned 32 or 64-bit integer load node.
1933 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1934 LoadSDNode *LD = cast<LoadSDNode>(Op);
1935 EVT MemVT = LD->getMemoryVT();
1937 // Return if load is aligned or if MemVT is neither i32 nor i64.
1938 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1939 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1942 bool IsLittle = Subtarget->isLittle();
1943 EVT VT = Op.getValueType();
1944 ISD::LoadExtType ExtType = LD->getExtensionType();
1945 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1947 assert((VT == MVT::i32) || (VT == MVT::i64));
1950 // (set dst, (i64 (load baseptr)))
1952 // (set tmp, (ldl (add baseptr, 7), undef))
1953 // (set dst, (ldr baseptr, tmp))
1954 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1955 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1957 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1961 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1963 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1967 // (set dst, (i32 (load baseptr))) or
1968 // (set dst, (i64 (sextload baseptr))) or
1969 // (set dst, (i64 (extload baseptr)))
1971 // (set tmp, (lwl (add baseptr, 3), undef))
1972 // (set dst, (lwr baseptr, tmp))
1973 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1974 (ExtType == ISD::EXTLOAD))
1977 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1980 // (set dst, (i64 (zextload baseptr)))
1982 // (set tmp0, (lwl (add baseptr, 3), undef))
1983 // (set tmp1, (lwr baseptr, tmp0))
1984 // (set tmp2, (shl tmp1, 32))
1985 // (set dst, (srl tmp2, 32))
1987 SDValue Const32 = DAG.getConstant(32, MVT::i32);
1988 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1989 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
1990 SDValue Ops[] = { SRL, LWR.getValue(1) };
1991 return DAG.getMergeValues(Ops, 2, DL);
1994 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
1995 SDValue Chain, unsigned Offset) {
1996 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
1997 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
1999 SDVTList VTList = DAG.getVTList(MVT::Other);
2002 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2003 DAG.getConstant(Offset, BasePtrVT));
2005 SDValue Ops[] = { Chain, Value, Ptr };
2006 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2007 SD->getMemOperand());
2010 // Expand an unaligned 32 or 64-bit integer store node.
2011 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2013 SDValue Value = SD->getValue(), Chain = SD->getChain();
2014 EVT VT = Value.getValueType();
2017 // (store val, baseptr) or
2018 // (truncstore val, baseptr)
2020 // (swl val, (add baseptr, 3))
2021 // (swr val, baseptr)
2022 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2023 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2025 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2028 assert(VT == MVT::i64);
2031 // (store val, baseptr)
2033 // (sdl val, (add baseptr, 7))
2034 // (sdr val, baseptr)
2035 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2036 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2039 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2040 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2041 SDValue Val = SD->getValue();
2043 if (Val.getOpcode() != ISD::FP_TO_SINT)
2046 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2047 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2050 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2051 SD->getPointerInfo(), SD->isVolatile(),
2052 SD->isNonTemporal(), SD->getAlignment());
2055 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2056 StoreSDNode *SD = cast<StoreSDNode>(Op);
2057 EVT MemVT = SD->getMemoryVT();
2059 // Lower unaligned integer stores.
2060 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2061 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2062 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2064 return lowerFP_TO_SINT_STORE(SD, DAG);
2067 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2068 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2069 || cast<ConstantSDNode>
2070 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2071 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2075 // (add (frameaddr 0), (frame_to_args_offset))
2076 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2077 // (add FrameObject, 0)
2078 // where FrameObject is a fixed StackObject with offset 0 which points to
2079 // the old stack pointer.
2080 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2081 EVT ValTy = Op->getValueType(0);
2082 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2083 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2084 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2085 DAG.getConstant(0, ValTy));
2088 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2089 SelectionDAG &DAG) const {
2090 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2091 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2093 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2096 //===----------------------------------------------------------------------===//
2097 // Calling Convention Implementation
2098 //===----------------------------------------------------------------------===//
2100 //===----------------------------------------------------------------------===//
2101 // TODO: Implement a generic logic using tblgen that can support this.
2102 // Mips O32 ABI rules:
2104 // i32 - Passed in A0, A1, A2, A3 and stack
2105 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2106 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2107 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2108 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2109 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2112 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2113 //===----------------------------------------------------------------------===//
2115 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2116 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2117 CCState &State, const uint16_t *F64Regs) {
2119 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2121 static const uint16_t IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2122 static const uint16_t F32Regs[] = { Mips::F12, Mips::F14 };
2124 // Do not process byval args here.
2125 if (ArgFlags.isByVal())
2128 // Promote i8 and i16
2129 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2131 if (ArgFlags.isSExt())
2132 LocInfo = CCValAssign::SExt;
2133 else if (ArgFlags.isZExt())
2134 LocInfo = CCValAssign::ZExt;
2136 LocInfo = CCValAssign::AExt;
2141 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2142 // is true: function is vararg, argument is 3rd or higher, there is previous
2143 // argument which is not f32 or f64.
2144 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2145 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2146 unsigned OrigAlign = ArgFlags.getOrigAlign();
2147 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2149 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2150 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2151 // If this is the first part of an i64 arg,
2152 // the allocated register must be either A0 or A2.
2153 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2154 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2156 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2157 // Allocate int register and shadow next int register. If first
2158 // available register is Mips::A1 or Mips::A3, shadow it too.
2159 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2160 if (Reg == Mips::A1 || Reg == Mips::A3)
2161 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2162 State.AllocateReg(IntRegs, IntRegsSize);
2164 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2165 // we are guaranteed to find an available float register
2166 if (ValVT == MVT::f32) {
2167 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2168 // Shadow int register
2169 State.AllocateReg(IntRegs, IntRegsSize);
2171 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2172 // Shadow int registers
2173 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2174 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2175 State.AllocateReg(IntRegs, IntRegsSize);
2176 State.AllocateReg(IntRegs, IntRegsSize);
2179 llvm_unreachable("Cannot handle this ValVT.");
2182 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2184 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2186 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2191 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2192 MVT LocVT, CCValAssign::LocInfo LocInfo,
2193 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2194 static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2196 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2199 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2200 MVT LocVT, CCValAssign::LocInfo LocInfo,
2201 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2202 static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D12_64 };
2204 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2207 #include "MipsGenCallingConv.inc"
2209 //===----------------------------------------------------------------------===//
2210 // Call Calling Convention Implementation
2211 //===----------------------------------------------------------------------===//
2213 // Return next O32 integer argument register.
2214 static unsigned getNextIntArgReg(unsigned Reg) {
2215 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2216 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2220 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2221 SDValue Chain, SDValue Arg, SDLoc DL,
2222 bool IsTailCall, SelectionDAG &DAG) const {
2224 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2225 DAG.getIntPtrConstant(Offset));
2226 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2230 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2231 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2232 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2233 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2234 /*isVolatile=*/ true, false, 0);
2237 void MipsTargetLowering::
2238 getOpndList(SmallVectorImpl<SDValue> &Ops,
2239 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2240 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2241 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2242 // Insert node "GP copy globalreg" before call to function.
2244 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2245 // in PIC mode) allow symbols to be resolved via lazy binding.
2246 // The lazy binding stub requires GP to point to the GOT.
2247 if (IsPICCall && !InternalLinkage) {
2248 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2249 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2250 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2253 // Build a sequence of copy-to-reg nodes chained together with token
2254 // chain and flag operands which copy the outgoing args into registers.
2255 // The InFlag in necessary since all emitted instructions must be
2259 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2260 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2261 RegsToPass[i].second, InFlag);
2262 InFlag = Chain.getValue(1);
2265 // Add argument registers to the end of the list so that they are
2266 // known live into the call.
2267 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2268 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2269 RegsToPass[i].second.getValueType()));
2271 // Add a register mask operand representing the call-preserved registers.
2272 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2273 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2274 assert(Mask && "Missing call preserved mask for calling convention");
2275 if (Subtarget->inMips16HardFloat()) {
2276 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2277 llvm::StringRef Sym = G->getGlobal()->getName();
2278 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2279 if (F->hasFnAttribute("__Mips16RetHelper")) {
2280 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2284 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2286 if (InFlag.getNode())
2287 Ops.push_back(InFlag);
2290 /// LowerCall - functions arguments are copied from virtual regs to
2291 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2293 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2294 SmallVectorImpl<SDValue> &InVals) const {
2295 SelectionDAG &DAG = CLI.DAG;
2297 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2298 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2299 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2300 SDValue Chain = CLI.Chain;
2301 SDValue Callee = CLI.Callee;
2302 bool &IsTailCall = CLI.IsTailCall;
2303 CallingConv::ID CallConv = CLI.CallConv;
2304 bool IsVarArg = CLI.IsVarArg;
2306 MachineFunction &MF = DAG.getMachineFunction();
2307 MachineFrameInfo *MFI = MF.getFrameInfo();
2308 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2309 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2310 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2312 // Analyze operands of the call, assigning locations to each operand.
2313 SmallVector<CCValAssign, 16> ArgLocs;
2314 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2315 getTargetMachine(), ArgLocs, *DAG.getContext());
2316 MipsCC::SpecialCallingConvType SpecialCallingConv =
2317 getSpecialCallingConv(Callee);
2318 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2319 SpecialCallingConv);
2321 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2322 Subtarget->mipsSEUsesSoftFloat(),
2323 Callee.getNode(), CLI.Args);
2325 // Get a count of how many bytes are to be pushed on the stack.
2326 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2328 // Check if it's really possible to do a tail call.
2331 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2332 *MF.getInfo<MipsFunctionInfo>());
2337 // Chain is the output chain of the last Load/Store or CopyToReg node.
2338 // ByValChain is the output chain of the last Memcpy node created for copying
2339 // byval arguments to the stack.
2340 unsigned StackAlignment = TFL->getStackAlignment();
2341 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2342 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2345 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2347 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2348 IsN64 ? Mips::SP_64 : Mips::SP,
2351 // With EABI is it possible to have 16 args on registers.
2352 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2353 SmallVector<SDValue, 8> MemOpChains;
2354 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2356 // Walk the register/memloc assignments, inserting copies/loads.
2357 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2358 SDValue Arg = OutVals[i];
2359 CCValAssign &VA = ArgLocs[i];
2360 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2361 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2364 if (Flags.isByVal()) {
2365 assert(Flags.getByValSize() &&
2366 "ByVal args of size 0 should have been ignored by front-end.");
2367 assert(ByValArg != MipsCCInfo.byval_end());
2368 assert(!IsTailCall &&
2369 "Do not tail-call optimize if there is a byval argument.");
2370 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2371 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2376 // Promote the value if needed.
2377 switch (VA.getLocInfo()) {
2378 default: llvm_unreachable("Unknown loc info!");
2379 case CCValAssign::Full:
2380 if (VA.isRegLoc()) {
2381 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2382 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2383 (ValVT == MVT::i64 && LocVT == MVT::f64))
2384 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2385 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2386 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2387 Arg, DAG.getConstant(0, MVT::i32));
2388 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2389 Arg, DAG.getConstant(1, MVT::i32));
2390 if (!Subtarget->isLittle())
2392 unsigned LocRegLo = VA.getLocReg();
2393 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2394 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2395 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2400 case CCValAssign::SExt:
2401 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2403 case CCValAssign::ZExt:
2404 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2406 case CCValAssign::AExt:
2407 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2411 // Arguments that can be passed on register must be kept at
2412 // RegsToPass vector
2413 if (VA.isRegLoc()) {
2414 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2418 // Register can't get to this point...
2419 assert(VA.isMemLoc());
2421 // emit ISD::STORE whichs stores the
2422 // parameter value to a stack Location
2423 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2424 Chain, Arg, DL, IsTailCall, DAG));
2427 // Transform all store nodes into one single node because all store
2428 // nodes are independent of each other.
2429 if (!MemOpChains.empty())
2430 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2431 &MemOpChains[0], MemOpChains.size());
2433 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2434 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2435 // node so that legalize doesn't hack it.
2436 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2437 bool GlobalOrExternal = false, InternalLinkage = false;
2439 EVT Ty = Callee.getValueType();
2441 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2443 const GlobalValue *Val = G->getGlobal();
2444 InternalLinkage = Val->hasInternalLinkage();
2446 if (InternalLinkage)
2447 Callee = getAddrLocal(G, Ty, DAG, HasMips64);
2449 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2450 MipsII::MO_CALL_LO16, Chain,
2451 FuncInfo->callPtrInfo(Val));
2453 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2454 FuncInfo->callPtrInfo(Val));
2456 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2457 MipsII::MO_NO_FLAG);
2458 GlobalOrExternal = true;
2460 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2461 const char *Sym = S->getSymbol();
2463 if (!IsN64 && !IsPIC) // !N64 && static
2464 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2465 MipsII::MO_NO_FLAG);
2467 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2468 MipsII::MO_CALL_LO16, Chain,
2469 FuncInfo->callPtrInfo(Sym));
2471 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2472 FuncInfo->callPtrInfo(Sym));
2474 GlobalOrExternal = true;
2477 SmallVector<SDValue, 8> Ops(1, Chain);
2478 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2480 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2481 CLI, Callee, Chain);
2484 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2486 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2487 SDValue InFlag = Chain.getValue(1);
2489 // Create the CALLSEQ_END node.
2490 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2491 DAG.getIntPtrConstant(0, true), InFlag, DL);
2492 InFlag = Chain.getValue(1);
2494 // Handle result values, copying them out of physregs into vregs that we
2496 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2497 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2500 /// LowerCallResult - Lower the result values of a call into the
2501 /// appropriate copies out of appropriate physical registers.
2503 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2504 CallingConv::ID CallConv, bool IsVarArg,
2505 const SmallVectorImpl<ISD::InputArg> &Ins,
2506 SDLoc DL, SelectionDAG &DAG,
2507 SmallVectorImpl<SDValue> &InVals,
2508 const SDNode *CallNode,
2509 const Type *RetTy) const {
2510 // Assign locations to each value returned by this call.
2511 SmallVector<CCValAssign, 16> RVLocs;
2512 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2513 getTargetMachine(), RVLocs, *DAG.getContext());
2514 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2516 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2519 // Copy all of the result registers out of their specified physreg.
2520 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2521 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2522 RVLocs[i].getLocVT(), InFlag);
2523 Chain = Val.getValue(1);
2524 InFlag = Val.getValue(2);
2526 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2527 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2529 InVals.push_back(Val);
2535 //===----------------------------------------------------------------------===//
2536 // Formal Arguments Calling Convention Implementation
2537 //===----------------------------------------------------------------------===//
2538 /// LowerFormalArguments - transform physical registers into virtual registers
2539 /// and generate load operations for arguments places on the stack.
2541 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2542 CallingConv::ID CallConv,
2544 const SmallVectorImpl<ISD::InputArg> &Ins,
2545 SDLoc DL, SelectionDAG &DAG,
2546 SmallVectorImpl<SDValue> &InVals)
2548 MachineFunction &MF = DAG.getMachineFunction();
2549 MachineFrameInfo *MFI = MF.getFrameInfo();
2550 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2552 MipsFI->setVarArgsFrameIndex(0);
2554 // Used with vargs to acumulate store chains.
2555 std::vector<SDValue> OutChains;
2557 // Assign locations to all of the incoming arguments.
2558 SmallVector<CCValAssign, 16> ArgLocs;
2559 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2560 getTargetMachine(), ArgLocs, *DAG.getContext());
2561 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2562 Function::const_arg_iterator FuncArg =
2563 DAG.getMachineFunction().getFunction()->arg_begin();
2564 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2566 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2567 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2568 MipsCCInfo.hasByValArg());
2570 unsigned CurArgIdx = 0;
2571 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2573 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2574 CCValAssign &VA = ArgLocs[i];
2575 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2576 CurArgIdx = Ins[i].OrigArgIndex;
2577 EVT ValVT = VA.getValVT();
2578 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2579 bool IsRegLoc = VA.isRegLoc();
2581 if (Flags.isByVal()) {
2582 assert(Flags.getByValSize() &&
2583 "ByVal args of size 0 should have been ignored by front-end.");
2584 assert(ByValArg != MipsCCInfo.byval_end());
2585 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2586 MipsCCInfo, *ByValArg);
2591 // Arguments stored on registers
2593 EVT RegVT = VA.getLocVT();
2594 unsigned ArgReg = VA.getLocReg();
2595 const TargetRegisterClass *RC;
2597 if (RegVT == MVT::i32)
2598 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2599 &Mips::GPR32RegClass;
2600 else if (RegVT == MVT::i64)
2601 RC = &Mips::GPR64RegClass;
2602 else if (RegVT == MVT::f32)
2603 RC = &Mips::FGR32RegClass;
2604 else if (RegVT == MVT::f64)
2605 RC = Subtarget->isFP64bit() ? &Mips::FGR64RegClass :
2606 &Mips::AFGR64RegClass;
2608 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2610 // Transform the arguments stored on
2611 // physical registers into virtual ones
2612 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2613 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2615 // If this is an 8 or 16-bit value, it has been passed promoted
2616 // to 32 bits. Insert an assert[sz]ext to capture this, then
2617 // truncate to the right size.
2618 if (VA.getLocInfo() != CCValAssign::Full) {
2619 unsigned Opcode = 0;
2620 if (VA.getLocInfo() == CCValAssign::SExt)
2621 Opcode = ISD::AssertSext;
2622 else if (VA.getLocInfo() == CCValAssign::ZExt)
2623 Opcode = ISD::AssertZext;
2625 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2626 DAG.getValueType(ValVT));
2627 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2630 // Handle floating point arguments passed in integer registers and
2631 // long double arguments passed in floating point registers.
2632 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2633 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2634 (RegVT == MVT::f64 && ValVT == MVT::i64))
2635 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2636 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2637 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2638 getNextIntArgReg(ArgReg), RC);
2639 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2640 if (!Subtarget->isLittle())
2641 std::swap(ArgValue, ArgValue2);
2642 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2643 ArgValue, ArgValue2);
2646 InVals.push_back(ArgValue);
2647 } else { // VA.isRegLoc()
2650 assert(VA.isMemLoc());
2652 // The stack pointer offset is relative to the caller stack frame.
2653 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2654 VA.getLocMemOffset(), true);
2656 // Create load nodes to retrieve arguments from the stack
2657 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2658 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2659 MachinePointerInfo::getFixedStack(FI),
2660 false, false, false, 0));
2664 // The mips ABIs for returning structs by value requires that we copy
2665 // the sret argument into $v0 for the return. Save the argument into
2666 // a virtual register so that we can access it from the return points.
2667 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2668 unsigned Reg = MipsFI->getSRetReturnReg();
2670 Reg = MF.getRegInfo().
2671 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2672 MipsFI->setSRetReturnReg(Reg);
2674 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2675 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2679 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2681 // All stores are grouped in one node to allow the matching between
2682 // the size of Ins and InVals. This only happens when on varg functions
2683 if (!OutChains.empty()) {
2684 OutChains.push_back(Chain);
2685 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2686 &OutChains[0], OutChains.size());
2692 //===----------------------------------------------------------------------===//
2693 // Return Value Calling Convention Implementation
2694 //===----------------------------------------------------------------------===//
2697 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2698 MachineFunction &MF, bool IsVarArg,
2699 const SmallVectorImpl<ISD::OutputArg> &Outs,
2700 LLVMContext &Context) const {
2701 SmallVector<CCValAssign, 16> RVLocs;
2702 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2704 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2708 MipsTargetLowering::LowerReturn(SDValue Chain,
2709 CallingConv::ID CallConv, bool IsVarArg,
2710 const SmallVectorImpl<ISD::OutputArg> &Outs,
2711 const SmallVectorImpl<SDValue> &OutVals,
2712 SDLoc DL, SelectionDAG &DAG) const {
2713 // CCValAssign - represent the assignment of
2714 // the return value to a location
2715 SmallVector<CCValAssign, 16> RVLocs;
2716 MachineFunction &MF = DAG.getMachineFunction();
2718 // CCState - Info about the registers and stack slot.
2719 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2721 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2723 // Analyze return values.
2724 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2725 MF.getFunction()->getReturnType());
2728 SmallVector<SDValue, 4> RetOps(1, Chain);
2730 // Copy the result values into the output registers.
2731 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2732 SDValue Val = OutVals[i];
2733 CCValAssign &VA = RVLocs[i];
2734 assert(VA.isRegLoc() && "Can only return in registers!");
2736 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2737 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2739 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2741 // Guarantee that all emitted copies are stuck together with flags.
2742 Flag = Chain.getValue(1);
2743 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2746 // The mips ABIs for returning structs by value requires that we copy
2747 // the sret argument into $v0 for the return. We saved the argument into
2748 // a virtual register in the entry block, so now we copy the value out
2750 if (MF.getFunction()->hasStructRetAttr()) {
2751 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2752 unsigned Reg = MipsFI->getSRetReturnReg();
2755 llvm_unreachable("sret virtual register not created in the entry block");
2756 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2757 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2759 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2760 Flag = Chain.getValue(1);
2761 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2764 RetOps[0] = Chain; // Update chain.
2766 // Add the flag if we have it.
2768 RetOps.push_back(Flag);
2770 // Return on Mips is always a "jr $ra"
2771 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2774 //===----------------------------------------------------------------------===//
2775 // Mips Inline Assembly Support
2776 //===----------------------------------------------------------------------===//
2778 /// getConstraintType - Given a constraint letter, return the type of
2779 /// constraint it is for this target.
2780 MipsTargetLowering::ConstraintType MipsTargetLowering::
2781 getConstraintType(const std::string &Constraint) const
2783 // Mips specific constrainy
2784 // GCC config/mips/constraints.md
2786 // 'd' : An address register. Equivalent to r
2787 // unless generating MIPS16 code.
2788 // 'y' : Equivalent to r; retained for
2789 // backwards compatibility.
2790 // 'c' : A register suitable for use in an indirect
2791 // jump. This will always be $25 for -mabicalls.
2792 // 'l' : The lo register. 1 word storage.
2793 // 'x' : The hilo register pair. Double word storage.
2794 if (Constraint.size() == 1) {
2795 switch (Constraint[0]) {
2803 return C_RegisterClass;
2808 return TargetLowering::getConstraintType(Constraint);
2811 /// Examine constraint type and operand type and determine a weight value.
2812 /// This object must already have been set up with the operand type
2813 /// and the current alternative constraint selected.
2814 TargetLowering::ConstraintWeight
2815 MipsTargetLowering::getSingleConstraintMatchWeight(
2816 AsmOperandInfo &info, const char *constraint) const {
2817 ConstraintWeight weight = CW_Invalid;
2818 Value *CallOperandVal = info.CallOperandVal;
2819 // If we don't have a value, we can't do a match,
2820 // but allow it at the lowest weight.
2821 if (CallOperandVal == NULL)
2823 Type *type = CallOperandVal->getType();
2824 // Look at the constraint type.
2825 switch (*constraint) {
2827 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2831 if (type->isIntegerTy())
2832 weight = CW_Register;
2835 if (type->isFloatTy())
2836 weight = CW_Register;
2838 case 'c': // $25 for indirect jumps
2839 case 'l': // lo register
2840 case 'x': // hilo register pair
2841 if (type->isIntegerTy())
2842 weight = CW_SpecificReg;
2844 case 'I': // signed 16 bit immediate
2845 case 'J': // integer zero
2846 case 'K': // unsigned 16 bit immediate
2847 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2848 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2849 case 'O': // signed 15 bit immediate (+- 16383)
2850 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2851 if (isa<ConstantInt>(CallOperandVal))
2852 weight = CW_Constant;
2861 /// This is a helper function to parse a physical register string and split it
2862 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2863 /// that is returned indicates whether parsing was successful. The second flag
2864 /// is true if the numeric part exists.
2865 static std::pair<bool, bool>
2866 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2867 unsigned long long &Reg) {
2868 if (C.front() != '{' || C.back() != '}')
2869 return std::make_pair(false, false);
2871 // Search for the first numeric character.
2872 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2873 I = std::find_if(B, E, std::ptr_fun(isdigit));
2875 Prefix.assign(B, I - B);
2877 // The second flag is set to false if no numeric characters were found.
2879 return std::make_pair(true, false);
2881 // Parse the numeric characters.
2882 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2886 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2887 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2888 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2889 const TargetRegisterClass *RC;
2891 unsigned long long Reg;
2893 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2896 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2898 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2899 // No numeric characters follow "hi" or "lo".
2901 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2903 RC = TRI->getRegClass(Prefix == "hi" ?
2904 Mips::HI32RegClassID : Mips::LO32RegClassID);
2905 return std::make_pair(*(RC->begin()), RC);
2909 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2911 if (Prefix == "$f") { // Parse $f0-$f31.
2912 // If the size of FP registers is 64-bit or Reg is an even number, select
2913 // the 64-bit register class. Otherwise, select the 32-bit register class.
2914 if (VT == MVT::Other)
2915 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2917 RC = getRegClassFor(VT);
2919 if (RC == &Mips::AFGR64RegClass) {
2920 assert(Reg % 2 == 0);
2923 } else if (Prefix == "$fcc") { // Parse $fcc0-$fcc7.
2924 RC = TRI->getRegClass(Mips::FCCRegClassID);
2925 } else { // Parse $0-$31.
2926 assert(Prefix == "$");
2927 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2930 assert(Reg < RC->getNumRegs());
2931 return std::make_pair(*(RC->begin() + Reg), RC);
2934 /// Given a register class constraint, like 'r', if this corresponds directly
2935 /// to an LLVM register class, return a register of 0 and the register class
2937 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2938 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2940 if (Constraint.size() == 1) {
2941 switch (Constraint[0]) {
2942 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2943 case 'y': // Same as 'r'. Exists for compatibility.
2945 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2946 if (Subtarget->inMips16Mode())
2947 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2948 return std::make_pair(0U, &Mips::GPR32RegClass);
2950 if (VT == MVT::i64 && !HasMips64)
2951 return std::make_pair(0U, &Mips::GPR32RegClass);
2952 if (VT == MVT::i64 && HasMips64)
2953 return std::make_pair(0U, &Mips::GPR64RegClass);
2954 // This will generate an error message
2955 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2958 return std::make_pair(0U, &Mips::FGR32RegClass);
2959 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2960 if (Subtarget->isFP64bit())
2961 return std::make_pair(0U, &Mips::FGR64RegClass);
2962 return std::make_pair(0U, &Mips::AFGR64RegClass);
2965 case 'c': // register suitable for indirect jump
2967 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
2968 assert(VT == MVT::i64 && "Unexpected type.");
2969 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
2970 case 'l': // register suitable for indirect jump
2972 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
2973 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
2974 case 'x': // register suitable for indirect jump
2975 // Fixme: Not triggering the use of both hi and low
2976 // This will generate an error message
2977 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2981 std::pair<unsigned, const TargetRegisterClass *> R;
2982 R = parseRegForInlineAsmConstraint(Constraint, VT);
2987 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2990 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2991 /// vector. If it is invalid, don't add anything to Ops.
2992 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2993 std::string &Constraint,
2994 std::vector<SDValue>&Ops,
2995 SelectionDAG &DAG) const {
2996 SDValue Result(0, 0);
2998 // Only support length 1 constraints for now.
2999 if (Constraint.length() > 1) return;
3001 char ConstraintLetter = Constraint[0];
3002 switch (ConstraintLetter) {
3003 default: break; // This will fall through to the generic implementation
3004 case 'I': // Signed 16 bit constant
3005 // If this fails, the parent routine will give an error
3006 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3007 EVT Type = Op.getValueType();
3008 int64_t Val = C->getSExtValue();
3009 if (isInt<16>(Val)) {
3010 Result = DAG.getTargetConstant(Val, Type);
3015 case 'J': // integer zero
3016 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3017 EVT Type = Op.getValueType();
3018 int64_t Val = C->getZExtValue();
3020 Result = DAG.getTargetConstant(0, Type);
3025 case 'K': // unsigned 16 bit immediate
3026 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3027 EVT Type = Op.getValueType();
3028 uint64_t Val = (uint64_t)C->getZExtValue();
3029 if (isUInt<16>(Val)) {
3030 Result = DAG.getTargetConstant(Val, Type);
3035 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3036 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3037 EVT Type = Op.getValueType();
3038 int64_t Val = C->getSExtValue();
3039 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3040 Result = DAG.getTargetConstant(Val, Type);
3045 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3046 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3047 EVT Type = Op.getValueType();
3048 int64_t Val = C->getSExtValue();
3049 if ((Val >= -65535) && (Val <= -1)) {
3050 Result = DAG.getTargetConstant(Val, Type);
3055 case 'O': // signed 15 bit immediate
3056 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3057 EVT Type = Op.getValueType();
3058 int64_t Val = C->getSExtValue();
3059 if ((isInt<15>(Val))) {
3060 Result = DAG.getTargetConstant(Val, Type);
3065 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3066 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3067 EVT Type = Op.getValueType();
3068 int64_t Val = C->getSExtValue();
3069 if ((Val <= 65535) && (Val >= 1)) {
3070 Result = DAG.getTargetConstant(Val, Type);
3077 if (Result.getNode()) {
3078 Ops.push_back(Result);
3082 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3085 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3087 // No global is ever allowed as a base.
3092 case 0: // "r+i" or just "i", depending on HasBaseReg.
3095 if (!AM.HasBaseReg) // allow "r+i".
3097 return false; // disallow "r+r" or "r+r+i".
3106 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3107 // The Mips target isn't yet aware of offsets.
3111 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3113 bool IsMemset, bool ZeroMemset,
3115 MachineFunction &MF) const {
3116 if (Subtarget->hasMips64())
3122 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3123 if (VT != MVT::f32 && VT != MVT::f64)
3125 if (Imm.isNegZero())
3127 return Imm.isZero();
3130 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3132 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3134 return TargetLowering::getJumpTableEncoding();
3137 /// This function returns true if CallSym is a long double emulation routine.
3138 static bool isF128SoftLibCall(const char *CallSym) {
3139 const char *const LibCalls[] =
3140 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3141 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3142 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3143 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3144 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3145 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3146 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3147 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3150 const char *const *End = LibCalls + array_lengthof(LibCalls);
3152 // Check that LibCalls is sorted alphabetically.
3153 MipsTargetLowering::LTStr Comp;
3156 for (const char *const *I = LibCalls; I < End - 1; ++I)
3157 assert(Comp(*I, *(I + 1)));
3160 return std::binary_search(LibCalls, End, CallSym, Comp);
3163 /// This function returns true if Ty is fp128 or i128 which was originally a
3165 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3166 if (Ty->isFP128Ty())
3169 const ExternalSymbolSDNode *ES =
3170 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3172 // If the Ty is i128 and the function being called is a long double emulation
3173 // routine, then the original type is f128.
3174 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3177 MipsTargetLowering::MipsCC::SpecialCallingConvType
3178 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3179 MipsCC::SpecialCallingConvType SpecialCallingConv =
3180 MipsCC::NoSpecialCallingConv;;
3181 if (Subtarget->inMips16HardFloat()) {
3182 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3183 llvm::StringRef Sym = G->getGlobal()->getName();
3184 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3185 if (F->hasFnAttribute("__Mips16RetHelper")) {
3186 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3190 return SpecialCallingConv;
3193 MipsTargetLowering::MipsCC::MipsCC(
3194 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3195 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3196 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3197 SpecialCallingConv(SpecialCallingConv_){
3198 // Pre-allocate reserved argument area.
3199 CCInfo.AllocateStack(reservedArgArea(), 1);
3203 void MipsTargetLowering::MipsCC::
3204 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3205 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3206 std::vector<ArgListEntry> &FuncArgs) {
3207 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3208 "CallingConv::Fast shouldn't be used for vararg functions.");
3210 unsigned NumOpnds = Args.size();
3211 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3213 for (unsigned I = 0; I != NumOpnds; ++I) {
3214 MVT ArgVT = Args[I].VT;
3215 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3218 if (ArgFlags.isByVal()) {
3219 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3223 if (IsVarArg && !Args[I].IsFixed)
3224 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3226 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3228 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3233 dbgs() << "Call operand #" << I << " has unhandled type "
3234 << EVT(ArgVT).getEVTString();
3236 llvm_unreachable(0);
3241 void MipsTargetLowering::MipsCC::
3242 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3243 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3244 unsigned NumArgs = Args.size();
3245 llvm::CCAssignFn *FixedFn = fixedArgFn();
3246 unsigned CurArgIdx = 0;
3248 for (unsigned I = 0; I != NumArgs; ++I) {
3249 MVT ArgVT = Args[I].VT;
3250 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3251 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3252 CurArgIdx = Args[I].OrigArgIndex;
3254 if (ArgFlags.isByVal()) {
3255 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3259 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3261 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3265 dbgs() << "Formal Arg #" << I << " has unhandled type "
3266 << EVT(ArgVT).getEVTString();
3268 llvm_unreachable(0);
3272 template<typename Ty>
3273 void MipsTargetLowering::MipsCC::
3274 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3275 const SDNode *CallNode, const Type *RetTy) const {
3278 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3279 Fn = RetCC_F128Soft;
3283 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3284 MVT VT = RetVals[I].VT;
3285 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3286 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3288 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3290 dbgs() << "Call result #" << I << " has unhandled type "
3291 << EVT(VT).getEVTString() << '\n';
3293 llvm_unreachable(0);
3298 void MipsTargetLowering::MipsCC::
3299 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3300 const SDNode *CallNode, const Type *RetTy) const {
3301 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3304 void MipsTargetLowering::MipsCC::
3305 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3306 const Type *RetTy) const {
3307 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3310 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3312 CCValAssign::LocInfo LocInfo,
3313 ISD::ArgFlagsTy ArgFlags) {
3314 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3316 struct ByValArgInfo ByVal;
3317 unsigned RegSize = regSize();
3318 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3319 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3322 if (useRegsForByval())
3323 allocateRegs(ByVal, ByValSize, Align);
3325 // Allocate space on caller's stack.
3326 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3328 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3330 ByValArgs.push_back(ByVal);
3333 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3334 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3337 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3338 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3341 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3342 return IsO32 ? O32IntRegs : Mips64IntRegs;
3345 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3346 if (CallConv == CallingConv::Fast)
3347 return CC_Mips_FastCC;
3349 if (SpecialCallingConv == Mips16RetHelperConv)
3350 return CC_Mips16RetHelper;
3351 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3354 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3355 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3358 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3359 return IsO32 ? O32IntRegs : Mips64DPRegs;
3362 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3365 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3366 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3367 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3368 "Byval argument's size and alignment should be a multiple of"
3371 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3373 // If Align > RegSize, the first arg register must be even.
3374 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3375 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3379 // Mark the registers allocated.
3380 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3381 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3382 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3385 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3386 const SDNode *CallNode,
3387 bool IsSoftFloat) const {
3388 if (IsSoftFloat || IsO32)
3391 // Check if the original type was fp128.
3392 if (originalTypeIsF128(OrigTy, CallNode)) {
3393 assert(VT == MVT::i64);
3400 void MipsTargetLowering::
3401 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3402 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3403 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3404 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3405 MachineFunction &MF = DAG.getMachineFunction();
3406 MachineFrameInfo *MFI = MF.getFrameInfo();
3407 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3408 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3412 FrameObjOffset = (int)CC.reservedArgArea() -
3413 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3415 FrameObjOffset = ByVal.Address;
3417 // Create frame object.
3418 EVT PtrTy = getPointerTy();
3419 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3420 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3421 InVals.push_back(FIN);
3426 // Copy arg registers.
3427 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3428 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3430 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3431 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3432 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3433 unsigned Offset = I * CC.regSize();
3434 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3435 DAG.getConstant(Offset, PtrTy));
3436 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3437 StorePtr, MachinePointerInfo(FuncArg, Offset),
3439 OutChains.push_back(Store);
3443 // Copy byVal arg to registers and stack.
3444 void MipsTargetLowering::
3445 passByValArg(SDValue Chain, SDLoc DL,
3446 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3447 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3448 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3449 const MipsCC &CC, const ByValArgInfo &ByVal,
3450 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3451 unsigned ByValSize = Flags.getByValSize();
3452 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3453 unsigned RegSize = CC.regSize();
3454 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3455 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3457 if (ByVal.NumRegs) {
3458 const uint16_t *ArgRegs = CC.intArgRegs();
3459 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3462 // Copy words to registers.
3463 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3464 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3465 DAG.getConstant(Offset, PtrTy));
3466 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3467 MachinePointerInfo(), false, false, false,
3469 MemOpChains.push_back(LoadVal.getValue(1));
3470 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3471 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3474 // Return if the struct has been fully copied.
3475 if (ByValSize == Offset)
3478 // Copy the remainder of the byval argument with sub-word loads and shifts.
3479 if (LeftoverBytes) {
3480 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3481 "Size of the remainder should be smaller than RegSize.");
3484 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3485 Offset < ByValSize; LoadSize /= 2) {
3486 unsigned RemSize = ByValSize - Offset;
3488 if (RemSize < LoadSize)
3492 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3493 DAG.getConstant(Offset, PtrTy));
3495 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3496 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3497 false, false, Alignment);
3498 MemOpChains.push_back(LoadVal.getValue(1));
3500 // Shift the loaded value.
3504 Shamt = TotalSizeLoaded;
3506 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3508 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3509 DAG.getConstant(Shamt, MVT::i32));
3512 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3517 TotalSizeLoaded += LoadSize;
3518 Alignment = std::min(Alignment, LoadSize);
3521 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3522 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3527 // Copy remainder of byval arg to it with memcpy.
3528 unsigned MemCpySize = ByValSize - Offset;
3529 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3530 DAG.getConstant(Offset, PtrTy));
3531 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3532 DAG.getIntPtrConstant(ByVal.Address));
3533 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3534 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3535 MachinePointerInfo(0), MachinePointerInfo(0));
3536 MemOpChains.push_back(Chain);
3539 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3540 const MipsCC &CC, SDValue Chain,
3541 SDLoc DL, SelectionDAG &DAG) const {
3542 unsigned NumRegs = CC.numIntArgRegs();
3543 const uint16_t *ArgRegs = CC.intArgRegs();
3544 const CCState &CCInfo = CC.getCCInfo();
3545 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3546 unsigned RegSize = CC.regSize();
3547 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3548 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3549 MachineFunction &MF = DAG.getMachineFunction();
3550 MachineFrameInfo *MFI = MF.getFrameInfo();
3551 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3553 // Offset of the first variable argument from stack pointer.
3557 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3559 VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3561 // Record the frame index of the first variable argument
3562 // which is a value necessary to VASTART.
3563 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3564 MipsFI->setVarArgsFrameIndex(FI);
3566 // Copy the integer registers that have not been used for argument passing
3567 // to the argument register save area. For O32, the save area is allocated
3568 // in the caller's stack frame, while for N32/64, it is allocated in the
3569 // callee's stack frame.
3570 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3571 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3572 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3573 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3574 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3575 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3576 MachinePointerInfo(), false, false, 0);
3577 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3578 OutChains.push_back(Store);