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/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NumTailCalls, "Number of tail calls");
45 LargeGOT("mxgot", cl::Hidden,
46 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
49 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
50 cl::desc("MIPS: Don't trap on integer division by zero."),
53 static const uint16_t O32IntRegs[4] = {
54 Mips::A0, Mips::A1, Mips::A2, Mips::A3
57 static const uint16_t Mips64IntRegs[8] = {
58 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
59 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
62 static const uint16_t Mips64DPRegs[8] = {
63 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
64 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
67 // If I is a shifted mask, set the size (Size) and the first bit of the
68 // mask (Pos), and return true.
69 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
70 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
71 if (!isShiftedMask_64(I))
74 Size = CountPopulation_64(I);
75 Pos = countTrailingZeros(I);
79 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
80 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
81 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
84 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
86 unsigned Flag) const {
87 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
90 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
92 unsigned Flag) const {
93 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
96 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
98 unsigned Flag) const {
99 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
102 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
104 unsigned Flag) const {
105 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
108 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
110 unsigned Flag) const {
111 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
112 N->getOffset(), Flag);
115 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
117 case MipsISD::JmpLink: return "MipsISD::JmpLink";
118 case MipsISD::TailCall: return "MipsISD::TailCall";
119 case MipsISD::Hi: return "MipsISD::Hi";
120 case MipsISD::Lo: return "MipsISD::Lo";
121 case MipsISD::GPRel: return "MipsISD::GPRel";
122 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
123 case MipsISD::Ret: return "MipsISD::Ret";
124 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
125 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
126 case MipsISD::FPCmp: return "MipsISD::FPCmp";
127 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
128 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
129 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
130 case MipsISD::MFHI: return "MipsISD::MFHI";
131 case MipsISD::MFLO: return "MipsISD::MFLO";
132 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
133 case MipsISD::Mult: return "MipsISD::Mult";
134 case MipsISD::Multu: return "MipsISD::Multu";
135 case MipsISD::MAdd: return "MipsISD::MAdd";
136 case MipsISD::MAddu: return "MipsISD::MAddu";
137 case MipsISD::MSub: return "MipsISD::MSub";
138 case MipsISD::MSubu: return "MipsISD::MSubu";
139 case MipsISD::DivRem: return "MipsISD::DivRem";
140 case MipsISD::DivRemU: return "MipsISD::DivRemU";
141 case MipsISD::DivRem16: return "MipsISD::DivRem16";
142 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
143 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
144 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
145 case MipsISD::Wrapper: return "MipsISD::Wrapper";
146 case MipsISD::Sync: return "MipsISD::Sync";
147 case MipsISD::Ext: return "MipsISD::Ext";
148 case MipsISD::Ins: return "MipsISD::Ins";
149 case MipsISD::LWL: return "MipsISD::LWL";
150 case MipsISD::LWR: return "MipsISD::LWR";
151 case MipsISD::SWL: return "MipsISD::SWL";
152 case MipsISD::SWR: return "MipsISD::SWR";
153 case MipsISD::LDL: return "MipsISD::LDL";
154 case MipsISD::LDR: return "MipsISD::LDR";
155 case MipsISD::SDL: return "MipsISD::SDL";
156 case MipsISD::SDR: return "MipsISD::SDR";
157 case MipsISD::EXTP: return "MipsISD::EXTP";
158 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
159 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
160 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
161 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
162 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
163 case MipsISD::SHILO: return "MipsISD::SHILO";
164 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
165 case MipsISD::MULT: return "MipsISD::MULT";
166 case MipsISD::MULTU: return "MipsISD::MULTU";
167 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
168 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
169 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
170 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
171 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
172 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
173 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
174 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
175 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
176 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
177 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
178 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
179 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
180 case MipsISD::VCEQ: return "MipsISD::VCEQ";
181 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
182 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
183 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
184 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
185 case MipsISD::VSMAX: return "MipsISD::VSMAX";
186 case MipsISD::VSMIN: return "MipsISD::VSMIN";
187 case MipsISD::VUMAX: return "MipsISD::VUMAX";
188 case MipsISD::VUMIN: return "MipsISD::VUMIN";
189 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
190 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
191 case MipsISD::VNOR: return "MipsISD::VNOR";
192 case MipsISD::VSHF: return "MipsISD::VSHF";
193 case MipsISD::SHF: return "MipsISD::SHF";
194 case MipsISD::ILVEV: return "MipsISD::ILVEV";
195 case MipsISD::ILVOD: return "MipsISD::ILVOD";
196 case MipsISD::ILVL: return "MipsISD::ILVL";
197 case MipsISD::ILVR: return "MipsISD::ILVR";
198 case MipsISD::PCKEV: return "MipsISD::PCKEV";
199 case MipsISD::PCKOD: return "MipsISD::PCKOD";
200 default: return NULL;
205 MipsTargetLowering(MipsTargetMachine &TM)
206 : TargetLowering(TM, new MipsTargetObjectFile()),
207 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
208 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
209 IsO32(Subtarget->isABI_O32()) {
210 // Mips does not have i1 type, so use i32 for
211 // setcc operations results (slt, sgt, ...).
212 setBooleanContents(ZeroOrOneBooleanContent);
213 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
215 // Load extented operations for i1 types must be promoted
216 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
217 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
218 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
220 // MIPS doesn't have extending float->double load/store
221 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
222 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
224 // Used by legalize types to correctly generate the setcc result.
225 // Without this, every float setcc comes with a AND/OR with the result,
226 // we don't want this, since the fpcmp result goes to a flag register,
227 // which is used implicitly by brcond and select operations.
228 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
230 // Mips Custom Operations
231 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
232 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
233 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
234 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
235 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
236 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
237 setOperationAction(ISD::SELECT, MVT::f32, Custom);
238 setOperationAction(ISD::SELECT, MVT::f64, Custom);
239 setOperationAction(ISD::SELECT, MVT::i32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
241 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 setOperationAction(ISD::SETCC, MVT::f32, Custom);
243 setOperationAction(ISD::SETCC, MVT::f64, Custom);
244 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
245 setOperationAction(ISD::VASTART, MVT::Other, Custom);
246 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
247 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
248 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
250 if (!TM.Options.NoNaNsFPMath) {
251 setOperationAction(ISD::FABS, MVT::f32, Custom);
252 setOperationAction(ISD::FABS, MVT::f64, Custom);
256 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
257 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
258 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
259 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
260 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
261 setOperationAction(ISD::SELECT, MVT::i64, Custom);
262 setOperationAction(ISD::LOAD, MVT::i64, Custom);
263 setOperationAction(ISD::STORE, MVT::i64, Custom);
264 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
268 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
269 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
270 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
273 setOperationAction(ISD::ADD, MVT::i32, Custom);
275 setOperationAction(ISD::ADD, MVT::i64, Custom);
277 setOperationAction(ISD::SDIV, MVT::i32, Expand);
278 setOperationAction(ISD::SREM, MVT::i32, Expand);
279 setOperationAction(ISD::UDIV, MVT::i32, Expand);
280 setOperationAction(ISD::UREM, MVT::i32, Expand);
281 setOperationAction(ISD::SDIV, MVT::i64, Expand);
282 setOperationAction(ISD::SREM, MVT::i64, Expand);
283 setOperationAction(ISD::UDIV, MVT::i64, Expand);
284 setOperationAction(ISD::UREM, MVT::i64, Expand);
286 // Operations not directly supported by Mips.
287 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
288 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
289 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
290 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
291 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
292 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
293 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
294 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
295 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
296 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
297 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
298 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
299 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
300 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
301 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
302 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
303 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
304 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
305 setOperationAction(ISD::ROTL, MVT::i32, Expand);
306 setOperationAction(ISD::ROTL, MVT::i64, Expand);
307 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
308 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
310 if (!Subtarget->hasMips32r2())
311 setOperationAction(ISD::ROTR, MVT::i32, Expand);
313 if (!Subtarget->hasMips64r2())
314 setOperationAction(ISD::ROTR, MVT::i64, Expand);
316 setOperationAction(ISD::FSIN, MVT::f32, Expand);
317 setOperationAction(ISD::FSIN, MVT::f64, Expand);
318 setOperationAction(ISD::FCOS, MVT::f32, Expand);
319 setOperationAction(ISD::FCOS, MVT::f64, Expand);
320 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
321 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
322 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
323 setOperationAction(ISD::FPOW, MVT::f32, Expand);
324 setOperationAction(ISD::FPOW, MVT::f64, Expand);
325 setOperationAction(ISD::FLOG, MVT::f32, Expand);
326 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
327 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
328 setOperationAction(ISD::FEXP, MVT::f32, Expand);
329 setOperationAction(ISD::FMA, MVT::f32, Expand);
330 setOperationAction(ISD::FMA, MVT::f64, Expand);
331 setOperationAction(ISD::FREM, MVT::f32, Expand);
332 setOperationAction(ISD::FREM, MVT::f64, Expand);
334 if (!TM.Options.NoNaNsFPMath) {
335 setOperationAction(ISD::FNEG, MVT::f32, Expand);
336 setOperationAction(ISD::FNEG, MVT::f64, Expand);
339 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
341 setOperationAction(ISD::VAARG, MVT::Other, Expand);
342 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
343 setOperationAction(ISD::VAEND, MVT::Other, Expand);
345 // Use the default for now
346 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
347 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
349 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
350 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
351 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
352 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
354 setInsertFencesForAtomic(true);
356 if (!Subtarget->hasSEInReg()) {
357 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
358 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
361 if (!Subtarget->hasBitCount()) {
362 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
363 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
366 if (!Subtarget->hasSwap()) {
367 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
368 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
372 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
373 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
374 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
375 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
378 setOperationAction(ISD::TRAP, MVT::Other, Legal);
380 setTargetDAGCombine(ISD::SDIVREM);
381 setTargetDAGCombine(ISD::UDIVREM);
382 setTargetDAGCombine(ISD::SELECT);
383 setTargetDAGCombine(ISD::AND);
384 setTargetDAGCombine(ISD::OR);
385 setTargetDAGCombine(ISD::ADD);
387 setMinFunctionAlignment(HasMips64 ? 3 : 2);
389 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
391 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
392 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
394 MaxStoresPerMemcpy = 16;
397 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
398 if (TM.getSubtargetImpl()->inMips16Mode())
399 return llvm::createMips16TargetLowering(TM);
401 return llvm::createMipsSETargetLowering(TM);
404 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
407 return VT.changeVectorElementTypeToInteger();
410 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
411 TargetLowering::DAGCombinerInfo &DCI,
412 const MipsSubtarget *Subtarget) {
413 if (DCI.isBeforeLegalizeOps())
416 EVT Ty = N->getValueType(0);
417 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
418 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
419 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
423 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
424 N->getOperand(0), N->getOperand(1));
425 SDValue InChain = DAG.getEntryNode();
426 SDValue InGlue = DivRem;
429 if (N->hasAnyUseOfValue(0)) {
430 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
432 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
433 InChain = CopyFromLo.getValue(1);
434 InGlue = CopyFromLo.getValue(2);
438 if (N->hasAnyUseOfValue(1)) {
439 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
441 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
447 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
449 default: llvm_unreachable("Unknown fp condition code!");
451 case ISD::SETOEQ: return Mips::FCOND_OEQ;
452 case ISD::SETUNE: return Mips::FCOND_UNE;
454 case ISD::SETOLT: return Mips::FCOND_OLT;
456 case ISD::SETOGT: return Mips::FCOND_OGT;
458 case ISD::SETOLE: return Mips::FCOND_OLE;
460 case ISD::SETOGE: return Mips::FCOND_OGE;
461 case ISD::SETULT: return Mips::FCOND_ULT;
462 case ISD::SETULE: return Mips::FCOND_ULE;
463 case ISD::SETUGT: return Mips::FCOND_UGT;
464 case ISD::SETUGE: return Mips::FCOND_UGE;
465 case ISD::SETUO: return Mips::FCOND_UN;
466 case ISD::SETO: return Mips::FCOND_OR;
468 case ISD::SETONE: return Mips::FCOND_ONE;
469 case ISD::SETUEQ: return Mips::FCOND_UEQ;
474 /// This function returns true if the floating point conditional branches and
475 /// conditional moves which use condition code CC should be inverted.
476 static bool invertFPCondCodeUser(Mips::CondCode CC) {
477 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
480 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
481 "Illegal Condition Code");
486 // Creates and returns an FPCmp node from a setcc node.
487 // Returns Op if setcc is not a floating point comparison.
488 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
489 // must be a SETCC node
490 if (Op.getOpcode() != ISD::SETCC)
493 SDValue LHS = Op.getOperand(0);
495 if (!LHS.getValueType().isFloatingPoint())
498 SDValue RHS = Op.getOperand(1);
501 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
502 // node if necessary.
503 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
505 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
506 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
509 // Creates and returns a CMovFPT/F node.
510 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
511 SDValue False, SDLoc DL) {
512 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
513 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
514 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
516 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
517 True.getValueType(), True, FCC0, False, Cond);
520 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
521 TargetLowering::DAGCombinerInfo &DCI,
522 const MipsSubtarget *Subtarget) {
523 if (DCI.isBeforeLegalizeOps())
526 SDValue SetCC = N->getOperand(0);
528 if ((SetCC.getOpcode() != ISD::SETCC) ||
529 !SetCC.getOperand(0).getValueType().isInteger())
532 SDValue False = N->getOperand(2);
533 EVT FalseTy = False.getValueType();
535 if (!FalseTy.isInteger())
538 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
540 if (!CN || CN->getZExtValue())
544 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
545 SDValue True = N->getOperand(1);
547 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
548 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
550 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
553 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
554 TargetLowering::DAGCombinerInfo &DCI,
555 const MipsSubtarget *Subtarget) {
556 // Pattern match EXT.
557 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
558 // => ext $dst, $src, size, pos
559 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
562 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
563 unsigned ShiftRightOpc = ShiftRight.getOpcode();
565 // Op's first operand must be a shift right.
566 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
569 // The second operand of the shift must be an immediate.
571 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
574 uint64_t Pos = CN->getZExtValue();
575 uint64_t SMPos, SMSize;
577 // Op's second operand must be a shifted mask.
578 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
579 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
582 // Return if the shifted mask does not start at bit 0 or the sum of its size
583 // and Pos exceeds the word's size.
584 EVT ValTy = N->getValueType(0);
585 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
588 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
589 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
590 DAG.getConstant(SMSize, MVT::i32));
593 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
594 TargetLowering::DAGCombinerInfo &DCI,
595 const MipsSubtarget *Subtarget) {
596 // Pattern match INS.
597 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
598 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
599 // => ins $dst, $src, size, pos, $src1
600 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
603 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
604 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
607 // See if Op's first operand matches (and $src1 , mask0).
608 if (And0.getOpcode() != ISD::AND)
611 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
612 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
615 // See if Op's second operand matches (and (shl $src, pos), mask1).
616 if (And1.getOpcode() != ISD::AND)
619 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
620 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
623 // The shift masks must have the same position and size.
624 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
627 SDValue Shl = And1.getOperand(0);
628 if (Shl.getOpcode() != ISD::SHL)
631 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
634 unsigned Shamt = CN->getZExtValue();
636 // Return if the shift amount and the first bit position of mask are not the
638 EVT ValTy = N->getValueType(0);
639 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
642 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
643 DAG.getConstant(SMPos0, MVT::i32),
644 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
647 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
648 TargetLowering::DAGCombinerInfo &DCI,
649 const MipsSubtarget *Subtarget) {
650 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
652 if (DCI.isBeforeLegalizeOps())
655 SDValue Add = N->getOperand(1);
657 if (Add.getOpcode() != ISD::ADD)
660 SDValue Lo = Add.getOperand(1);
662 if ((Lo.getOpcode() != MipsISD::Lo) ||
663 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
666 EVT ValTy = N->getValueType(0);
669 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
671 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
674 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
676 SelectionDAG &DAG = DCI.DAG;
677 unsigned Opc = N->getOpcode();
683 return performDivRemCombine(N, DAG, DCI, Subtarget);
685 return performSELECTCombine(N, DAG, DCI, Subtarget);
687 return performANDCombine(N, DAG, DCI, Subtarget);
689 return performORCombine(N, DAG, DCI, Subtarget);
691 return performADDCombine(N, DAG, DCI, Subtarget);
698 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
699 SmallVectorImpl<SDValue> &Results,
700 SelectionDAG &DAG) const {
701 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
703 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
704 Results.push_back(Res.getValue(I));
708 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
709 SmallVectorImpl<SDValue> &Results,
710 SelectionDAG &DAG) const {
711 return LowerOperationWrapper(N, Results, DAG);
714 SDValue MipsTargetLowering::
715 LowerOperation(SDValue Op, SelectionDAG &DAG) const
717 switch (Op.getOpcode())
719 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
720 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
721 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
722 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
723 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
724 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
725 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
726 case ISD::SELECT: return lowerSELECT(Op, DAG);
727 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
728 case ISD::SETCC: return lowerSETCC(Op, DAG);
729 case ISD::VASTART: return lowerVASTART(Op, DAG);
730 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
731 case ISD::FABS: return lowerFABS(Op, DAG);
732 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
733 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
734 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
735 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
736 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
737 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
738 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
739 case ISD::LOAD: return lowerLOAD(Op, DAG);
740 case ISD::STORE: return lowerSTORE(Op, DAG);
741 case ISD::ADD: return lowerADD(Op, DAG);
742 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
747 //===----------------------------------------------------------------------===//
748 // Lower helper functions
749 //===----------------------------------------------------------------------===//
751 // addLiveIn - This helper function adds the specified physical register to the
752 // MachineFunction as a live in value. It also creates a corresponding
753 // virtual register for it.
755 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
757 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
758 MF.getRegInfo().addLiveIn(PReg, VReg);
762 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
763 MachineBasicBlock &MBB,
764 const TargetInstrInfo &TII,
769 // Insert instruction "teq $divisor_reg, $zero, 7".
770 MachineBasicBlock::iterator I(MI);
771 MachineInstrBuilder MIB;
772 MachineOperand &Divisor = MI->getOperand(2);
773 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
774 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
775 .addReg(Mips::ZERO).addImm(7);
777 // Use the 32-bit sub-register if this is a 64-bit division.
779 MIB->getOperand(0).setSubReg(Mips::sub_32);
781 // Clear Divisor's kill flag.
782 Divisor.setIsKill(false);
787 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
788 MachineBasicBlock *BB) const {
789 switch (MI->getOpcode()) {
791 llvm_unreachable("Unexpected instr type to insert");
792 case Mips::ATOMIC_LOAD_ADD_I8:
793 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
794 case Mips::ATOMIC_LOAD_ADD_I16:
795 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
796 case Mips::ATOMIC_LOAD_ADD_I32:
797 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
798 case Mips::ATOMIC_LOAD_ADD_I64:
799 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
801 case Mips::ATOMIC_LOAD_AND_I8:
802 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
803 case Mips::ATOMIC_LOAD_AND_I16:
804 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
805 case Mips::ATOMIC_LOAD_AND_I32:
806 return emitAtomicBinary(MI, BB, 4, Mips::AND);
807 case Mips::ATOMIC_LOAD_AND_I64:
808 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
810 case Mips::ATOMIC_LOAD_OR_I8:
811 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
812 case Mips::ATOMIC_LOAD_OR_I16:
813 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
814 case Mips::ATOMIC_LOAD_OR_I32:
815 return emitAtomicBinary(MI, BB, 4, Mips::OR);
816 case Mips::ATOMIC_LOAD_OR_I64:
817 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
819 case Mips::ATOMIC_LOAD_XOR_I8:
820 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
821 case Mips::ATOMIC_LOAD_XOR_I16:
822 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
823 case Mips::ATOMIC_LOAD_XOR_I32:
824 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
825 case Mips::ATOMIC_LOAD_XOR_I64:
826 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
828 case Mips::ATOMIC_LOAD_NAND_I8:
829 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
830 case Mips::ATOMIC_LOAD_NAND_I16:
831 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
832 case Mips::ATOMIC_LOAD_NAND_I32:
833 return emitAtomicBinary(MI, BB, 4, 0, true);
834 case Mips::ATOMIC_LOAD_NAND_I64:
835 return emitAtomicBinary(MI, BB, 8, 0, true);
837 case Mips::ATOMIC_LOAD_SUB_I8:
838 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
839 case Mips::ATOMIC_LOAD_SUB_I16:
840 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
841 case Mips::ATOMIC_LOAD_SUB_I32:
842 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
843 case Mips::ATOMIC_LOAD_SUB_I64:
844 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
846 case Mips::ATOMIC_SWAP_I8:
847 return emitAtomicBinaryPartword(MI, BB, 1, 0);
848 case Mips::ATOMIC_SWAP_I16:
849 return emitAtomicBinaryPartword(MI, BB, 2, 0);
850 case Mips::ATOMIC_SWAP_I32:
851 return emitAtomicBinary(MI, BB, 4, 0);
852 case Mips::ATOMIC_SWAP_I64:
853 return emitAtomicBinary(MI, BB, 8, 0);
855 case Mips::ATOMIC_CMP_SWAP_I8:
856 return emitAtomicCmpSwapPartword(MI, BB, 1);
857 case Mips::ATOMIC_CMP_SWAP_I16:
858 return emitAtomicCmpSwapPartword(MI, BB, 2);
859 case Mips::ATOMIC_CMP_SWAP_I32:
860 return emitAtomicCmpSwap(MI, BB, 4);
861 case Mips::ATOMIC_CMP_SWAP_I64:
862 return emitAtomicCmpSwap(MI, BB, 8);
863 case Mips::PseudoSDIV:
864 case Mips::PseudoUDIV:
865 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
866 case Mips::PseudoDSDIV:
867 case Mips::PseudoDUDIV:
868 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
872 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
873 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
875 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
876 unsigned Size, unsigned BinOpcode,
878 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
880 MachineFunction *MF = BB->getParent();
881 MachineRegisterInfo &RegInfo = MF->getRegInfo();
882 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
883 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
884 DebugLoc DL = MI->getDebugLoc();
885 unsigned LL, SC, AND, NOR, ZERO, BEQ;
900 ZERO = Mips::ZERO_64;
904 unsigned OldVal = MI->getOperand(0).getReg();
905 unsigned Ptr = MI->getOperand(1).getReg();
906 unsigned Incr = MI->getOperand(2).getReg();
908 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
909 unsigned AndRes = RegInfo.createVirtualRegister(RC);
910 unsigned Success = RegInfo.createVirtualRegister(RC);
912 // insert new blocks after the current block
913 const BasicBlock *LLVM_BB = BB->getBasicBlock();
914 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
915 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
916 MachineFunction::iterator It = BB;
918 MF->insert(It, loopMBB);
919 MF->insert(It, exitMBB);
921 // Transfer the remainder of BB and its successor edges to exitMBB.
922 exitMBB->splice(exitMBB->begin(), BB,
923 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
924 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
928 // fallthrough --> loopMBB
929 BB->addSuccessor(loopMBB);
930 loopMBB->addSuccessor(loopMBB);
931 loopMBB->addSuccessor(exitMBB);
935 // <binop> storeval, oldval, incr
936 // sc success, storeval, 0(ptr)
937 // beq success, $0, loopMBB
939 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
941 // and andres, oldval, incr
942 // nor storeval, $0, andres
943 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
944 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
945 } else if (BinOpcode) {
946 // <binop> storeval, oldval, incr
947 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
951 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
952 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
954 MI->eraseFromParent(); // The instruction is gone now.
960 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
961 MachineBasicBlock *BB,
962 unsigned Size, unsigned BinOpcode,
964 assert((Size == 1 || Size == 2) &&
965 "Unsupported size for EmitAtomicBinaryPartial.");
967 MachineFunction *MF = BB->getParent();
968 MachineRegisterInfo &RegInfo = MF->getRegInfo();
969 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
970 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
971 DebugLoc DL = MI->getDebugLoc();
973 unsigned Dest = MI->getOperand(0).getReg();
974 unsigned Ptr = MI->getOperand(1).getReg();
975 unsigned Incr = MI->getOperand(2).getReg();
977 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
978 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
979 unsigned Mask = RegInfo.createVirtualRegister(RC);
980 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
981 unsigned NewVal = RegInfo.createVirtualRegister(RC);
982 unsigned OldVal = RegInfo.createVirtualRegister(RC);
983 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
984 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
985 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
986 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
987 unsigned AndRes = RegInfo.createVirtualRegister(RC);
988 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
989 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
990 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
991 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
992 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
993 unsigned SllRes = RegInfo.createVirtualRegister(RC);
994 unsigned Success = RegInfo.createVirtualRegister(RC);
996 // insert new blocks after the current block
997 const BasicBlock *LLVM_BB = BB->getBasicBlock();
998 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
999 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1000 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1001 MachineFunction::iterator It = BB;
1003 MF->insert(It, loopMBB);
1004 MF->insert(It, sinkMBB);
1005 MF->insert(It, exitMBB);
1007 // Transfer the remainder of BB and its successor edges to exitMBB.
1008 exitMBB->splice(exitMBB->begin(), BB,
1009 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1010 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1012 BB->addSuccessor(loopMBB);
1013 loopMBB->addSuccessor(loopMBB);
1014 loopMBB->addSuccessor(sinkMBB);
1015 sinkMBB->addSuccessor(exitMBB);
1018 // addiu masklsb2,$0,-4 # 0xfffffffc
1019 // and alignedaddr,ptr,masklsb2
1020 // andi ptrlsb2,ptr,3
1021 // sll shiftamt,ptrlsb2,3
1022 // ori maskupper,$0,255 # 0xff
1023 // sll mask,maskupper,shiftamt
1024 // nor mask2,$0,mask
1025 // sll incr2,incr,shiftamt
1027 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1028 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1029 .addReg(Mips::ZERO).addImm(-4);
1030 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1031 .addReg(Ptr).addReg(MaskLSB2);
1032 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1033 if (Subtarget->isLittle()) {
1034 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1036 unsigned Off = RegInfo.createVirtualRegister(RC);
1037 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1038 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1039 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1041 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1042 .addReg(Mips::ZERO).addImm(MaskImm);
1043 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1044 .addReg(MaskUpper).addReg(ShiftAmt);
1045 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1046 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1048 // atomic.load.binop
1050 // ll oldval,0(alignedaddr)
1051 // binop binopres,oldval,incr2
1052 // and newval,binopres,mask
1053 // and maskedoldval0,oldval,mask2
1054 // or storeval,maskedoldval0,newval
1055 // sc success,storeval,0(alignedaddr)
1056 // beq success,$0,loopMBB
1060 // ll oldval,0(alignedaddr)
1061 // and newval,incr2,mask
1062 // and maskedoldval0,oldval,mask2
1063 // or storeval,maskedoldval0,newval
1064 // sc success,storeval,0(alignedaddr)
1065 // beq success,$0,loopMBB
1068 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1070 // and andres, oldval, incr2
1071 // nor binopres, $0, andres
1072 // and newval, binopres, mask
1073 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1074 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1075 .addReg(Mips::ZERO).addReg(AndRes);
1076 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1077 } else if (BinOpcode) {
1078 // <binop> binopres, oldval, incr2
1079 // and newval, binopres, mask
1080 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1081 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1082 } else { // atomic.swap
1083 // and newval, incr2, mask
1084 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1087 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1088 .addReg(OldVal).addReg(Mask2);
1089 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1090 .addReg(MaskedOldVal0).addReg(NewVal);
1091 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1092 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1093 BuildMI(BB, DL, TII->get(Mips::BEQ))
1094 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1097 // and maskedoldval1,oldval,mask
1098 // srl srlres,maskedoldval1,shiftamt
1099 // sll sllres,srlres,24
1100 // sra dest,sllres,24
1102 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1104 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1105 .addReg(OldVal).addReg(Mask);
1106 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1107 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1108 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1109 .addReg(SrlRes).addImm(ShiftImm);
1110 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1111 .addReg(SllRes).addImm(ShiftImm);
1113 MI->eraseFromParent(); // The instruction is gone now.
1118 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1119 MachineBasicBlock *BB,
1120 unsigned Size) const {
1121 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1123 MachineFunction *MF = BB->getParent();
1124 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1125 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1126 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1127 DebugLoc DL = MI->getDebugLoc();
1128 unsigned LL, SC, ZERO, BNE, BEQ;
1139 ZERO = Mips::ZERO_64;
1144 unsigned Dest = MI->getOperand(0).getReg();
1145 unsigned Ptr = MI->getOperand(1).getReg();
1146 unsigned OldVal = MI->getOperand(2).getReg();
1147 unsigned NewVal = MI->getOperand(3).getReg();
1149 unsigned Success = RegInfo.createVirtualRegister(RC);
1151 // insert new blocks after the current block
1152 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1153 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1154 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1155 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1156 MachineFunction::iterator It = BB;
1158 MF->insert(It, loop1MBB);
1159 MF->insert(It, loop2MBB);
1160 MF->insert(It, exitMBB);
1162 // Transfer the remainder of BB and its successor edges to exitMBB.
1163 exitMBB->splice(exitMBB->begin(), BB,
1164 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1165 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1169 // fallthrough --> loop1MBB
1170 BB->addSuccessor(loop1MBB);
1171 loop1MBB->addSuccessor(exitMBB);
1172 loop1MBB->addSuccessor(loop2MBB);
1173 loop2MBB->addSuccessor(loop1MBB);
1174 loop2MBB->addSuccessor(exitMBB);
1178 // bne dest, oldval, exitMBB
1180 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1181 BuildMI(BB, DL, TII->get(BNE))
1182 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1185 // sc success, newval, 0(ptr)
1186 // beq success, $0, loop1MBB
1188 BuildMI(BB, DL, TII->get(SC), Success)
1189 .addReg(NewVal).addReg(Ptr).addImm(0);
1190 BuildMI(BB, DL, TII->get(BEQ))
1191 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1193 MI->eraseFromParent(); // The instruction is gone now.
1199 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1200 MachineBasicBlock *BB,
1201 unsigned Size) const {
1202 assert((Size == 1 || Size == 2) &&
1203 "Unsupported size for EmitAtomicCmpSwapPartial.");
1205 MachineFunction *MF = BB->getParent();
1206 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1207 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1208 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1209 DebugLoc DL = MI->getDebugLoc();
1211 unsigned Dest = MI->getOperand(0).getReg();
1212 unsigned Ptr = MI->getOperand(1).getReg();
1213 unsigned CmpVal = MI->getOperand(2).getReg();
1214 unsigned NewVal = MI->getOperand(3).getReg();
1216 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1217 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1218 unsigned Mask = RegInfo.createVirtualRegister(RC);
1219 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1220 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1221 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1222 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1223 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1224 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1225 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1226 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1227 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1228 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1229 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1230 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1231 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1232 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1233 unsigned Success = RegInfo.createVirtualRegister(RC);
1235 // insert new blocks after the current block
1236 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1237 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1238 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1239 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1240 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1241 MachineFunction::iterator It = BB;
1243 MF->insert(It, loop1MBB);
1244 MF->insert(It, loop2MBB);
1245 MF->insert(It, sinkMBB);
1246 MF->insert(It, exitMBB);
1248 // Transfer the remainder of BB and its successor edges to exitMBB.
1249 exitMBB->splice(exitMBB->begin(), BB,
1250 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1251 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1253 BB->addSuccessor(loop1MBB);
1254 loop1MBB->addSuccessor(sinkMBB);
1255 loop1MBB->addSuccessor(loop2MBB);
1256 loop2MBB->addSuccessor(loop1MBB);
1257 loop2MBB->addSuccessor(sinkMBB);
1258 sinkMBB->addSuccessor(exitMBB);
1260 // FIXME: computation of newval2 can be moved to loop2MBB.
1262 // addiu masklsb2,$0,-4 # 0xfffffffc
1263 // and alignedaddr,ptr,masklsb2
1264 // andi ptrlsb2,ptr,3
1265 // sll shiftamt,ptrlsb2,3
1266 // ori maskupper,$0,255 # 0xff
1267 // sll mask,maskupper,shiftamt
1268 // nor mask2,$0,mask
1269 // andi maskedcmpval,cmpval,255
1270 // sll shiftedcmpval,maskedcmpval,shiftamt
1271 // andi maskednewval,newval,255
1272 // sll shiftednewval,maskednewval,shiftamt
1273 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1274 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1275 .addReg(Mips::ZERO).addImm(-4);
1276 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1277 .addReg(Ptr).addReg(MaskLSB2);
1278 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1279 if (Subtarget->isLittle()) {
1280 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1282 unsigned Off = RegInfo.createVirtualRegister(RC);
1283 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1284 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1285 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1287 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1288 .addReg(Mips::ZERO).addImm(MaskImm);
1289 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1290 .addReg(MaskUpper).addReg(ShiftAmt);
1291 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1292 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1293 .addReg(CmpVal).addImm(MaskImm);
1294 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1295 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1296 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1297 .addReg(NewVal).addImm(MaskImm);
1298 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1299 .addReg(MaskedNewVal).addReg(ShiftAmt);
1302 // ll oldval,0(alginedaddr)
1303 // and maskedoldval0,oldval,mask
1304 // bne maskedoldval0,shiftedcmpval,sinkMBB
1306 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1307 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1308 .addReg(OldVal).addReg(Mask);
1309 BuildMI(BB, DL, TII->get(Mips::BNE))
1310 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1313 // and maskedoldval1,oldval,mask2
1314 // or storeval,maskedoldval1,shiftednewval
1315 // sc success,storeval,0(alignedaddr)
1316 // beq success,$0,loop1MBB
1318 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1319 .addReg(OldVal).addReg(Mask2);
1320 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1321 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1322 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1323 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1324 BuildMI(BB, DL, TII->get(Mips::BEQ))
1325 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1328 // srl srlres,maskedoldval0,shiftamt
1329 // sll sllres,srlres,24
1330 // sra dest,sllres,24
1332 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1334 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1335 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1336 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1337 .addReg(SrlRes).addImm(ShiftImm);
1338 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1339 .addReg(SllRes).addImm(ShiftImm);
1341 MI->eraseFromParent(); // The instruction is gone now.
1346 //===----------------------------------------------------------------------===//
1347 // Misc Lower Operation implementation
1348 //===----------------------------------------------------------------------===//
1349 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1350 SDValue Chain = Op.getOperand(0);
1351 SDValue Table = Op.getOperand(1);
1352 SDValue Index = Op.getOperand(2);
1354 EVT PTy = getPointerTy();
1355 unsigned EntrySize =
1356 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1358 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1359 DAG.getConstant(EntrySize, PTy));
1360 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1362 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1363 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1364 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1366 Chain = Addr.getValue(1);
1368 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1369 // For PIC, the sequence is:
1370 // BRIND(load(Jumptable + index) + RelocBase)
1371 // RelocBase can be JumpTable, GOT or some sort of global base.
1372 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1373 getPICJumpTableRelocBase(Table, DAG));
1376 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1379 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1380 // The first operand is the chain, the second is the condition, the third is
1381 // the block to branch to if the condition is true.
1382 SDValue Chain = Op.getOperand(0);
1383 SDValue Dest = Op.getOperand(2);
1386 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1388 // Return if flag is not set by a floating point comparison.
1389 if (CondRes.getOpcode() != MipsISD::FPCmp)
1392 SDValue CCNode = CondRes.getOperand(2);
1394 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1395 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1396 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1397 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1398 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1399 FCC0, Dest, CondRes);
1402 SDValue MipsTargetLowering::
1403 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1405 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1407 // Return if flag is not set by a floating point comparison.
1408 if (Cond.getOpcode() != MipsISD::FPCmp)
1411 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1415 SDValue MipsTargetLowering::
1416 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1419 EVT Ty = Op.getOperand(0).getValueType();
1420 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1421 getSetCCResultType(*DAG.getContext(), Ty),
1422 Op.getOperand(0), Op.getOperand(1),
1425 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1429 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1430 SDValue Cond = createFPCmp(DAG, Op);
1432 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1433 "Floating point operand expected.");
1435 SDValue True = DAG.getConstant(1, MVT::i32);
1436 SDValue False = DAG.getConstant(0, MVT::i32);
1438 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1441 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1442 SelectionDAG &DAG) const {
1443 // FIXME there isn't actually debug info here
1445 EVT Ty = Op.getValueType();
1446 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1447 const GlobalValue *GV = N->getGlobal();
1449 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1450 const MipsTargetObjectFile &TLOF =
1451 (const MipsTargetObjectFile&)getObjFileLowering();
1453 // %gp_rel relocation
1454 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1455 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1457 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1458 DAG.getVTList(MVT::i32), &GA, 1);
1459 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1460 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1463 // %hi/%lo relocation
1464 return getAddrNonPIC(N, Ty, DAG);
1467 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1468 return getAddrLocal(N, Ty, DAG, HasMips64);
1471 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1472 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1473 MachinePointerInfo::getGOT());
1475 return getAddrGlobal(N, Ty, DAG,
1476 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16,
1477 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1480 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1481 SelectionDAG &DAG) const {
1482 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1483 EVT Ty = Op.getValueType();
1485 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1486 return getAddrNonPIC(N, Ty, DAG);
1488 return getAddrLocal(N, Ty, DAG, HasMips64);
1491 SDValue MipsTargetLowering::
1492 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1494 // If the relocation model is PIC, use the General Dynamic TLS Model or
1495 // Local Dynamic TLS model, otherwise use the Initial Exec or
1496 // Local Exec TLS Model.
1498 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1500 const GlobalValue *GV = GA->getGlobal();
1501 EVT PtrVT = getPointerTy();
1503 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1505 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1506 // General Dynamic and Local Dynamic TLS Model.
1507 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1510 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1511 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1512 getGlobalReg(DAG, PtrVT), TGA);
1513 unsigned PtrSize = PtrVT.getSizeInBits();
1514 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1516 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1520 Entry.Node = Argument;
1522 Args.push_back(Entry);
1524 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1525 false, false, false, false, 0, CallingConv::C,
1526 /*IsTailCall=*/false, /*doesNotRet=*/false,
1527 /*isReturnValueUsed=*/true,
1528 TlsGetAddr, Args, DAG, DL);
1529 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1531 SDValue Ret = CallResult.first;
1533 if (model != TLSModel::LocalDynamic)
1536 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1537 MipsII::MO_DTPREL_HI);
1538 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1539 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1540 MipsII::MO_DTPREL_LO);
1541 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1542 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1543 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1547 if (model == TLSModel::InitialExec) {
1548 // Initial Exec TLS Model
1549 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1550 MipsII::MO_GOTTPREL);
1551 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1553 Offset = DAG.getLoad(PtrVT, DL,
1554 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1555 false, false, false, 0);
1557 // Local Exec TLS Model
1558 assert(model == TLSModel::LocalExec);
1559 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1560 MipsII::MO_TPREL_HI);
1561 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1562 MipsII::MO_TPREL_LO);
1563 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1564 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1565 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1568 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1569 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1572 SDValue MipsTargetLowering::
1573 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1575 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1576 EVT Ty = Op.getValueType();
1578 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1579 return getAddrNonPIC(N, Ty, DAG);
1581 return getAddrLocal(N, Ty, DAG, HasMips64);
1584 SDValue MipsTargetLowering::
1585 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1587 // gp_rel relocation
1588 // FIXME: we should reference the constant pool using small data sections,
1589 // but the asm printer currently doesn't support this feature without
1590 // hacking it. This feature should come soon so we can uncomment the
1592 //if (IsInSmallSection(C->getType())) {
1593 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1594 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1595 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1596 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1597 EVT Ty = Op.getValueType();
1599 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1600 return getAddrNonPIC(N, Ty, DAG);
1602 return getAddrLocal(N, Ty, DAG, HasMips64);
1605 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1606 MachineFunction &MF = DAG.getMachineFunction();
1607 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1610 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1613 // vastart just stores the address of the VarArgsFrameIndex slot into the
1614 // memory location argument.
1615 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1616 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1617 MachinePointerInfo(SV), false, false, 0);
1620 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1621 bool HasExtractInsert) {
1622 EVT TyX = Op.getOperand(0).getValueType();
1623 EVT TyY = Op.getOperand(1).getValueType();
1624 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1625 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1629 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1631 SDValue X = (TyX == MVT::f32) ?
1632 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1633 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1635 SDValue Y = (TyY == MVT::f32) ?
1636 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1637 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1640 if (HasExtractInsert) {
1641 // ext E, Y, 31, 1 ; extract bit31 of Y
1642 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1643 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1644 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1647 // srl SrlX, SllX, 1
1649 // sll SllY, SrlX, 31
1650 // or Or, SrlX, SllY
1651 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1652 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1653 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1654 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1655 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1658 if (TyX == MVT::f32)
1659 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1661 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1662 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1663 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1666 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1667 bool HasExtractInsert) {
1668 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1669 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1670 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1671 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1674 // Bitcast to integer nodes.
1675 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1676 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1678 if (HasExtractInsert) {
1679 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1680 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1681 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1682 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1684 if (WidthX > WidthY)
1685 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1686 else if (WidthY > WidthX)
1687 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1689 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1690 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1691 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1694 // (d)sll SllX, X, 1
1695 // (d)srl SrlX, SllX, 1
1696 // (d)srl SrlY, Y, width(Y)-1
1697 // (d)sll SllY, SrlX, width(Y)-1
1698 // or Or, SrlX, SllY
1699 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1700 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1701 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1702 DAG.getConstant(WidthY - 1, MVT::i32));
1704 if (WidthX > WidthY)
1705 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1706 else if (WidthY > WidthX)
1707 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1709 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1710 DAG.getConstant(WidthX - 1, MVT::i32));
1711 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1712 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1716 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1717 if (Subtarget->hasMips64())
1718 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasExtractInsert());
1720 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasExtractInsert());
1723 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG,
1724 bool HasExtractInsert) {
1725 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1728 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1730 SDValue X = (Op.getValueType() == MVT::f32) ?
1731 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1732 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1736 if (HasExtractInsert)
1737 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1738 DAG.getRegister(Mips::ZERO, MVT::i32),
1739 DAG.getConstant(31, MVT::i32), Const1, X);
1741 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1742 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1745 if (Op.getValueType() == MVT::f32)
1746 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1748 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1749 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1750 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1753 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG,
1754 bool HasExtractInsert) {
1755 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1758 // Bitcast to integer node.
1759 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1762 if (HasExtractInsert)
1763 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1764 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1765 DAG.getConstant(63, MVT::i32), Const1, X);
1767 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1768 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1771 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1775 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1776 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1777 return lowerFABS64(Op, DAG, Subtarget->hasExtractInsert());
1779 return lowerFABS32(Op, DAG, Subtarget->hasExtractInsert());
1782 SDValue MipsTargetLowering::
1783 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1785 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1786 "Frame address can only be determined for current frame.");
1788 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1789 MFI->setFrameAddressIsTaken(true);
1790 EVT VT = Op.getValueType();
1792 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1793 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1797 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1798 SelectionDAG &DAG) const {
1800 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1801 "Return address can be determined only for current frame.");
1803 MachineFunction &MF = DAG.getMachineFunction();
1804 MachineFrameInfo *MFI = MF.getFrameInfo();
1805 MVT VT = Op.getSimpleValueType();
1806 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1807 MFI->setReturnAddressIsTaken(true);
1809 // Return RA, which contains the return address. Mark it an implicit live-in.
1810 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1811 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1814 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1815 // generated from __builtin_eh_return (offset, handler)
1816 // The effect of this is to adjust the stack pointer by "offset"
1817 // and then branch to "handler".
1818 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1820 MachineFunction &MF = DAG.getMachineFunction();
1821 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1823 MipsFI->setCallsEhReturn();
1824 SDValue Chain = Op.getOperand(0);
1825 SDValue Offset = Op.getOperand(1);
1826 SDValue Handler = Op.getOperand(2);
1828 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1830 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1831 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1832 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1833 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1834 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1835 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1836 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1837 DAG.getRegister(OffsetReg, Ty),
1838 DAG.getRegister(AddrReg, getPointerTy()),
1842 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1843 SelectionDAG &DAG) const {
1844 // FIXME: Need pseudo-fence for 'singlethread' fences
1845 // FIXME: Set SType for weaker fences where supported/appropriate.
1848 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1849 DAG.getConstant(SType, MVT::i32));
1852 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1853 SelectionDAG &DAG) const {
1855 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1856 SDValue Shamt = Op.getOperand(2);
1859 // lo = (shl lo, shamt)
1860 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1863 // hi = (shl lo, shamt[4:0])
1864 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1865 DAG.getConstant(-1, MVT::i32));
1866 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1867 DAG.getConstant(1, MVT::i32));
1868 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1870 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1871 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1872 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1873 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1874 DAG.getConstant(0x20, MVT::i32));
1875 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1876 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1877 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1879 SDValue Ops[2] = {Lo, Hi};
1880 return DAG.getMergeValues(Ops, 2, DL);
1883 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1886 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1887 SDValue Shamt = Op.getOperand(2);
1890 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1892 // hi = (sra hi, shamt)
1894 // hi = (srl hi, shamt)
1897 // lo = (sra hi, shamt[4:0])
1898 // hi = (sra hi, 31)
1900 // lo = (srl hi, shamt[4:0])
1902 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1903 DAG.getConstant(-1, MVT::i32));
1904 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1905 DAG.getConstant(1, MVT::i32));
1906 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1907 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1908 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1909 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1911 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1912 DAG.getConstant(0x20, MVT::i32));
1913 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1914 DAG.getConstant(31, MVT::i32));
1915 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1916 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1917 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1920 SDValue Ops[2] = {Lo, Hi};
1921 return DAG.getMergeValues(Ops, 2, DL);
1924 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1925 SDValue Chain, SDValue Src, unsigned Offset) {
1926 SDValue Ptr = LD->getBasePtr();
1927 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1928 EVT BasePtrVT = Ptr.getValueType();
1930 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1933 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1934 DAG.getConstant(Offset, BasePtrVT));
1936 SDValue Ops[] = { Chain, Ptr, Src };
1937 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1938 LD->getMemOperand());
1941 // Expand an unaligned 32 or 64-bit integer load node.
1942 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1943 LoadSDNode *LD = cast<LoadSDNode>(Op);
1944 EVT MemVT = LD->getMemoryVT();
1946 // Return if load is aligned or if MemVT is neither i32 nor i64.
1947 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1948 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1951 bool IsLittle = Subtarget->isLittle();
1952 EVT VT = Op.getValueType();
1953 ISD::LoadExtType ExtType = LD->getExtensionType();
1954 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1956 assert((VT == MVT::i32) || (VT == MVT::i64));
1959 // (set dst, (i64 (load baseptr)))
1961 // (set tmp, (ldl (add baseptr, 7), undef))
1962 // (set dst, (ldr baseptr, tmp))
1963 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1964 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1966 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1970 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1972 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1976 // (set dst, (i32 (load baseptr))) or
1977 // (set dst, (i64 (sextload baseptr))) or
1978 // (set dst, (i64 (extload baseptr)))
1980 // (set tmp, (lwl (add baseptr, 3), undef))
1981 // (set dst, (lwr baseptr, tmp))
1982 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1983 (ExtType == ISD::EXTLOAD))
1986 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1989 // (set dst, (i64 (zextload baseptr)))
1991 // (set tmp0, (lwl (add baseptr, 3), undef))
1992 // (set tmp1, (lwr baseptr, tmp0))
1993 // (set tmp2, (shl tmp1, 32))
1994 // (set dst, (srl tmp2, 32))
1996 SDValue Const32 = DAG.getConstant(32, MVT::i32);
1997 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1998 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
1999 SDValue Ops[] = { SRL, LWR.getValue(1) };
2000 return DAG.getMergeValues(Ops, 2, DL);
2003 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2004 SDValue Chain, unsigned Offset) {
2005 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2006 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2008 SDVTList VTList = DAG.getVTList(MVT::Other);
2011 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2012 DAG.getConstant(Offset, BasePtrVT));
2014 SDValue Ops[] = { Chain, Value, Ptr };
2015 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2016 SD->getMemOperand());
2019 // Expand an unaligned 32 or 64-bit integer store node.
2020 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2022 SDValue Value = SD->getValue(), Chain = SD->getChain();
2023 EVT VT = Value.getValueType();
2026 // (store val, baseptr) or
2027 // (truncstore val, baseptr)
2029 // (swl val, (add baseptr, 3))
2030 // (swr val, baseptr)
2031 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2032 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2034 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2037 assert(VT == MVT::i64);
2040 // (store val, baseptr)
2042 // (sdl val, (add baseptr, 7))
2043 // (sdr val, baseptr)
2044 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2045 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2048 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2049 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2050 SDValue Val = SD->getValue();
2052 if (Val.getOpcode() != ISD::FP_TO_SINT)
2055 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2056 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2059 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2060 SD->getPointerInfo(), SD->isVolatile(),
2061 SD->isNonTemporal(), SD->getAlignment());
2064 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2065 StoreSDNode *SD = cast<StoreSDNode>(Op);
2066 EVT MemVT = SD->getMemoryVT();
2068 // Lower unaligned integer stores.
2069 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2070 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2071 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2073 return lowerFP_TO_SINT_STORE(SD, DAG);
2076 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2077 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2078 || cast<ConstantSDNode>
2079 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2080 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2084 // (add (frameaddr 0), (frame_to_args_offset))
2085 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2086 // (add FrameObject, 0)
2087 // where FrameObject is a fixed StackObject with offset 0 which points to
2088 // the old stack pointer.
2089 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2090 EVT ValTy = Op->getValueType(0);
2091 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2092 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2093 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2094 DAG.getConstant(0, ValTy));
2097 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2098 SelectionDAG &DAG) const {
2099 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2100 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2102 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2105 //===----------------------------------------------------------------------===//
2106 // Calling Convention Implementation
2107 //===----------------------------------------------------------------------===//
2109 //===----------------------------------------------------------------------===//
2110 // TODO: Implement a generic logic using tblgen that can support this.
2111 // Mips O32 ABI rules:
2113 // i32 - Passed in A0, A1, A2, A3 and stack
2114 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2115 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2116 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2117 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2118 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2121 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2122 //===----------------------------------------------------------------------===//
2124 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2125 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2126 CCState &State, const uint16_t *F64Regs) {
2128 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2130 static const uint16_t IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2131 static const uint16_t F32Regs[] = { Mips::F12, Mips::F14 };
2133 // Do not process byval args here.
2134 if (ArgFlags.isByVal())
2137 // Promote i8 and i16
2138 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2140 if (ArgFlags.isSExt())
2141 LocInfo = CCValAssign::SExt;
2142 else if (ArgFlags.isZExt())
2143 LocInfo = CCValAssign::ZExt;
2145 LocInfo = CCValAssign::AExt;
2150 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2151 // is true: function is vararg, argument is 3rd or higher, there is previous
2152 // argument which is not f32 or f64.
2153 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2154 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2155 unsigned OrigAlign = ArgFlags.getOrigAlign();
2156 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2158 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2159 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2160 // If this is the first part of an i64 arg,
2161 // the allocated register must be either A0 or A2.
2162 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2163 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2165 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2166 // Allocate int register and shadow next int register. If first
2167 // available register is Mips::A1 or Mips::A3, shadow it too.
2168 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2169 if (Reg == Mips::A1 || Reg == Mips::A3)
2170 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2171 State.AllocateReg(IntRegs, IntRegsSize);
2173 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2174 // we are guaranteed to find an available float register
2175 if (ValVT == MVT::f32) {
2176 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2177 // Shadow int register
2178 State.AllocateReg(IntRegs, IntRegsSize);
2180 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2181 // Shadow int registers
2182 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2183 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2184 State.AllocateReg(IntRegs, IntRegsSize);
2185 State.AllocateReg(IntRegs, IntRegsSize);
2188 llvm_unreachable("Cannot handle this ValVT.");
2191 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2193 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2195 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2200 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2201 MVT LocVT, CCValAssign::LocInfo LocInfo,
2202 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2203 static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2205 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2208 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2209 MVT LocVT, CCValAssign::LocInfo LocInfo,
2210 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2211 static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2213 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2216 #include "MipsGenCallingConv.inc"
2218 //===----------------------------------------------------------------------===//
2219 // Call Calling Convention Implementation
2220 //===----------------------------------------------------------------------===//
2222 // Return next O32 integer argument register.
2223 static unsigned getNextIntArgReg(unsigned Reg) {
2224 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2225 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2229 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2230 SDValue Chain, SDValue Arg, SDLoc DL,
2231 bool IsTailCall, SelectionDAG &DAG) const {
2233 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2234 DAG.getIntPtrConstant(Offset));
2235 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2239 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2240 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2241 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2242 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2243 /*isVolatile=*/ true, false, 0);
2246 void MipsTargetLowering::
2247 getOpndList(SmallVectorImpl<SDValue> &Ops,
2248 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2249 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2250 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2251 // Insert node "GP copy globalreg" before call to function.
2253 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2254 // in PIC mode) allow symbols to be resolved via lazy binding.
2255 // The lazy binding stub requires GP to point to the GOT.
2256 if (IsPICCall && !InternalLinkage) {
2257 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2258 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2259 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2262 // Build a sequence of copy-to-reg nodes chained together with token
2263 // chain and flag operands which copy the outgoing args into registers.
2264 // The InFlag in necessary since all emitted instructions must be
2268 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2269 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2270 RegsToPass[i].second, InFlag);
2271 InFlag = Chain.getValue(1);
2274 // Add argument registers to the end of the list so that they are
2275 // known live into the call.
2276 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2277 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2278 RegsToPass[i].second.getValueType()));
2280 // Add a register mask operand representing the call-preserved registers.
2281 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2282 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2283 assert(Mask && "Missing call preserved mask for calling convention");
2284 if (Subtarget->inMips16HardFloat()) {
2285 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2286 llvm::StringRef Sym = G->getGlobal()->getName();
2287 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2288 if (F->hasFnAttribute("__Mips16RetHelper")) {
2289 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2293 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2295 if (InFlag.getNode())
2296 Ops.push_back(InFlag);
2299 /// LowerCall - functions arguments are copied from virtual regs to
2300 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2302 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2303 SmallVectorImpl<SDValue> &InVals) const {
2304 SelectionDAG &DAG = CLI.DAG;
2306 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2307 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2308 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2309 SDValue Chain = CLI.Chain;
2310 SDValue Callee = CLI.Callee;
2311 bool &IsTailCall = CLI.IsTailCall;
2312 CallingConv::ID CallConv = CLI.CallConv;
2313 bool IsVarArg = CLI.IsVarArg;
2315 MachineFunction &MF = DAG.getMachineFunction();
2316 MachineFrameInfo *MFI = MF.getFrameInfo();
2317 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2318 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2319 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2321 // Analyze operands of the call, assigning locations to each operand.
2322 SmallVector<CCValAssign, 16> ArgLocs;
2323 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2324 getTargetMachine(), ArgLocs, *DAG.getContext());
2325 MipsCC::SpecialCallingConvType SpecialCallingConv =
2326 getSpecialCallingConv(Callee);
2327 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2328 SpecialCallingConv);
2330 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2331 Subtarget->mipsSEUsesSoftFloat(),
2332 Callee.getNode(), CLI.Args);
2334 // Get a count of how many bytes are to be pushed on the stack.
2335 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2337 // Check if it's really possible to do a tail call.
2340 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2341 *MF.getInfo<MipsFunctionInfo>());
2346 // Chain is the output chain of the last Load/Store or CopyToReg node.
2347 // ByValChain is the output chain of the last Memcpy node created for copying
2348 // byval arguments to the stack.
2349 unsigned StackAlignment = TFL->getStackAlignment();
2350 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2351 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2354 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2356 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2357 IsN64 ? Mips::SP_64 : Mips::SP,
2360 // With EABI is it possible to have 16 args on registers.
2361 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2362 SmallVector<SDValue, 8> MemOpChains;
2363 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2365 // Walk the register/memloc assignments, inserting copies/loads.
2366 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2367 SDValue Arg = OutVals[i];
2368 CCValAssign &VA = ArgLocs[i];
2369 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2370 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2373 if (Flags.isByVal()) {
2374 assert(Flags.getByValSize() &&
2375 "ByVal args of size 0 should have been ignored by front-end.");
2376 assert(ByValArg != MipsCCInfo.byval_end());
2377 assert(!IsTailCall &&
2378 "Do not tail-call optimize if there is a byval argument.");
2379 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2380 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2385 // Promote the value if needed.
2386 switch (VA.getLocInfo()) {
2387 default: llvm_unreachable("Unknown loc info!");
2388 case CCValAssign::Full:
2389 if (VA.isRegLoc()) {
2390 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2391 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2392 (ValVT == MVT::i64 && LocVT == MVT::f64))
2393 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2394 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2395 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2396 Arg, DAG.getConstant(0, MVT::i32));
2397 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2398 Arg, DAG.getConstant(1, MVT::i32));
2399 if (!Subtarget->isLittle())
2401 unsigned LocRegLo = VA.getLocReg();
2402 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2403 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2404 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2409 case CCValAssign::SExt:
2410 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2412 case CCValAssign::ZExt:
2413 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2415 case CCValAssign::AExt:
2416 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2420 // Arguments that can be passed on register must be kept at
2421 // RegsToPass vector
2422 if (VA.isRegLoc()) {
2423 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2427 // Register can't get to this point...
2428 assert(VA.isMemLoc());
2430 // emit ISD::STORE whichs stores the
2431 // parameter value to a stack Location
2432 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2433 Chain, Arg, DL, IsTailCall, DAG));
2436 // Transform all store nodes into one single node because all store
2437 // nodes are independent of each other.
2438 if (!MemOpChains.empty())
2439 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2440 &MemOpChains[0], MemOpChains.size());
2442 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2443 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2444 // node so that legalize doesn't hack it.
2445 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2446 bool GlobalOrExternal = false, InternalLinkage = false;
2448 EVT Ty = Callee.getValueType();
2450 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2452 const GlobalValue *Val = G->getGlobal();
2453 InternalLinkage = Val->hasInternalLinkage();
2455 if (InternalLinkage)
2456 Callee = getAddrLocal(G, Ty, DAG, HasMips64);
2458 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2459 MipsII::MO_CALL_LO16, Chain,
2460 FuncInfo->callPtrInfo(Val));
2462 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2463 FuncInfo->callPtrInfo(Val));
2465 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2466 MipsII::MO_NO_FLAG);
2467 GlobalOrExternal = true;
2469 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2470 const char *Sym = S->getSymbol();
2472 if (!IsN64 && !IsPIC) // !N64 && static
2473 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2474 MipsII::MO_NO_FLAG);
2476 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2477 MipsII::MO_CALL_LO16, Chain,
2478 FuncInfo->callPtrInfo(Sym));
2480 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2481 FuncInfo->callPtrInfo(Sym));
2483 GlobalOrExternal = true;
2486 SmallVector<SDValue, 8> Ops(1, Chain);
2487 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2489 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2490 CLI, Callee, Chain);
2493 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2495 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2496 SDValue InFlag = Chain.getValue(1);
2498 // Create the CALLSEQ_END node.
2499 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2500 DAG.getIntPtrConstant(0, true), InFlag, DL);
2501 InFlag = Chain.getValue(1);
2503 // Handle result values, copying them out of physregs into vregs that we
2505 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2506 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2509 /// LowerCallResult - Lower the result values of a call into the
2510 /// appropriate copies out of appropriate physical registers.
2512 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2513 CallingConv::ID CallConv, bool IsVarArg,
2514 const SmallVectorImpl<ISD::InputArg> &Ins,
2515 SDLoc DL, SelectionDAG &DAG,
2516 SmallVectorImpl<SDValue> &InVals,
2517 const SDNode *CallNode,
2518 const Type *RetTy) const {
2519 // Assign locations to each value returned by this call.
2520 SmallVector<CCValAssign, 16> RVLocs;
2521 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2522 getTargetMachine(), RVLocs, *DAG.getContext());
2523 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2525 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2528 // Copy all of the result registers out of their specified physreg.
2529 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2530 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2531 RVLocs[i].getLocVT(), InFlag);
2532 Chain = Val.getValue(1);
2533 InFlag = Val.getValue(2);
2535 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2536 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2538 InVals.push_back(Val);
2544 //===----------------------------------------------------------------------===//
2545 // Formal Arguments Calling Convention Implementation
2546 //===----------------------------------------------------------------------===//
2547 /// LowerFormalArguments - transform physical registers into virtual registers
2548 /// and generate load operations for arguments places on the stack.
2550 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2551 CallingConv::ID CallConv,
2553 const SmallVectorImpl<ISD::InputArg> &Ins,
2554 SDLoc DL, SelectionDAG &DAG,
2555 SmallVectorImpl<SDValue> &InVals)
2557 MachineFunction &MF = DAG.getMachineFunction();
2558 MachineFrameInfo *MFI = MF.getFrameInfo();
2559 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2561 MipsFI->setVarArgsFrameIndex(0);
2563 // Used with vargs to acumulate store chains.
2564 std::vector<SDValue> OutChains;
2566 // Assign locations to all of the incoming arguments.
2567 SmallVector<CCValAssign, 16> ArgLocs;
2568 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2569 getTargetMachine(), ArgLocs, *DAG.getContext());
2570 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2571 Function::const_arg_iterator FuncArg =
2572 DAG.getMachineFunction().getFunction()->arg_begin();
2573 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2575 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2576 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2577 MipsCCInfo.hasByValArg());
2579 unsigned CurArgIdx = 0;
2580 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2582 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2583 CCValAssign &VA = ArgLocs[i];
2584 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2585 CurArgIdx = Ins[i].OrigArgIndex;
2586 EVT ValVT = VA.getValVT();
2587 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2588 bool IsRegLoc = VA.isRegLoc();
2590 if (Flags.isByVal()) {
2591 assert(Flags.getByValSize() &&
2592 "ByVal args of size 0 should have been ignored by front-end.");
2593 assert(ByValArg != MipsCCInfo.byval_end());
2594 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2595 MipsCCInfo, *ByValArg);
2600 // Arguments stored on registers
2602 MVT RegVT = VA.getLocVT();
2603 unsigned ArgReg = VA.getLocReg();
2604 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2606 // Transform the arguments stored on
2607 // physical registers into virtual ones
2608 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2609 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2611 // If this is an 8 or 16-bit value, it has been passed promoted
2612 // to 32 bits. Insert an assert[sz]ext to capture this, then
2613 // truncate to the right size.
2614 if (VA.getLocInfo() != CCValAssign::Full) {
2615 unsigned Opcode = 0;
2616 if (VA.getLocInfo() == CCValAssign::SExt)
2617 Opcode = ISD::AssertSext;
2618 else if (VA.getLocInfo() == CCValAssign::ZExt)
2619 Opcode = ISD::AssertZext;
2621 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2622 DAG.getValueType(ValVT));
2623 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2626 // Handle floating point arguments passed in integer registers and
2627 // long double arguments passed in floating point registers.
2628 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2629 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2630 (RegVT == MVT::f64 && ValVT == MVT::i64))
2631 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2632 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2633 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2634 getNextIntArgReg(ArgReg), RC);
2635 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2636 if (!Subtarget->isLittle())
2637 std::swap(ArgValue, ArgValue2);
2638 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2639 ArgValue, ArgValue2);
2642 InVals.push_back(ArgValue);
2643 } else { // VA.isRegLoc()
2646 assert(VA.isMemLoc());
2648 // The stack pointer offset is relative to the caller stack frame.
2649 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2650 VA.getLocMemOffset(), true);
2652 // Create load nodes to retrieve arguments from the stack
2653 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2654 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2655 MachinePointerInfo::getFixedStack(FI),
2656 false, false, false, 0);
2657 InVals.push_back(Load);
2658 OutChains.push_back(Load.getValue(1));
2662 // The mips ABIs for returning structs by value requires that we copy
2663 // the sret argument into $v0 for the return. Save the argument into
2664 // a virtual register so that we can access it from the return points.
2665 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2666 unsigned Reg = MipsFI->getSRetReturnReg();
2668 Reg = MF.getRegInfo().
2669 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2670 MipsFI->setSRetReturnReg(Reg);
2672 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2673 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2677 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2679 // All stores are grouped in one node to allow the matching between
2680 // the size of Ins and InVals. This only happens when on varg functions
2681 if (!OutChains.empty()) {
2682 OutChains.push_back(Chain);
2683 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2684 &OutChains[0], OutChains.size());
2690 //===----------------------------------------------------------------------===//
2691 // Return Value Calling Convention Implementation
2692 //===----------------------------------------------------------------------===//
2695 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2696 MachineFunction &MF, bool IsVarArg,
2697 const SmallVectorImpl<ISD::OutputArg> &Outs,
2698 LLVMContext &Context) const {
2699 SmallVector<CCValAssign, 16> RVLocs;
2700 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2702 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2706 MipsTargetLowering::LowerReturn(SDValue Chain,
2707 CallingConv::ID CallConv, bool IsVarArg,
2708 const SmallVectorImpl<ISD::OutputArg> &Outs,
2709 const SmallVectorImpl<SDValue> &OutVals,
2710 SDLoc DL, SelectionDAG &DAG) const {
2711 // CCValAssign - represent the assignment of
2712 // the return value to a location
2713 SmallVector<CCValAssign, 16> RVLocs;
2714 MachineFunction &MF = DAG.getMachineFunction();
2716 // CCState - Info about the registers and stack slot.
2717 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2719 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2721 // Analyze return values.
2722 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2723 MF.getFunction()->getReturnType());
2726 SmallVector<SDValue, 4> RetOps(1, Chain);
2728 // Copy the result values into the output registers.
2729 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2730 SDValue Val = OutVals[i];
2731 CCValAssign &VA = RVLocs[i];
2732 assert(VA.isRegLoc() && "Can only return in registers!");
2734 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2735 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2737 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2739 // Guarantee that all emitted copies are stuck together with flags.
2740 Flag = Chain.getValue(1);
2741 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2744 // The mips ABIs for returning structs by value requires that we copy
2745 // the sret argument into $v0 for the return. We saved the argument into
2746 // a virtual register in the entry block, so now we copy the value out
2748 if (MF.getFunction()->hasStructRetAttr()) {
2749 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2750 unsigned Reg = MipsFI->getSRetReturnReg();
2753 llvm_unreachable("sret virtual register not created in the entry block");
2754 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2755 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2757 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2758 Flag = Chain.getValue(1);
2759 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2762 RetOps[0] = Chain; // Update chain.
2764 // Add the flag if we have it.
2766 RetOps.push_back(Flag);
2768 // Return on Mips is always a "jr $ra"
2769 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2772 //===----------------------------------------------------------------------===//
2773 // Mips Inline Assembly Support
2774 //===----------------------------------------------------------------------===//
2776 /// getConstraintType - Given a constraint letter, return the type of
2777 /// constraint it is for this target.
2778 MipsTargetLowering::ConstraintType MipsTargetLowering::
2779 getConstraintType(const std::string &Constraint) const
2781 // Mips specific constraints
2782 // GCC config/mips/constraints.md
2784 // 'd' : An address register. Equivalent to r
2785 // unless generating MIPS16 code.
2786 // 'y' : Equivalent to r; retained for
2787 // backwards compatibility.
2788 // 'c' : A register suitable for use in an indirect
2789 // jump. This will always be $25 for -mabicalls.
2790 // 'l' : The lo register. 1 word storage.
2791 // 'x' : The hilo register pair. Double word storage.
2792 if (Constraint.size() == 1) {
2793 switch (Constraint[0]) {
2801 return C_RegisterClass;
2806 return TargetLowering::getConstraintType(Constraint);
2809 /// Examine constraint type and operand type and determine a weight value.
2810 /// This object must already have been set up with the operand type
2811 /// and the current alternative constraint selected.
2812 TargetLowering::ConstraintWeight
2813 MipsTargetLowering::getSingleConstraintMatchWeight(
2814 AsmOperandInfo &info, const char *constraint) const {
2815 ConstraintWeight weight = CW_Invalid;
2816 Value *CallOperandVal = info.CallOperandVal;
2817 // If we don't have a value, we can't do a match,
2818 // but allow it at the lowest weight.
2819 if (CallOperandVal == NULL)
2821 Type *type = CallOperandVal->getType();
2822 // Look at the constraint type.
2823 switch (*constraint) {
2825 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2829 if (type->isIntegerTy())
2830 weight = CW_Register;
2832 case 'f': // FPU or MSA register
2833 if (Subtarget->hasMSA() && type->isVectorTy() &&
2834 cast<VectorType>(type)->getBitWidth() == 128)
2835 weight = CW_Register;
2836 else if (type->isFloatTy())
2837 weight = CW_Register;
2839 case 'c': // $25 for indirect jumps
2840 case 'l': // lo register
2841 case 'x': // hilo register pair
2842 if (type->isIntegerTy())
2843 weight = CW_SpecificReg;
2845 case 'I': // signed 16 bit immediate
2846 case 'J': // integer zero
2847 case 'K': // unsigned 16 bit immediate
2848 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2849 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2850 case 'O': // signed 15 bit immediate (+- 16383)
2851 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2852 if (isa<ConstantInt>(CallOperandVal))
2853 weight = CW_Constant;
2862 /// This is a helper function to parse a physical register string and split it
2863 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2864 /// that is returned indicates whether parsing was successful. The second flag
2865 /// is true if the numeric part exists.
2866 static std::pair<bool, bool>
2867 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2868 unsigned long long &Reg) {
2869 if (C.front() != '{' || C.back() != '}')
2870 return std::make_pair(false, false);
2872 // Search for the first numeric character.
2873 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2874 I = std::find_if(B, E, std::ptr_fun(isdigit));
2876 Prefix.assign(B, I - B);
2878 // The second flag is set to false if no numeric characters were found.
2880 return std::make_pair(true, false);
2882 // Parse the numeric characters.
2883 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2887 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2888 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2889 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2890 const TargetRegisterClass *RC;
2892 unsigned long long Reg;
2894 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2897 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2899 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2900 // No numeric characters follow "hi" or "lo".
2902 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2904 RC = TRI->getRegClass(Prefix == "hi" ?
2905 Mips::HI32RegClassID : Mips::LO32RegClassID);
2906 return std::make_pair(*(RC->begin()), RC);
2907 } else if (Prefix.compare(0, 4, "$msa") == 0) {
2908 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
2910 // No numeric characters follow the name.
2912 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2914 Reg = StringSwitch<unsigned long long>(Prefix)
2915 .Case("$msair", Mips::MSAIR)
2916 .Case("$msacsr", Mips::MSACSR)
2917 .Case("$msaaccess", Mips::MSAAccess)
2918 .Case("$msasave", Mips::MSASave)
2919 .Case("$msamodify", Mips::MSAModify)
2920 .Case("$msarequest", Mips::MSARequest)
2921 .Case("$msamap", Mips::MSAMap)
2922 .Case("$msaunmap", Mips::MSAUnmap)
2926 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2928 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
2929 return std::make_pair(Reg, RC);
2933 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2935 if (Prefix == "$f") { // Parse $f0-$f31.
2936 // If the size of FP registers is 64-bit or Reg is an even number, select
2937 // the 64-bit register class. Otherwise, select the 32-bit register class.
2938 if (VT == MVT::Other)
2939 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2941 RC = getRegClassFor(VT);
2943 if (RC == &Mips::AFGR64RegClass) {
2944 assert(Reg % 2 == 0);
2947 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
2948 RC = TRI->getRegClass(Mips::FCCRegClassID);
2949 else if (Prefix == "$w") { // Parse $w0-$w31.
2950 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
2951 } else { // Parse $0-$31.
2952 assert(Prefix == "$");
2953 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2956 assert(Reg < RC->getNumRegs());
2957 return std::make_pair(*(RC->begin() + Reg), RC);
2960 /// Given a register class constraint, like 'r', if this corresponds directly
2961 /// to an LLVM register class, return a register of 0 and the register class
2963 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2964 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2966 if (Constraint.size() == 1) {
2967 switch (Constraint[0]) {
2968 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2969 case 'y': // Same as 'r'. Exists for compatibility.
2971 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2972 if (Subtarget->inMips16Mode())
2973 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2974 return std::make_pair(0U, &Mips::GPR32RegClass);
2976 if (VT == MVT::i64 && !HasMips64)
2977 return std::make_pair(0U, &Mips::GPR32RegClass);
2978 if (VT == MVT::i64 && HasMips64)
2979 return std::make_pair(0U, &Mips::GPR64RegClass);
2980 // This will generate an error message
2981 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2982 case 'f': // FPU or MSA register
2983 if (VT == MVT::v16i8)
2984 return std::make_pair(0U, &Mips::MSA128BRegClass);
2985 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
2986 return std::make_pair(0U, &Mips::MSA128HRegClass);
2987 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2988 return std::make_pair(0U, &Mips::MSA128WRegClass);
2989 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2990 return std::make_pair(0U, &Mips::MSA128DRegClass);
2991 else if (VT == MVT::f32)
2992 return std::make_pair(0U, &Mips::FGR32RegClass);
2993 else if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2994 if (Subtarget->isFP64bit())
2995 return std::make_pair(0U, &Mips::FGR64RegClass);
2996 return std::make_pair(0U, &Mips::AFGR64RegClass);
2999 case 'c': // register suitable for indirect jump
3001 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3002 assert(VT == MVT::i64 && "Unexpected type.");
3003 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3004 case 'l': // register suitable for indirect jump
3006 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3007 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3008 case 'x': // register suitable for indirect jump
3009 // Fixme: Not triggering the use of both hi and low
3010 // This will generate an error message
3011 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3015 std::pair<unsigned, const TargetRegisterClass *> R;
3016 R = parseRegForInlineAsmConstraint(Constraint, VT);
3021 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3024 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3025 /// vector. If it is invalid, don't add anything to Ops.
3026 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3027 std::string &Constraint,
3028 std::vector<SDValue>&Ops,
3029 SelectionDAG &DAG) const {
3030 SDValue Result(0, 0);
3032 // Only support length 1 constraints for now.
3033 if (Constraint.length() > 1) return;
3035 char ConstraintLetter = Constraint[0];
3036 switch (ConstraintLetter) {
3037 default: break; // This will fall through to the generic implementation
3038 case 'I': // Signed 16 bit constant
3039 // If this fails, the parent routine will give an error
3040 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3041 EVT Type = Op.getValueType();
3042 int64_t Val = C->getSExtValue();
3043 if (isInt<16>(Val)) {
3044 Result = DAG.getTargetConstant(Val, Type);
3049 case 'J': // integer zero
3050 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3051 EVT Type = Op.getValueType();
3052 int64_t Val = C->getZExtValue();
3054 Result = DAG.getTargetConstant(0, Type);
3059 case 'K': // unsigned 16 bit immediate
3060 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3061 EVT Type = Op.getValueType();
3062 uint64_t Val = (uint64_t)C->getZExtValue();
3063 if (isUInt<16>(Val)) {
3064 Result = DAG.getTargetConstant(Val, Type);
3069 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3070 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3071 EVT Type = Op.getValueType();
3072 int64_t Val = C->getSExtValue();
3073 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3074 Result = DAG.getTargetConstant(Val, Type);
3079 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3080 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3081 EVT Type = Op.getValueType();
3082 int64_t Val = C->getSExtValue();
3083 if ((Val >= -65535) && (Val <= -1)) {
3084 Result = DAG.getTargetConstant(Val, Type);
3089 case 'O': // signed 15 bit immediate
3090 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3091 EVT Type = Op.getValueType();
3092 int64_t Val = C->getSExtValue();
3093 if ((isInt<15>(Val))) {
3094 Result = DAG.getTargetConstant(Val, Type);
3099 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3100 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3101 EVT Type = Op.getValueType();
3102 int64_t Val = C->getSExtValue();
3103 if ((Val <= 65535) && (Val >= 1)) {
3104 Result = DAG.getTargetConstant(Val, Type);
3111 if (Result.getNode()) {
3112 Ops.push_back(Result);
3116 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3119 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3121 // No global is ever allowed as a base.
3126 case 0: // "r+i" or just "i", depending on HasBaseReg.
3129 if (!AM.HasBaseReg) // allow "r+i".
3131 return false; // disallow "r+r" or "r+r+i".
3140 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3141 // The Mips target isn't yet aware of offsets.
3145 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3147 bool IsMemset, bool ZeroMemset,
3149 MachineFunction &MF) const {
3150 if (Subtarget->hasMips64())
3156 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3157 if (VT != MVT::f32 && VT != MVT::f64)
3159 if (Imm.isNegZero())
3161 return Imm.isZero();
3164 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3166 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3168 return TargetLowering::getJumpTableEncoding();
3171 /// This function returns true if CallSym is a long double emulation routine.
3172 static bool isF128SoftLibCall(const char *CallSym) {
3173 const char *const LibCalls[] =
3174 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3175 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3176 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3177 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3178 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3179 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3180 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3181 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3184 const char *const *End = LibCalls + array_lengthof(LibCalls);
3186 // Check that LibCalls is sorted alphabetically.
3187 MipsTargetLowering::LTStr Comp;
3190 for (const char *const *I = LibCalls; I < End - 1; ++I)
3191 assert(Comp(*I, *(I + 1)));
3194 return std::binary_search(LibCalls, End, CallSym, Comp);
3197 /// This function returns true if Ty is fp128 or i128 which was originally a
3199 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3200 if (Ty->isFP128Ty())
3203 const ExternalSymbolSDNode *ES =
3204 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3206 // If the Ty is i128 and the function being called is a long double emulation
3207 // routine, then the original type is f128.
3208 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3211 MipsTargetLowering::MipsCC::SpecialCallingConvType
3212 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3213 MipsCC::SpecialCallingConvType SpecialCallingConv =
3214 MipsCC::NoSpecialCallingConv;;
3215 if (Subtarget->inMips16HardFloat()) {
3216 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3217 llvm::StringRef Sym = G->getGlobal()->getName();
3218 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3219 if (F->hasFnAttribute("__Mips16RetHelper")) {
3220 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3224 return SpecialCallingConv;
3227 MipsTargetLowering::MipsCC::MipsCC(
3228 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3229 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3230 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3231 SpecialCallingConv(SpecialCallingConv_){
3232 // Pre-allocate reserved argument area.
3233 CCInfo.AllocateStack(reservedArgArea(), 1);
3237 void MipsTargetLowering::MipsCC::
3238 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3239 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3240 std::vector<ArgListEntry> &FuncArgs) {
3241 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3242 "CallingConv::Fast shouldn't be used for vararg functions.");
3244 unsigned NumOpnds = Args.size();
3245 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3247 for (unsigned I = 0; I != NumOpnds; ++I) {
3248 MVT ArgVT = Args[I].VT;
3249 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3252 if (ArgFlags.isByVal()) {
3253 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3257 if (IsVarArg && !Args[I].IsFixed)
3258 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3260 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3262 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3267 dbgs() << "Call operand #" << I << " has unhandled type "
3268 << EVT(ArgVT).getEVTString();
3270 llvm_unreachable(0);
3275 void MipsTargetLowering::MipsCC::
3276 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3277 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3278 unsigned NumArgs = Args.size();
3279 llvm::CCAssignFn *FixedFn = fixedArgFn();
3280 unsigned CurArgIdx = 0;
3282 for (unsigned I = 0; I != NumArgs; ++I) {
3283 MVT ArgVT = Args[I].VT;
3284 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3285 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3286 CurArgIdx = Args[I].OrigArgIndex;
3288 if (ArgFlags.isByVal()) {
3289 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3293 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3295 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3299 dbgs() << "Formal Arg #" << I << " has unhandled type "
3300 << EVT(ArgVT).getEVTString();
3302 llvm_unreachable(0);
3306 template<typename Ty>
3307 void MipsTargetLowering::MipsCC::
3308 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3309 const SDNode *CallNode, const Type *RetTy) const {
3312 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3313 Fn = RetCC_F128Soft;
3317 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3318 MVT VT = RetVals[I].VT;
3319 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3320 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3322 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3324 dbgs() << "Call result #" << I << " has unhandled type "
3325 << EVT(VT).getEVTString() << '\n';
3327 llvm_unreachable(0);
3332 void MipsTargetLowering::MipsCC::
3333 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3334 const SDNode *CallNode, const Type *RetTy) const {
3335 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3338 void MipsTargetLowering::MipsCC::
3339 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3340 const Type *RetTy) const {
3341 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3344 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3346 CCValAssign::LocInfo LocInfo,
3347 ISD::ArgFlagsTy ArgFlags) {
3348 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3350 struct ByValArgInfo ByVal;
3351 unsigned RegSize = regSize();
3352 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3353 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3356 if (useRegsForByval())
3357 allocateRegs(ByVal, ByValSize, Align);
3359 // Allocate space on caller's stack.
3360 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3362 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3364 ByValArgs.push_back(ByVal);
3367 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3368 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3371 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3372 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3375 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3376 return IsO32 ? O32IntRegs : Mips64IntRegs;
3379 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3380 if (CallConv == CallingConv::Fast)
3381 return CC_Mips_FastCC;
3383 if (SpecialCallingConv == Mips16RetHelperConv)
3384 return CC_Mips16RetHelper;
3385 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3388 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3389 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3392 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3393 return IsO32 ? O32IntRegs : Mips64DPRegs;
3396 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3399 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3400 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3401 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3402 "Byval argument's size and alignment should be a multiple of"
3405 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3407 // If Align > RegSize, the first arg register must be even.
3408 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3409 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3413 // Mark the registers allocated.
3414 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3415 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3416 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3419 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3420 const SDNode *CallNode,
3421 bool IsSoftFloat) const {
3422 if (IsSoftFloat || IsO32)
3425 // Check if the original type was fp128.
3426 if (originalTypeIsF128(OrigTy, CallNode)) {
3427 assert(VT == MVT::i64);
3434 void MipsTargetLowering::
3435 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3436 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3437 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3438 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3439 MachineFunction &MF = DAG.getMachineFunction();
3440 MachineFrameInfo *MFI = MF.getFrameInfo();
3441 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3442 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3446 FrameObjOffset = (int)CC.reservedArgArea() -
3447 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3449 FrameObjOffset = ByVal.Address;
3451 // Create frame object.
3452 EVT PtrTy = getPointerTy();
3453 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3454 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3455 InVals.push_back(FIN);
3460 // Copy arg registers.
3461 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3462 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3464 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3465 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3466 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3467 unsigned Offset = I * CC.regSize();
3468 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3469 DAG.getConstant(Offset, PtrTy));
3470 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3471 StorePtr, MachinePointerInfo(FuncArg, Offset),
3473 OutChains.push_back(Store);
3477 // Copy byVal arg to registers and stack.
3478 void MipsTargetLowering::
3479 passByValArg(SDValue Chain, SDLoc DL,
3480 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3481 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3482 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3483 const MipsCC &CC, const ByValArgInfo &ByVal,
3484 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3485 unsigned ByValSize = Flags.getByValSize();
3486 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3487 unsigned RegSize = CC.regSize();
3488 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3489 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3491 if (ByVal.NumRegs) {
3492 const uint16_t *ArgRegs = CC.intArgRegs();
3493 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3496 // Copy words to registers.
3497 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3498 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3499 DAG.getConstant(Offset, PtrTy));
3500 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3501 MachinePointerInfo(), false, false, false,
3503 MemOpChains.push_back(LoadVal.getValue(1));
3504 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3505 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3508 // Return if the struct has been fully copied.
3509 if (ByValSize == Offset)
3512 // Copy the remainder of the byval argument with sub-word loads and shifts.
3513 if (LeftoverBytes) {
3514 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3515 "Size of the remainder should be smaller than RegSize.");
3518 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3519 Offset < ByValSize; LoadSize /= 2) {
3520 unsigned RemSize = ByValSize - Offset;
3522 if (RemSize < LoadSize)
3526 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3527 DAG.getConstant(Offset, PtrTy));
3529 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3530 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3531 false, false, Alignment);
3532 MemOpChains.push_back(LoadVal.getValue(1));
3534 // Shift the loaded value.
3538 Shamt = TotalSizeLoaded;
3540 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3542 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3543 DAG.getConstant(Shamt, MVT::i32));
3546 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3551 TotalSizeLoaded += LoadSize;
3552 Alignment = std::min(Alignment, LoadSize);
3555 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3556 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3561 // Copy remainder of byval arg to it with memcpy.
3562 unsigned MemCpySize = ByValSize - Offset;
3563 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3564 DAG.getConstant(Offset, PtrTy));
3565 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3566 DAG.getIntPtrConstant(ByVal.Address));
3567 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3568 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3569 MachinePointerInfo(0), MachinePointerInfo(0));
3570 MemOpChains.push_back(Chain);
3573 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3574 const MipsCC &CC, SDValue Chain,
3575 SDLoc DL, SelectionDAG &DAG) const {
3576 unsigned NumRegs = CC.numIntArgRegs();
3577 const uint16_t *ArgRegs = CC.intArgRegs();
3578 const CCState &CCInfo = CC.getCCInfo();
3579 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3580 unsigned RegSize = CC.regSize();
3581 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3582 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3583 MachineFunction &MF = DAG.getMachineFunction();
3584 MachineFrameInfo *MFI = MF.getFrameInfo();
3585 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3587 // Offset of the first variable argument from stack pointer.
3591 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3593 VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3595 // Record the frame index of the first variable argument
3596 // which is a value necessary to VASTART.
3597 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3598 MipsFI->setVarArgsFrameIndex(FI);
3600 // Copy the integer registers that have not been used for argument passing
3601 // to the argument register save area. For O32, the save area is allocated
3602 // in the caller's stack frame, while for N32/64, it is allocated in the
3603 // callee's stack frame.
3604 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3605 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3606 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3607 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3608 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3609 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3610 MachinePointerInfo(), false, false, 0);
3611 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3612 OutChains.push_back(Store);