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 #include "MipsISelLowering.h"
15 #include "InstPrinter/MipsInstPrinter.h"
16 #include "MCTargetDesc/MipsBaseInfo.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsSubtarget.h"
19 #include "MipsTargetMachine.h"
20 #include "MipsTargetObjectFile.h"
21 #include "llvm/ADT/Statistic.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
41 #define DEBUG_TYPE "mips-lower"
43 STATISTIC(NumTailCalls, "Number of tail calls");
46 LargeGOT("mxgot", cl::Hidden,
47 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
50 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
51 cl::desc("MIPS: Don't trap on integer division by zero."),
55 EnableMipsFastISel("mips-fast-isel", cl::Hidden,
56 cl::desc("Allow mips-fast-isel to be used"),
59 static const MCPhysReg O32IntRegs[4] = {
60 Mips::A0, Mips::A1, Mips::A2, Mips::A3
63 static const MCPhysReg Mips64IntRegs[8] = {
64 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
65 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
68 static const MCPhysReg Mips64DPRegs[8] = {
69 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
70 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
73 // If I is a shifted mask, set the size (Size) and the first bit of the
74 // mask (Pos), and return true.
75 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
76 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
77 if (!isShiftedMask_64(I))
80 Size = CountPopulation_64(I);
81 Pos = countTrailingZeros(I);
85 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
86 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
87 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
90 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
92 unsigned Flag) const {
93 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
96 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
98 unsigned Flag) const {
99 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
102 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
104 unsigned Flag) const {
105 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
108 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
110 unsigned Flag) const {
111 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
114 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
116 unsigned Flag) const {
117 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
118 N->getOffset(), Flag);
121 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
123 case MipsISD::JmpLink: return "MipsISD::JmpLink";
124 case MipsISD::TailCall: return "MipsISD::TailCall";
125 case MipsISD::Hi: return "MipsISD::Hi";
126 case MipsISD::Lo: return "MipsISD::Lo";
127 case MipsISD::GPRel: return "MipsISD::GPRel";
128 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
129 case MipsISD::Ret: return "MipsISD::Ret";
130 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
131 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
132 case MipsISD::FPCmp: return "MipsISD::FPCmp";
133 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
134 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
135 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
136 case MipsISD::MFHI: return "MipsISD::MFHI";
137 case MipsISD::MFLO: return "MipsISD::MFLO";
138 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
139 case MipsISD::Mult: return "MipsISD::Mult";
140 case MipsISD::Multu: return "MipsISD::Multu";
141 case MipsISD::MAdd: return "MipsISD::MAdd";
142 case MipsISD::MAddu: return "MipsISD::MAddu";
143 case MipsISD::MSub: return "MipsISD::MSub";
144 case MipsISD::MSubu: return "MipsISD::MSubu";
145 case MipsISD::DivRem: return "MipsISD::DivRem";
146 case MipsISD::DivRemU: return "MipsISD::DivRemU";
147 case MipsISD::DivRem16: return "MipsISD::DivRem16";
148 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
149 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
150 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
151 case MipsISD::Wrapper: return "MipsISD::Wrapper";
152 case MipsISD::Sync: return "MipsISD::Sync";
153 case MipsISD::Ext: return "MipsISD::Ext";
154 case MipsISD::Ins: return "MipsISD::Ins";
155 case MipsISD::LWL: return "MipsISD::LWL";
156 case MipsISD::LWR: return "MipsISD::LWR";
157 case MipsISD::SWL: return "MipsISD::SWL";
158 case MipsISD::SWR: return "MipsISD::SWR";
159 case MipsISD::LDL: return "MipsISD::LDL";
160 case MipsISD::LDR: return "MipsISD::LDR";
161 case MipsISD::SDL: return "MipsISD::SDL";
162 case MipsISD::SDR: return "MipsISD::SDR";
163 case MipsISD::EXTP: return "MipsISD::EXTP";
164 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
165 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
166 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
167 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
168 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
169 case MipsISD::SHILO: return "MipsISD::SHILO";
170 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
171 case MipsISD::MULT: return "MipsISD::MULT";
172 case MipsISD::MULTU: return "MipsISD::MULTU";
173 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
174 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
175 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
176 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
177 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
178 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
179 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
180 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
181 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
182 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
183 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
184 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
185 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
186 case MipsISD::VCEQ: return "MipsISD::VCEQ";
187 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
188 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
189 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
190 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
191 case MipsISD::VSMAX: return "MipsISD::VSMAX";
192 case MipsISD::VSMIN: return "MipsISD::VSMIN";
193 case MipsISD::VUMAX: return "MipsISD::VUMAX";
194 case MipsISD::VUMIN: return "MipsISD::VUMIN";
195 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
196 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
197 case MipsISD::VNOR: return "MipsISD::VNOR";
198 case MipsISD::VSHF: return "MipsISD::VSHF";
199 case MipsISD::SHF: return "MipsISD::SHF";
200 case MipsISD::ILVEV: return "MipsISD::ILVEV";
201 case MipsISD::ILVOD: return "MipsISD::ILVOD";
202 case MipsISD::ILVL: return "MipsISD::ILVL";
203 case MipsISD::ILVR: return "MipsISD::ILVR";
204 case MipsISD::PCKEV: return "MipsISD::PCKEV";
205 case MipsISD::PCKOD: return "MipsISD::PCKOD";
206 case MipsISD::INSVE: return "MipsISD::INSVE";
207 default: return nullptr;
211 MipsTargetLowering::MipsTargetLowering(MipsTargetMachine &TM)
212 : TargetLowering(TM, new MipsTargetObjectFile()),
213 Subtarget(&TM.getSubtarget<MipsSubtarget>()) {
214 // Mips does not have i1 type, so use i32 for
215 // setcc operations results (slt, sgt, ...).
216 setBooleanContents(ZeroOrOneBooleanContent);
217 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
219 // Load extented operations for i1 types must be promoted
220 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
221 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
222 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
224 // MIPS doesn't have extending float->double load/store
225 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
226 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
228 // Used by legalize types to correctly generate the setcc result.
229 // Without this, every float setcc comes with a AND/OR with the result,
230 // we don't want this, since the fpcmp result goes to a flag register,
231 // which is used implicitly by brcond and select operations.
232 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
234 // Mips Custom Operations
235 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
236 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
237 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
238 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
239 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
240 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
241 setOperationAction(ISD::SELECT, MVT::f32, Custom);
242 setOperationAction(ISD::SELECT, MVT::f64, Custom);
243 setOperationAction(ISD::SELECT, MVT::i32, Custom);
244 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
245 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
246 setOperationAction(ISD::SETCC, MVT::f32, Custom);
247 setOperationAction(ISD::SETCC, MVT::f64, Custom);
248 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
249 setOperationAction(ISD::VASTART, MVT::Other, Custom);
250 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
251 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
252 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
255 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
256 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
257 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
258 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
259 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
260 setOperationAction(ISD::SELECT, MVT::i64, Custom);
261 setOperationAction(ISD::LOAD, MVT::i64, Custom);
262 setOperationAction(ISD::STORE, MVT::i64, Custom);
263 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
267 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
268 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
269 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
272 setOperationAction(ISD::ADD, MVT::i32, Custom);
274 setOperationAction(ISD::ADD, MVT::i64, Custom);
276 setOperationAction(ISD::SDIV, MVT::i32, Expand);
277 setOperationAction(ISD::SREM, MVT::i32, Expand);
278 setOperationAction(ISD::UDIV, MVT::i32, Expand);
279 setOperationAction(ISD::UREM, MVT::i32, Expand);
280 setOperationAction(ISD::SDIV, MVT::i64, Expand);
281 setOperationAction(ISD::SREM, MVT::i64, Expand);
282 setOperationAction(ISD::UDIV, MVT::i64, Expand);
283 setOperationAction(ISD::UREM, MVT::i64, Expand);
285 // Operations not directly supported by Mips.
286 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
287 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
288 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
289 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
290 setOperationAction(ISD::SELECT_CC, MVT::i32, Expand);
291 setOperationAction(ISD::SELECT_CC, MVT::i64, 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 if (Subtarget->hasCnMips()) {
298 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
299 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
301 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
302 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
304 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
305 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
306 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
307 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
308 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
309 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
310 setOperationAction(ISD::ROTL, MVT::i32, Expand);
311 setOperationAction(ISD::ROTL, MVT::i64, Expand);
312 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
313 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
315 if (!Subtarget->hasMips32r2())
316 setOperationAction(ISD::ROTR, MVT::i32, Expand);
318 if (!Subtarget->hasMips64r2())
319 setOperationAction(ISD::ROTR, MVT::i64, Expand);
321 setOperationAction(ISD::FSIN, MVT::f32, Expand);
322 setOperationAction(ISD::FSIN, MVT::f64, Expand);
323 setOperationAction(ISD::FCOS, MVT::f32, Expand);
324 setOperationAction(ISD::FCOS, MVT::f64, Expand);
325 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
326 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
327 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
328 setOperationAction(ISD::FPOW, MVT::f32, Expand);
329 setOperationAction(ISD::FPOW, MVT::f64, Expand);
330 setOperationAction(ISD::FLOG, MVT::f32, Expand);
331 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
332 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
333 setOperationAction(ISD::FEXP, MVT::f32, Expand);
334 setOperationAction(ISD::FMA, MVT::f32, Expand);
335 setOperationAction(ISD::FMA, MVT::f64, Expand);
336 setOperationAction(ISD::FREM, MVT::f32, Expand);
337 setOperationAction(ISD::FREM, 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->hasMips32r2()) {
357 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
358 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
361 // MIPS16 lacks MIPS32's clz and clo instructions.
362 if (!Subtarget->hasMips32() || Subtarget->inMips16Mode())
363 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
364 if (!Subtarget->hasMips64())
365 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
367 if (!Subtarget->hasMips32r2())
368 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
369 if (!Subtarget->hasMips64r2())
370 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
373 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
374 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
375 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
376 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
379 setOperationAction(ISD::TRAP, MVT::Other, Legal);
381 setTargetDAGCombine(ISD::SDIVREM);
382 setTargetDAGCombine(ISD::UDIVREM);
383 setTargetDAGCombine(ISD::SELECT);
384 setTargetDAGCombine(ISD::AND);
385 setTargetDAGCombine(ISD::OR);
386 setTargetDAGCombine(ISD::ADD);
388 setMinFunctionAlignment(isGP64bit() ? 3 : 2);
390 setStackPointerRegisterToSaveRestore(isN64() ? Mips::SP_64 : Mips::SP);
392 setExceptionPointerRegister(isN64() ? Mips::A0_64 : Mips::A0);
393 setExceptionSelectorRegister(isN64() ? Mips::A1_64 : Mips::A1);
395 MaxStoresPerMemcpy = 16;
397 isMicroMips = Subtarget->inMicroMipsMode();
400 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
401 if (TM.getSubtargetImpl()->inMips16Mode())
402 return llvm::createMips16TargetLowering(TM);
404 return llvm::createMipsSETargetLowering(TM);
407 // Create a fast isel object.
409 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
410 const TargetLibraryInfo *libInfo) const {
411 if (!EnableMipsFastISel)
412 return TargetLowering::createFastISel(funcInfo, libInfo);
413 return Mips::createFastISel(funcInfo, libInfo);
416 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
419 return VT.changeVectorElementTypeToInteger();
422 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
423 TargetLowering::DAGCombinerInfo &DCI,
424 const MipsSubtarget *Subtarget) {
425 if (DCI.isBeforeLegalizeOps())
428 EVT Ty = N->getValueType(0);
429 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
430 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
431 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
435 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
436 N->getOperand(0), N->getOperand(1));
437 SDValue InChain = DAG.getEntryNode();
438 SDValue InGlue = DivRem;
441 if (N->hasAnyUseOfValue(0)) {
442 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
444 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
445 InChain = CopyFromLo.getValue(1);
446 InGlue = CopyFromLo.getValue(2);
450 if (N->hasAnyUseOfValue(1)) {
451 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
453 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
459 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
461 default: llvm_unreachable("Unknown fp condition code!");
463 case ISD::SETOEQ: return Mips::FCOND_OEQ;
464 case ISD::SETUNE: return Mips::FCOND_UNE;
466 case ISD::SETOLT: return Mips::FCOND_OLT;
468 case ISD::SETOGT: return Mips::FCOND_OGT;
470 case ISD::SETOLE: return Mips::FCOND_OLE;
472 case ISD::SETOGE: return Mips::FCOND_OGE;
473 case ISD::SETULT: return Mips::FCOND_ULT;
474 case ISD::SETULE: return Mips::FCOND_ULE;
475 case ISD::SETUGT: return Mips::FCOND_UGT;
476 case ISD::SETUGE: return Mips::FCOND_UGE;
477 case ISD::SETUO: return Mips::FCOND_UN;
478 case ISD::SETO: return Mips::FCOND_OR;
480 case ISD::SETONE: return Mips::FCOND_ONE;
481 case ISD::SETUEQ: return Mips::FCOND_UEQ;
486 /// This function returns true if the floating point conditional branches and
487 /// conditional moves which use condition code CC should be inverted.
488 static bool invertFPCondCodeUser(Mips::CondCode CC) {
489 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
492 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
493 "Illegal Condition Code");
498 // Creates and returns an FPCmp node from a setcc node.
499 // Returns Op if setcc is not a floating point comparison.
500 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
501 // must be a SETCC node
502 if (Op.getOpcode() != ISD::SETCC)
505 SDValue LHS = Op.getOperand(0);
507 if (!LHS.getValueType().isFloatingPoint())
510 SDValue RHS = Op.getOperand(1);
513 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
514 // node if necessary.
515 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
517 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
518 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
521 // Creates and returns a CMovFPT/F node.
522 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
523 SDValue False, SDLoc DL) {
524 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
525 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
526 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
528 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
529 True.getValueType(), True, FCC0, False, Cond);
532 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
533 TargetLowering::DAGCombinerInfo &DCI,
534 const MipsSubtarget *Subtarget) {
535 if (DCI.isBeforeLegalizeOps())
538 SDValue SetCC = N->getOperand(0);
540 if ((SetCC.getOpcode() != ISD::SETCC) ||
541 !SetCC.getOperand(0).getValueType().isInteger())
544 SDValue False = N->getOperand(2);
545 EVT FalseTy = False.getValueType();
547 if (!FalseTy.isInteger())
550 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
552 // If the RHS (False) is 0, we swap the order of the operands
553 // of ISD::SELECT (obviously also inverting the condition) so that we can
554 // take advantage of conditional moves using the $0 register.
556 // return (a != 0) ? x : 0;
564 if (!FalseC->getZExtValue()) {
565 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
566 SDValue True = N->getOperand(1);
568 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
569 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
571 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
574 // If both operands are integer constants there's a possibility that we
575 // can do some interesting optimizations.
576 SDValue True = N->getOperand(1);
577 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
579 if (!TrueC || !True.getValueType().isInteger())
582 // We'll also ignore MVT::i64 operands as this optimizations proves
583 // to be ineffective because of the required sign extensions as the result
584 // of a SETCC operator is always MVT::i32 for non-vector types.
585 if (True.getValueType() == MVT::i64)
588 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
590 // 1) (a < x) ? y : y-1
592 // addiu $reg2, $reg1, y-1
594 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
596 // 2) (a < x) ? y-1 : y
598 // xor $reg1, $reg1, 1
599 // addiu $reg2, $reg1, y-1
601 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
602 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
603 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
604 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
607 // Couldn't optimize.
611 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
612 TargetLowering::DAGCombinerInfo &DCI,
613 const MipsSubtarget *Subtarget) {
614 // Pattern match EXT.
615 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
616 // => ext $dst, $src, size, pos
617 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
620 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
621 unsigned ShiftRightOpc = ShiftRight.getOpcode();
623 // Op's first operand must be a shift right.
624 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
627 // The second operand of the shift must be an immediate.
629 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
632 uint64_t Pos = CN->getZExtValue();
633 uint64_t SMPos, SMSize;
635 // Op's second operand must be a shifted mask.
636 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
637 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
640 // Return if the shifted mask does not start at bit 0 or the sum of its size
641 // and Pos exceeds the word's size.
642 EVT ValTy = N->getValueType(0);
643 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
646 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
647 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
648 DAG.getConstant(SMSize, MVT::i32));
651 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
652 TargetLowering::DAGCombinerInfo &DCI,
653 const MipsSubtarget *Subtarget) {
654 // Pattern match INS.
655 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
656 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
657 // => ins $dst, $src, size, pos, $src1
658 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
661 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
662 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
665 // See if Op's first operand matches (and $src1 , mask0).
666 if (And0.getOpcode() != ISD::AND)
669 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
670 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
673 // See if Op's second operand matches (and (shl $src, pos), mask1).
674 if (And1.getOpcode() != ISD::AND)
677 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
678 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
681 // The shift masks must have the same position and size.
682 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
685 SDValue Shl = And1.getOperand(0);
686 if (Shl.getOpcode() != ISD::SHL)
689 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
692 unsigned Shamt = CN->getZExtValue();
694 // Return if the shift amount and the first bit position of mask are not the
696 EVT ValTy = N->getValueType(0);
697 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
700 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
701 DAG.getConstant(SMPos0, MVT::i32),
702 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
705 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
706 TargetLowering::DAGCombinerInfo &DCI,
707 const MipsSubtarget *Subtarget) {
708 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
710 if (DCI.isBeforeLegalizeOps())
713 SDValue Add = N->getOperand(1);
715 if (Add.getOpcode() != ISD::ADD)
718 SDValue Lo = Add.getOperand(1);
720 if ((Lo.getOpcode() != MipsISD::Lo) ||
721 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
724 EVT ValTy = N->getValueType(0);
727 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
729 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
732 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
734 SelectionDAG &DAG = DCI.DAG;
735 unsigned Opc = N->getOpcode();
741 return performDivRemCombine(N, DAG, DCI, Subtarget);
743 return performSELECTCombine(N, DAG, DCI, Subtarget);
745 return performANDCombine(N, DAG, DCI, Subtarget);
747 return performORCombine(N, DAG, DCI, Subtarget);
749 return performADDCombine(N, DAG, DCI, Subtarget);
756 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
757 SmallVectorImpl<SDValue> &Results,
758 SelectionDAG &DAG) const {
759 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
761 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
762 Results.push_back(Res.getValue(I));
766 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
767 SmallVectorImpl<SDValue> &Results,
768 SelectionDAG &DAG) const {
769 return LowerOperationWrapper(N, Results, DAG);
772 SDValue MipsTargetLowering::
773 LowerOperation(SDValue Op, SelectionDAG &DAG) const
775 switch (Op.getOpcode())
777 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
778 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
779 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
780 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
781 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
782 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
783 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
784 case ISD::SELECT: return lowerSELECT(Op, DAG);
785 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
786 case ISD::SETCC: return lowerSETCC(Op, DAG);
787 case ISD::VASTART: return lowerVASTART(Op, DAG);
788 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
789 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
790 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
791 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
792 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
793 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
794 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
795 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
796 case ISD::LOAD: return lowerLOAD(Op, DAG);
797 case ISD::STORE: return lowerSTORE(Op, DAG);
798 case ISD::ADD: return lowerADD(Op, DAG);
799 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
804 //===----------------------------------------------------------------------===//
805 // Lower helper functions
806 //===----------------------------------------------------------------------===//
808 // addLiveIn - This helper function adds the specified physical register to the
809 // MachineFunction as a live in value. It also creates a corresponding
810 // virtual register for it.
812 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
814 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
815 MF.getRegInfo().addLiveIn(PReg, VReg);
819 static MachineBasicBlock *insertDivByZeroTrap(MachineInstr *MI,
820 MachineBasicBlock &MBB,
821 const TargetInstrInfo &TII,
826 // Insert instruction "teq $divisor_reg, $zero, 7".
827 MachineBasicBlock::iterator I(MI);
828 MachineInstrBuilder MIB;
829 MachineOperand &Divisor = MI->getOperand(2);
830 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
831 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
832 .addReg(Mips::ZERO).addImm(7);
834 // Use the 32-bit sub-register if this is a 64-bit division.
836 MIB->getOperand(0).setSubReg(Mips::sub_32);
838 // Clear Divisor's kill flag.
839 Divisor.setIsKill(false);
841 // We would normally delete the original instruction here but in this case
842 // we only needed to inject an additional instruction rather than replace it.
848 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
849 MachineBasicBlock *BB) const {
850 switch (MI->getOpcode()) {
852 llvm_unreachable("Unexpected instr type to insert");
853 case Mips::ATOMIC_LOAD_ADD_I8:
854 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
855 case Mips::ATOMIC_LOAD_ADD_I16:
856 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
857 case Mips::ATOMIC_LOAD_ADD_I32:
858 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
859 case Mips::ATOMIC_LOAD_ADD_I64:
860 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
862 case Mips::ATOMIC_LOAD_AND_I8:
863 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
864 case Mips::ATOMIC_LOAD_AND_I16:
865 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
866 case Mips::ATOMIC_LOAD_AND_I32:
867 return emitAtomicBinary(MI, BB, 4, Mips::AND);
868 case Mips::ATOMIC_LOAD_AND_I64:
869 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
871 case Mips::ATOMIC_LOAD_OR_I8:
872 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
873 case Mips::ATOMIC_LOAD_OR_I16:
874 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
875 case Mips::ATOMIC_LOAD_OR_I32:
876 return emitAtomicBinary(MI, BB, 4, Mips::OR);
877 case Mips::ATOMIC_LOAD_OR_I64:
878 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
880 case Mips::ATOMIC_LOAD_XOR_I8:
881 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
882 case Mips::ATOMIC_LOAD_XOR_I16:
883 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
884 case Mips::ATOMIC_LOAD_XOR_I32:
885 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
886 case Mips::ATOMIC_LOAD_XOR_I64:
887 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
889 case Mips::ATOMIC_LOAD_NAND_I8:
890 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
891 case Mips::ATOMIC_LOAD_NAND_I16:
892 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
893 case Mips::ATOMIC_LOAD_NAND_I32:
894 return emitAtomicBinary(MI, BB, 4, 0, true);
895 case Mips::ATOMIC_LOAD_NAND_I64:
896 return emitAtomicBinary(MI, BB, 8, 0, true);
898 case Mips::ATOMIC_LOAD_SUB_I8:
899 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
900 case Mips::ATOMIC_LOAD_SUB_I16:
901 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
902 case Mips::ATOMIC_LOAD_SUB_I32:
903 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
904 case Mips::ATOMIC_LOAD_SUB_I64:
905 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
907 case Mips::ATOMIC_SWAP_I8:
908 return emitAtomicBinaryPartword(MI, BB, 1, 0);
909 case Mips::ATOMIC_SWAP_I16:
910 return emitAtomicBinaryPartword(MI, BB, 2, 0);
911 case Mips::ATOMIC_SWAP_I32:
912 return emitAtomicBinary(MI, BB, 4, 0);
913 case Mips::ATOMIC_SWAP_I64:
914 return emitAtomicBinary(MI, BB, 8, 0);
916 case Mips::ATOMIC_CMP_SWAP_I8:
917 return emitAtomicCmpSwapPartword(MI, BB, 1);
918 case Mips::ATOMIC_CMP_SWAP_I16:
919 return emitAtomicCmpSwapPartword(MI, BB, 2);
920 case Mips::ATOMIC_CMP_SWAP_I32:
921 return emitAtomicCmpSwap(MI, BB, 4);
922 case Mips::ATOMIC_CMP_SWAP_I64:
923 return emitAtomicCmpSwap(MI, BB, 8);
924 case Mips::PseudoSDIV:
925 case Mips::PseudoUDIV:
930 return insertDivByZeroTrap(MI, *BB, *getTargetMachine().getInstrInfo(),
932 case Mips::PseudoDSDIV:
933 case Mips::PseudoDUDIV:
938 return insertDivByZeroTrap(MI, *BB, *getTargetMachine().getInstrInfo(),
941 return emitSEL_D(MI, BB);
945 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
946 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
948 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
949 unsigned Size, unsigned BinOpcode,
951 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
953 MachineFunction *MF = BB->getParent();
954 MachineRegisterInfo &RegInfo = MF->getRegInfo();
955 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
956 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
957 DebugLoc DL = MI->getDebugLoc();
958 unsigned LL, SC, AND, NOR, ZERO, BEQ;
961 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
962 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
973 ZERO = Mips::ZERO_64;
977 unsigned OldVal = MI->getOperand(0).getReg();
978 unsigned Ptr = MI->getOperand(1).getReg();
979 unsigned Incr = MI->getOperand(2).getReg();
981 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
982 unsigned AndRes = RegInfo.createVirtualRegister(RC);
983 unsigned Success = RegInfo.createVirtualRegister(RC);
985 // insert new blocks after the current block
986 const BasicBlock *LLVM_BB = BB->getBasicBlock();
987 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
988 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
989 MachineFunction::iterator It = BB;
991 MF->insert(It, loopMBB);
992 MF->insert(It, exitMBB);
994 // Transfer the remainder of BB and its successor edges to exitMBB.
995 exitMBB->splice(exitMBB->begin(), BB,
996 std::next(MachineBasicBlock::iterator(MI)), BB->end());
997 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1001 // fallthrough --> loopMBB
1002 BB->addSuccessor(loopMBB);
1003 loopMBB->addSuccessor(loopMBB);
1004 loopMBB->addSuccessor(exitMBB);
1007 // ll oldval, 0(ptr)
1008 // <binop> storeval, oldval, incr
1009 // sc success, storeval, 0(ptr)
1010 // beq success, $0, loopMBB
1012 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1014 // and andres, oldval, incr
1015 // nor storeval, $0, andres
1016 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1017 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1018 } else if (BinOpcode) {
1019 // <binop> storeval, oldval, incr
1020 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1024 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1025 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1027 MI->eraseFromParent(); // The instruction is gone now.
1033 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
1034 MachineBasicBlock *BB,
1035 unsigned Size, unsigned BinOpcode,
1037 assert((Size == 1 || Size == 2) &&
1038 "Unsupported size for EmitAtomicBinaryPartial.");
1040 MachineFunction *MF = BB->getParent();
1041 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1042 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1043 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1044 DebugLoc DL = MI->getDebugLoc();
1046 unsigned Dest = MI->getOperand(0).getReg();
1047 unsigned Ptr = MI->getOperand(1).getReg();
1048 unsigned Incr = MI->getOperand(2).getReg();
1050 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1051 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1052 unsigned Mask = RegInfo.createVirtualRegister(RC);
1053 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1054 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1055 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1056 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1057 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1058 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1059 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1060 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1061 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1062 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1063 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1064 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1065 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1066 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1067 unsigned Success = RegInfo.createVirtualRegister(RC);
1069 // insert new blocks after the current block
1070 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1071 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1072 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1073 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1074 MachineFunction::iterator It = BB;
1076 MF->insert(It, loopMBB);
1077 MF->insert(It, sinkMBB);
1078 MF->insert(It, exitMBB);
1080 // Transfer the remainder of BB and its successor edges to exitMBB.
1081 exitMBB->splice(exitMBB->begin(), BB,
1082 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1083 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1085 BB->addSuccessor(loopMBB);
1086 loopMBB->addSuccessor(loopMBB);
1087 loopMBB->addSuccessor(sinkMBB);
1088 sinkMBB->addSuccessor(exitMBB);
1091 // addiu masklsb2,$0,-4 # 0xfffffffc
1092 // and alignedaddr,ptr,masklsb2
1093 // andi ptrlsb2,ptr,3
1094 // sll shiftamt,ptrlsb2,3
1095 // ori maskupper,$0,255 # 0xff
1096 // sll mask,maskupper,shiftamt
1097 // nor mask2,$0,mask
1098 // sll incr2,incr,shiftamt
1100 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1101 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1102 .addReg(Mips::ZERO).addImm(-4);
1103 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1104 .addReg(Ptr).addReg(MaskLSB2);
1105 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1106 if (Subtarget->isLittle()) {
1107 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1109 unsigned Off = RegInfo.createVirtualRegister(RC);
1110 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1111 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1112 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1114 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1115 .addReg(Mips::ZERO).addImm(MaskImm);
1116 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1117 .addReg(MaskUpper).addReg(ShiftAmt);
1118 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1119 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1121 // atomic.load.binop
1123 // ll oldval,0(alignedaddr)
1124 // binop binopres,oldval,incr2
1125 // and newval,binopres,mask
1126 // and maskedoldval0,oldval,mask2
1127 // or storeval,maskedoldval0,newval
1128 // sc success,storeval,0(alignedaddr)
1129 // beq success,$0,loopMBB
1133 // ll oldval,0(alignedaddr)
1134 // and newval,incr2,mask
1135 // and maskedoldval0,oldval,mask2
1136 // or storeval,maskedoldval0,newval
1137 // sc success,storeval,0(alignedaddr)
1138 // beq success,$0,loopMBB
1141 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1143 // and andres, oldval, incr2
1144 // nor binopres, $0, andres
1145 // and newval, binopres, mask
1146 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1147 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1148 .addReg(Mips::ZERO).addReg(AndRes);
1149 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1150 } else if (BinOpcode) {
1151 // <binop> binopres, oldval, incr2
1152 // and newval, binopres, mask
1153 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1154 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1155 } else { // atomic.swap
1156 // and newval, incr2, mask
1157 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1160 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1161 .addReg(OldVal).addReg(Mask2);
1162 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1163 .addReg(MaskedOldVal0).addReg(NewVal);
1164 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1165 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1166 BuildMI(BB, DL, TII->get(Mips::BEQ))
1167 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1170 // and maskedoldval1,oldval,mask
1171 // srl srlres,maskedoldval1,shiftamt
1172 // sll sllres,srlres,24
1173 // sra dest,sllres,24
1175 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1177 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1178 .addReg(OldVal).addReg(Mask);
1179 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1180 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1181 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1182 .addReg(SrlRes).addImm(ShiftImm);
1183 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1184 .addReg(SllRes).addImm(ShiftImm);
1186 MI->eraseFromParent(); // The instruction is gone now.
1191 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1192 MachineBasicBlock *BB,
1193 unsigned Size) const {
1194 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1196 MachineFunction *MF = BB->getParent();
1197 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1198 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1199 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1200 DebugLoc DL = MI->getDebugLoc();
1201 unsigned LL, SC, ZERO, BNE, BEQ;
1204 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1205 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1212 ZERO = Mips::ZERO_64;
1217 unsigned Dest = MI->getOperand(0).getReg();
1218 unsigned Ptr = MI->getOperand(1).getReg();
1219 unsigned OldVal = MI->getOperand(2).getReg();
1220 unsigned NewVal = MI->getOperand(3).getReg();
1222 unsigned Success = RegInfo.createVirtualRegister(RC);
1224 // insert new blocks after the current block
1225 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1226 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1227 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1228 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1229 MachineFunction::iterator It = BB;
1231 MF->insert(It, loop1MBB);
1232 MF->insert(It, loop2MBB);
1233 MF->insert(It, exitMBB);
1235 // Transfer the remainder of BB and its successor edges to exitMBB.
1236 exitMBB->splice(exitMBB->begin(), BB,
1237 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1238 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1242 // fallthrough --> loop1MBB
1243 BB->addSuccessor(loop1MBB);
1244 loop1MBB->addSuccessor(exitMBB);
1245 loop1MBB->addSuccessor(loop2MBB);
1246 loop2MBB->addSuccessor(loop1MBB);
1247 loop2MBB->addSuccessor(exitMBB);
1251 // bne dest, oldval, exitMBB
1253 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1254 BuildMI(BB, DL, TII->get(BNE))
1255 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1258 // sc success, newval, 0(ptr)
1259 // beq success, $0, loop1MBB
1261 BuildMI(BB, DL, TII->get(SC), Success)
1262 .addReg(NewVal).addReg(Ptr).addImm(0);
1263 BuildMI(BB, DL, TII->get(BEQ))
1264 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1266 MI->eraseFromParent(); // The instruction is gone now.
1272 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1273 MachineBasicBlock *BB,
1274 unsigned Size) const {
1275 assert((Size == 1 || Size == 2) &&
1276 "Unsupported size for EmitAtomicCmpSwapPartial.");
1278 MachineFunction *MF = BB->getParent();
1279 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1280 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1281 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1282 DebugLoc DL = MI->getDebugLoc();
1284 unsigned Dest = MI->getOperand(0).getReg();
1285 unsigned Ptr = MI->getOperand(1).getReg();
1286 unsigned CmpVal = MI->getOperand(2).getReg();
1287 unsigned NewVal = MI->getOperand(3).getReg();
1289 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1290 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1291 unsigned Mask = RegInfo.createVirtualRegister(RC);
1292 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1293 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1294 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1295 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1296 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1297 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1298 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1299 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1300 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1301 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1302 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1303 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1304 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1305 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1306 unsigned Success = RegInfo.createVirtualRegister(RC);
1308 // insert new blocks after the current block
1309 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1310 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1311 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1312 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1313 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1314 MachineFunction::iterator It = BB;
1316 MF->insert(It, loop1MBB);
1317 MF->insert(It, loop2MBB);
1318 MF->insert(It, sinkMBB);
1319 MF->insert(It, exitMBB);
1321 // Transfer the remainder of BB and its successor edges to exitMBB.
1322 exitMBB->splice(exitMBB->begin(), BB,
1323 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1324 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1326 BB->addSuccessor(loop1MBB);
1327 loop1MBB->addSuccessor(sinkMBB);
1328 loop1MBB->addSuccessor(loop2MBB);
1329 loop2MBB->addSuccessor(loop1MBB);
1330 loop2MBB->addSuccessor(sinkMBB);
1331 sinkMBB->addSuccessor(exitMBB);
1333 // FIXME: computation of newval2 can be moved to loop2MBB.
1335 // addiu masklsb2,$0,-4 # 0xfffffffc
1336 // and alignedaddr,ptr,masklsb2
1337 // andi ptrlsb2,ptr,3
1338 // sll shiftamt,ptrlsb2,3
1339 // ori maskupper,$0,255 # 0xff
1340 // sll mask,maskupper,shiftamt
1341 // nor mask2,$0,mask
1342 // andi maskedcmpval,cmpval,255
1343 // sll shiftedcmpval,maskedcmpval,shiftamt
1344 // andi maskednewval,newval,255
1345 // sll shiftednewval,maskednewval,shiftamt
1346 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1347 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1348 .addReg(Mips::ZERO).addImm(-4);
1349 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1350 .addReg(Ptr).addReg(MaskLSB2);
1351 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1352 if (Subtarget->isLittle()) {
1353 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1355 unsigned Off = RegInfo.createVirtualRegister(RC);
1356 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1357 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1358 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1360 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1361 .addReg(Mips::ZERO).addImm(MaskImm);
1362 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1363 .addReg(MaskUpper).addReg(ShiftAmt);
1364 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1365 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1366 .addReg(CmpVal).addImm(MaskImm);
1367 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1368 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1369 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1370 .addReg(NewVal).addImm(MaskImm);
1371 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1372 .addReg(MaskedNewVal).addReg(ShiftAmt);
1375 // ll oldval,0(alginedaddr)
1376 // and maskedoldval0,oldval,mask
1377 // bne maskedoldval0,shiftedcmpval,sinkMBB
1379 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1380 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1381 .addReg(OldVal).addReg(Mask);
1382 BuildMI(BB, DL, TII->get(Mips::BNE))
1383 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1386 // and maskedoldval1,oldval,mask2
1387 // or storeval,maskedoldval1,shiftednewval
1388 // sc success,storeval,0(alignedaddr)
1389 // beq success,$0,loop1MBB
1391 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1392 .addReg(OldVal).addReg(Mask2);
1393 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1394 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1395 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1396 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1397 BuildMI(BB, DL, TII->get(Mips::BEQ))
1398 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1401 // srl srlres,maskedoldval0,shiftamt
1402 // sll sllres,srlres,24
1403 // sra dest,sllres,24
1405 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1407 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1408 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1409 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1410 .addReg(SrlRes).addImm(ShiftImm);
1411 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1412 .addReg(SllRes).addImm(ShiftImm);
1414 MI->eraseFromParent(); // The instruction is gone now.
1419 MachineBasicBlock *MipsTargetLowering::emitSEL_D(MachineInstr *MI,
1420 MachineBasicBlock *BB) const {
1421 MachineFunction *MF = BB->getParent();
1422 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
1423 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1424 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1425 DebugLoc DL = MI->getDebugLoc();
1426 MachineBasicBlock::iterator II(MI);
1428 unsigned Fc = MI->getOperand(1).getReg();
1429 const auto &FGR64RegClass = TRI->getRegClass(Mips::FGR64RegClassID);
1431 unsigned Fc2 = RegInfo.createVirtualRegister(FGR64RegClass);
1433 BuildMI(*BB, II, DL, TII->get(Mips::SUBREG_TO_REG), Fc2)
1436 .addImm(Mips::sub_lo);
1438 // We don't erase the original instruction, we just replace the condition
1439 // register with the 64-bit super-register.
1440 MI->getOperand(1).setReg(Fc2);
1445 //===----------------------------------------------------------------------===//
1446 // Misc Lower Operation implementation
1447 //===----------------------------------------------------------------------===//
1448 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1449 SDValue Chain = Op.getOperand(0);
1450 SDValue Table = Op.getOperand(1);
1451 SDValue Index = Op.getOperand(2);
1453 EVT PTy = getPointerTy();
1454 unsigned EntrySize =
1455 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1457 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1458 DAG.getConstant(EntrySize, PTy));
1459 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1461 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1462 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1463 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1465 Chain = Addr.getValue(1);
1467 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || isN64()) {
1468 // For PIC, the sequence is:
1469 // BRIND(load(Jumptable + index) + RelocBase)
1470 // RelocBase can be JumpTable, GOT or some sort of global base.
1471 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1472 getPICJumpTableRelocBase(Table, DAG));
1475 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1478 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1479 // The first operand is the chain, the second is the condition, the third is
1480 // the block to branch to if the condition is true.
1481 SDValue Chain = Op.getOperand(0);
1482 SDValue Dest = Op.getOperand(2);
1485 assert(!Subtarget->hasMips32r6() && !Subtarget->hasMips64r6());
1486 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1488 // Return if flag is not set by a floating point comparison.
1489 if (CondRes.getOpcode() != MipsISD::FPCmp)
1492 SDValue CCNode = CondRes.getOperand(2);
1494 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1495 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1496 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1497 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1498 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1499 FCC0, Dest, CondRes);
1502 SDValue MipsTargetLowering::
1503 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1505 assert(!Subtarget->hasMips32r6() && !Subtarget->hasMips64r6());
1506 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1508 // Return if flag is not set by a floating point comparison.
1509 if (Cond.getOpcode() != MipsISD::FPCmp)
1512 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1516 SDValue MipsTargetLowering::
1517 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1520 EVT Ty = Op.getOperand(0).getValueType();
1521 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1522 getSetCCResultType(*DAG.getContext(), Ty),
1523 Op.getOperand(0), Op.getOperand(1),
1526 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1530 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1531 assert(!Subtarget->hasMips32r6() && !Subtarget->hasMips64r6());
1532 SDValue Cond = createFPCmp(DAG, Op);
1534 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1535 "Floating point operand expected.");
1537 SDValue True = DAG.getConstant(1, MVT::i32);
1538 SDValue False = DAG.getConstant(0, MVT::i32);
1540 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1543 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1544 SelectionDAG &DAG) const {
1545 // FIXME there isn't actually debug info here
1547 EVT Ty = Op.getValueType();
1548 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1549 const GlobalValue *GV = N->getGlobal();
1551 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64()) {
1552 const MipsTargetObjectFile &TLOF =
1553 (const MipsTargetObjectFile&)getObjFileLowering();
1555 // %gp_rel relocation
1556 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1557 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1559 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1560 DAG.getVTList(MVT::i32), GA);
1561 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1562 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1565 // %hi/%lo relocation
1566 return getAddrNonPIC(N, Ty, DAG);
1569 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1570 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1573 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1574 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1575 MachinePointerInfo::getGOT());
1577 return getAddrGlobal(N, Ty, DAG, (isN32() || isN64()) ? MipsII::MO_GOT_DISP
1579 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1582 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1583 SelectionDAG &DAG) const {
1584 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1585 EVT Ty = Op.getValueType();
1587 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1588 return getAddrNonPIC(N, Ty, DAG);
1590 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1593 SDValue MipsTargetLowering::
1594 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1596 // If the relocation model is PIC, use the General Dynamic TLS Model or
1597 // Local Dynamic TLS model, otherwise use the Initial Exec or
1598 // Local Exec TLS Model.
1600 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1602 const GlobalValue *GV = GA->getGlobal();
1603 EVT PtrVT = getPointerTy();
1605 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1607 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1608 // General Dynamic and Local Dynamic TLS Model.
1609 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1612 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1613 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1614 getGlobalReg(DAG, PtrVT), TGA);
1615 unsigned PtrSize = PtrVT.getSizeInBits();
1616 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1618 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1622 Entry.Node = Argument;
1624 Args.push_back(Entry);
1626 TargetLowering::CallLoweringInfo CLI(DAG);
1627 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1628 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, &Args, 0);
1629 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1631 SDValue Ret = CallResult.first;
1633 if (model != TLSModel::LocalDynamic)
1636 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1637 MipsII::MO_DTPREL_HI);
1638 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1639 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1640 MipsII::MO_DTPREL_LO);
1641 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1642 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1643 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1647 if (model == TLSModel::InitialExec) {
1648 // Initial Exec TLS Model
1649 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1650 MipsII::MO_GOTTPREL);
1651 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1653 Offset = DAG.getLoad(PtrVT, DL,
1654 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1655 false, false, false, 0);
1657 // Local Exec TLS Model
1658 assert(model == TLSModel::LocalExec);
1659 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1660 MipsII::MO_TPREL_HI);
1661 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1662 MipsII::MO_TPREL_LO);
1663 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1664 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1665 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1668 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1669 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1672 SDValue MipsTargetLowering::
1673 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1675 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1676 EVT Ty = Op.getValueType();
1678 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1679 return getAddrNonPIC(N, Ty, DAG);
1681 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1684 SDValue MipsTargetLowering::
1685 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1687 // gp_rel relocation
1688 // FIXME: we should reference the constant pool using small data sections,
1689 // but the asm printer currently doesn't support this feature without
1690 // hacking it. This feature should come soon so we can uncomment the
1692 //if (IsInSmallSection(C->getType())) {
1693 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1694 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1695 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1696 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1697 EVT Ty = Op.getValueType();
1699 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1700 return getAddrNonPIC(N, Ty, DAG);
1702 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1705 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1706 MachineFunction &MF = DAG.getMachineFunction();
1707 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1710 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1713 // vastart just stores the address of the VarArgsFrameIndex slot into the
1714 // memory location argument.
1715 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1716 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1717 MachinePointerInfo(SV), false, false, 0);
1720 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1721 bool HasExtractInsert) {
1722 EVT TyX = Op.getOperand(0).getValueType();
1723 EVT TyY = Op.getOperand(1).getValueType();
1724 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1725 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1729 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1731 SDValue X = (TyX == MVT::f32) ?
1732 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1733 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1735 SDValue Y = (TyY == MVT::f32) ?
1736 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1737 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1740 if (HasExtractInsert) {
1741 // ext E, Y, 31, 1 ; extract bit31 of Y
1742 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1743 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1744 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1747 // srl SrlX, SllX, 1
1749 // sll SllY, SrlX, 31
1750 // or Or, SrlX, SllY
1751 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1752 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1753 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1754 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1755 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1758 if (TyX == MVT::f32)
1759 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1761 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1762 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1763 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1766 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1767 bool HasExtractInsert) {
1768 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1769 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1770 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1771 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1774 // Bitcast to integer nodes.
1775 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1776 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1778 if (HasExtractInsert) {
1779 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1780 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1781 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1782 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1784 if (WidthX > WidthY)
1785 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1786 else if (WidthY > WidthX)
1787 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1789 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1790 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1791 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1794 // (d)sll SllX, X, 1
1795 // (d)srl SrlX, SllX, 1
1796 // (d)srl SrlY, Y, width(Y)-1
1797 // (d)sll SllY, SrlX, width(Y)-1
1798 // or Or, SrlX, SllY
1799 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1800 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1801 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1802 DAG.getConstant(WidthY - 1, MVT::i32));
1804 if (WidthX > WidthY)
1805 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1806 else if (WidthY > WidthX)
1807 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1809 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1810 DAG.getConstant(WidthX - 1, MVT::i32));
1811 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1812 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1816 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1817 if (Subtarget->isGP64bit())
1818 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasExtractInsert());
1820 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasExtractInsert());
1823 SDValue MipsTargetLowering::
1824 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1826 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1827 "Frame address can only be determined for current frame.");
1829 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1830 MFI->setFrameAddressIsTaken(true);
1831 EVT VT = Op.getValueType();
1833 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1834 isN64() ? Mips::FP_64 : Mips::FP, VT);
1838 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1839 SelectionDAG &DAG) const {
1840 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1844 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1845 "Return address can be determined only for current frame.");
1847 MachineFunction &MF = DAG.getMachineFunction();
1848 MachineFrameInfo *MFI = MF.getFrameInfo();
1849 MVT VT = Op.getSimpleValueType();
1850 unsigned RA = isN64() ? Mips::RA_64 : Mips::RA;
1851 MFI->setReturnAddressIsTaken(true);
1853 // Return RA, which contains the return address. Mark it an implicit live-in.
1854 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1855 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1858 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1859 // generated from __builtin_eh_return (offset, handler)
1860 // The effect of this is to adjust the stack pointer by "offset"
1861 // and then branch to "handler".
1862 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1864 MachineFunction &MF = DAG.getMachineFunction();
1865 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1867 MipsFI->setCallsEhReturn();
1868 SDValue Chain = Op.getOperand(0);
1869 SDValue Offset = Op.getOperand(1);
1870 SDValue Handler = Op.getOperand(2);
1872 EVT Ty = isN64() ? MVT::i64 : MVT::i32;
1874 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1875 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1876 unsigned OffsetReg = isN64() ? Mips::V1_64 : Mips::V1;
1877 unsigned AddrReg = isN64() ? Mips::V0_64 : Mips::V0;
1878 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1879 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1880 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1881 DAG.getRegister(OffsetReg, Ty),
1882 DAG.getRegister(AddrReg, getPointerTy()),
1886 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1887 SelectionDAG &DAG) const {
1888 // FIXME: Need pseudo-fence for 'singlethread' fences
1889 // FIXME: Set SType for weaker fences where supported/appropriate.
1892 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1893 DAG.getConstant(SType, MVT::i32));
1896 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1897 SelectionDAG &DAG) const {
1899 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1900 SDValue Shamt = Op.getOperand(2);
1903 // lo = (shl lo, shamt)
1904 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1907 // hi = (shl lo, shamt[4:0])
1908 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1909 DAG.getConstant(-1, MVT::i32));
1910 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1911 DAG.getConstant(1, MVT::i32));
1912 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1914 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1915 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1916 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1917 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1918 DAG.getConstant(0x20, MVT::i32));
1919 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1920 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1921 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1923 SDValue Ops[2] = {Lo, Hi};
1924 return DAG.getMergeValues(Ops, DL);
1927 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1930 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1931 SDValue Shamt = Op.getOperand(2);
1934 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1936 // hi = (sra hi, shamt)
1938 // hi = (srl hi, shamt)
1941 // lo = (sra hi, shamt[4:0])
1942 // hi = (sra hi, 31)
1944 // lo = (srl hi, shamt[4:0])
1946 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1947 DAG.getConstant(-1, MVT::i32));
1948 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1949 DAG.getConstant(1, MVT::i32));
1950 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1951 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1952 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1953 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1955 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1956 DAG.getConstant(0x20, MVT::i32));
1957 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1958 DAG.getConstant(31, MVT::i32));
1959 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1960 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1961 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1964 SDValue Ops[2] = {Lo, Hi};
1965 return DAG.getMergeValues(Ops, DL);
1968 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1969 SDValue Chain, SDValue Src, unsigned Offset) {
1970 SDValue Ptr = LD->getBasePtr();
1971 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1972 EVT BasePtrVT = Ptr.getValueType();
1974 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1977 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1978 DAG.getConstant(Offset, BasePtrVT));
1980 SDValue Ops[] = { Chain, Ptr, Src };
1981 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
1982 LD->getMemOperand());
1985 // Expand an unaligned 32 or 64-bit integer load node.
1986 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1987 LoadSDNode *LD = cast<LoadSDNode>(Op);
1988 EVT MemVT = LD->getMemoryVT();
1990 if (Subtarget->systemSupportsUnalignedAccess())
1993 // Return if load is aligned or if MemVT is neither i32 nor i64.
1994 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1995 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1998 bool IsLittle = Subtarget->isLittle();
1999 EVT VT = Op.getValueType();
2000 ISD::LoadExtType ExtType = LD->getExtensionType();
2001 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2003 assert((VT == MVT::i32) || (VT == MVT::i64));
2006 // (set dst, (i64 (load baseptr)))
2008 // (set tmp, (ldl (add baseptr, 7), undef))
2009 // (set dst, (ldr baseptr, tmp))
2010 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2011 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2013 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2017 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2019 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2023 // (set dst, (i32 (load baseptr))) or
2024 // (set dst, (i64 (sextload baseptr))) or
2025 // (set dst, (i64 (extload baseptr)))
2027 // (set tmp, (lwl (add baseptr, 3), undef))
2028 // (set dst, (lwr baseptr, tmp))
2029 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2030 (ExtType == ISD::EXTLOAD))
2033 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2036 // (set dst, (i64 (zextload baseptr)))
2038 // (set tmp0, (lwl (add baseptr, 3), undef))
2039 // (set tmp1, (lwr baseptr, tmp0))
2040 // (set tmp2, (shl tmp1, 32))
2041 // (set dst, (srl tmp2, 32))
2043 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2044 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2045 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2046 SDValue Ops[] = { SRL, LWR.getValue(1) };
2047 return DAG.getMergeValues(Ops, DL);
2050 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2051 SDValue Chain, unsigned Offset) {
2052 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2053 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2055 SDVTList VTList = DAG.getVTList(MVT::Other);
2058 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2059 DAG.getConstant(Offset, BasePtrVT));
2061 SDValue Ops[] = { Chain, Value, Ptr };
2062 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2063 SD->getMemOperand());
2066 // Expand an unaligned 32 or 64-bit integer store node.
2067 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2069 SDValue Value = SD->getValue(), Chain = SD->getChain();
2070 EVT VT = Value.getValueType();
2073 // (store val, baseptr) or
2074 // (truncstore val, baseptr)
2076 // (swl val, (add baseptr, 3))
2077 // (swr val, baseptr)
2078 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2079 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2081 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2084 assert(VT == MVT::i64);
2087 // (store val, baseptr)
2089 // (sdl val, (add baseptr, 7))
2090 // (sdr val, baseptr)
2091 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2092 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2095 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2096 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2097 SDValue Val = SD->getValue();
2099 if (Val.getOpcode() != ISD::FP_TO_SINT)
2102 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2103 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2106 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2107 SD->getPointerInfo(), SD->isVolatile(),
2108 SD->isNonTemporal(), SD->getAlignment());
2111 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2112 StoreSDNode *SD = cast<StoreSDNode>(Op);
2113 EVT MemVT = SD->getMemoryVT();
2115 // Lower unaligned integer stores.
2116 if (!Subtarget->systemSupportsUnalignedAccess() &&
2117 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2118 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2119 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2121 return lowerFP_TO_SINT_STORE(SD, DAG);
2124 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2125 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2126 || cast<ConstantSDNode>
2127 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2128 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2132 // (add (frameaddr 0), (frame_to_args_offset))
2133 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2134 // (add FrameObject, 0)
2135 // where FrameObject is a fixed StackObject with offset 0 which points to
2136 // the old stack pointer.
2137 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2138 EVT ValTy = Op->getValueType(0);
2139 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2140 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2141 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2142 DAG.getConstant(0, ValTy));
2145 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2146 SelectionDAG &DAG) const {
2147 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2148 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2150 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2153 //===----------------------------------------------------------------------===//
2154 // Calling Convention Implementation
2155 //===----------------------------------------------------------------------===//
2157 //===----------------------------------------------------------------------===//
2158 // TODO: Implement a generic logic using tblgen that can support this.
2159 // Mips O32 ABI rules:
2161 // i32 - Passed in A0, A1, A2, A3 and stack
2162 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2163 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2164 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2165 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2166 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2169 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2170 //===----------------------------------------------------------------------===//
2172 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2173 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2174 CCState &State, const MCPhysReg *F64Regs) {
2176 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2178 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2179 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2181 // Do not process byval args here.
2182 if (ArgFlags.isByVal())
2185 // Promote i8 and i16
2186 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2188 if (ArgFlags.isSExt())
2189 LocInfo = CCValAssign::SExt;
2190 else if (ArgFlags.isZExt())
2191 LocInfo = CCValAssign::ZExt;
2193 LocInfo = CCValAssign::AExt;
2198 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2199 // is true: function is vararg, argument is 3rd or higher, there is previous
2200 // argument which is not f32 or f64.
2201 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2202 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2203 unsigned OrigAlign = ArgFlags.getOrigAlign();
2204 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2206 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2207 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2208 // If this is the first part of an i64 arg,
2209 // the allocated register must be either A0 or A2.
2210 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2211 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2213 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2214 // Allocate int register and shadow next int register. If first
2215 // available register is Mips::A1 or Mips::A3, shadow it too.
2216 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2217 if (Reg == Mips::A1 || Reg == Mips::A3)
2218 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2219 State.AllocateReg(IntRegs, IntRegsSize);
2221 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2222 // we are guaranteed to find an available float register
2223 if (ValVT == MVT::f32) {
2224 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2225 // Shadow int register
2226 State.AllocateReg(IntRegs, IntRegsSize);
2228 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2229 // Shadow int registers
2230 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2231 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2232 State.AllocateReg(IntRegs, IntRegsSize);
2233 State.AllocateReg(IntRegs, IntRegsSize);
2236 llvm_unreachable("Cannot handle this ValVT.");
2239 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2241 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2243 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2248 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2249 MVT LocVT, CCValAssign::LocInfo LocInfo,
2250 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2251 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2253 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2256 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2257 MVT LocVT, CCValAssign::LocInfo LocInfo,
2258 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2259 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2261 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2264 #include "MipsGenCallingConv.inc"
2266 //===----------------------------------------------------------------------===//
2267 // Call Calling Convention Implementation
2268 //===----------------------------------------------------------------------===//
2270 // Return next O32 integer argument register.
2271 static unsigned getNextIntArgReg(unsigned Reg) {
2272 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2273 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2277 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2278 SDValue Chain, SDValue Arg, SDLoc DL,
2279 bool IsTailCall, SelectionDAG &DAG) const {
2281 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2282 DAG.getIntPtrConstant(Offset));
2283 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2287 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2288 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2289 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2290 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2291 /*isVolatile=*/ true, false, 0);
2294 void MipsTargetLowering::
2295 getOpndList(SmallVectorImpl<SDValue> &Ops,
2296 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2297 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2298 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2299 // Insert node "GP copy globalreg" before call to function.
2301 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2302 // in PIC mode) allow symbols to be resolved via lazy binding.
2303 // The lazy binding stub requires GP to point to the GOT.
2304 if (IsPICCall && !InternalLinkage) {
2305 unsigned GPReg = isN64() ? Mips::GP_64 : Mips::GP;
2306 EVT Ty = isN64() ? MVT::i64 : MVT::i32;
2307 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2310 // Build a sequence of copy-to-reg nodes chained together with token
2311 // chain and flag operands which copy the outgoing args into registers.
2312 // The InFlag in necessary since all emitted instructions must be
2316 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2317 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2318 RegsToPass[i].second, InFlag);
2319 InFlag = Chain.getValue(1);
2322 // Add argument registers to the end of the list so that they are
2323 // known live into the call.
2324 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2325 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2326 RegsToPass[i].second.getValueType()));
2328 // Add a register mask operand representing the call-preserved registers.
2329 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2330 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2331 assert(Mask && "Missing call preserved mask for calling convention");
2332 if (Subtarget->inMips16HardFloat()) {
2333 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2334 llvm::StringRef Sym = G->getGlobal()->getName();
2335 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2336 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2337 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2341 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2343 if (InFlag.getNode())
2344 Ops.push_back(InFlag);
2347 /// LowerCall - functions arguments are copied from virtual regs to
2348 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2350 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2351 SmallVectorImpl<SDValue> &InVals) const {
2352 SelectionDAG &DAG = CLI.DAG;
2354 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2355 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2356 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2357 SDValue Chain = CLI.Chain;
2358 SDValue Callee = CLI.Callee;
2359 bool &IsTailCall = CLI.IsTailCall;
2360 CallingConv::ID CallConv = CLI.CallConv;
2361 bool IsVarArg = CLI.IsVarArg;
2363 MachineFunction &MF = DAG.getMachineFunction();
2364 MachineFrameInfo *MFI = MF.getFrameInfo();
2365 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2366 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2367 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2369 // Analyze operands of the call, assigning locations to each operand.
2370 SmallVector<CCValAssign, 16> ArgLocs;
2371 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2372 getTargetMachine(), ArgLocs, *DAG.getContext());
2373 MipsCC::SpecialCallingConvType SpecialCallingConv =
2374 getSpecialCallingConv(Callee);
2375 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo,
2376 SpecialCallingConv);
2378 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2379 Subtarget->mipsSEUsesSoftFloat(),
2380 Callee.getNode(), CLI.getArgs());
2382 // Get a count of how many bytes are to be pushed on the stack.
2383 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2385 // Check if it's really possible to do a tail call.
2388 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2389 *MF.getInfo<MipsFunctionInfo>());
2391 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2392 report_fatal_error("failed to perform tail call elimination on a call "
2393 "site marked musttail");
2398 // Chain is the output chain of the last Load/Store or CopyToReg node.
2399 // ByValChain is the output chain of the last Memcpy node created for copying
2400 // byval arguments to the stack.
2401 unsigned StackAlignment = TFL->getStackAlignment();
2402 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2403 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2406 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2408 SDValue StackPtr = DAG.getCopyFromReg(
2409 Chain, DL, isN64() ? Mips::SP_64 : Mips::SP, getPointerTy());
2411 // With EABI is it possible to have 16 args on registers.
2412 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2413 SmallVector<SDValue, 8> MemOpChains;
2414 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2416 // Walk the register/memloc assignments, inserting copies/loads.
2417 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2418 SDValue Arg = OutVals[i];
2419 CCValAssign &VA = ArgLocs[i];
2420 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2421 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2424 if (Flags.isByVal()) {
2425 assert(Flags.getByValSize() &&
2426 "ByVal args of size 0 should have been ignored by front-end.");
2427 assert(ByValArg != MipsCCInfo.byval_end());
2428 assert(!IsTailCall &&
2429 "Do not tail-call optimize if there is a byval argument.");
2430 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2431 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2436 // Promote the value if needed.
2437 switch (VA.getLocInfo()) {
2438 default: llvm_unreachable("Unknown loc info!");
2439 case CCValAssign::Full:
2440 if (VA.isRegLoc()) {
2441 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2442 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2443 (ValVT == MVT::i64 && LocVT == MVT::f64))
2444 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2445 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2446 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2447 Arg, DAG.getConstant(0, MVT::i32));
2448 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2449 Arg, DAG.getConstant(1, MVT::i32));
2450 if (!Subtarget->isLittle())
2452 unsigned LocRegLo = VA.getLocReg();
2453 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2454 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2455 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2460 case CCValAssign::SExt:
2461 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2463 case CCValAssign::ZExt:
2464 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2466 case CCValAssign::AExt:
2467 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2471 // Arguments that can be passed on register must be kept at
2472 // RegsToPass vector
2473 if (VA.isRegLoc()) {
2474 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2478 // Register can't get to this point...
2479 assert(VA.isMemLoc());
2481 // emit ISD::STORE whichs stores the
2482 // parameter value to a stack Location
2483 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2484 Chain, Arg, DL, IsTailCall, DAG));
2487 // Transform all store nodes into one single node because all store
2488 // nodes are independent of each other.
2489 if (!MemOpChains.empty())
2490 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2492 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2493 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2494 // node so that legalize doesn't hack it.
2495 bool IsPICCall = (isN64() || IsPIC); // true if calls are translated to
2497 bool GlobalOrExternal = false, InternalLinkage = false;
2499 EVT Ty = Callee.getValueType();
2501 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2503 const GlobalValue *Val = G->getGlobal();
2504 InternalLinkage = Val->hasInternalLinkage();
2506 if (InternalLinkage)
2507 Callee = getAddrLocal(G, Ty, DAG, isN32() || isN64());
2509 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2510 MipsII::MO_CALL_LO16, Chain,
2511 FuncInfo->callPtrInfo(Val));
2513 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2514 FuncInfo->callPtrInfo(Val));
2516 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2517 MipsII::MO_NO_FLAG);
2518 GlobalOrExternal = true;
2520 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2521 const char *Sym = S->getSymbol();
2523 if (!isN64() && !IsPIC) // !N64 && static
2524 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2525 MipsII::MO_NO_FLAG);
2527 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2528 MipsII::MO_CALL_LO16, Chain,
2529 FuncInfo->callPtrInfo(Sym));
2531 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2532 FuncInfo->callPtrInfo(Sym));
2534 GlobalOrExternal = true;
2537 SmallVector<SDValue, 8> Ops(1, Chain);
2538 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2540 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2541 CLI, Callee, Chain);
2544 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2546 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2547 SDValue InFlag = Chain.getValue(1);
2549 // Create the CALLSEQ_END node.
2550 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2551 DAG.getIntPtrConstant(0, true), InFlag, DL);
2552 InFlag = Chain.getValue(1);
2554 // Handle result values, copying them out of physregs into vregs that we
2556 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2557 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2560 /// LowerCallResult - Lower the result values of a call into the
2561 /// appropriate copies out of appropriate physical registers.
2563 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2564 CallingConv::ID CallConv, bool IsVarArg,
2565 const SmallVectorImpl<ISD::InputArg> &Ins,
2566 SDLoc DL, SelectionDAG &DAG,
2567 SmallVectorImpl<SDValue> &InVals,
2568 const SDNode *CallNode,
2569 const Type *RetTy) const {
2570 // Assign locations to each value returned by this call.
2571 SmallVector<CCValAssign, 16> RVLocs;
2572 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2573 getTargetMachine(), RVLocs, *DAG.getContext());
2574 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2576 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2579 // Copy all of the result registers out of their specified physreg.
2580 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2581 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2582 RVLocs[i].getLocVT(), InFlag);
2583 Chain = Val.getValue(1);
2584 InFlag = Val.getValue(2);
2586 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2587 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2589 InVals.push_back(Val);
2595 //===----------------------------------------------------------------------===//
2596 // Formal Arguments Calling Convention Implementation
2597 //===----------------------------------------------------------------------===//
2598 /// LowerFormalArguments - transform physical registers into virtual registers
2599 /// and generate load operations for arguments places on the stack.
2601 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2602 CallingConv::ID CallConv,
2604 const SmallVectorImpl<ISD::InputArg> &Ins,
2605 SDLoc DL, SelectionDAG &DAG,
2606 SmallVectorImpl<SDValue> &InVals)
2608 MachineFunction &MF = DAG.getMachineFunction();
2609 MachineFrameInfo *MFI = MF.getFrameInfo();
2610 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2612 MipsFI->setVarArgsFrameIndex(0);
2614 // Used with vargs to acumulate store chains.
2615 std::vector<SDValue> OutChains;
2617 // Assign locations to all of the incoming arguments.
2618 SmallVector<CCValAssign, 16> ArgLocs;
2619 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2620 getTargetMachine(), ArgLocs, *DAG.getContext());
2621 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2622 Function::const_arg_iterator FuncArg =
2623 DAG.getMachineFunction().getFunction()->arg_begin();
2624 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2626 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2627 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2628 MipsCCInfo.hasByValArg());
2630 unsigned CurArgIdx = 0;
2631 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2633 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2634 CCValAssign &VA = ArgLocs[i];
2635 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2636 CurArgIdx = Ins[i].OrigArgIndex;
2637 EVT ValVT = VA.getValVT();
2638 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2639 bool IsRegLoc = VA.isRegLoc();
2641 if (Flags.isByVal()) {
2642 assert(Flags.getByValSize() &&
2643 "ByVal args of size 0 should have been ignored by front-end.");
2644 assert(ByValArg != MipsCCInfo.byval_end());
2645 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2646 MipsCCInfo, *ByValArg);
2651 // Arguments stored on registers
2653 MVT RegVT = VA.getLocVT();
2654 unsigned ArgReg = VA.getLocReg();
2655 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2657 // Transform the arguments stored on
2658 // physical registers into virtual ones
2659 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2660 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2662 // If this is an 8 or 16-bit value, it has been passed promoted
2663 // to 32 bits. Insert an assert[sz]ext to capture this, then
2664 // truncate to the right size.
2665 if (VA.getLocInfo() != CCValAssign::Full) {
2666 unsigned Opcode = 0;
2667 if (VA.getLocInfo() == CCValAssign::SExt)
2668 Opcode = ISD::AssertSext;
2669 else if (VA.getLocInfo() == CCValAssign::ZExt)
2670 Opcode = ISD::AssertZext;
2672 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2673 DAG.getValueType(ValVT));
2674 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2677 // Handle floating point arguments passed in integer registers and
2678 // long double arguments passed in floating point registers.
2679 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2680 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2681 (RegVT == MVT::f64 && ValVT == MVT::i64))
2682 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2683 else if (isO32() && RegVT == MVT::i32 && ValVT == MVT::f64) {
2684 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2685 getNextIntArgReg(ArgReg), RC);
2686 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2687 if (!Subtarget->isLittle())
2688 std::swap(ArgValue, ArgValue2);
2689 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2690 ArgValue, ArgValue2);
2693 InVals.push_back(ArgValue);
2694 } else { // VA.isRegLoc()
2697 assert(VA.isMemLoc());
2699 // The stack pointer offset is relative to the caller stack frame.
2700 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2701 VA.getLocMemOffset(), true);
2703 // Create load nodes to retrieve arguments from the stack
2704 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2705 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2706 MachinePointerInfo::getFixedStack(FI),
2707 false, false, false, 0);
2708 InVals.push_back(Load);
2709 OutChains.push_back(Load.getValue(1));
2713 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2714 // The mips ABIs for returning structs by value requires that we copy
2715 // the sret argument into $v0 for the return. Save the argument into
2716 // a virtual register so that we can access it from the return points.
2717 if (Ins[i].Flags.isSRet()) {
2718 unsigned Reg = MipsFI->getSRetReturnReg();
2720 Reg = MF.getRegInfo().createVirtualRegister(
2721 getRegClassFor(isN64() ? MVT::i64 : MVT::i32));
2722 MipsFI->setSRetReturnReg(Reg);
2724 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
2725 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2731 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2733 // All stores are grouped in one node to allow the matching between
2734 // the size of Ins and InVals. This only happens when on varg functions
2735 if (!OutChains.empty()) {
2736 OutChains.push_back(Chain);
2737 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2743 //===----------------------------------------------------------------------===//
2744 // Return Value Calling Convention Implementation
2745 //===----------------------------------------------------------------------===//
2748 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2749 MachineFunction &MF, bool IsVarArg,
2750 const SmallVectorImpl<ISD::OutputArg> &Outs,
2751 LLVMContext &Context) const {
2752 SmallVector<CCValAssign, 16> RVLocs;
2753 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2755 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2759 MipsTargetLowering::LowerReturn(SDValue Chain,
2760 CallingConv::ID CallConv, bool IsVarArg,
2761 const SmallVectorImpl<ISD::OutputArg> &Outs,
2762 const SmallVectorImpl<SDValue> &OutVals,
2763 SDLoc DL, SelectionDAG &DAG) const {
2764 // CCValAssign - represent the assignment of
2765 // the return value to a location
2766 SmallVector<CCValAssign, 16> RVLocs;
2767 MachineFunction &MF = DAG.getMachineFunction();
2769 // CCState - Info about the registers and stack slot.
2770 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2772 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2774 // Analyze return values.
2775 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2776 MF.getFunction()->getReturnType());
2779 SmallVector<SDValue, 4> RetOps(1, Chain);
2781 // Copy the result values into the output registers.
2782 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2783 SDValue Val = OutVals[i];
2784 CCValAssign &VA = RVLocs[i];
2785 assert(VA.isRegLoc() && "Can only return in registers!");
2787 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2788 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2790 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2792 // Guarantee that all emitted copies are stuck together with flags.
2793 Flag = Chain.getValue(1);
2794 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2797 // The mips ABIs for returning structs by value requires that we copy
2798 // the sret argument into $v0 for the return. We saved the argument into
2799 // a virtual register in the entry block, so now we copy the value out
2801 if (MF.getFunction()->hasStructRetAttr()) {
2802 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2803 unsigned Reg = MipsFI->getSRetReturnReg();
2806 llvm_unreachable("sret virtual register not created in the entry block");
2807 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2808 unsigned V0 = isN64() ? Mips::V0_64 : Mips::V0;
2810 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2811 Flag = Chain.getValue(1);
2812 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2815 RetOps[0] = Chain; // Update chain.
2817 // Add the flag if we have it.
2819 RetOps.push_back(Flag);
2821 // Return on Mips is always a "jr $ra"
2822 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
2825 //===----------------------------------------------------------------------===//
2826 // Mips Inline Assembly Support
2827 //===----------------------------------------------------------------------===//
2829 /// getConstraintType - Given a constraint letter, return the type of
2830 /// constraint it is for this target.
2831 MipsTargetLowering::ConstraintType MipsTargetLowering::
2832 getConstraintType(const std::string &Constraint) const
2834 // Mips specific constraints
2835 // GCC config/mips/constraints.md
2837 // 'd' : An address register. Equivalent to r
2838 // unless generating MIPS16 code.
2839 // 'y' : Equivalent to r; retained for
2840 // backwards compatibility.
2841 // 'c' : A register suitable for use in an indirect
2842 // jump. This will always be $25 for -mabicalls.
2843 // 'l' : The lo register. 1 word storage.
2844 // 'x' : The hilo register pair. Double word storage.
2845 if (Constraint.size() == 1) {
2846 switch (Constraint[0]) {
2854 return C_RegisterClass;
2859 return TargetLowering::getConstraintType(Constraint);
2862 /// Examine constraint type and operand type and determine a weight value.
2863 /// This object must already have been set up with the operand type
2864 /// and the current alternative constraint selected.
2865 TargetLowering::ConstraintWeight
2866 MipsTargetLowering::getSingleConstraintMatchWeight(
2867 AsmOperandInfo &info, const char *constraint) const {
2868 ConstraintWeight weight = CW_Invalid;
2869 Value *CallOperandVal = info.CallOperandVal;
2870 // If we don't have a value, we can't do a match,
2871 // but allow it at the lowest weight.
2872 if (!CallOperandVal)
2874 Type *type = CallOperandVal->getType();
2875 // Look at the constraint type.
2876 switch (*constraint) {
2878 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2882 if (type->isIntegerTy())
2883 weight = CW_Register;
2885 case 'f': // FPU or MSA register
2886 if (Subtarget->hasMSA() && type->isVectorTy() &&
2887 cast<VectorType>(type)->getBitWidth() == 128)
2888 weight = CW_Register;
2889 else if (type->isFloatTy())
2890 weight = CW_Register;
2892 case 'c': // $25 for indirect jumps
2893 case 'l': // lo register
2894 case 'x': // hilo register pair
2895 if (type->isIntegerTy())
2896 weight = CW_SpecificReg;
2898 case 'I': // signed 16 bit immediate
2899 case 'J': // integer zero
2900 case 'K': // unsigned 16 bit immediate
2901 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2902 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2903 case 'O': // signed 15 bit immediate (+- 16383)
2904 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2905 if (isa<ConstantInt>(CallOperandVal))
2906 weight = CW_Constant;
2915 /// This is a helper function to parse a physical register string and split it
2916 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2917 /// that is returned indicates whether parsing was successful. The second flag
2918 /// is true if the numeric part exists.
2919 static std::pair<bool, bool>
2920 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2921 unsigned long long &Reg) {
2922 if (C.front() != '{' || C.back() != '}')
2923 return std::make_pair(false, false);
2925 // Search for the first numeric character.
2926 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2927 I = std::find_if(B, E, std::ptr_fun(isdigit));
2929 Prefix.assign(B, I - B);
2931 // The second flag is set to false if no numeric characters were found.
2933 return std::make_pair(true, false);
2935 // Parse the numeric characters.
2936 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2940 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2941 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2942 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2943 const TargetRegisterClass *RC;
2945 unsigned long long Reg;
2947 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2950 return std::make_pair(0U, nullptr);
2952 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2953 // No numeric characters follow "hi" or "lo".
2955 return std::make_pair(0U, nullptr);
2957 RC = TRI->getRegClass(Prefix == "hi" ?
2958 Mips::HI32RegClassID : Mips::LO32RegClassID);
2959 return std::make_pair(*(RC->begin()), RC);
2960 } else if (Prefix.compare(0, 4, "$msa") == 0) {
2961 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
2963 // No numeric characters follow the name.
2965 return std::make_pair(0U, nullptr);
2967 Reg = StringSwitch<unsigned long long>(Prefix)
2968 .Case("$msair", Mips::MSAIR)
2969 .Case("$msacsr", Mips::MSACSR)
2970 .Case("$msaaccess", Mips::MSAAccess)
2971 .Case("$msasave", Mips::MSASave)
2972 .Case("$msamodify", Mips::MSAModify)
2973 .Case("$msarequest", Mips::MSARequest)
2974 .Case("$msamap", Mips::MSAMap)
2975 .Case("$msaunmap", Mips::MSAUnmap)
2979 return std::make_pair(0U, nullptr);
2981 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
2982 return std::make_pair(Reg, RC);
2986 return std::make_pair(0U, nullptr);
2988 if (Prefix == "$f") { // Parse $f0-$f31.
2989 // If the size of FP registers is 64-bit or Reg is an even number, select
2990 // the 64-bit register class. Otherwise, select the 32-bit register class.
2991 if (VT == MVT::Other)
2992 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2994 RC = getRegClassFor(VT);
2996 if (RC == &Mips::AFGR64RegClass) {
2997 assert(Reg % 2 == 0);
3000 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
3001 RC = TRI->getRegClass(Mips::FCCRegClassID);
3002 else if (Prefix == "$w") { // Parse $w0-$w31.
3003 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
3004 } else { // Parse $0-$31.
3005 assert(Prefix == "$");
3006 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3009 assert(Reg < RC->getNumRegs());
3010 return std::make_pair(*(RC->begin() + Reg), RC);
3013 /// Given a register class constraint, like 'r', if this corresponds directly
3014 /// to an LLVM register class, return a register of 0 and the register class
3016 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3017 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3019 if (Constraint.size() == 1) {
3020 switch (Constraint[0]) {
3021 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3022 case 'y': // Same as 'r'. Exists for compatibility.
3024 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3025 if (Subtarget->inMips16Mode())
3026 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3027 return std::make_pair(0U, &Mips::GPR32RegClass);
3029 if (VT == MVT::i64 && !isGP64bit())
3030 return std::make_pair(0U, &Mips::GPR32RegClass);
3031 if (VT == MVT::i64 && isGP64bit())
3032 return std::make_pair(0U, &Mips::GPR64RegClass);
3033 // This will generate an error message
3034 return std::make_pair(0U, nullptr);
3035 case 'f': // FPU or MSA register
3036 if (VT == MVT::v16i8)
3037 return std::make_pair(0U, &Mips::MSA128BRegClass);
3038 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3039 return std::make_pair(0U, &Mips::MSA128HRegClass);
3040 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3041 return std::make_pair(0U, &Mips::MSA128WRegClass);
3042 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3043 return std::make_pair(0U, &Mips::MSA128DRegClass);
3044 else if (VT == MVT::f32)
3045 return std::make_pair(0U, &Mips::FGR32RegClass);
3046 else if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3047 if (Subtarget->isFP64bit())
3048 return std::make_pair(0U, &Mips::FGR64RegClass);
3049 return std::make_pair(0U, &Mips::AFGR64RegClass);
3052 case 'c': // register suitable for indirect jump
3054 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3055 assert(VT == MVT::i64 && "Unexpected type.");
3056 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3057 case 'l': // register suitable for indirect jump
3059 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3060 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3061 case 'x': // register suitable for indirect jump
3062 // Fixme: Not triggering the use of both hi and low
3063 // This will generate an error message
3064 return std::make_pair(0U, nullptr);
3068 std::pair<unsigned, const TargetRegisterClass *> R;
3069 R = parseRegForInlineAsmConstraint(Constraint, VT);
3074 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3077 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3078 /// vector. If it is invalid, don't add anything to Ops.
3079 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3080 std::string &Constraint,
3081 std::vector<SDValue>&Ops,
3082 SelectionDAG &DAG) const {
3085 // Only support length 1 constraints for now.
3086 if (Constraint.length() > 1) return;
3088 char ConstraintLetter = Constraint[0];
3089 switch (ConstraintLetter) {
3090 default: break; // This will fall through to the generic implementation
3091 case 'I': // Signed 16 bit constant
3092 // If this fails, the parent routine will give an error
3093 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3094 EVT Type = Op.getValueType();
3095 int64_t Val = C->getSExtValue();
3096 if (isInt<16>(Val)) {
3097 Result = DAG.getTargetConstant(Val, Type);
3102 case 'J': // integer zero
3103 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3104 EVT Type = Op.getValueType();
3105 int64_t Val = C->getZExtValue();
3107 Result = DAG.getTargetConstant(0, Type);
3112 case 'K': // unsigned 16 bit immediate
3113 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3114 EVT Type = Op.getValueType();
3115 uint64_t Val = (uint64_t)C->getZExtValue();
3116 if (isUInt<16>(Val)) {
3117 Result = DAG.getTargetConstant(Val, Type);
3122 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3123 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3124 EVT Type = Op.getValueType();
3125 int64_t Val = C->getSExtValue();
3126 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3127 Result = DAG.getTargetConstant(Val, Type);
3132 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3133 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3134 EVT Type = Op.getValueType();
3135 int64_t Val = C->getSExtValue();
3136 if ((Val >= -65535) && (Val <= -1)) {
3137 Result = DAG.getTargetConstant(Val, Type);
3142 case 'O': // signed 15 bit immediate
3143 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3144 EVT Type = Op.getValueType();
3145 int64_t Val = C->getSExtValue();
3146 if ((isInt<15>(Val))) {
3147 Result = DAG.getTargetConstant(Val, Type);
3152 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3153 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3154 EVT Type = Op.getValueType();
3155 int64_t Val = C->getSExtValue();
3156 if ((Val <= 65535) && (Val >= 1)) {
3157 Result = DAG.getTargetConstant(Val, Type);
3164 if (Result.getNode()) {
3165 Ops.push_back(Result);
3169 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3172 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3174 // No global is ever allowed as a base.
3179 case 0: // "r+i" or just "i", depending on HasBaseReg.
3182 if (!AM.HasBaseReg) // allow "r+i".
3184 return false; // disallow "r+r" or "r+r+i".
3193 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3194 // The Mips target isn't yet aware of offsets.
3198 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3200 bool IsMemset, bool ZeroMemset,
3202 MachineFunction &MF) const {
3203 if (Subtarget->hasMips64())
3209 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3210 if (VT != MVT::f32 && VT != MVT::f64)
3212 if (Imm.isNegZero())
3214 return Imm.isZero();
3217 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3219 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3221 return TargetLowering::getJumpTableEncoding();
3224 /// This function returns true if CallSym is a long double emulation routine.
3225 static bool isF128SoftLibCall(const char *CallSym) {
3226 const char *const LibCalls[] =
3227 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3228 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3229 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3230 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3231 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3232 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3233 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3234 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3237 const char *const *End = LibCalls + array_lengthof(LibCalls);
3239 // Check that LibCalls is sorted alphabetically.
3240 MipsTargetLowering::LTStr Comp;
3243 for (const char *const *I = LibCalls; I < End - 1; ++I)
3244 assert(Comp(*I, *(I + 1)));
3247 return std::binary_search(LibCalls, End, CallSym, Comp);
3250 /// This function returns true if Ty is fp128 or i128 which was originally a
3252 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3253 if (Ty->isFP128Ty())
3256 const ExternalSymbolSDNode *ES =
3257 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3259 // If the Ty is i128 and the function being called is a long double emulation
3260 // routine, then the original type is f128.
3261 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3264 MipsTargetLowering::MipsCC::SpecialCallingConvType
3265 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3266 MipsCC::SpecialCallingConvType SpecialCallingConv =
3267 MipsCC::NoSpecialCallingConv;
3268 if (Subtarget->inMips16HardFloat()) {
3269 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3270 llvm::StringRef Sym = G->getGlobal()->getName();
3271 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3272 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3273 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3277 return SpecialCallingConv;
3280 MipsTargetLowering::MipsCC::MipsCC(
3281 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3282 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3283 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3284 SpecialCallingConv(SpecialCallingConv_){
3285 // Pre-allocate reserved argument area.
3286 CCInfo.AllocateStack(reservedArgArea(), 1);
3290 void MipsTargetLowering::MipsCC::
3291 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3292 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3293 std::vector<ArgListEntry> &FuncArgs) {
3294 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3295 "CallingConv::Fast shouldn't be used for vararg functions.");
3297 unsigned NumOpnds = Args.size();
3298 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3300 for (unsigned I = 0; I != NumOpnds; ++I) {
3301 MVT ArgVT = Args[I].VT;
3302 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3305 if (ArgFlags.isByVal()) {
3306 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3310 if (IsVarArg && !Args[I].IsFixed)
3311 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3313 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3315 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3320 dbgs() << "Call operand #" << I << " has unhandled type "
3321 << EVT(ArgVT).getEVTString();
3323 llvm_unreachable(nullptr);
3328 void MipsTargetLowering::MipsCC::
3329 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3330 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3331 unsigned NumArgs = Args.size();
3332 llvm::CCAssignFn *FixedFn = fixedArgFn();
3333 unsigned CurArgIdx = 0;
3335 for (unsigned I = 0; I != NumArgs; ++I) {
3336 MVT ArgVT = Args[I].VT;
3337 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3338 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3339 CurArgIdx = Args[I].OrigArgIndex;
3341 if (ArgFlags.isByVal()) {
3342 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3346 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), nullptr, IsSoftFloat);
3348 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3352 dbgs() << "Formal Arg #" << I << " has unhandled type "
3353 << EVT(ArgVT).getEVTString();
3355 llvm_unreachable(nullptr);
3359 template<typename Ty>
3360 void MipsTargetLowering::MipsCC::
3361 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3362 const SDNode *CallNode, const Type *RetTy) const {
3365 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3366 Fn = RetCC_F128Soft;
3370 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3371 MVT VT = RetVals[I].VT;
3372 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3373 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3375 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3377 dbgs() << "Call result #" << I << " has unhandled type "
3378 << EVT(VT).getEVTString() << '\n';
3380 llvm_unreachable(nullptr);
3385 void MipsTargetLowering::MipsCC::
3386 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3387 const SDNode *CallNode, const Type *RetTy) const {
3388 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3391 void MipsTargetLowering::MipsCC::
3392 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3393 const Type *RetTy) const {
3394 analyzeReturn(Outs, IsSoftFloat, nullptr, RetTy);
3397 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3399 CCValAssign::LocInfo LocInfo,
3400 ISD::ArgFlagsTy ArgFlags) {
3401 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3403 struct ByValArgInfo ByVal;
3404 unsigned RegSize = regSize();
3405 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3406 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3409 if (useRegsForByval())
3410 allocateRegs(ByVal, ByValSize, Align);
3412 // Allocate space on caller's stack.
3413 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3415 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3417 ByValArgs.push_back(ByVal);
3420 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3421 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3424 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3425 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3428 const MCPhysReg *MipsTargetLowering::MipsCC::intArgRegs() const {
3429 return IsO32 ? O32IntRegs : Mips64IntRegs;
3432 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3433 if (CallConv == CallingConv::Fast)
3434 return CC_Mips_FastCC;
3436 if (SpecialCallingConv == Mips16RetHelperConv)
3437 return CC_Mips16RetHelper;
3438 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3441 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3442 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3445 const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
3446 return IsO32 ? O32IntRegs : Mips64DPRegs;
3449 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3452 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3453 const MCPhysReg *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3454 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3455 "Byval argument's size and alignment should be a multiple of"
3458 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3460 // If Align > RegSize, the first arg register must be even.
3461 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3462 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3466 // Mark the registers allocated.
3467 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3468 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3469 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3472 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3473 const SDNode *CallNode,
3474 bool IsSoftFloat) const {
3475 if (IsSoftFloat || IsO32)
3478 // Check if the original type was fp128.
3479 if (originalTypeIsF128(OrigTy, CallNode)) {
3480 assert(VT == MVT::i64);
3487 void MipsTargetLowering::
3488 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3489 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3490 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3491 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3492 MachineFunction &MF = DAG.getMachineFunction();
3493 MachineFrameInfo *MFI = MF.getFrameInfo();
3494 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3495 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3499 FrameObjOffset = (int)CC.reservedArgArea() -
3500 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3502 FrameObjOffset = ByVal.Address;
3504 // Create frame object.
3505 EVT PtrTy = getPointerTy();
3506 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3507 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3508 InVals.push_back(FIN);
3513 // Copy arg registers.
3514 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3515 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3517 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3518 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3519 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3520 unsigned Offset = I * CC.regSize();
3521 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3522 DAG.getConstant(Offset, PtrTy));
3523 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3524 StorePtr, MachinePointerInfo(FuncArg, Offset),
3526 OutChains.push_back(Store);
3530 // Copy byVal arg to registers and stack.
3531 void MipsTargetLowering::
3532 passByValArg(SDValue Chain, SDLoc DL,
3533 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3534 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3535 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3536 const MipsCC &CC, const ByValArgInfo &ByVal,
3537 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3538 unsigned ByValSizeInBytes = Flags.getByValSize();
3539 unsigned OffsetInBytes = 0; // From beginning of struct
3540 unsigned RegSizeInBytes = CC.regSize();
3541 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3542 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3544 if (ByVal.NumRegs) {
3545 const MCPhysReg *ArgRegs = CC.intArgRegs();
3546 bool LeftoverBytes = (ByVal.NumRegs * RegSizeInBytes > ByValSizeInBytes);
3549 // Copy words to registers.
3550 for (; I < ByVal.NumRegs - LeftoverBytes;
3551 ++I, OffsetInBytes += RegSizeInBytes) {
3552 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3553 DAG.getConstant(OffsetInBytes, PtrTy));
3554 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3555 MachinePointerInfo(), false, false, false,
3557 MemOpChains.push_back(LoadVal.getValue(1));
3558 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3559 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3562 // Return if the struct has been fully copied.
3563 if (ByValSizeInBytes == OffsetInBytes)
3566 // Copy the remainder of the byval argument with sub-word loads and shifts.
3567 if (LeftoverBytes) {
3568 assert((ByValSizeInBytes > OffsetInBytes) &&
3569 (ByValSizeInBytes < OffsetInBytes + RegSizeInBytes) &&
3570 "Size of the remainder should be smaller than RegSizeInBytes.");
3573 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3574 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3575 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3577 if (RemainingSizeInBytes < LoadSizeInBytes)
3581 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3582 DAG.getConstant(OffsetInBytes, PtrTy));
3583 SDValue LoadVal = DAG.getExtLoad(
3584 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3585 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, Alignment);
3586 MemOpChains.push_back(LoadVal.getValue(1));
3588 // Shift the loaded value.
3592 Shamt = TotalBytesLoaded * 8;
3594 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3596 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3597 DAG.getConstant(Shamt, MVT::i32));
3600 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3604 OffsetInBytes += LoadSizeInBytes;
3605 TotalBytesLoaded += LoadSizeInBytes;
3606 Alignment = std::min(Alignment, LoadSizeInBytes);
3609 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3610 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3615 // Copy remainder of byval arg to it with memcpy.
3616 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3617 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3618 DAG.getConstant(OffsetInBytes, PtrTy));
3619 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3620 DAG.getIntPtrConstant(ByVal.Address));
3621 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3622 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3623 MachinePointerInfo(), MachinePointerInfo());
3624 MemOpChains.push_back(Chain);
3627 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3628 const MipsCC &CC, SDValue Chain,
3629 SDLoc DL, SelectionDAG &DAG) const {
3630 unsigned NumRegs = CC.numIntArgRegs();
3631 const MCPhysReg *ArgRegs = CC.intArgRegs();
3632 const CCState &CCInfo = CC.getCCInfo();
3633 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3634 unsigned RegSize = CC.regSize();
3635 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3636 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3637 MachineFunction &MF = DAG.getMachineFunction();
3638 MachineFrameInfo *MFI = MF.getFrameInfo();
3639 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3641 // Offset of the first variable argument from stack pointer.
3645 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3647 VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3649 // Record the frame index of the first variable argument
3650 // which is a value necessary to VASTART.
3651 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3652 MipsFI->setVarArgsFrameIndex(FI);
3654 // Copy the integer registers that have not been used for argument passing
3655 // to the argument register save area. For O32, the save area is allocated
3656 // in the caller's stack frame, while for N32/64, it is allocated in the
3657 // callee's stack frame.
3658 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3659 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3660 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3661 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3662 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3663 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3664 MachinePointerInfo(), false, false, 0);
3665 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue((Value*)nullptr);
3666 OutChains.push_back(Store);