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::Other, Expand);
291 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
292 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
293 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
294 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
295 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
296 if (Subtarget->hasCnMips()) {
297 setOperationAction(ISD::CTPOP, MVT::i32, Legal);
298 setOperationAction(ISD::CTPOP, MVT::i64, Legal);
300 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
301 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
303 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
304 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
305 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
306 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
307 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
308 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
309 setOperationAction(ISD::ROTL, MVT::i32, Expand);
310 setOperationAction(ISD::ROTL, MVT::i64, Expand);
311 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
312 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
314 if (!Subtarget->hasMips32r2())
315 setOperationAction(ISD::ROTR, MVT::i32, Expand);
317 if (!Subtarget->hasMips64r2())
318 setOperationAction(ISD::ROTR, MVT::i64, Expand);
320 setOperationAction(ISD::FSIN, MVT::f32, Expand);
321 setOperationAction(ISD::FSIN, MVT::f64, Expand);
322 setOperationAction(ISD::FCOS, MVT::f32, Expand);
323 setOperationAction(ISD::FCOS, MVT::f64, Expand);
324 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
325 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
326 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
327 setOperationAction(ISD::FPOW, MVT::f32, Expand);
328 setOperationAction(ISD::FPOW, MVT::f64, Expand);
329 setOperationAction(ISD::FLOG, MVT::f32, Expand);
330 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
331 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
332 setOperationAction(ISD::FEXP, MVT::f32, Expand);
333 setOperationAction(ISD::FMA, MVT::f32, Expand);
334 setOperationAction(ISD::FMA, MVT::f64, Expand);
335 setOperationAction(ISD::FREM, MVT::f32, Expand);
336 setOperationAction(ISD::FREM, MVT::f64, Expand);
338 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
340 setOperationAction(ISD::VAARG, MVT::Other, Expand);
341 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
342 setOperationAction(ISD::VAEND, MVT::Other, Expand);
344 // Use the default for now
345 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
346 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
348 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
349 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
350 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
351 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
353 setInsertFencesForAtomic(true);
355 if (!Subtarget->hasMips32r2()) {
356 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
357 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
360 // MIPS16 lacks MIPS32's clz and clo instructions.
361 if (!Subtarget->hasMips32() || Subtarget->inMips16Mode())
362 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
363 if (!Subtarget->hasMips64())
364 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
366 if (!Subtarget->hasMips32r2())
367 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
368 if (!Subtarget->hasMips64r2())
369 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
372 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
373 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
374 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
375 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
378 setOperationAction(ISD::TRAP, MVT::Other, Legal);
380 setTargetDAGCombine(ISD::SDIVREM);
381 setTargetDAGCombine(ISD::UDIVREM);
382 setTargetDAGCombine(ISD::SELECT);
383 setTargetDAGCombine(ISD::AND);
384 setTargetDAGCombine(ISD::OR);
385 setTargetDAGCombine(ISD::ADD);
387 setMinFunctionAlignment(isGP64bit() ? 3 : 2);
389 setStackPointerRegisterToSaveRestore(isN64() ? Mips::SP_64 : Mips::SP);
391 setExceptionPointerRegister(isN64() ? Mips::A0_64 : Mips::A0);
392 setExceptionSelectorRegister(isN64() ? Mips::A1_64 : Mips::A1);
394 MaxStoresPerMemcpy = 16;
396 isMicroMips = Subtarget->inMicroMipsMode();
399 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
400 if (TM.getSubtargetImpl()->inMips16Mode())
401 return llvm::createMips16TargetLowering(TM);
403 return llvm::createMipsSETargetLowering(TM);
406 // Create a fast isel object.
408 MipsTargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
409 const TargetLibraryInfo *libInfo) const {
410 if (!EnableMipsFastISel)
411 return TargetLowering::createFastISel(funcInfo, libInfo);
412 return Mips::createFastISel(funcInfo, libInfo);
415 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
418 return VT.changeVectorElementTypeToInteger();
421 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
422 TargetLowering::DAGCombinerInfo &DCI,
423 const MipsSubtarget *Subtarget) {
424 if (DCI.isBeforeLegalizeOps())
427 EVT Ty = N->getValueType(0);
428 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
429 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
430 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
434 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
435 N->getOperand(0), N->getOperand(1));
436 SDValue InChain = DAG.getEntryNode();
437 SDValue InGlue = DivRem;
440 if (N->hasAnyUseOfValue(0)) {
441 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
443 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
444 InChain = CopyFromLo.getValue(1);
445 InGlue = CopyFromLo.getValue(2);
449 if (N->hasAnyUseOfValue(1)) {
450 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
452 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
458 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
460 default: llvm_unreachable("Unknown fp condition code!");
462 case ISD::SETOEQ: return Mips::FCOND_OEQ;
463 case ISD::SETUNE: return Mips::FCOND_UNE;
465 case ISD::SETOLT: return Mips::FCOND_OLT;
467 case ISD::SETOGT: return Mips::FCOND_OGT;
469 case ISD::SETOLE: return Mips::FCOND_OLE;
471 case ISD::SETOGE: return Mips::FCOND_OGE;
472 case ISD::SETULT: return Mips::FCOND_ULT;
473 case ISD::SETULE: return Mips::FCOND_ULE;
474 case ISD::SETUGT: return Mips::FCOND_UGT;
475 case ISD::SETUGE: return Mips::FCOND_UGE;
476 case ISD::SETUO: return Mips::FCOND_UN;
477 case ISD::SETO: return Mips::FCOND_OR;
479 case ISD::SETONE: return Mips::FCOND_ONE;
480 case ISD::SETUEQ: return Mips::FCOND_UEQ;
485 /// This function returns true if the floating point conditional branches and
486 /// conditional moves which use condition code CC should be inverted.
487 static bool invertFPCondCodeUser(Mips::CondCode CC) {
488 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
491 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
492 "Illegal Condition Code");
497 // Creates and returns an FPCmp node from a setcc node.
498 // Returns Op if setcc is not a floating point comparison.
499 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
500 // must be a SETCC node
501 if (Op.getOpcode() != ISD::SETCC)
504 SDValue LHS = Op.getOperand(0);
506 if (!LHS.getValueType().isFloatingPoint())
509 SDValue RHS = Op.getOperand(1);
512 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
513 // node if necessary.
514 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
516 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
517 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
520 // Creates and returns a CMovFPT/F node.
521 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
522 SDValue False, SDLoc DL) {
523 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
524 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
525 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
527 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
528 True.getValueType(), True, FCC0, False, Cond);
531 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
532 TargetLowering::DAGCombinerInfo &DCI,
533 const MipsSubtarget *Subtarget) {
534 if (DCI.isBeforeLegalizeOps())
537 SDValue SetCC = N->getOperand(0);
539 if ((SetCC.getOpcode() != ISD::SETCC) ||
540 !SetCC.getOperand(0).getValueType().isInteger())
543 SDValue False = N->getOperand(2);
544 EVT FalseTy = False.getValueType();
546 if (!FalseTy.isInteger())
549 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
551 // If the RHS (False) is 0, we swap the order of the operands
552 // of ISD::SELECT (obviously also inverting the condition) so that we can
553 // take advantage of conditional moves using the $0 register.
555 // return (a != 0) ? x : 0;
563 if (!FalseC->getZExtValue()) {
564 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
565 SDValue True = N->getOperand(1);
567 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
568 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
570 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
573 // If both operands are integer constants there's a possibility that we
574 // can do some interesting optimizations.
575 SDValue True = N->getOperand(1);
576 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
578 if (!TrueC || !True.getValueType().isInteger())
581 // We'll also ignore MVT::i64 operands as this optimizations proves
582 // to be ineffective because of the required sign extensions as the result
583 // of a SETCC operator is always MVT::i32 for non-vector types.
584 if (True.getValueType() == MVT::i64)
587 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
589 // 1) (a < x) ? y : y-1
591 // addiu $reg2, $reg1, y-1
593 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
595 // 2) (a < x) ? y-1 : y
597 // xor $reg1, $reg1, 1
598 // addiu $reg2, $reg1, y-1
600 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
601 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
602 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
603 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
606 // Couldn't optimize.
610 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
611 TargetLowering::DAGCombinerInfo &DCI,
612 const MipsSubtarget *Subtarget) {
613 // Pattern match EXT.
614 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
615 // => ext $dst, $src, size, pos
616 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
619 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
620 unsigned ShiftRightOpc = ShiftRight.getOpcode();
622 // Op's first operand must be a shift right.
623 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
626 // The second operand of the shift must be an immediate.
628 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
631 uint64_t Pos = CN->getZExtValue();
632 uint64_t SMPos, SMSize;
634 // Op's second operand must be a shifted mask.
635 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
636 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
639 // Return if the shifted mask does not start at bit 0 or the sum of its size
640 // and Pos exceeds the word's size.
641 EVT ValTy = N->getValueType(0);
642 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
645 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
646 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
647 DAG.getConstant(SMSize, MVT::i32));
650 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
651 TargetLowering::DAGCombinerInfo &DCI,
652 const MipsSubtarget *Subtarget) {
653 // Pattern match INS.
654 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
655 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
656 // => ins $dst, $src, size, pos, $src1
657 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
660 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
661 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
664 // See if Op's first operand matches (and $src1 , mask0).
665 if (And0.getOpcode() != ISD::AND)
668 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
669 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
672 // See if Op's second operand matches (and (shl $src, pos), mask1).
673 if (And1.getOpcode() != ISD::AND)
676 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
677 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
680 // The shift masks must have the same position and size.
681 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
684 SDValue Shl = And1.getOperand(0);
685 if (Shl.getOpcode() != ISD::SHL)
688 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
691 unsigned Shamt = CN->getZExtValue();
693 // Return if the shift amount and the first bit position of mask are not the
695 EVT ValTy = N->getValueType(0);
696 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
699 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
700 DAG.getConstant(SMPos0, MVT::i32),
701 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
704 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
705 TargetLowering::DAGCombinerInfo &DCI,
706 const MipsSubtarget *Subtarget) {
707 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
709 if (DCI.isBeforeLegalizeOps())
712 SDValue Add = N->getOperand(1);
714 if (Add.getOpcode() != ISD::ADD)
717 SDValue Lo = Add.getOperand(1);
719 if ((Lo.getOpcode() != MipsISD::Lo) ||
720 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
723 EVT ValTy = N->getValueType(0);
726 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
728 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
731 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
733 SelectionDAG &DAG = DCI.DAG;
734 unsigned Opc = N->getOpcode();
740 return performDivRemCombine(N, DAG, DCI, Subtarget);
742 return performSELECTCombine(N, DAG, DCI, Subtarget);
744 return performANDCombine(N, DAG, DCI, Subtarget);
746 return performORCombine(N, DAG, DCI, Subtarget);
748 return performADDCombine(N, DAG, DCI, Subtarget);
755 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
756 SmallVectorImpl<SDValue> &Results,
757 SelectionDAG &DAG) const {
758 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
760 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
761 Results.push_back(Res.getValue(I));
765 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
766 SmallVectorImpl<SDValue> &Results,
767 SelectionDAG &DAG) const {
768 return LowerOperationWrapper(N, Results, DAG);
771 SDValue MipsTargetLowering::
772 LowerOperation(SDValue Op, SelectionDAG &DAG) const
774 switch (Op.getOpcode())
776 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
777 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
778 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
779 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
780 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
781 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
782 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
783 case ISD::SELECT: return lowerSELECT(Op, DAG);
784 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
785 case ISD::SETCC: return lowerSETCC(Op, DAG);
786 case ISD::VASTART: return lowerVASTART(Op, DAG);
787 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
788 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
789 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
790 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
791 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
792 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
793 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
794 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
795 case ISD::LOAD: return lowerLOAD(Op, DAG);
796 case ISD::STORE: return lowerSTORE(Op, DAG);
797 case ISD::ADD: return lowerADD(Op, DAG);
798 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
803 //===----------------------------------------------------------------------===//
804 // Lower helper functions
805 //===----------------------------------------------------------------------===//
807 // addLiveIn - This helper function adds the specified physical register to the
808 // MachineFunction as a live in value. It also creates a corresponding
809 // virtual register for it.
811 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
813 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
814 MF.getRegInfo().addLiveIn(PReg, VReg);
818 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
819 MachineBasicBlock &MBB,
820 const TargetInstrInfo &TII,
825 // Insert instruction "teq $divisor_reg, $zero, 7".
826 MachineBasicBlock::iterator I(MI);
827 MachineInstrBuilder MIB;
828 MachineOperand &Divisor = MI->getOperand(2);
829 MIB = BuildMI(MBB, std::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
830 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
831 .addReg(Mips::ZERO).addImm(7);
833 // Use the 32-bit sub-register if this is a 64-bit division.
835 MIB->getOperand(0).setSubReg(Mips::sub_32);
837 // Clear Divisor's kill flag.
838 Divisor.setIsKill(false);
843 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
844 MachineBasicBlock *BB) const {
845 switch (MI->getOpcode()) {
847 llvm_unreachable("Unexpected instr type to insert");
848 case Mips::ATOMIC_LOAD_ADD_I8:
849 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
850 case Mips::ATOMIC_LOAD_ADD_I16:
851 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
852 case Mips::ATOMIC_LOAD_ADD_I32:
853 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
854 case Mips::ATOMIC_LOAD_ADD_I64:
855 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
857 case Mips::ATOMIC_LOAD_AND_I8:
858 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
859 case Mips::ATOMIC_LOAD_AND_I16:
860 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
861 case Mips::ATOMIC_LOAD_AND_I32:
862 return emitAtomicBinary(MI, BB, 4, Mips::AND);
863 case Mips::ATOMIC_LOAD_AND_I64:
864 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
866 case Mips::ATOMIC_LOAD_OR_I8:
867 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
868 case Mips::ATOMIC_LOAD_OR_I16:
869 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
870 case Mips::ATOMIC_LOAD_OR_I32:
871 return emitAtomicBinary(MI, BB, 4, Mips::OR);
872 case Mips::ATOMIC_LOAD_OR_I64:
873 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
875 case Mips::ATOMIC_LOAD_XOR_I8:
876 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
877 case Mips::ATOMIC_LOAD_XOR_I16:
878 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
879 case Mips::ATOMIC_LOAD_XOR_I32:
880 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
881 case Mips::ATOMIC_LOAD_XOR_I64:
882 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
884 case Mips::ATOMIC_LOAD_NAND_I8:
885 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
886 case Mips::ATOMIC_LOAD_NAND_I16:
887 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
888 case Mips::ATOMIC_LOAD_NAND_I32:
889 return emitAtomicBinary(MI, BB, 4, 0, true);
890 case Mips::ATOMIC_LOAD_NAND_I64:
891 return emitAtomicBinary(MI, BB, 8, 0, true);
893 case Mips::ATOMIC_LOAD_SUB_I8:
894 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
895 case Mips::ATOMIC_LOAD_SUB_I16:
896 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
897 case Mips::ATOMIC_LOAD_SUB_I32:
898 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
899 case Mips::ATOMIC_LOAD_SUB_I64:
900 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
902 case Mips::ATOMIC_SWAP_I8:
903 return emitAtomicBinaryPartword(MI, BB, 1, 0);
904 case Mips::ATOMIC_SWAP_I16:
905 return emitAtomicBinaryPartword(MI, BB, 2, 0);
906 case Mips::ATOMIC_SWAP_I32:
907 return emitAtomicBinary(MI, BB, 4, 0);
908 case Mips::ATOMIC_SWAP_I64:
909 return emitAtomicBinary(MI, BB, 8, 0);
911 case Mips::ATOMIC_CMP_SWAP_I8:
912 return emitAtomicCmpSwapPartword(MI, BB, 1);
913 case Mips::ATOMIC_CMP_SWAP_I16:
914 return emitAtomicCmpSwapPartword(MI, BB, 2);
915 case Mips::ATOMIC_CMP_SWAP_I32:
916 return emitAtomicCmpSwap(MI, BB, 4);
917 case Mips::ATOMIC_CMP_SWAP_I64:
918 return emitAtomicCmpSwap(MI, BB, 8);
919 case Mips::PseudoSDIV:
920 case Mips::PseudoUDIV:
921 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
922 case Mips::PseudoDSDIV:
923 case Mips::PseudoDUDIV:
924 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
928 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
929 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
931 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
932 unsigned Size, unsigned BinOpcode,
934 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
936 MachineFunction *MF = BB->getParent();
937 MachineRegisterInfo &RegInfo = MF->getRegInfo();
938 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
939 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
940 DebugLoc DL = MI->getDebugLoc();
941 unsigned LL, SC, AND, NOR, ZERO, BEQ;
944 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
945 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
956 ZERO = Mips::ZERO_64;
960 unsigned OldVal = MI->getOperand(0).getReg();
961 unsigned Ptr = MI->getOperand(1).getReg();
962 unsigned Incr = MI->getOperand(2).getReg();
964 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
965 unsigned AndRes = RegInfo.createVirtualRegister(RC);
966 unsigned Success = RegInfo.createVirtualRegister(RC);
968 // insert new blocks after the current block
969 const BasicBlock *LLVM_BB = BB->getBasicBlock();
970 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
971 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
972 MachineFunction::iterator It = BB;
974 MF->insert(It, loopMBB);
975 MF->insert(It, exitMBB);
977 // Transfer the remainder of BB and its successor edges to exitMBB.
978 exitMBB->splice(exitMBB->begin(), BB,
979 std::next(MachineBasicBlock::iterator(MI)), BB->end());
980 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
984 // fallthrough --> loopMBB
985 BB->addSuccessor(loopMBB);
986 loopMBB->addSuccessor(loopMBB);
987 loopMBB->addSuccessor(exitMBB);
991 // <binop> storeval, oldval, incr
992 // sc success, storeval, 0(ptr)
993 // beq success, $0, loopMBB
995 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
997 // and andres, oldval, incr
998 // nor storeval, $0, andres
999 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1000 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1001 } else if (BinOpcode) {
1002 // <binop> storeval, oldval, incr
1003 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1007 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1008 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1010 MI->eraseFromParent(); // The instruction is gone now.
1016 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
1017 MachineBasicBlock *BB,
1018 unsigned Size, unsigned BinOpcode,
1020 assert((Size == 1 || Size == 2) &&
1021 "Unsupported size for EmitAtomicBinaryPartial.");
1023 MachineFunction *MF = BB->getParent();
1024 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1025 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1026 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1027 DebugLoc DL = MI->getDebugLoc();
1029 unsigned Dest = MI->getOperand(0).getReg();
1030 unsigned Ptr = MI->getOperand(1).getReg();
1031 unsigned Incr = MI->getOperand(2).getReg();
1033 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1034 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1035 unsigned Mask = RegInfo.createVirtualRegister(RC);
1036 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1037 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1038 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1039 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1040 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1041 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1042 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1043 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1044 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1045 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1046 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1047 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1048 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1049 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1050 unsigned Success = RegInfo.createVirtualRegister(RC);
1052 // insert new blocks after the current block
1053 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1054 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1055 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1056 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1057 MachineFunction::iterator It = BB;
1059 MF->insert(It, loopMBB);
1060 MF->insert(It, sinkMBB);
1061 MF->insert(It, exitMBB);
1063 // Transfer the remainder of BB and its successor edges to exitMBB.
1064 exitMBB->splice(exitMBB->begin(), BB,
1065 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1066 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1068 BB->addSuccessor(loopMBB);
1069 loopMBB->addSuccessor(loopMBB);
1070 loopMBB->addSuccessor(sinkMBB);
1071 sinkMBB->addSuccessor(exitMBB);
1074 // addiu masklsb2,$0,-4 # 0xfffffffc
1075 // and alignedaddr,ptr,masklsb2
1076 // andi ptrlsb2,ptr,3
1077 // sll shiftamt,ptrlsb2,3
1078 // ori maskupper,$0,255 # 0xff
1079 // sll mask,maskupper,shiftamt
1080 // nor mask2,$0,mask
1081 // sll incr2,incr,shiftamt
1083 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1084 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1085 .addReg(Mips::ZERO).addImm(-4);
1086 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1087 .addReg(Ptr).addReg(MaskLSB2);
1088 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1089 if (Subtarget->isLittle()) {
1090 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1092 unsigned Off = RegInfo.createVirtualRegister(RC);
1093 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1094 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1095 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1097 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1098 .addReg(Mips::ZERO).addImm(MaskImm);
1099 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1100 .addReg(MaskUpper).addReg(ShiftAmt);
1101 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1102 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1104 // atomic.load.binop
1106 // ll oldval,0(alignedaddr)
1107 // binop binopres,oldval,incr2
1108 // and newval,binopres,mask
1109 // and maskedoldval0,oldval,mask2
1110 // or storeval,maskedoldval0,newval
1111 // sc success,storeval,0(alignedaddr)
1112 // beq success,$0,loopMBB
1116 // ll oldval,0(alignedaddr)
1117 // and newval,incr2,mask
1118 // and maskedoldval0,oldval,mask2
1119 // or storeval,maskedoldval0,newval
1120 // sc success,storeval,0(alignedaddr)
1121 // beq success,$0,loopMBB
1124 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1126 // and andres, oldval, incr2
1127 // nor binopres, $0, andres
1128 // and newval, binopres, mask
1129 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1130 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1131 .addReg(Mips::ZERO).addReg(AndRes);
1132 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1133 } else if (BinOpcode) {
1134 // <binop> binopres, oldval, incr2
1135 // and newval, binopres, mask
1136 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1137 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1138 } else { // atomic.swap
1139 // and newval, incr2, mask
1140 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1143 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1144 .addReg(OldVal).addReg(Mask2);
1145 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1146 .addReg(MaskedOldVal0).addReg(NewVal);
1147 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1148 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1149 BuildMI(BB, DL, TII->get(Mips::BEQ))
1150 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1153 // and maskedoldval1,oldval,mask
1154 // srl srlres,maskedoldval1,shiftamt
1155 // sll sllres,srlres,24
1156 // sra dest,sllres,24
1158 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1160 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1161 .addReg(OldVal).addReg(Mask);
1162 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1163 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1164 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1165 .addReg(SrlRes).addImm(ShiftImm);
1166 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1167 .addReg(SllRes).addImm(ShiftImm);
1169 MI->eraseFromParent(); // The instruction is gone now.
1174 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1175 MachineBasicBlock *BB,
1176 unsigned Size) const {
1177 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1179 MachineFunction *MF = BB->getParent();
1180 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1181 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1182 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1183 DebugLoc DL = MI->getDebugLoc();
1184 unsigned LL, SC, ZERO, BNE, BEQ;
1187 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1188 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1195 ZERO = Mips::ZERO_64;
1200 unsigned Dest = MI->getOperand(0).getReg();
1201 unsigned Ptr = MI->getOperand(1).getReg();
1202 unsigned OldVal = MI->getOperand(2).getReg();
1203 unsigned NewVal = MI->getOperand(3).getReg();
1205 unsigned Success = RegInfo.createVirtualRegister(RC);
1207 // insert new blocks after the current block
1208 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1209 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1210 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1211 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1212 MachineFunction::iterator It = BB;
1214 MF->insert(It, loop1MBB);
1215 MF->insert(It, loop2MBB);
1216 MF->insert(It, exitMBB);
1218 // Transfer the remainder of BB and its successor edges to exitMBB.
1219 exitMBB->splice(exitMBB->begin(), BB,
1220 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1221 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1225 // fallthrough --> loop1MBB
1226 BB->addSuccessor(loop1MBB);
1227 loop1MBB->addSuccessor(exitMBB);
1228 loop1MBB->addSuccessor(loop2MBB);
1229 loop2MBB->addSuccessor(loop1MBB);
1230 loop2MBB->addSuccessor(exitMBB);
1234 // bne dest, oldval, exitMBB
1236 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1237 BuildMI(BB, DL, TII->get(BNE))
1238 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1241 // sc success, newval, 0(ptr)
1242 // beq success, $0, loop1MBB
1244 BuildMI(BB, DL, TII->get(SC), Success)
1245 .addReg(NewVal).addReg(Ptr).addImm(0);
1246 BuildMI(BB, DL, TII->get(BEQ))
1247 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1249 MI->eraseFromParent(); // The instruction is gone now.
1255 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1256 MachineBasicBlock *BB,
1257 unsigned Size) const {
1258 assert((Size == 1 || Size == 2) &&
1259 "Unsupported size for EmitAtomicCmpSwapPartial.");
1261 MachineFunction *MF = BB->getParent();
1262 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1263 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1264 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1265 DebugLoc DL = MI->getDebugLoc();
1267 unsigned Dest = MI->getOperand(0).getReg();
1268 unsigned Ptr = MI->getOperand(1).getReg();
1269 unsigned CmpVal = MI->getOperand(2).getReg();
1270 unsigned NewVal = MI->getOperand(3).getReg();
1272 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1273 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1274 unsigned Mask = RegInfo.createVirtualRegister(RC);
1275 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1276 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1277 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1278 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1279 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1280 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1281 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1282 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1283 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1284 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1285 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1286 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1287 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1288 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1289 unsigned Success = RegInfo.createVirtualRegister(RC);
1291 // insert new blocks after the current block
1292 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1293 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1294 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1295 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1296 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1297 MachineFunction::iterator It = BB;
1299 MF->insert(It, loop1MBB);
1300 MF->insert(It, loop2MBB);
1301 MF->insert(It, sinkMBB);
1302 MF->insert(It, exitMBB);
1304 // Transfer the remainder of BB and its successor edges to exitMBB.
1305 exitMBB->splice(exitMBB->begin(), BB,
1306 std::next(MachineBasicBlock::iterator(MI)), BB->end());
1307 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1309 BB->addSuccessor(loop1MBB);
1310 loop1MBB->addSuccessor(sinkMBB);
1311 loop1MBB->addSuccessor(loop2MBB);
1312 loop2MBB->addSuccessor(loop1MBB);
1313 loop2MBB->addSuccessor(sinkMBB);
1314 sinkMBB->addSuccessor(exitMBB);
1316 // FIXME: computation of newval2 can be moved to loop2MBB.
1318 // addiu masklsb2,$0,-4 # 0xfffffffc
1319 // and alignedaddr,ptr,masklsb2
1320 // andi ptrlsb2,ptr,3
1321 // sll shiftamt,ptrlsb2,3
1322 // ori maskupper,$0,255 # 0xff
1323 // sll mask,maskupper,shiftamt
1324 // nor mask2,$0,mask
1325 // andi maskedcmpval,cmpval,255
1326 // sll shiftedcmpval,maskedcmpval,shiftamt
1327 // andi maskednewval,newval,255
1328 // sll shiftednewval,maskednewval,shiftamt
1329 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1330 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1331 .addReg(Mips::ZERO).addImm(-4);
1332 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1333 .addReg(Ptr).addReg(MaskLSB2);
1334 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1335 if (Subtarget->isLittle()) {
1336 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1338 unsigned Off = RegInfo.createVirtualRegister(RC);
1339 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1340 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1341 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1343 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1344 .addReg(Mips::ZERO).addImm(MaskImm);
1345 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1346 .addReg(MaskUpper).addReg(ShiftAmt);
1347 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1348 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1349 .addReg(CmpVal).addImm(MaskImm);
1350 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1351 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1352 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1353 .addReg(NewVal).addImm(MaskImm);
1354 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1355 .addReg(MaskedNewVal).addReg(ShiftAmt);
1358 // ll oldval,0(alginedaddr)
1359 // and maskedoldval0,oldval,mask
1360 // bne maskedoldval0,shiftedcmpval,sinkMBB
1362 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1363 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1364 .addReg(OldVal).addReg(Mask);
1365 BuildMI(BB, DL, TII->get(Mips::BNE))
1366 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1369 // and maskedoldval1,oldval,mask2
1370 // or storeval,maskedoldval1,shiftednewval
1371 // sc success,storeval,0(alignedaddr)
1372 // beq success,$0,loop1MBB
1374 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1375 .addReg(OldVal).addReg(Mask2);
1376 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1377 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1378 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1379 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1380 BuildMI(BB, DL, TII->get(Mips::BEQ))
1381 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1384 // srl srlres,maskedoldval0,shiftamt
1385 // sll sllres,srlres,24
1386 // sra dest,sllres,24
1388 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1390 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1391 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1392 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1393 .addReg(SrlRes).addImm(ShiftImm);
1394 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1395 .addReg(SllRes).addImm(ShiftImm);
1397 MI->eraseFromParent(); // The instruction is gone now.
1402 //===----------------------------------------------------------------------===//
1403 // Misc Lower Operation implementation
1404 //===----------------------------------------------------------------------===//
1405 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1406 SDValue Chain = Op.getOperand(0);
1407 SDValue Table = Op.getOperand(1);
1408 SDValue Index = Op.getOperand(2);
1410 EVT PTy = getPointerTy();
1411 unsigned EntrySize =
1412 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1414 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1415 DAG.getConstant(EntrySize, PTy));
1416 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1418 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1419 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1420 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1422 Chain = Addr.getValue(1);
1424 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || isN64()) {
1425 // For PIC, the sequence is:
1426 // BRIND(load(Jumptable + index) + RelocBase)
1427 // RelocBase can be JumpTable, GOT or some sort of global base.
1428 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1429 getPICJumpTableRelocBase(Table, DAG));
1432 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1435 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1436 // The first operand is the chain, the second is the condition, the third is
1437 // the block to branch to if the condition is true.
1438 SDValue Chain = Op.getOperand(0);
1439 SDValue Dest = Op.getOperand(2);
1442 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1444 // Return if flag is not set by a floating point comparison.
1445 if (CondRes.getOpcode() != MipsISD::FPCmp)
1448 SDValue CCNode = CondRes.getOperand(2);
1450 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1451 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1452 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1453 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1454 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1455 FCC0, Dest, CondRes);
1458 SDValue MipsTargetLowering::
1459 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1461 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1463 // Return if flag is not set by a floating point comparison.
1464 if (Cond.getOpcode() != MipsISD::FPCmp)
1467 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1471 SDValue MipsTargetLowering::
1472 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1475 EVT Ty = Op.getOperand(0).getValueType();
1476 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1477 getSetCCResultType(*DAG.getContext(), Ty),
1478 Op.getOperand(0), Op.getOperand(1),
1481 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1485 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1486 SDValue Cond = createFPCmp(DAG, Op);
1488 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1489 "Floating point operand expected.");
1491 SDValue True = DAG.getConstant(1, MVT::i32);
1492 SDValue False = DAG.getConstant(0, MVT::i32);
1494 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1497 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1498 SelectionDAG &DAG) const {
1499 // FIXME there isn't actually debug info here
1501 EVT Ty = Op.getValueType();
1502 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1503 const GlobalValue *GV = N->getGlobal();
1505 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64()) {
1506 const MipsTargetObjectFile &TLOF =
1507 (const MipsTargetObjectFile&)getObjFileLowering();
1509 // %gp_rel relocation
1510 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1511 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1513 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1514 DAG.getVTList(MVT::i32), GA);
1515 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1516 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1519 // %hi/%lo relocation
1520 return getAddrNonPIC(N, Ty, DAG);
1523 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1524 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1527 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1528 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1529 MachinePointerInfo::getGOT());
1531 return getAddrGlobal(N, Ty, DAG, (isN32() || isN64()) ? MipsII::MO_GOT_DISP
1533 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1536 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1537 SelectionDAG &DAG) const {
1538 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1539 EVT Ty = Op.getValueType();
1541 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1542 return getAddrNonPIC(N, Ty, DAG);
1544 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1547 SDValue MipsTargetLowering::
1548 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1550 // If the relocation model is PIC, use the General Dynamic TLS Model or
1551 // Local Dynamic TLS model, otherwise use the Initial Exec or
1552 // Local Exec TLS Model.
1554 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1556 const GlobalValue *GV = GA->getGlobal();
1557 EVT PtrVT = getPointerTy();
1559 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1561 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1562 // General Dynamic and Local Dynamic TLS Model.
1563 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1566 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1567 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1568 getGlobalReg(DAG, PtrVT), TGA);
1569 unsigned PtrSize = PtrVT.getSizeInBits();
1570 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1572 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1576 Entry.Node = Argument;
1578 Args.push_back(Entry);
1580 TargetLowering::CallLoweringInfo CLI(DAG);
1581 CLI.setDebugLoc(DL).setChain(DAG.getEntryNode())
1582 .setCallee(CallingConv::C, PtrTy, TlsGetAddr, &Args, 0);
1583 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1585 SDValue Ret = CallResult.first;
1587 if (model != TLSModel::LocalDynamic)
1590 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1591 MipsII::MO_DTPREL_HI);
1592 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1593 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1594 MipsII::MO_DTPREL_LO);
1595 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1596 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1597 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1601 if (model == TLSModel::InitialExec) {
1602 // Initial Exec TLS Model
1603 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1604 MipsII::MO_GOTTPREL);
1605 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1607 Offset = DAG.getLoad(PtrVT, DL,
1608 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1609 false, false, false, 0);
1611 // Local Exec TLS Model
1612 assert(model == TLSModel::LocalExec);
1613 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1614 MipsII::MO_TPREL_HI);
1615 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1616 MipsII::MO_TPREL_LO);
1617 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1618 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1619 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1622 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1623 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1626 SDValue MipsTargetLowering::
1627 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1629 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1630 EVT Ty = Op.getValueType();
1632 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1633 return getAddrNonPIC(N, Ty, DAG);
1635 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1638 SDValue MipsTargetLowering::
1639 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1641 // gp_rel relocation
1642 // FIXME: we should reference the constant pool using small data sections,
1643 // but the asm printer currently doesn't support this feature without
1644 // hacking it. This feature should come soon so we can uncomment the
1646 //if (IsInSmallSection(C->getType())) {
1647 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1648 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1649 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1650 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1651 EVT Ty = Op.getValueType();
1653 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !isN64())
1654 return getAddrNonPIC(N, Ty, DAG);
1656 return getAddrLocal(N, Ty, DAG, isN32() || isN64());
1659 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1660 MachineFunction &MF = DAG.getMachineFunction();
1661 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1664 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1667 // vastart just stores the address of the VarArgsFrameIndex slot into the
1668 // memory location argument.
1669 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1670 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1671 MachinePointerInfo(SV), false, false, 0);
1674 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1675 bool HasExtractInsert) {
1676 EVT TyX = Op.getOperand(0).getValueType();
1677 EVT TyY = Op.getOperand(1).getValueType();
1678 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1679 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1683 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1685 SDValue X = (TyX == MVT::f32) ?
1686 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1687 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1689 SDValue Y = (TyY == MVT::f32) ?
1690 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1691 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1694 if (HasExtractInsert) {
1695 // ext E, Y, 31, 1 ; extract bit31 of Y
1696 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1697 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1698 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1701 // srl SrlX, SllX, 1
1703 // sll SllY, SrlX, 31
1704 // or Or, SrlX, SllY
1705 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1706 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1707 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1708 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1709 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1712 if (TyX == MVT::f32)
1713 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1715 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1716 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1717 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1720 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1721 bool HasExtractInsert) {
1722 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1723 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1724 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1725 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1728 // Bitcast to integer nodes.
1729 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1730 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1732 if (HasExtractInsert) {
1733 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1734 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1735 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1736 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1738 if (WidthX > WidthY)
1739 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1740 else if (WidthY > WidthX)
1741 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1743 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1744 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1745 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1748 // (d)sll SllX, X, 1
1749 // (d)srl SrlX, SllX, 1
1750 // (d)srl SrlY, Y, width(Y)-1
1751 // (d)sll SllY, SrlX, width(Y)-1
1752 // or Or, SrlX, SllY
1753 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1754 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1755 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1756 DAG.getConstant(WidthY - 1, MVT::i32));
1758 if (WidthX > WidthY)
1759 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1760 else if (WidthY > WidthX)
1761 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1763 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1764 DAG.getConstant(WidthX - 1, MVT::i32));
1765 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1766 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1770 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1771 if (Subtarget->isGP64bit())
1772 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasExtractInsert());
1774 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasExtractInsert());
1777 SDValue MipsTargetLowering::
1778 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1780 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1781 "Frame address can only be determined for current frame.");
1783 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1784 MFI->setFrameAddressIsTaken(true);
1785 EVT VT = Op.getValueType();
1787 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1788 isN64() ? Mips::FP_64 : Mips::FP, VT);
1792 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1793 SelectionDAG &DAG) const {
1794 if (verifyReturnAddressArgumentIsConstant(Op, DAG))
1798 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1799 "Return address can be determined only for current frame.");
1801 MachineFunction &MF = DAG.getMachineFunction();
1802 MachineFrameInfo *MFI = MF.getFrameInfo();
1803 MVT VT = Op.getSimpleValueType();
1804 unsigned RA = isN64() ? Mips::RA_64 : Mips::RA;
1805 MFI->setReturnAddressIsTaken(true);
1807 // Return RA, which contains the return address. Mark it an implicit live-in.
1808 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1809 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1812 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1813 // generated from __builtin_eh_return (offset, handler)
1814 // The effect of this is to adjust the stack pointer by "offset"
1815 // and then branch to "handler".
1816 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1818 MachineFunction &MF = DAG.getMachineFunction();
1819 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1821 MipsFI->setCallsEhReturn();
1822 SDValue Chain = Op.getOperand(0);
1823 SDValue Offset = Op.getOperand(1);
1824 SDValue Handler = Op.getOperand(2);
1826 EVT Ty = isN64() ? MVT::i64 : MVT::i32;
1828 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1829 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1830 unsigned OffsetReg = isN64() ? Mips::V1_64 : Mips::V1;
1831 unsigned AddrReg = isN64() ? Mips::V0_64 : Mips::V0;
1832 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1833 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1834 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1835 DAG.getRegister(OffsetReg, Ty),
1836 DAG.getRegister(AddrReg, getPointerTy()),
1840 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1841 SelectionDAG &DAG) const {
1842 // FIXME: Need pseudo-fence for 'singlethread' fences
1843 // FIXME: Set SType for weaker fences where supported/appropriate.
1846 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1847 DAG.getConstant(SType, MVT::i32));
1850 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1851 SelectionDAG &DAG) const {
1853 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1854 SDValue Shamt = Op.getOperand(2);
1857 // lo = (shl lo, shamt)
1858 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1861 // hi = (shl lo, shamt[4:0])
1862 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1863 DAG.getConstant(-1, MVT::i32));
1864 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1865 DAG.getConstant(1, MVT::i32));
1866 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1868 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1869 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1870 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1871 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1872 DAG.getConstant(0x20, MVT::i32));
1873 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1874 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1875 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1877 SDValue Ops[2] = {Lo, Hi};
1878 return DAG.getMergeValues(Ops, DL);
1881 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1884 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1885 SDValue Shamt = Op.getOperand(2);
1888 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1890 // hi = (sra hi, shamt)
1892 // hi = (srl hi, shamt)
1895 // lo = (sra hi, shamt[4:0])
1896 // hi = (sra hi, 31)
1898 // lo = (srl hi, shamt[4:0])
1900 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1901 DAG.getConstant(-1, MVT::i32));
1902 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1903 DAG.getConstant(1, MVT::i32));
1904 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1905 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1906 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1907 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1909 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1910 DAG.getConstant(0x20, MVT::i32));
1911 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1912 DAG.getConstant(31, MVT::i32));
1913 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1914 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1915 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1918 SDValue Ops[2] = {Lo, Hi};
1919 return DAG.getMergeValues(Ops, DL);
1922 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1923 SDValue Chain, SDValue Src, unsigned Offset) {
1924 SDValue Ptr = LD->getBasePtr();
1925 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1926 EVT BasePtrVT = Ptr.getValueType();
1928 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1931 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1932 DAG.getConstant(Offset, BasePtrVT));
1934 SDValue Ops[] = { Chain, Ptr, Src };
1935 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
1936 LD->getMemOperand());
1939 // Expand an unaligned 32 or 64-bit integer load node.
1940 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1941 LoadSDNode *LD = cast<LoadSDNode>(Op);
1942 EVT MemVT = LD->getMemoryVT();
1944 if (Subtarget->systemSupportsUnalignedAccess())
1947 // Return if load is aligned or if MemVT is neither i32 nor i64.
1948 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1949 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1952 bool IsLittle = Subtarget->isLittle();
1953 EVT VT = Op.getValueType();
1954 ISD::LoadExtType ExtType = LD->getExtensionType();
1955 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1957 assert((VT == MVT::i32) || (VT == MVT::i64));
1960 // (set dst, (i64 (load baseptr)))
1962 // (set tmp, (ldl (add baseptr, 7), undef))
1963 // (set dst, (ldr baseptr, tmp))
1964 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1965 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1967 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1971 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1973 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1977 // (set dst, (i32 (load baseptr))) or
1978 // (set dst, (i64 (sextload baseptr))) or
1979 // (set dst, (i64 (extload baseptr)))
1981 // (set tmp, (lwl (add baseptr, 3), undef))
1982 // (set dst, (lwr baseptr, tmp))
1983 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1984 (ExtType == ISD::EXTLOAD))
1987 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1990 // (set dst, (i64 (zextload baseptr)))
1992 // (set tmp0, (lwl (add baseptr, 3), undef))
1993 // (set tmp1, (lwr baseptr, tmp0))
1994 // (set tmp2, (shl tmp1, 32))
1995 // (set dst, (srl tmp2, 32))
1997 SDValue Const32 = DAG.getConstant(32, MVT::i32);
1998 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1999 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2000 SDValue Ops[] = { SRL, LWR.getValue(1) };
2001 return DAG.getMergeValues(Ops, DL);
2004 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2005 SDValue Chain, unsigned Offset) {
2006 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2007 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2009 SDVTList VTList = DAG.getVTList(MVT::Other);
2012 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2013 DAG.getConstant(Offset, BasePtrVT));
2015 SDValue Ops[] = { Chain, Value, Ptr };
2016 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, MemVT,
2017 SD->getMemOperand());
2020 // Expand an unaligned 32 or 64-bit integer store node.
2021 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2023 SDValue Value = SD->getValue(), Chain = SD->getChain();
2024 EVT VT = Value.getValueType();
2027 // (store val, baseptr) or
2028 // (truncstore val, baseptr)
2030 // (swl val, (add baseptr, 3))
2031 // (swr val, baseptr)
2032 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2033 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2035 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2038 assert(VT == MVT::i64);
2041 // (store val, baseptr)
2043 // (sdl val, (add baseptr, 7))
2044 // (sdr val, baseptr)
2045 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2046 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2049 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2050 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2051 SDValue Val = SD->getValue();
2053 if (Val.getOpcode() != ISD::FP_TO_SINT)
2056 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2057 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2060 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2061 SD->getPointerInfo(), SD->isVolatile(),
2062 SD->isNonTemporal(), SD->getAlignment());
2065 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2066 StoreSDNode *SD = cast<StoreSDNode>(Op);
2067 EVT MemVT = SD->getMemoryVT();
2069 // Lower unaligned integer stores.
2070 if (!Subtarget->systemSupportsUnalignedAccess() &&
2071 (SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2072 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2073 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2075 return lowerFP_TO_SINT_STORE(SD, DAG);
2078 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2079 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2080 || cast<ConstantSDNode>
2081 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2082 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2086 // (add (frameaddr 0), (frame_to_args_offset))
2087 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2088 // (add FrameObject, 0)
2089 // where FrameObject is a fixed StackObject with offset 0 which points to
2090 // the old stack pointer.
2091 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2092 EVT ValTy = Op->getValueType(0);
2093 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2094 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2095 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2096 DAG.getConstant(0, ValTy));
2099 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2100 SelectionDAG &DAG) const {
2101 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2102 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2104 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2107 //===----------------------------------------------------------------------===//
2108 // Calling Convention Implementation
2109 //===----------------------------------------------------------------------===//
2111 //===----------------------------------------------------------------------===//
2112 // TODO: Implement a generic logic using tblgen that can support this.
2113 // Mips O32 ABI rules:
2115 // i32 - Passed in A0, A1, A2, A3 and stack
2116 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2117 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2118 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2119 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2120 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2123 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2124 //===----------------------------------------------------------------------===//
2126 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2127 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2128 CCState &State, const MCPhysReg *F64Regs) {
2130 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2132 static const MCPhysReg IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2133 static const MCPhysReg F32Regs[] = { Mips::F12, Mips::F14 };
2135 // Do not process byval args here.
2136 if (ArgFlags.isByVal())
2139 // Promote i8 and i16
2140 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2142 if (ArgFlags.isSExt())
2143 LocInfo = CCValAssign::SExt;
2144 else if (ArgFlags.isZExt())
2145 LocInfo = CCValAssign::ZExt;
2147 LocInfo = CCValAssign::AExt;
2152 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2153 // is true: function is vararg, argument is 3rd or higher, there is previous
2154 // argument which is not f32 or f64.
2155 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2156 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2157 unsigned OrigAlign = ArgFlags.getOrigAlign();
2158 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2160 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2161 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2162 // If this is the first part of an i64 arg,
2163 // the allocated register must be either A0 or A2.
2164 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2165 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2167 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2168 // Allocate int register and shadow next int register. If first
2169 // available register is Mips::A1 or Mips::A3, shadow it too.
2170 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2171 if (Reg == Mips::A1 || Reg == Mips::A3)
2172 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2173 State.AllocateReg(IntRegs, IntRegsSize);
2175 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2176 // we are guaranteed to find an available float register
2177 if (ValVT == MVT::f32) {
2178 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2179 // Shadow int register
2180 State.AllocateReg(IntRegs, IntRegsSize);
2182 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2183 // Shadow int registers
2184 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2185 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2186 State.AllocateReg(IntRegs, IntRegsSize);
2187 State.AllocateReg(IntRegs, IntRegsSize);
2190 llvm_unreachable("Cannot handle this ValVT.");
2193 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2195 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2197 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2202 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2203 MVT LocVT, CCValAssign::LocInfo LocInfo,
2204 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2205 static const MCPhysReg F64Regs[] = { Mips::D6, Mips::D7 };
2207 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2210 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2211 MVT LocVT, CCValAssign::LocInfo LocInfo,
2212 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2213 static const MCPhysReg F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2215 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2218 #include "MipsGenCallingConv.inc"
2220 //===----------------------------------------------------------------------===//
2221 // Call Calling Convention Implementation
2222 //===----------------------------------------------------------------------===//
2224 // Return next O32 integer argument register.
2225 static unsigned getNextIntArgReg(unsigned Reg) {
2226 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2227 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2231 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2232 SDValue Chain, SDValue Arg, SDLoc DL,
2233 bool IsTailCall, SelectionDAG &DAG) const {
2235 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2236 DAG.getIntPtrConstant(Offset));
2237 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2241 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2242 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2243 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2244 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2245 /*isVolatile=*/ true, false, 0);
2248 void MipsTargetLowering::
2249 getOpndList(SmallVectorImpl<SDValue> &Ops,
2250 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2251 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2252 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2253 // Insert node "GP copy globalreg" before call to function.
2255 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2256 // in PIC mode) allow symbols to be resolved via lazy binding.
2257 // The lazy binding stub requires GP to point to the GOT.
2258 if (IsPICCall && !InternalLinkage) {
2259 unsigned GPReg = isN64() ? Mips::GP_64 : Mips::GP;
2260 EVT Ty = isN64() ? MVT::i64 : MVT::i32;
2261 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2264 // Build a sequence of copy-to-reg nodes chained together with token
2265 // chain and flag operands which copy the outgoing args into registers.
2266 // The InFlag in necessary since all emitted instructions must be
2270 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2271 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2272 RegsToPass[i].second, InFlag);
2273 InFlag = Chain.getValue(1);
2276 // Add argument registers to the end of the list so that they are
2277 // known live into the call.
2278 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2279 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2280 RegsToPass[i].second.getValueType()));
2282 // Add a register mask operand representing the call-preserved registers.
2283 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2284 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2285 assert(Mask && "Missing call preserved mask for calling convention");
2286 if (Subtarget->inMips16HardFloat()) {
2287 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2288 llvm::StringRef Sym = G->getGlobal()->getName();
2289 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2290 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2291 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2295 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2297 if (InFlag.getNode())
2298 Ops.push_back(InFlag);
2301 /// LowerCall - functions arguments are copied from virtual regs to
2302 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2304 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2305 SmallVectorImpl<SDValue> &InVals) const {
2306 SelectionDAG &DAG = CLI.DAG;
2308 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2309 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2310 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2311 SDValue Chain = CLI.Chain;
2312 SDValue Callee = CLI.Callee;
2313 bool &IsTailCall = CLI.IsTailCall;
2314 CallingConv::ID CallConv = CLI.CallConv;
2315 bool IsVarArg = CLI.IsVarArg;
2317 MachineFunction &MF = DAG.getMachineFunction();
2318 MachineFrameInfo *MFI = MF.getFrameInfo();
2319 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2320 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2321 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2323 // Analyze operands of the call, assigning locations to each operand.
2324 SmallVector<CCValAssign, 16> ArgLocs;
2325 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2326 getTargetMachine(), ArgLocs, *DAG.getContext());
2327 MipsCC::SpecialCallingConvType SpecialCallingConv =
2328 getSpecialCallingConv(Callee);
2329 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo,
2330 SpecialCallingConv);
2332 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2333 Subtarget->mipsSEUsesSoftFloat(),
2334 Callee.getNode(), CLI.getArgs());
2336 // Get a count of how many bytes are to be pushed on the stack.
2337 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2339 // Check if it's really possible to do a tail call.
2342 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2343 *MF.getInfo<MipsFunctionInfo>());
2345 if (!IsTailCall && CLI.CS && CLI.CS->isMustTailCall())
2346 report_fatal_error("failed to perform tail call elimination on a call "
2347 "site marked musttail");
2352 // Chain is the output chain of the last Load/Store or CopyToReg node.
2353 // ByValChain is the output chain of the last Memcpy node created for copying
2354 // byval arguments to the stack.
2355 unsigned StackAlignment = TFL->getStackAlignment();
2356 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2357 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2360 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2362 SDValue StackPtr = DAG.getCopyFromReg(
2363 Chain, DL, isN64() ? Mips::SP_64 : Mips::SP, getPointerTy());
2365 // With EABI is it possible to have 16 args on registers.
2366 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2367 SmallVector<SDValue, 8> MemOpChains;
2368 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2370 // Walk the register/memloc assignments, inserting copies/loads.
2371 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2372 SDValue Arg = OutVals[i];
2373 CCValAssign &VA = ArgLocs[i];
2374 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2375 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2378 if (Flags.isByVal()) {
2379 assert(Flags.getByValSize() &&
2380 "ByVal args of size 0 should have been ignored by front-end.");
2381 assert(ByValArg != MipsCCInfo.byval_end());
2382 assert(!IsTailCall &&
2383 "Do not tail-call optimize if there is a byval argument.");
2384 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2385 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2390 // Promote the value if needed.
2391 switch (VA.getLocInfo()) {
2392 default: llvm_unreachable("Unknown loc info!");
2393 case CCValAssign::Full:
2394 if (VA.isRegLoc()) {
2395 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2396 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2397 (ValVT == MVT::i64 && LocVT == MVT::f64))
2398 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2399 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2400 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2401 Arg, DAG.getConstant(0, MVT::i32));
2402 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2403 Arg, DAG.getConstant(1, MVT::i32));
2404 if (!Subtarget->isLittle())
2406 unsigned LocRegLo = VA.getLocReg();
2407 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2408 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2409 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2414 case CCValAssign::SExt:
2415 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2417 case CCValAssign::ZExt:
2418 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2420 case CCValAssign::AExt:
2421 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2425 // Arguments that can be passed on register must be kept at
2426 // RegsToPass vector
2427 if (VA.isRegLoc()) {
2428 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2432 // Register can't get to this point...
2433 assert(VA.isMemLoc());
2435 // emit ISD::STORE whichs stores the
2436 // parameter value to a stack Location
2437 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2438 Chain, Arg, DL, IsTailCall, DAG));
2441 // Transform all store nodes into one single node because all store
2442 // nodes are independent of each other.
2443 if (!MemOpChains.empty())
2444 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
2446 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2447 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2448 // node so that legalize doesn't hack it.
2449 bool IsPICCall = (isN64() || IsPIC); // true if calls are translated to
2451 bool GlobalOrExternal = false, InternalLinkage = false;
2453 EVT Ty = Callee.getValueType();
2455 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2457 const GlobalValue *Val = G->getGlobal();
2458 InternalLinkage = Val->hasInternalLinkage();
2460 if (InternalLinkage)
2461 Callee = getAddrLocal(G, Ty, DAG, isN32() || isN64());
2463 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2464 MipsII::MO_CALL_LO16, Chain,
2465 FuncInfo->callPtrInfo(Val));
2467 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2468 FuncInfo->callPtrInfo(Val));
2470 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2471 MipsII::MO_NO_FLAG);
2472 GlobalOrExternal = true;
2474 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2475 const char *Sym = S->getSymbol();
2477 if (!isN64() && !IsPIC) // !N64 && static
2478 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2479 MipsII::MO_NO_FLAG);
2481 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2482 MipsII::MO_CALL_LO16, Chain,
2483 FuncInfo->callPtrInfo(Sym));
2485 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2486 FuncInfo->callPtrInfo(Sym));
2488 GlobalOrExternal = true;
2491 SmallVector<SDValue, 8> Ops(1, Chain);
2492 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2494 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2495 CLI, Callee, Chain);
2498 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, Ops);
2500 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, Ops);
2501 SDValue InFlag = Chain.getValue(1);
2503 // Create the CALLSEQ_END node.
2504 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2505 DAG.getIntPtrConstant(0, true), InFlag, DL);
2506 InFlag = Chain.getValue(1);
2508 // Handle result values, copying them out of physregs into vregs that we
2510 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2511 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2514 /// LowerCallResult - Lower the result values of a call into the
2515 /// appropriate copies out of appropriate physical registers.
2517 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2518 CallingConv::ID CallConv, bool IsVarArg,
2519 const SmallVectorImpl<ISD::InputArg> &Ins,
2520 SDLoc DL, SelectionDAG &DAG,
2521 SmallVectorImpl<SDValue> &InVals,
2522 const SDNode *CallNode,
2523 const Type *RetTy) const {
2524 // Assign locations to each value returned by this call.
2525 SmallVector<CCValAssign, 16> RVLocs;
2526 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2527 getTargetMachine(), RVLocs, *DAG.getContext());
2528 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2530 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2533 // Copy all of the result registers out of their specified physreg.
2534 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2535 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2536 RVLocs[i].getLocVT(), InFlag);
2537 Chain = Val.getValue(1);
2538 InFlag = Val.getValue(2);
2540 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2541 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2543 InVals.push_back(Val);
2549 //===----------------------------------------------------------------------===//
2550 // Formal Arguments Calling Convention Implementation
2551 //===----------------------------------------------------------------------===//
2552 /// LowerFormalArguments - transform physical registers into virtual registers
2553 /// and generate load operations for arguments places on the stack.
2555 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2556 CallingConv::ID CallConv,
2558 const SmallVectorImpl<ISD::InputArg> &Ins,
2559 SDLoc DL, SelectionDAG &DAG,
2560 SmallVectorImpl<SDValue> &InVals)
2562 MachineFunction &MF = DAG.getMachineFunction();
2563 MachineFrameInfo *MFI = MF.getFrameInfo();
2564 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2566 MipsFI->setVarArgsFrameIndex(0);
2568 // Used with vargs to acumulate store chains.
2569 std::vector<SDValue> OutChains;
2571 // Assign locations to all of the incoming arguments.
2572 SmallVector<CCValAssign, 16> ArgLocs;
2573 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2574 getTargetMachine(), ArgLocs, *DAG.getContext());
2575 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2576 Function::const_arg_iterator FuncArg =
2577 DAG.getMachineFunction().getFunction()->arg_begin();
2578 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2580 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2581 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2582 MipsCCInfo.hasByValArg());
2584 unsigned CurArgIdx = 0;
2585 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2587 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2588 CCValAssign &VA = ArgLocs[i];
2589 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2590 CurArgIdx = Ins[i].OrigArgIndex;
2591 EVT ValVT = VA.getValVT();
2592 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2593 bool IsRegLoc = VA.isRegLoc();
2595 if (Flags.isByVal()) {
2596 assert(Flags.getByValSize() &&
2597 "ByVal args of size 0 should have been ignored by front-end.");
2598 assert(ByValArg != MipsCCInfo.byval_end());
2599 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2600 MipsCCInfo, *ByValArg);
2605 // Arguments stored on registers
2607 MVT RegVT = VA.getLocVT();
2608 unsigned ArgReg = VA.getLocReg();
2609 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2611 // Transform the arguments stored on
2612 // physical registers into virtual ones
2613 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2614 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2616 // If this is an 8 or 16-bit value, it has been passed promoted
2617 // to 32 bits. Insert an assert[sz]ext to capture this, then
2618 // truncate to the right size.
2619 if (VA.getLocInfo() != CCValAssign::Full) {
2620 unsigned Opcode = 0;
2621 if (VA.getLocInfo() == CCValAssign::SExt)
2622 Opcode = ISD::AssertSext;
2623 else if (VA.getLocInfo() == CCValAssign::ZExt)
2624 Opcode = ISD::AssertZext;
2626 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2627 DAG.getValueType(ValVT));
2628 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2631 // Handle floating point arguments passed in integer registers and
2632 // long double arguments passed in floating point registers.
2633 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2634 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2635 (RegVT == MVT::f64 && ValVT == MVT::i64))
2636 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2637 else if (isO32() && RegVT == MVT::i32 && ValVT == MVT::f64) {
2638 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2639 getNextIntArgReg(ArgReg), RC);
2640 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2641 if (!Subtarget->isLittle())
2642 std::swap(ArgValue, ArgValue2);
2643 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2644 ArgValue, ArgValue2);
2647 InVals.push_back(ArgValue);
2648 } else { // VA.isRegLoc()
2651 assert(VA.isMemLoc());
2653 // The stack pointer offset is relative to the caller stack frame.
2654 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2655 VA.getLocMemOffset(), true);
2657 // Create load nodes to retrieve arguments from the stack
2658 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2659 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2660 MachinePointerInfo::getFixedStack(FI),
2661 false, false, false, 0);
2662 InVals.push_back(Load);
2663 OutChains.push_back(Load.getValue(1));
2667 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2668 // The mips ABIs for returning structs by value requires that we copy
2669 // the sret argument into $v0 for the return. Save the argument into
2670 // a virtual register so that we can access it from the return points.
2671 if (Ins[i].Flags.isSRet()) {
2672 unsigned Reg = MipsFI->getSRetReturnReg();
2674 Reg = MF.getRegInfo().createVirtualRegister(
2675 getRegClassFor(isN64() ? MVT::i64 : MVT::i32));
2676 MipsFI->setSRetReturnReg(Reg);
2678 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[i]);
2679 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2685 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2687 // All stores are grouped in one node to allow the matching between
2688 // the size of Ins and InVals. This only happens when on varg functions
2689 if (!OutChains.empty()) {
2690 OutChains.push_back(Chain);
2691 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
2697 //===----------------------------------------------------------------------===//
2698 // Return Value Calling Convention Implementation
2699 //===----------------------------------------------------------------------===//
2702 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2703 MachineFunction &MF, bool IsVarArg,
2704 const SmallVectorImpl<ISD::OutputArg> &Outs,
2705 LLVMContext &Context) const {
2706 SmallVector<CCValAssign, 16> RVLocs;
2707 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2709 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2713 MipsTargetLowering::LowerReturn(SDValue Chain,
2714 CallingConv::ID CallConv, bool IsVarArg,
2715 const SmallVectorImpl<ISD::OutputArg> &Outs,
2716 const SmallVectorImpl<SDValue> &OutVals,
2717 SDLoc DL, SelectionDAG &DAG) const {
2718 // CCValAssign - represent the assignment of
2719 // the return value to a location
2720 SmallVector<CCValAssign, 16> RVLocs;
2721 MachineFunction &MF = DAG.getMachineFunction();
2723 // CCState - Info about the registers and stack slot.
2724 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2726 MipsCC MipsCCInfo(CallConv, isO32(), Subtarget->isFP64bit(), CCInfo);
2728 // Analyze return values.
2729 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2730 MF.getFunction()->getReturnType());
2733 SmallVector<SDValue, 4> RetOps(1, Chain);
2735 // Copy the result values into the output registers.
2736 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2737 SDValue Val = OutVals[i];
2738 CCValAssign &VA = RVLocs[i];
2739 assert(VA.isRegLoc() && "Can only return in registers!");
2741 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2742 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2744 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2746 // Guarantee that all emitted copies are stuck together with flags.
2747 Flag = Chain.getValue(1);
2748 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2751 // The mips ABIs for returning structs by value requires that we copy
2752 // the sret argument into $v0 for the return. We saved the argument into
2753 // a virtual register in the entry block, so now we copy the value out
2755 if (MF.getFunction()->hasStructRetAttr()) {
2756 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2757 unsigned Reg = MipsFI->getSRetReturnReg();
2760 llvm_unreachable("sret virtual register not created in the entry block");
2761 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2762 unsigned V0 = isN64() ? Mips::V0_64 : Mips::V0;
2764 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2765 Flag = Chain.getValue(1);
2766 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2769 RetOps[0] = Chain; // Update chain.
2771 // Add the flag if we have it.
2773 RetOps.push_back(Flag);
2775 // Return on Mips is always a "jr $ra"
2776 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, RetOps);
2779 //===----------------------------------------------------------------------===//
2780 // Mips Inline Assembly Support
2781 //===----------------------------------------------------------------------===//
2783 /// getConstraintType - Given a constraint letter, return the type of
2784 /// constraint it is for this target.
2785 MipsTargetLowering::ConstraintType MipsTargetLowering::
2786 getConstraintType(const std::string &Constraint) const
2788 // Mips specific constraints
2789 // GCC config/mips/constraints.md
2791 // 'd' : An address register. Equivalent to r
2792 // unless generating MIPS16 code.
2793 // 'y' : Equivalent to r; retained for
2794 // backwards compatibility.
2795 // 'c' : A register suitable for use in an indirect
2796 // jump. This will always be $25 for -mabicalls.
2797 // 'l' : The lo register. 1 word storage.
2798 // 'x' : The hilo register pair. Double word storage.
2799 if (Constraint.size() == 1) {
2800 switch (Constraint[0]) {
2808 return C_RegisterClass;
2813 return TargetLowering::getConstraintType(Constraint);
2816 /// Examine constraint type and operand type and determine a weight value.
2817 /// This object must already have been set up with the operand type
2818 /// and the current alternative constraint selected.
2819 TargetLowering::ConstraintWeight
2820 MipsTargetLowering::getSingleConstraintMatchWeight(
2821 AsmOperandInfo &info, const char *constraint) const {
2822 ConstraintWeight weight = CW_Invalid;
2823 Value *CallOperandVal = info.CallOperandVal;
2824 // If we don't have a value, we can't do a match,
2825 // but allow it at the lowest weight.
2826 if (!CallOperandVal)
2828 Type *type = CallOperandVal->getType();
2829 // Look at the constraint type.
2830 switch (*constraint) {
2832 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2836 if (type->isIntegerTy())
2837 weight = CW_Register;
2839 case 'f': // FPU or MSA register
2840 if (Subtarget->hasMSA() && type->isVectorTy() &&
2841 cast<VectorType>(type)->getBitWidth() == 128)
2842 weight = CW_Register;
2843 else if (type->isFloatTy())
2844 weight = CW_Register;
2846 case 'c': // $25 for indirect jumps
2847 case 'l': // lo register
2848 case 'x': // hilo register pair
2849 if (type->isIntegerTy())
2850 weight = CW_SpecificReg;
2852 case 'I': // signed 16 bit immediate
2853 case 'J': // integer zero
2854 case 'K': // unsigned 16 bit immediate
2855 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2856 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2857 case 'O': // signed 15 bit immediate (+- 16383)
2858 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2859 if (isa<ConstantInt>(CallOperandVal))
2860 weight = CW_Constant;
2869 /// This is a helper function to parse a physical register string and split it
2870 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2871 /// that is returned indicates whether parsing was successful. The second flag
2872 /// is true if the numeric part exists.
2873 static std::pair<bool, bool>
2874 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2875 unsigned long long &Reg) {
2876 if (C.front() != '{' || C.back() != '}')
2877 return std::make_pair(false, false);
2879 // Search for the first numeric character.
2880 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2881 I = std::find_if(B, E, std::ptr_fun(isdigit));
2883 Prefix.assign(B, I - B);
2885 // The second flag is set to false if no numeric characters were found.
2887 return std::make_pair(true, false);
2889 // Parse the numeric characters.
2890 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2894 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2895 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2896 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2897 const TargetRegisterClass *RC;
2899 unsigned long long Reg;
2901 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2904 return std::make_pair(0U, nullptr);
2906 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2907 // No numeric characters follow "hi" or "lo".
2909 return std::make_pair(0U, nullptr);
2911 RC = TRI->getRegClass(Prefix == "hi" ?
2912 Mips::HI32RegClassID : Mips::LO32RegClassID);
2913 return std::make_pair(*(RC->begin()), RC);
2914 } else if (Prefix.compare(0, 4, "$msa") == 0) {
2915 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
2917 // No numeric characters follow the name.
2919 return std::make_pair(0U, nullptr);
2921 Reg = StringSwitch<unsigned long long>(Prefix)
2922 .Case("$msair", Mips::MSAIR)
2923 .Case("$msacsr", Mips::MSACSR)
2924 .Case("$msaaccess", Mips::MSAAccess)
2925 .Case("$msasave", Mips::MSASave)
2926 .Case("$msamodify", Mips::MSAModify)
2927 .Case("$msarequest", Mips::MSARequest)
2928 .Case("$msamap", Mips::MSAMap)
2929 .Case("$msaunmap", Mips::MSAUnmap)
2933 return std::make_pair(0U, nullptr);
2935 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
2936 return std::make_pair(Reg, RC);
2940 return std::make_pair(0U, nullptr);
2942 if (Prefix == "$f") { // Parse $f0-$f31.
2943 // If the size of FP registers is 64-bit or Reg is an even number, select
2944 // the 64-bit register class. Otherwise, select the 32-bit register class.
2945 if (VT == MVT::Other)
2946 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2948 RC = getRegClassFor(VT);
2950 if (RC == &Mips::AFGR64RegClass) {
2951 assert(Reg % 2 == 0);
2954 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
2955 RC = TRI->getRegClass(Mips::FCCRegClassID);
2956 else if (Prefix == "$w") { // Parse $w0-$w31.
2957 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
2958 } else { // Parse $0-$31.
2959 assert(Prefix == "$");
2960 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
2963 assert(Reg < RC->getNumRegs());
2964 return std::make_pair(*(RC->begin() + Reg), RC);
2967 /// Given a register class constraint, like 'r', if this corresponds directly
2968 /// to an LLVM register class, return a register of 0 and the register class
2970 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2971 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
2973 if (Constraint.size() == 1) {
2974 switch (Constraint[0]) {
2975 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2976 case 'y': // Same as 'r'. Exists for compatibility.
2978 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2979 if (Subtarget->inMips16Mode())
2980 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2981 return std::make_pair(0U, &Mips::GPR32RegClass);
2983 if (VT == MVT::i64 && !isGP64bit())
2984 return std::make_pair(0U, &Mips::GPR32RegClass);
2985 if (VT == MVT::i64 && isGP64bit())
2986 return std::make_pair(0U, &Mips::GPR64RegClass);
2987 // This will generate an error message
2988 return std::make_pair(0U, nullptr);
2989 case 'f': // FPU or MSA register
2990 if (VT == MVT::v16i8)
2991 return std::make_pair(0U, &Mips::MSA128BRegClass);
2992 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
2993 return std::make_pair(0U, &Mips::MSA128HRegClass);
2994 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
2995 return std::make_pair(0U, &Mips::MSA128WRegClass);
2996 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
2997 return std::make_pair(0U, &Mips::MSA128DRegClass);
2998 else if (VT == MVT::f32)
2999 return std::make_pair(0U, &Mips::FGR32RegClass);
3000 else if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3001 if (Subtarget->isFP64bit())
3002 return std::make_pair(0U, &Mips::FGR64RegClass);
3003 return std::make_pair(0U, &Mips::AFGR64RegClass);
3006 case 'c': // register suitable for indirect jump
3008 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3009 assert(VT == MVT::i64 && "Unexpected type.");
3010 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3011 case 'l': // register suitable for indirect jump
3013 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3014 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3015 case 'x': // register suitable for indirect jump
3016 // Fixme: Not triggering the use of both hi and low
3017 // This will generate an error message
3018 return std::make_pair(0U, nullptr);
3022 std::pair<unsigned, const TargetRegisterClass *> R;
3023 R = parseRegForInlineAsmConstraint(Constraint, VT);
3028 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3031 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3032 /// vector. If it is invalid, don't add anything to Ops.
3033 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3034 std::string &Constraint,
3035 std::vector<SDValue>&Ops,
3036 SelectionDAG &DAG) const {
3039 // Only support length 1 constraints for now.
3040 if (Constraint.length() > 1) return;
3042 char ConstraintLetter = Constraint[0];
3043 switch (ConstraintLetter) {
3044 default: break; // This will fall through to the generic implementation
3045 case 'I': // Signed 16 bit constant
3046 // If this fails, the parent routine will give an error
3047 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3048 EVT Type = Op.getValueType();
3049 int64_t Val = C->getSExtValue();
3050 if (isInt<16>(Val)) {
3051 Result = DAG.getTargetConstant(Val, Type);
3056 case 'J': // integer zero
3057 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3058 EVT Type = Op.getValueType();
3059 int64_t Val = C->getZExtValue();
3061 Result = DAG.getTargetConstant(0, Type);
3066 case 'K': // unsigned 16 bit immediate
3067 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3068 EVT Type = Op.getValueType();
3069 uint64_t Val = (uint64_t)C->getZExtValue();
3070 if (isUInt<16>(Val)) {
3071 Result = DAG.getTargetConstant(Val, Type);
3076 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3077 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3078 EVT Type = Op.getValueType();
3079 int64_t Val = C->getSExtValue();
3080 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3081 Result = DAG.getTargetConstant(Val, Type);
3086 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3087 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3088 EVT Type = Op.getValueType();
3089 int64_t Val = C->getSExtValue();
3090 if ((Val >= -65535) && (Val <= -1)) {
3091 Result = DAG.getTargetConstant(Val, Type);
3096 case 'O': // signed 15 bit immediate
3097 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3098 EVT Type = Op.getValueType();
3099 int64_t Val = C->getSExtValue();
3100 if ((isInt<15>(Val))) {
3101 Result = DAG.getTargetConstant(Val, Type);
3106 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3107 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3108 EVT Type = Op.getValueType();
3109 int64_t Val = C->getSExtValue();
3110 if ((Val <= 65535) && (Val >= 1)) {
3111 Result = DAG.getTargetConstant(Val, Type);
3118 if (Result.getNode()) {
3119 Ops.push_back(Result);
3123 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3126 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3128 // No global is ever allowed as a base.
3133 case 0: // "r+i" or just "i", depending on HasBaseReg.
3136 if (!AM.HasBaseReg) // allow "r+i".
3138 return false; // disallow "r+r" or "r+r+i".
3147 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3148 // The Mips target isn't yet aware of offsets.
3152 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3154 bool IsMemset, bool ZeroMemset,
3156 MachineFunction &MF) const {
3157 if (Subtarget->hasMips64())
3163 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3164 if (VT != MVT::f32 && VT != MVT::f64)
3166 if (Imm.isNegZero())
3168 return Imm.isZero();
3171 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3173 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3175 return TargetLowering::getJumpTableEncoding();
3178 /// This function returns true if CallSym is a long double emulation routine.
3179 static bool isF128SoftLibCall(const char *CallSym) {
3180 const char *const LibCalls[] =
3181 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3182 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3183 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3184 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3185 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3186 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3187 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3188 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3191 const char *const *End = LibCalls + array_lengthof(LibCalls);
3193 // Check that LibCalls is sorted alphabetically.
3194 MipsTargetLowering::LTStr Comp;
3197 for (const char *const *I = LibCalls; I < End - 1; ++I)
3198 assert(Comp(*I, *(I + 1)));
3201 return std::binary_search(LibCalls, End, CallSym, Comp);
3204 /// This function returns true if Ty is fp128 or i128 which was originally a
3206 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3207 if (Ty->isFP128Ty())
3210 const ExternalSymbolSDNode *ES =
3211 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3213 // If the Ty is i128 and the function being called is a long double emulation
3214 // routine, then the original type is f128.
3215 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3218 MipsTargetLowering::MipsCC::SpecialCallingConvType
3219 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3220 MipsCC::SpecialCallingConvType SpecialCallingConv =
3221 MipsCC::NoSpecialCallingConv;
3222 if (Subtarget->inMips16HardFloat()) {
3223 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3224 llvm::StringRef Sym = G->getGlobal()->getName();
3225 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3226 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3227 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3231 return SpecialCallingConv;
3234 MipsTargetLowering::MipsCC::MipsCC(
3235 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3236 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3237 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3238 SpecialCallingConv(SpecialCallingConv_){
3239 // Pre-allocate reserved argument area.
3240 CCInfo.AllocateStack(reservedArgArea(), 1);
3244 void MipsTargetLowering::MipsCC::
3245 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3246 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3247 std::vector<ArgListEntry> &FuncArgs) {
3248 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3249 "CallingConv::Fast shouldn't be used for vararg functions.");
3251 unsigned NumOpnds = Args.size();
3252 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3254 for (unsigned I = 0; I != NumOpnds; ++I) {
3255 MVT ArgVT = Args[I].VT;
3256 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3259 if (ArgFlags.isByVal()) {
3260 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3264 if (IsVarArg && !Args[I].IsFixed)
3265 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3267 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3269 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3274 dbgs() << "Call operand #" << I << " has unhandled type "
3275 << EVT(ArgVT).getEVTString();
3277 llvm_unreachable(nullptr);
3282 void MipsTargetLowering::MipsCC::
3283 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3284 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3285 unsigned NumArgs = Args.size();
3286 llvm::CCAssignFn *FixedFn = fixedArgFn();
3287 unsigned CurArgIdx = 0;
3289 for (unsigned I = 0; I != NumArgs; ++I) {
3290 MVT ArgVT = Args[I].VT;
3291 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3292 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3293 CurArgIdx = Args[I].OrigArgIndex;
3295 if (ArgFlags.isByVal()) {
3296 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3300 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), nullptr, IsSoftFloat);
3302 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3306 dbgs() << "Formal Arg #" << I << " has unhandled type "
3307 << EVT(ArgVT).getEVTString();
3309 llvm_unreachable(nullptr);
3313 template<typename Ty>
3314 void MipsTargetLowering::MipsCC::
3315 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3316 const SDNode *CallNode, const Type *RetTy) const {
3319 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3320 Fn = RetCC_F128Soft;
3324 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3325 MVT VT = RetVals[I].VT;
3326 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3327 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3329 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3331 dbgs() << "Call result #" << I << " has unhandled type "
3332 << EVT(VT).getEVTString() << '\n';
3334 llvm_unreachable(nullptr);
3339 void MipsTargetLowering::MipsCC::
3340 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3341 const SDNode *CallNode, const Type *RetTy) const {
3342 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3345 void MipsTargetLowering::MipsCC::
3346 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3347 const Type *RetTy) const {
3348 analyzeReturn(Outs, IsSoftFloat, nullptr, RetTy);
3351 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3353 CCValAssign::LocInfo LocInfo,
3354 ISD::ArgFlagsTy ArgFlags) {
3355 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3357 struct ByValArgInfo ByVal;
3358 unsigned RegSize = regSize();
3359 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3360 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3363 if (useRegsForByval())
3364 allocateRegs(ByVal, ByValSize, Align);
3366 // Allocate space on caller's stack.
3367 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3369 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3371 ByValArgs.push_back(ByVal);
3374 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3375 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3378 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3379 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3382 const MCPhysReg *MipsTargetLowering::MipsCC::intArgRegs() const {
3383 return IsO32 ? O32IntRegs : Mips64IntRegs;
3386 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3387 if (CallConv == CallingConv::Fast)
3388 return CC_Mips_FastCC;
3390 if (SpecialCallingConv == Mips16RetHelperConv)
3391 return CC_Mips16RetHelper;
3392 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3395 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3396 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3399 const MCPhysReg *MipsTargetLowering::MipsCC::shadowRegs() const {
3400 return IsO32 ? O32IntRegs : Mips64DPRegs;
3403 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3406 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3407 const MCPhysReg *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3408 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3409 "Byval argument's size and alignment should be a multiple of"
3412 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3414 // If Align > RegSize, the first arg register must be even.
3415 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3416 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3420 // Mark the registers allocated.
3421 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3422 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3423 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3426 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3427 const SDNode *CallNode,
3428 bool IsSoftFloat) const {
3429 if (IsSoftFloat || IsO32)
3432 // Check if the original type was fp128.
3433 if (originalTypeIsF128(OrigTy, CallNode)) {
3434 assert(VT == MVT::i64);
3441 void MipsTargetLowering::
3442 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3443 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3444 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3445 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3446 MachineFunction &MF = DAG.getMachineFunction();
3447 MachineFrameInfo *MFI = MF.getFrameInfo();
3448 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3449 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3453 FrameObjOffset = (int)CC.reservedArgArea() -
3454 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3456 FrameObjOffset = ByVal.Address;
3458 // Create frame object.
3459 EVT PtrTy = getPointerTy();
3460 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3461 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3462 InVals.push_back(FIN);
3467 // Copy arg registers.
3468 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3469 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3471 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3472 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3473 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3474 unsigned Offset = I * CC.regSize();
3475 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3476 DAG.getConstant(Offset, PtrTy));
3477 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3478 StorePtr, MachinePointerInfo(FuncArg, Offset),
3480 OutChains.push_back(Store);
3484 // Copy byVal arg to registers and stack.
3485 void MipsTargetLowering::
3486 passByValArg(SDValue Chain, SDLoc DL,
3487 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3488 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3489 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3490 const MipsCC &CC, const ByValArgInfo &ByVal,
3491 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3492 unsigned ByValSizeInBytes = Flags.getByValSize();
3493 unsigned OffsetInBytes = 0; // From beginning of struct
3494 unsigned RegSizeInBytes = CC.regSize();
3495 unsigned Alignment = std::min(Flags.getByValAlign(), RegSizeInBytes);
3496 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSizeInBytes * 8);
3498 if (ByVal.NumRegs) {
3499 const MCPhysReg *ArgRegs = CC.intArgRegs();
3500 bool LeftoverBytes = (ByVal.NumRegs * RegSizeInBytes > ByValSizeInBytes);
3503 // Copy words to registers.
3504 for (; I < ByVal.NumRegs - LeftoverBytes;
3505 ++I, OffsetInBytes += RegSizeInBytes) {
3506 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3507 DAG.getConstant(OffsetInBytes, PtrTy));
3508 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3509 MachinePointerInfo(), false, false, false,
3511 MemOpChains.push_back(LoadVal.getValue(1));
3512 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3513 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3516 // Return if the struct has been fully copied.
3517 if (ByValSizeInBytes == OffsetInBytes)
3520 // Copy the remainder of the byval argument with sub-word loads and shifts.
3521 if (LeftoverBytes) {
3522 assert((ByValSizeInBytes > OffsetInBytes) &&
3523 (ByValSizeInBytes < OffsetInBytes + RegSizeInBytes) &&
3524 "Size of the remainder should be smaller than RegSizeInBytes.");
3527 for (unsigned LoadSizeInBytes = RegSizeInBytes / 2, TotalBytesLoaded = 0;
3528 OffsetInBytes < ByValSizeInBytes; LoadSizeInBytes /= 2) {
3529 unsigned RemainingSizeInBytes = ByValSizeInBytes - OffsetInBytes;
3531 if (RemainingSizeInBytes < LoadSizeInBytes)
3535 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3536 DAG.getConstant(OffsetInBytes, PtrTy));
3537 SDValue LoadVal = DAG.getExtLoad(
3538 ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr, MachinePointerInfo(),
3539 MVT::getIntegerVT(LoadSizeInBytes * 8), false, false, Alignment);
3540 MemOpChains.push_back(LoadVal.getValue(1));
3542 // Shift the loaded value.
3546 Shamt = TotalBytesLoaded * 8;
3548 Shamt = (RegSizeInBytes - (TotalBytesLoaded + LoadSizeInBytes)) * 8;
3550 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3551 DAG.getConstant(Shamt, MVT::i32));
3554 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3558 OffsetInBytes += LoadSizeInBytes;
3559 TotalBytesLoaded += LoadSizeInBytes;
3560 Alignment = std::min(Alignment, LoadSizeInBytes);
3563 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3564 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3569 // Copy remainder of byval arg to it with memcpy.
3570 unsigned MemCpySize = ByValSizeInBytes - OffsetInBytes;
3571 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3572 DAG.getConstant(OffsetInBytes, PtrTy));
3573 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3574 DAG.getIntPtrConstant(ByVal.Address));
3575 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3576 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3577 MachinePointerInfo(), MachinePointerInfo());
3578 MemOpChains.push_back(Chain);
3581 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3582 const MipsCC &CC, SDValue Chain,
3583 SDLoc DL, SelectionDAG &DAG) const {
3584 unsigned NumRegs = CC.numIntArgRegs();
3585 const MCPhysReg *ArgRegs = CC.intArgRegs();
3586 const CCState &CCInfo = CC.getCCInfo();
3587 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3588 unsigned RegSize = CC.regSize();
3589 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3590 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3591 MachineFunction &MF = DAG.getMachineFunction();
3592 MachineFrameInfo *MFI = MF.getFrameInfo();
3593 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3595 // Offset of the first variable argument from stack pointer.
3599 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3601 VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3603 // Record the frame index of the first variable argument
3604 // which is a value necessary to VASTART.
3605 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3606 MipsFI->setVarArgsFrameIndex(FI);
3608 // Copy the integer registers that have not been used for argument passing
3609 // to the argument register save area. For O32, the save area is allocated
3610 // in the caller's stack frame, while for N32/64, it is allocated in the
3611 // callee's stack frame.
3612 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3613 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3614 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3615 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3616 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3617 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3618 MachinePointerInfo(), false, false, 0);
3619 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue((Value*)nullptr);
3620 OutChains.push_back(Store);