1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "mips-lower"
15 #include "MipsISelLowering.h"
16 #include "InstPrinter/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsBaseInfo.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NumTailCalls, "Number of tail calls");
45 LargeGOT("mxgot", cl::Hidden,
46 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
49 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
50 cl::desc("MIPS: Don't trap on integer division by zero."),
53 static const uint16_t O32IntRegs[4] = {
54 Mips::A0, Mips::A1, Mips::A2, Mips::A3
57 static const uint16_t Mips64IntRegs[8] = {
58 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
59 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
62 static const uint16_t Mips64DPRegs[8] = {
63 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
64 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
67 // If I is a shifted mask, set the size (Size) and the first bit of the
68 // mask (Pos), and return true.
69 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
70 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
71 if (!isShiftedMask_64(I))
74 Size = CountPopulation_64(I);
75 Pos = countTrailingZeros(I);
79 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
80 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
81 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
84 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
86 unsigned Flag) const {
87 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
90 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
92 unsigned Flag) const {
93 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
96 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
98 unsigned Flag) const {
99 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
102 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
104 unsigned Flag) const {
105 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
108 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
110 unsigned Flag) const {
111 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
112 N->getOffset(), Flag);
115 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
117 case MipsISD::JmpLink: return "MipsISD::JmpLink";
118 case MipsISD::TailCall: return "MipsISD::TailCall";
119 case MipsISD::Hi: return "MipsISD::Hi";
120 case MipsISD::Lo: return "MipsISD::Lo";
121 case MipsISD::GPRel: return "MipsISD::GPRel";
122 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
123 case MipsISD::Ret: return "MipsISD::Ret";
124 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
125 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
126 case MipsISD::FPCmp: return "MipsISD::FPCmp";
127 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
128 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
129 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
130 case MipsISD::MFHI: return "MipsISD::MFHI";
131 case MipsISD::MFLO: return "MipsISD::MFLO";
132 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
133 case MipsISD::Mult: return "MipsISD::Mult";
134 case MipsISD::Multu: return "MipsISD::Multu";
135 case MipsISD::MAdd: return "MipsISD::MAdd";
136 case MipsISD::MAddu: return "MipsISD::MAddu";
137 case MipsISD::MSub: return "MipsISD::MSub";
138 case MipsISD::MSubu: return "MipsISD::MSubu";
139 case MipsISD::DivRem: return "MipsISD::DivRem";
140 case MipsISD::DivRemU: return "MipsISD::DivRemU";
141 case MipsISD::DivRem16: return "MipsISD::DivRem16";
142 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
143 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
144 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
145 case MipsISD::Wrapper: return "MipsISD::Wrapper";
146 case MipsISD::Sync: return "MipsISD::Sync";
147 case MipsISD::Ext: return "MipsISD::Ext";
148 case MipsISD::Ins: return "MipsISD::Ins";
149 case MipsISD::LWL: return "MipsISD::LWL";
150 case MipsISD::LWR: return "MipsISD::LWR";
151 case MipsISD::SWL: return "MipsISD::SWL";
152 case MipsISD::SWR: return "MipsISD::SWR";
153 case MipsISD::LDL: return "MipsISD::LDL";
154 case MipsISD::LDR: return "MipsISD::LDR";
155 case MipsISD::SDL: return "MipsISD::SDL";
156 case MipsISD::SDR: return "MipsISD::SDR";
157 case MipsISD::EXTP: return "MipsISD::EXTP";
158 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
159 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
160 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
161 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
162 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
163 case MipsISD::SHILO: return "MipsISD::SHILO";
164 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
165 case MipsISD::MULT: return "MipsISD::MULT";
166 case MipsISD::MULTU: return "MipsISD::MULTU";
167 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
168 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
169 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
170 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
171 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
172 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
173 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
174 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
175 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
176 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
177 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
178 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
179 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
180 case MipsISD::VCEQ: return "MipsISD::VCEQ";
181 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
182 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
183 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
184 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
185 case MipsISD::VSMAX: return "MipsISD::VSMAX";
186 case MipsISD::VSMIN: return "MipsISD::VSMIN";
187 case MipsISD::VUMAX: return "MipsISD::VUMAX";
188 case MipsISD::VUMIN: return "MipsISD::VUMIN";
189 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
190 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
191 case MipsISD::VNOR: return "MipsISD::VNOR";
192 case MipsISD::VSHF: return "MipsISD::VSHF";
193 case MipsISD::SHF: return "MipsISD::SHF";
194 case MipsISD::ILVEV: return "MipsISD::ILVEV";
195 case MipsISD::ILVOD: return "MipsISD::ILVOD";
196 case MipsISD::ILVL: return "MipsISD::ILVL";
197 case MipsISD::ILVR: return "MipsISD::ILVR";
198 case MipsISD::PCKEV: return "MipsISD::PCKEV";
199 case MipsISD::PCKOD: return "MipsISD::PCKOD";
200 default: return NULL;
205 MipsTargetLowering(MipsTargetMachine &TM)
206 : TargetLowering(TM, new MipsTargetObjectFile()),
207 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
208 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
209 IsO32(Subtarget->isABI_O32()) {
210 // Mips does not have i1 type, so use i32 for
211 // setcc operations results (slt, sgt, ...).
212 setBooleanContents(ZeroOrOneBooleanContent);
213 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
215 // Load extented operations for i1 types must be promoted
216 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
217 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
218 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
220 // MIPS doesn't have extending float->double load/store
221 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
222 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
224 // Used by legalize types to correctly generate the setcc result.
225 // Without this, every float setcc comes with a AND/OR with the result,
226 // we don't want this, since the fpcmp result goes to a flag register,
227 // which is used implicitly by brcond and select operations.
228 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
230 // Mips Custom Operations
231 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
232 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
233 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
234 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
235 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
236 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
237 setOperationAction(ISD::SELECT, MVT::f32, Custom);
238 setOperationAction(ISD::SELECT, MVT::f64, Custom);
239 setOperationAction(ISD::SELECT, MVT::i32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
241 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 setOperationAction(ISD::SETCC, MVT::f32, Custom);
243 setOperationAction(ISD::SETCC, MVT::f64, Custom);
244 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
245 setOperationAction(ISD::VASTART, MVT::Other, Custom);
246 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
247 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
248 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
250 if (!TM.Options.NoNaNsFPMath) {
251 setOperationAction(ISD::FABS, MVT::f32, Custom);
252 setOperationAction(ISD::FABS, MVT::f64, Custom);
256 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
257 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
258 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
259 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
260 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
261 setOperationAction(ISD::SELECT, MVT::i64, Custom);
262 setOperationAction(ISD::LOAD, MVT::i64, Custom);
263 setOperationAction(ISD::STORE, MVT::i64, Custom);
264 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
268 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
269 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
270 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
273 setOperationAction(ISD::ADD, MVT::i32, Custom);
275 setOperationAction(ISD::ADD, MVT::i64, Custom);
277 setOperationAction(ISD::SDIV, MVT::i32, Expand);
278 setOperationAction(ISD::SREM, MVT::i32, Expand);
279 setOperationAction(ISD::UDIV, MVT::i32, Expand);
280 setOperationAction(ISD::UREM, MVT::i32, Expand);
281 setOperationAction(ISD::SDIV, MVT::i64, Expand);
282 setOperationAction(ISD::SREM, MVT::i64, Expand);
283 setOperationAction(ISD::UDIV, MVT::i64, Expand);
284 setOperationAction(ISD::UREM, MVT::i64, Expand);
286 // Operations not directly supported by Mips.
287 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
288 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
289 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
290 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
291 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
292 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
293 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
294 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
295 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
296 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
297 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
298 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
299 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
300 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
301 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
302 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
303 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
304 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
305 setOperationAction(ISD::ROTL, MVT::i32, Expand);
306 setOperationAction(ISD::ROTL, MVT::i64, Expand);
307 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
308 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
310 if (!Subtarget->hasMips32r2())
311 setOperationAction(ISD::ROTR, MVT::i32, Expand);
313 if (!Subtarget->hasMips64r2())
314 setOperationAction(ISD::ROTR, MVT::i64, Expand);
316 setOperationAction(ISD::FSIN, MVT::f32, Expand);
317 setOperationAction(ISD::FSIN, MVT::f64, Expand);
318 setOperationAction(ISD::FCOS, MVT::f32, Expand);
319 setOperationAction(ISD::FCOS, MVT::f64, Expand);
320 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
321 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
322 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
323 setOperationAction(ISD::FPOW, MVT::f32, Expand);
324 setOperationAction(ISD::FPOW, MVT::f64, Expand);
325 setOperationAction(ISD::FLOG, MVT::f32, Expand);
326 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
327 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
328 setOperationAction(ISD::FEXP, MVT::f32, Expand);
329 setOperationAction(ISD::FMA, MVT::f32, Expand);
330 setOperationAction(ISD::FMA, MVT::f64, Expand);
331 setOperationAction(ISD::FREM, MVT::f32, Expand);
332 setOperationAction(ISD::FREM, MVT::f64, Expand);
334 if (!TM.Options.NoNaNsFPMath) {
335 setOperationAction(ISD::FNEG, MVT::f32, Expand);
336 setOperationAction(ISD::FNEG, MVT::f64, Expand);
339 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
341 setOperationAction(ISD::VAARG, MVT::Other, Expand);
342 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
343 setOperationAction(ISD::VAEND, MVT::Other, Expand);
345 // Use the default for now
346 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
347 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
349 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
350 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
351 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
352 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
354 setInsertFencesForAtomic(true);
356 if (!Subtarget->hasSEInReg()) {
357 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
358 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
361 if (!Subtarget->hasBitCount()) {
362 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
363 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
366 if (!Subtarget->hasSwap()) {
367 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
368 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
372 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
373 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
374 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
375 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
378 setOperationAction(ISD::TRAP, MVT::Other, Legal);
380 setTargetDAGCombine(ISD::SDIVREM);
381 setTargetDAGCombine(ISD::UDIVREM);
382 setTargetDAGCombine(ISD::SELECT);
383 setTargetDAGCombine(ISD::AND);
384 setTargetDAGCombine(ISD::OR);
385 setTargetDAGCombine(ISD::ADD);
387 setMinFunctionAlignment(HasMips64 ? 3 : 2);
389 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
391 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
392 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
394 MaxStoresPerMemcpy = 16;
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 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
409 return VT.changeVectorElementTypeToInteger();
412 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
413 TargetLowering::DAGCombinerInfo &DCI,
414 const MipsSubtarget *Subtarget) {
415 if (DCI.isBeforeLegalizeOps())
418 EVT Ty = N->getValueType(0);
419 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
420 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
421 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
425 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
426 N->getOperand(0), N->getOperand(1));
427 SDValue InChain = DAG.getEntryNode();
428 SDValue InGlue = DivRem;
431 if (N->hasAnyUseOfValue(0)) {
432 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
434 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
435 InChain = CopyFromLo.getValue(1);
436 InGlue = CopyFromLo.getValue(2);
440 if (N->hasAnyUseOfValue(1)) {
441 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
443 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
449 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
451 default: llvm_unreachable("Unknown fp condition code!");
453 case ISD::SETOEQ: return Mips::FCOND_OEQ;
454 case ISD::SETUNE: return Mips::FCOND_UNE;
456 case ISD::SETOLT: return Mips::FCOND_OLT;
458 case ISD::SETOGT: return Mips::FCOND_OGT;
460 case ISD::SETOLE: return Mips::FCOND_OLE;
462 case ISD::SETOGE: return Mips::FCOND_OGE;
463 case ISD::SETULT: return Mips::FCOND_ULT;
464 case ISD::SETULE: return Mips::FCOND_ULE;
465 case ISD::SETUGT: return Mips::FCOND_UGT;
466 case ISD::SETUGE: return Mips::FCOND_UGE;
467 case ISD::SETUO: return Mips::FCOND_UN;
468 case ISD::SETO: return Mips::FCOND_OR;
470 case ISD::SETONE: return Mips::FCOND_ONE;
471 case ISD::SETUEQ: return Mips::FCOND_UEQ;
476 /// This function returns true if the floating point conditional branches and
477 /// conditional moves which use condition code CC should be inverted.
478 static bool invertFPCondCodeUser(Mips::CondCode CC) {
479 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
482 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
483 "Illegal Condition Code");
488 // Creates and returns an FPCmp node from a setcc node.
489 // Returns Op if setcc is not a floating point comparison.
490 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
491 // must be a SETCC node
492 if (Op.getOpcode() != ISD::SETCC)
495 SDValue LHS = Op.getOperand(0);
497 if (!LHS.getValueType().isFloatingPoint())
500 SDValue RHS = Op.getOperand(1);
503 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
504 // node if necessary.
505 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
507 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
508 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
511 // Creates and returns a CMovFPT/F node.
512 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
513 SDValue False, SDLoc DL) {
514 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
515 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
516 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
518 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
519 True.getValueType(), True, FCC0, False, Cond);
522 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
523 TargetLowering::DAGCombinerInfo &DCI,
524 const MipsSubtarget *Subtarget) {
525 if (DCI.isBeforeLegalizeOps())
528 SDValue SetCC = N->getOperand(0);
530 if ((SetCC.getOpcode() != ISD::SETCC) ||
531 !SetCC.getOperand(0).getValueType().isInteger())
534 SDValue False = N->getOperand(2);
535 EVT FalseTy = False.getValueType();
537 if (!FalseTy.isInteger())
540 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
542 // If the RHS (False) is 0, we swap the order of the operands
543 // of ISD::SELECT (obviously also inverting the condition) so that we can
544 // take advantage of conditional moves using the $0 register.
546 // return (a != 0) ? x : 0;
554 if (!FalseC->getZExtValue()) {
555 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
556 SDValue True = N->getOperand(1);
558 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
559 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
561 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
564 // If both operands are integer constants there's a possibility that we
565 // can do some interesting optimizations.
566 SDValue True = N->getOperand(1);
567 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
569 if (!TrueC || !True.getValueType().isInteger())
572 // We'll also ignore MVT::i64 operands as this optimizations proves
573 // to be ineffective because of the required sign extensions as the result
574 // of a SETCC operator is always MVT::i32 for non-vector types.
575 if (True.getValueType() == MVT::i64)
578 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
580 // 1) (a < x) ? y : y-1
582 // addiu $reg2, $reg1, y-1
584 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
586 // 2) (a < x) ? y-1 : y
588 // xor $reg1, $reg1, 1
589 // addiu $reg2, $reg1, y-1
591 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
592 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
593 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
594 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
597 // Couldn't optimize.
601 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
602 TargetLowering::DAGCombinerInfo &DCI,
603 const MipsSubtarget *Subtarget) {
604 // Pattern match EXT.
605 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
606 // => ext $dst, $src, size, pos
607 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
610 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
611 unsigned ShiftRightOpc = ShiftRight.getOpcode();
613 // Op's first operand must be a shift right.
614 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
617 // The second operand of the shift must be an immediate.
619 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
622 uint64_t Pos = CN->getZExtValue();
623 uint64_t SMPos, SMSize;
625 // Op's second operand must be a shifted mask.
626 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
627 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
630 // Return if the shifted mask does not start at bit 0 or the sum of its size
631 // and Pos exceeds the word's size.
632 EVT ValTy = N->getValueType(0);
633 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
636 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
637 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
638 DAG.getConstant(SMSize, MVT::i32));
641 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
642 TargetLowering::DAGCombinerInfo &DCI,
643 const MipsSubtarget *Subtarget) {
644 // Pattern match INS.
645 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
646 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
647 // => ins $dst, $src, size, pos, $src1
648 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
651 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
652 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
655 // See if Op's first operand matches (and $src1 , mask0).
656 if (And0.getOpcode() != ISD::AND)
659 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
660 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
663 // See if Op's second operand matches (and (shl $src, pos), mask1).
664 if (And1.getOpcode() != ISD::AND)
667 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
668 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
671 // The shift masks must have the same position and size.
672 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
675 SDValue Shl = And1.getOperand(0);
676 if (Shl.getOpcode() != ISD::SHL)
679 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
682 unsigned Shamt = CN->getZExtValue();
684 // Return if the shift amount and the first bit position of mask are not the
686 EVT ValTy = N->getValueType(0);
687 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
690 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
691 DAG.getConstant(SMPos0, MVT::i32),
692 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
695 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
696 TargetLowering::DAGCombinerInfo &DCI,
697 const MipsSubtarget *Subtarget) {
698 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
700 if (DCI.isBeforeLegalizeOps())
703 SDValue Add = N->getOperand(1);
705 if (Add.getOpcode() != ISD::ADD)
708 SDValue Lo = Add.getOperand(1);
710 if ((Lo.getOpcode() != MipsISD::Lo) ||
711 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
714 EVT ValTy = N->getValueType(0);
717 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
719 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
722 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
724 SelectionDAG &DAG = DCI.DAG;
725 unsigned Opc = N->getOpcode();
731 return performDivRemCombine(N, DAG, DCI, Subtarget);
733 return performSELECTCombine(N, DAG, DCI, Subtarget);
735 return performANDCombine(N, DAG, DCI, Subtarget);
737 return performORCombine(N, DAG, DCI, Subtarget);
739 return performADDCombine(N, DAG, DCI, Subtarget);
746 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
747 SmallVectorImpl<SDValue> &Results,
748 SelectionDAG &DAG) const {
749 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
751 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
752 Results.push_back(Res.getValue(I));
756 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
757 SmallVectorImpl<SDValue> &Results,
758 SelectionDAG &DAG) const {
759 return LowerOperationWrapper(N, Results, DAG);
762 SDValue MipsTargetLowering::
763 LowerOperation(SDValue Op, SelectionDAG &DAG) const
765 switch (Op.getOpcode())
767 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
768 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
769 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
770 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
771 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
772 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
773 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
774 case ISD::SELECT: return lowerSELECT(Op, DAG);
775 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
776 case ISD::SETCC: return lowerSETCC(Op, DAG);
777 case ISD::VASTART: return lowerVASTART(Op, DAG);
778 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
779 case ISD::FABS: return lowerFABS(Op, DAG);
780 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
781 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
782 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
783 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
784 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
785 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
786 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
787 case ISD::LOAD: return lowerLOAD(Op, DAG);
788 case ISD::STORE: return lowerSTORE(Op, DAG);
789 case ISD::ADD: return lowerADD(Op, DAG);
790 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
795 //===----------------------------------------------------------------------===//
796 // Lower helper functions
797 //===----------------------------------------------------------------------===//
799 // addLiveIn - This helper function adds the specified physical register to the
800 // MachineFunction as a live in value. It also creates a corresponding
801 // virtual register for it.
803 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
805 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
806 MF.getRegInfo().addLiveIn(PReg, VReg);
810 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
811 MachineBasicBlock &MBB,
812 const TargetInstrInfo &TII,
817 // Insert instruction "teq $divisor_reg, $zero, 7".
818 MachineBasicBlock::iterator I(MI);
819 MachineInstrBuilder MIB;
820 MachineOperand &Divisor = MI->getOperand(2);
821 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
822 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
823 .addReg(Mips::ZERO).addImm(7);
825 // Use the 32-bit sub-register if this is a 64-bit division.
827 MIB->getOperand(0).setSubReg(Mips::sub_32);
829 // Clear Divisor's kill flag.
830 Divisor.setIsKill(false);
835 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
836 MachineBasicBlock *BB) const {
837 switch (MI->getOpcode()) {
839 llvm_unreachable("Unexpected instr type to insert");
840 case Mips::ATOMIC_LOAD_ADD_I8:
841 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
842 case Mips::ATOMIC_LOAD_ADD_I16:
843 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
844 case Mips::ATOMIC_LOAD_ADD_I32:
845 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
846 case Mips::ATOMIC_LOAD_ADD_I64:
847 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
849 case Mips::ATOMIC_LOAD_AND_I8:
850 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
851 case Mips::ATOMIC_LOAD_AND_I16:
852 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
853 case Mips::ATOMIC_LOAD_AND_I32:
854 return emitAtomicBinary(MI, BB, 4, Mips::AND);
855 case Mips::ATOMIC_LOAD_AND_I64:
856 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
858 case Mips::ATOMIC_LOAD_OR_I8:
859 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
860 case Mips::ATOMIC_LOAD_OR_I16:
861 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
862 case Mips::ATOMIC_LOAD_OR_I32:
863 return emitAtomicBinary(MI, BB, 4, Mips::OR);
864 case Mips::ATOMIC_LOAD_OR_I64:
865 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
867 case Mips::ATOMIC_LOAD_XOR_I8:
868 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
869 case Mips::ATOMIC_LOAD_XOR_I16:
870 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
871 case Mips::ATOMIC_LOAD_XOR_I32:
872 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
873 case Mips::ATOMIC_LOAD_XOR_I64:
874 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
876 case Mips::ATOMIC_LOAD_NAND_I8:
877 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
878 case Mips::ATOMIC_LOAD_NAND_I16:
879 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
880 case Mips::ATOMIC_LOAD_NAND_I32:
881 return emitAtomicBinary(MI, BB, 4, 0, true);
882 case Mips::ATOMIC_LOAD_NAND_I64:
883 return emitAtomicBinary(MI, BB, 8, 0, true);
885 case Mips::ATOMIC_LOAD_SUB_I8:
886 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
887 case Mips::ATOMIC_LOAD_SUB_I16:
888 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
889 case Mips::ATOMIC_LOAD_SUB_I32:
890 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
891 case Mips::ATOMIC_LOAD_SUB_I64:
892 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
894 case Mips::ATOMIC_SWAP_I8:
895 return emitAtomicBinaryPartword(MI, BB, 1, 0);
896 case Mips::ATOMIC_SWAP_I16:
897 return emitAtomicBinaryPartword(MI, BB, 2, 0);
898 case Mips::ATOMIC_SWAP_I32:
899 return emitAtomicBinary(MI, BB, 4, 0);
900 case Mips::ATOMIC_SWAP_I64:
901 return emitAtomicBinary(MI, BB, 8, 0);
903 case Mips::ATOMIC_CMP_SWAP_I8:
904 return emitAtomicCmpSwapPartword(MI, BB, 1);
905 case Mips::ATOMIC_CMP_SWAP_I16:
906 return emitAtomicCmpSwapPartword(MI, BB, 2);
907 case Mips::ATOMIC_CMP_SWAP_I32:
908 return emitAtomicCmpSwap(MI, BB, 4);
909 case Mips::ATOMIC_CMP_SWAP_I64:
910 return emitAtomicCmpSwap(MI, BB, 8);
911 case Mips::PseudoSDIV:
912 case Mips::PseudoUDIV:
913 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
914 case Mips::PseudoDSDIV:
915 case Mips::PseudoDUDIV:
916 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
920 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
921 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
923 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
924 unsigned Size, unsigned BinOpcode,
926 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
928 MachineFunction *MF = BB->getParent();
929 MachineRegisterInfo &RegInfo = MF->getRegInfo();
930 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
931 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
932 DebugLoc DL = MI->getDebugLoc();
933 unsigned LL, SC, AND, NOR, ZERO, BEQ;
936 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
937 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
948 ZERO = Mips::ZERO_64;
952 unsigned OldVal = MI->getOperand(0).getReg();
953 unsigned Ptr = MI->getOperand(1).getReg();
954 unsigned Incr = MI->getOperand(2).getReg();
956 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
957 unsigned AndRes = RegInfo.createVirtualRegister(RC);
958 unsigned Success = RegInfo.createVirtualRegister(RC);
960 // insert new blocks after the current block
961 const BasicBlock *LLVM_BB = BB->getBasicBlock();
962 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
963 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
964 MachineFunction::iterator It = BB;
966 MF->insert(It, loopMBB);
967 MF->insert(It, exitMBB);
969 // Transfer the remainder of BB and its successor edges to exitMBB.
970 exitMBB->splice(exitMBB->begin(), BB,
971 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
972 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
976 // fallthrough --> loopMBB
977 BB->addSuccessor(loopMBB);
978 loopMBB->addSuccessor(loopMBB);
979 loopMBB->addSuccessor(exitMBB);
983 // <binop> storeval, oldval, incr
984 // sc success, storeval, 0(ptr)
985 // beq success, $0, loopMBB
987 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
989 // and andres, oldval, incr
990 // nor storeval, $0, andres
991 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
992 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
993 } else if (BinOpcode) {
994 // <binop> storeval, oldval, incr
995 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
999 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1000 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1002 MI->eraseFromParent(); // The instruction is gone now.
1008 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
1009 MachineBasicBlock *BB,
1010 unsigned Size, unsigned BinOpcode,
1012 assert((Size == 1 || Size == 2) &&
1013 "Unsupported size for EmitAtomicBinaryPartial.");
1015 MachineFunction *MF = BB->getParent();
1016 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1017 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1018 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1019 DebugLoc DL = MI->getDebugLoc();
1021 unsigned Dest = MI->getOperand(0).getReg();
1022 unsigned Ptr = MI->getOperand(1).getReg();
1023 unsigned Incr = MI->getOperand(2).getReg();
1025 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1026 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1027 unsigned Mask = RegInfo.createVirtualRegister(RC);
1028 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1029 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1030 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1031 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1032 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1033 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1034 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1035 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1036 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1037 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1038 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1039 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1040 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1041 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1042 unsigned Success = RegInfo.createVirtualRegister(RC);
1044 // insert new blocks after the current block
1045 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1046 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1047 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1048 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1049 MachineFunction::iterator It = BB;
1051 MF->insert(It, loopMBB);
1052 MF->insert(It, sinkMBB);
1053 MF->insert(It, exitMBB);
1055 // Transfer the remainder of BB and its successor edges to exitMBB.
1056 exitMBB->splice(exitMBB->begin(), BB,
1057 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1058 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1060 BB->addSuccessor(loopMBB);
1061 loopMBB->addSuccessor(loopMBB);
1062 loopMBB->addSuccessor(sinkMBB);
1063 sinkMBB->addSuccessor(exitMBB);
1066 // addiu masklsb2,$0,-4 # 0xfffffffc
1067 // and alignedaddr,ptr,masklsb2
1068 // andi ptrlsb2,ptr,3
1069 // sll shiftamt,ptrlsb2,3
1070 // ori maskupper,$0,255 # 0xff
1071 // sll mask,maskupper,shiftamt
1072 // nor mask2,$0,mask
1073 // sll incr2,incr,shiftamt
1075 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1076 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1077 .addReg(Mips::ZERO).addImm(-4);
1078 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1079 .addReg(Ptr).addReg(MaskLSB2);
1080 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1081 if (Subtarget->isLittle()) {
1082 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1084 unsigned Off = RegInfo.createVirtualRegister(RC);
1085 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1086 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1087 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1089 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1090 .addReg(Mips::ZERO).addImm(MaskImm);
1091 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1092 .addReg(MaskUpper).addReg(ShiftAmt);
1093 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1094 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1096 // atomic.load.binop
1098 // ll oldval,0(alignedaddr)
1099 // binop binopres,oldval,incr2
1100 // and newval,binopres,mask
1101 // and maskedoldval0,oldval,mask2
1102 // or storeval,maskedoldval0,newval
1103 // sc success,storeval,0(alignedaddr)
1104 // beq success,$0,loopMBB
1108 // ll oldval,0(alignedaddr)
1109 // and newval,incr2,mask
1110 // and maskedoldval0,oldval,mask2
1111 // or storeval,maskedoldval0,newval
1112 // sc success,storeval,0(alignedaddr)
1113 // beq success,$0,loopMBB
1116 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1118 // and andres, oldval, incr2
1119 // nor binopres, $0, andres
1120 // and newval, binopres, mask
1121 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1122 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1123 .addReg(Mips::ZERO).addReg(AndRes);
1124 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1125 } else if (BinOpcode) {
1126 // <binop> binopres, oldval, incr2
1127 // and newval, binopres, mask
1128 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1129 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1130 } else { // atomic.swap
1131 // and newval, incr2, mask
1132 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1135 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1136 .addReg(OldVal).addReg(Mask2);
1137 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1138 .addReg(MaskedOldVal0).addReg(NewVal);
1139 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1140 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1141 BuildMI(BB, DL, TII->get(Mips::BEQ))
1142 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1145 // and maskedoldval1,oldval,mask
1146 // srl srlres,maskedoldval1,shiftamt
1147 // sll sllres,srlres,24
1148 // sra dest,sllres,24
1150 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1152 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1153 .addReg(OldVal).addReg(Mask);
1154 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1155 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1156 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1157 .addReg(SrlRes).addImm(ShiftImm);
1158 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1159 .addReg(SllRes).addImm(ShiftImm);
1161 MI->eraseFromParent(); // The instruction is gone now.
1166 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1167 MachineBasicBlock *BB,
1168 unsigned Size) const {
1169 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1171 MachineFunction *MF = BB->getParent();
1172 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1173 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1174 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1175 DebugLoc DL = MI->getDebugLoc();
1176 unsigned LL, SC, ZERO, BNE, BEQ;
1179 LL = isMicroMips ? Mips::LL_MM : Mips::LL;
1180 SC = isMicroMips ? Mips::SC_MM : Mips::SC;
1187 ZERO = Mips::ZERO_64;
1192 unsigned Dest = MI->getOperand(0).getReg();
1193 unsigned Ptr = MI->getOperand(1).getReg();
1194 unsigned OldVal = MI->getOperand(2).getReg();
1195 unsigned NewVal = MI->getOperand(3).getReg();
1197 unsigned Success = RegInfo.createVirtualRegister(RC);
1199 // insert new blocks after the current block
1200 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1201 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1202 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1203 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1204 MachineFunction::iterator It = BB;
1206 MF->insert(It, loop1MBB);
1207 MF->insert(It, loop2MBB);
1208 MF->insert(It, exitMBB);
1210 // Transfer the remainder of BB and its successor edges to exitMBB.
1211 exitMBB->splice(exitMBB->begin(), BB,
1212 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1213 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1217 // fallthrough --> loop1MBB
1218 BB->addSuccessor(loop1MBB);
1219 loop1MBB->addSuccessor(exitMBB);
1220 loop1MBB->addSuccessor(loop2MBB);
1221 loop2MBB->addSuccessor(loop1MBB);
1222 loop2MBB->addSuccessor(exitMBB);
1226 // bne dest, oldval, exitMBB
1228 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1229 BuildMI(BB, DL, TII->get(BNE))
1230 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1233 // sc success, newval, 0(ptr)
1234 // beq success, $0, loop1MBB
1236 BuildMI(BB, DL, TII->get(SC), Success)
1237 .addReg(NewVal).addReg(Ptr).addImm(0);
1238 BuildMI(BB, DL, TII->get(BEQ))
1239 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1241 MI->eraseFromParent(); // The instruction is gone now.
1247 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1248 MachineBasicBlock *BB,
1249 unsigned Size) const {
1250 assert((Size == 1 || Size == 2) &&
1251 "Unsupported size for EmitAtomicCmpSwapPartial.");
1253 MachineFunction *MF = BB->getParent();
1254 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1255 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1256 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1257 DebugLoc DL = MI->getDebugLoc();
1259 unsigned Dest = MI->getOperand(0).getReg();
1260 unsigned Ptr = MI->getOperand(1).getReg();
1261 unsigned CmpVal = MI->getOperand(2).getReg();
1262 unsigned NewVal = MI->getOperand(3).getReg();
1264 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1265 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1266 unsigned Mask = RegInfo.createVirtualRegister(RC);
1267 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1268 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1269 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1270 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1271 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1272 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1273 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1274 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1275 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1276 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1277 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1278 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1279 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1280 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1281 unsigned Success = RegInfo.createVirtualRegister(RC);
1283 // insert new blocks after the current block
1284 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1285 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1286 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1287 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1288 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1289 MachineFunction::iterator It = BB;
1291 MF->insert(It, loop1MBB);
1292 MF->insert(It, loop2MBB);
1293 MF->insert(It, sinkMBB);
1294 MF->insert(It, exitMBB);
1296 // Transfer the remainder of BB and its successor edges to exitMBB.
1297 exitMBB->splice(exitMBB->begin(), BB,
1298 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1299 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1301 BB->addSuccessor(loop1MBB);
1302 loop1MBB->addSuccessor(sinkMBB);
1303 loop1MBB->addSuccessor(loop2MBB);
1304 loop2MBB->addSuccessor(loop1MBB);
1305 loop2MBB->addSuccessor(sinkMBB);
1306 sinkMBB->addSuccessor(exitMBB);
1308 // FIXME: computation of newval2 can be moved to loop2MBB.
1310 // addiu masklsb2,$0,-4 # 0xfffffffc
1311 // and alignedaddr,ptr,masklsb2
1312 // andi ptrlsb2,ptr,3
1313 // sll shiftamt,ptrlsb2,3
1314 // ori maskupper,$0,255 # 0xff
1315 // sll mask,maskupper,shiftamt
1316 // nor mask2,$0,mask
1317 // andi maskedcmpval,cmpval,255
1318 // sll shiftedcmpval,maskedcmpval,shiftamt
1319 // andi maskednewval,newval,255
1320 // sll shiftednewval,maskednewval,shiftamt
1321 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1322 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1323 .addReg(Mips::ZERO).addImm(-4);
1324 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1325 .addReg(Ptr).addReg(MaskLSB2);
1326 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1327 if (Subtarget->isLittle()) {
1328 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1330 unsigned Off = RegInfo.createVirtualRegister(RC);
1331 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1332 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1333 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1335 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1336 .addReg(Mips::ZERO).addImm(MaskImm);
1337 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1338 .addReg(MaskUpper).addReg(ShiftAmt);
1339 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1340 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1341 .addReg(CmpVal).addImm(MaskImm);
1342 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1343 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1344 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1345 .addReg(NewVal).addImm(MaskImm);
1346 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1347 .addReg(MaskedNewVal).addReg(ShiftAmt);
1350 // ll oldval,0(alginedaddr)
1351 // and maskedoldval0,oldval,mask
1352 // bne maskedoldval0,shiftedcmpval,sinkMBB
1354 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1355 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1356 .addReg(OldVal).addReg(Mask);
1357 BuildMI(BB, DL, TII->get(Mips::BNE))
1358 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1361 // and maskedoldval1,oldval,mask2
1362 // or storeval,maskedoldval1,shiftednewval
1363 // sc success,storeval,0(alignedaddr)
1364 // beq success,$0,loop1MBB
1366 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1367 .addReg(OldVal).addReg(Mask2);
1368 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1369 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1370 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1371 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1372 BuildMI(BB, DL, TII->get(Mips::BEQ))
1373 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1376 // srl srlres,maskedoldval0,shiftamt
1377 // sll sllres,srlres,24
1378 // sra dest,sllres,24
1380 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1382 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1383 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1384 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1385 .addReg(SrlRes).addImm(ShiftImm);
1386 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1387 .addReg(SllRes).addImm(ShiftImm);
1389 MI->eraseFromParent(); // The instruction is gone now.
1394 //===----------------------------------------------------------------------===//
1395 // Misc Lower Operation implementation
1396 //===----------------------------------------------------------------------===//
1397 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1398 SDValue Chain = Op.getOperand(0);
1399 SDValue Table = Op.getOperand(1);
1400 SDValue Index = Op.getOperand(2);
1402 EVT PTy = getPointerTy();
1403 unsigned EntrySize =
1404 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1406 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1407 DAG.getConstant(EntrySize, PTy));
1408 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1410 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1411 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1412 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1414 Chain = Addr.getValue(1);
1416 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1417 // For PIC, the sequence is:
1418 // BRIND(load(Jumptable + index) + RelocBase)
1419 // RelocBase can be JumpTable, GOT or some sort of global base.
1420 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1421 getPICJumpTableRelocBase(Table, DAG));
1424 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1427 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1428 // The first operand is the chain, the second is the condition, the third is
1429 // the block to branch to if the condition is true.
1430 SDValue Chain = Op.getOperand(0);
1431 SDValue Dest = Op.getOperand(2);
1434 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1436 // Return if flag is not set by a floating point comparison.
1437 if (CondRes.getOpcode() != MipsISD::FPCmp)
1440 SDValue CCNode = CondRes.getOperand(2);
1442 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1443 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1444 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1445 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1446 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1447 FCC0, Dest, CondRes);
1450 SDValue MipsTargetLowering::
1451 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1453 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1455 // Return if flag is not set by a floating point comparison.
1456 if (Cond.getOpcode() != MipsISD::FPCmp)
1459 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1463 SDValue MipsTargetLowering::
1464 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1467 EVT Ty = Op.getOperand(0).getValueType();
1468 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1469 getSetCCResultType(*DAG.getContext(), Ty),
1470 Op.getOperand(0), Op.getOperand(1),
1473 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1477 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1478 SDValue Cond = createFPCmp(DAG, Op);
1480 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1481 "Floating point operand expected.");
1483 SDValue True = DAG.getConstant(1, MVT::i32);
1484 SDValue False = DAG.getConstant(0, MVT::i32);
1486 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1489 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1490 SelectionDAG &DAG) const {
1491 // FIXME there isn't actually debug info here
1493 EVT Ty = Op.getValueType();
1494 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1495 const GlobalValue *GV = N->getGlobal();
1497 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1498 const MipsTargetObjectFile &TLOF =
1499 (const MipsTargetObjectFile&)getObjFileLowering();
1501 // %gp_rel relocation
1502 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1503 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1505 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1506 DAG.getVTList(MVT::i32), &GA, 1);
1507 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1508 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1511 // %hi/%lo relocation
1512 return getAddrNonPIC(N, Ty, DAG);
1515 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1516 return getAddrLocal(N, Ty, DAG, HasMips64);
1519 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1520 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1521 MachinePointerInfo::getGOT());
1523 return getAddrGlobal(N, Ty, DAG,
1524 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16,
1525 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1528 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1529 SelectionDAG &DAG) const {
1530 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1531 EVT Ty = Op.getValueType();
1533 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1534 return getAddrNonPIC(N, Ty, DAG);
1536 return getAddrLocal(N, Ty, DAG, HasMips64);
1539 SDValue MipsTargetLowering::
1540 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1542 // If the relocation model is PIC, use the General Dynamic TLS Model or
1543 // Local Dynamic TLS model, otherwise use the Initial Exec or
1544 // Local Exec TLS Model.
1546 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1548 const GlobalValue *GV = GA->getGlobal();
1549 EVT PtrVT = getPointerTy();
1551 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1553 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1554 // General Dynamic and Local Dynamic TLS Model.
1555 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1558 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1559 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1560 getGlobalReg(DAG, PtrVT), TGA);
1561 unsigned PtrSize = PtrVT.getSizeInBits();
1562 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1564 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1568 Entry.Node = Argument;
1570 Args.push_back(Entry);
1572 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1573 false, false, false, false, 0, CallingConv::C,
1574 /*IsTailCall=*/false, /*doesNotRet=*/false,
1575 /*isReturnValueUsed=*/true,
1576 TlsGetAddr, Args, DAG, DL);
1577 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1579 SDValue Ret = CallResult.first;
1581 if (model != TLSModel::LocalDynamic)
1584 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1585 MipsII::MO_DTPREL_HI);
1586 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1587 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1588 MipsII::MO_DTPREL_LO);
1589 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1590 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1591 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1595 if (model == TLSModel::InitialExec) {
1596 // Initial Exec TLS Model
1597 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1598 MipsII::MO_GOTTPREL);
1599 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1601 Offset = DAG.getLoad(PtrVT, DL,
1602 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1603 false, false, false, 0);
1605 // Local Exec TLS Model
1606 assert(model == TLSModel::LocalExec);
1607 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1608 MipsII::MO_TPREL_HI);
1609 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1610 MipsII::MO_TPREL_LO);
1611 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1612 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1613 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1616 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1617 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1620 SDValue MipsTargetLowering::
1621 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1623 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1624 EVT Ty = Op.getValueType();
1626 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1627 return getAddrNonPIC(N, Ty, DAG);
1629 return getAddrLocal(N, Ty, DAG, HasMips64);
1632 SDValue MipsTargetLowering::
1633 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1635 // gp_rel relocation
1636 // FIXME: we should reference the constant pool using small data sections,
1637 // but the asm printer currently doesn't support this feature without
1638 // hacking it. This feature should come soon so we can uncomment the
1640 //if (IsInSmallSection(C->getType())) {
1641 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1642 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1643 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1644 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1645 EVT Ty = Op.getValueType();
1647 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1648 return getAddrNonPIC(N, Ty, DAG);
1650 return getAddrLocal(N, Ty, DAG, HasMips64);
1653 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1654 MachineFunction &MF = DAG.getMachineFunction();
1655 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1658 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1661 // vastart just stores the address of the VarArgsFrameIndex slot into the
1662 // memory location argument.
1663 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1664 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1665 MachinePointerInfo(SV), false, false, 0);
1668 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1669 bool HasExtractInsert) {
1670 EVT TyX = Op.getOperand(0).getValueType();
1671 EVT TyY = Op.getOperand(1).getValueType();
1672 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1673 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1677 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1679 SDValue X = (TyX == MVT::f32) ?
1680 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1681 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1683 SDValue Y = (TyY == MVT::f32) ?
1684 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1685 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1688 if (HasExtractInsert) {
1689 // ext E, Y, 31, 1 ; extract bit31 of Y
1690 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1691 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1692 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1695 // srl SrlX, SllX, 1
1697 // sll SllY, SrlX, 31
1698 // or Or, SrlX, SllY
1699 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1700 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1701 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1702 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1703 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1706 if (TyX == MVT::f32)
1707 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1709 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1710 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1711 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1714 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1715 bool HasExtractInsert) {
1716 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1717 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1718 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1719 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1722 // Bitcast to integer nodes.
1723 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1724 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1726 if (HasExtractInsert) {
1727 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1728 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1729 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1730 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1732 if (WidthX > WidthY)
1733 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1734 else if (WidthY > WidthX)
1735 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1737 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1738 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1739 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1742 // (d)sll SllX, X, 1
1743 // (d)srl SrlX, SllX, 1
1744 // (d)srl SrlY, Y, width(Y)-1
1745 // (d)sll SllY, SrlX, width(Y)-1
1746 // or Or, SrlX, SllY
1747 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1748 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1749 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1750 DAG.getConstant(WidthY - 1, MVT::i32));
1752 if (WidthX > WidthY)
1753 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1754 else if (WidthY > WidthX)
1755 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1757 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1758 DAG.getConstant(WidthX - 1, MVT::i32));
1759 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1760 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1764 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1765 if (Subtarget->hasMips64())
1766 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasExtractInsert());
1768 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasExtractInsert());
1771 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG,
1772 bool HasExtractInsert) {
1773 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1776 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1778 SDValue X = (Op.getValueType() == MVT::f32) ?
1779 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1780 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1784 if (HasExtractInsert)
1785 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1786 DAG.getRegister(Mips::ZERO, MVT::i32),
1787 DAG.getConstant(31, MVT::i32), Const1, X);
1789 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1790 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1793 if (Op.getValueType() == MVT::f32)
1794 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1796 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1797 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1798 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1801 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG,
1802 bool HasExtractInsert) {
1803 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1806 // Bitcast to integer node.
1807 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1810 if (HasExtractInsert)
1811 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1812 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1813 DAG.getConstant(63, MVT::i32), Const1, X);
1815 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1816 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1819 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1823 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1824 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1825 return lowerFABS64(Op, DAG, Subtarget->hasExtractInsert());
1827 return lowerFABS32(Op, DAG, Subtarget->hasExtractInsert());
1830 SDValue MipsTargetLowering::
1831 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1833 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1834 "Frame address can only be determined for current frame.");
1836 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1837 MFI->setFrameAddressIsTaken(true);
1838 EVT VT = Op.getValueType();
1840 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1841 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1845 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1846 SelectionDAG &DAG) const {
1848 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1849 "Return address can be determined only for current frame.");
1851 MachineFunction &MF = DAG.getMachineFunction();
1852 MachineFrameInfo *MFI = MF.getFrameInfo();
1853 MVT VT = Op.getSimpleValueType();
1854 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1855 MFI->setReturnAddressIsTaken(true);
1857 // Return RA, which contains the return address. Mark it an implicit live-in.
1858 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1859 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1862 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1863 // generated from __builtin_eh_return (offset, handler)
1864 // The effect of this is to adjust the stack pointer by "offset"
1865 // and then branch to "handler".
1866 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1868 MachineFunction &MF = DAG.getMachineFunction();
1869 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1871 MipsFI->setCallsEhReturn();
1872 SDValue Chain = Op.getOperand(0);
1873 SDValue Offset = Op.getOperand(1);
1874 SDValue Handler = Op.getOperand(2);
1876 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1878 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1879 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1880 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1881 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1882 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1883 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1884 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1885 DAG.getRegister(OffsetReg, Ty),
1886 DAG.getRegister(AddrReg, getPointerTy()),
1890 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1891 SelectionDAG &DAG) const {
1892 // FIXME: Need pseudo-fence for 'singlethread' fences
1893 // FIXME: Set SType for weaker fences where supported/appropriate.
1896 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1897 DAG.getConstant(SType, MVT::i32));
1900 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1901 SelectionDAG &DAG) const {
1903 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1904 SDValue Shamt = Op.getOperand(2);
1907 // lo = (shl lo, shamt)
1908 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1911 // hi = (shl lo, shamt[4:0])
1912 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1913 DAG.getConstant(-1, MVT::i32));
1914 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1915 DAG.getConstant(1, MVT::i32));
1916 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1918 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1919 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1920 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1921 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1922 DAG.getConstant(0x20, MVT::i32));
1923 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1924 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1925 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1927 SDValue Ops[2] = {Lo, Hi};
1928 return DAG.getMergeValues(Ops, 2, DL);
1931 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1934 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1935 SDValue Shamt = Op.getOperand(2);
1938 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1940 // hi = (sra hi, shamt)
1942 // hi = (srl hi, shamt)
1945 // lo = (sra hi, shamt[4:0])
1946 // hi = (sra hi, 31)
1948 // lo = (srl hi, shamt[4:0])
1950 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1951 DAG.getConstant(-1, MVT::i32));
1952 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1953 DAG.getConstant(1, MVT::i32));
1954 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1955 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1956 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1957 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1959 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1960 DAG.getConstant(0x20, MVT::i32));
1961 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1962 DAG.getConstant(31, MVT::i32));
1963 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1964 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1965 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1968 SDValue Ops[2] = {Lo, Hi};
1969 return DAG.getMergeValues(Ops, 2, DL);
1972 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1973 SDValue Chain, SDValue Src, unsigned Offset) {
1974 SDValue Ptr = LD->getBasePtr();
1975 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1976 EVT BasePtrVT = Ptr.getValueType();
1978 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1981 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1982 DAG.getConstant(Offset, BasePtrVT));
1984 SDValue Ops[] = { Chain, Ptr, Src };
1985 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1986 LD->getMemOperand());
1989 // Expand an unaligned 32 or 64-bit integer load node.
1990 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1991 LoadSDNode *LD = cast<LoadSDNode>(Op);
1992 EVT MemVT = LD->getMemoryVT();
1994 // Return if load is aligned or if MemVT is neither i32 nor i64.
1995 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1996 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1999 bool IsLittle = Subtarget->isLittle();
2000 EVT VT = Op.getValueType();
2001 ISD::LoadExtType ExtType = LD->getExtensionType();
2002 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2004 assert((VT == MVT::i32) || (VT == MVT::i64));
2007 // (set dst, (i64 (load baseptr)))
2009 // (set tmp, (ldl (add baseptr, 7), undef))
2010 // (set dst, (ldr baseptr, tmp))
2011 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2012 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2014 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2018 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2020 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2024 // (set dst, (i32 (load baseptr))) or
2025 // (set dst, (i64 (sextload baseptr))) or
2026 // (set dst, (i64 (extload baseptr)))
2028 // (set tmp, (lwl (add baseptr, 3), undef))
2029 // (set dst, (lwr baseptr, tmp))
2030 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2031 (ExtType == ISD::EXTLOAD))
2034 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2037 // (set dst, (i64 (zextload baseptr)))
2039 // (set tmp0, (lwl (add baseptr, 3), undef))
2040 // (set tmp1, (lwr baseptr, tmp0))
2041 // (set tmp2, (shl tmp1, 32))
2042 // (set dst, (srl tmp2, 32))
2044 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2045 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2046 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2047 SDValue Ops[] = { SRL, LWR.getValue(1) };
2048 return DAG.getMergeValues(Ops, 2, DL);
2051 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2052 SDValue Chain, unsigned Offset) {
2053 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2054 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2056 SDVTList VTList = DAG.getVTList(MVT::Other);
2059 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2060 DAG.getConstant(Offset, BasePtrVT));
2062 SDValue Ops[] = { Chain, Value, Ptr };
2063 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2064 SD->getMemOperand());
2067 // Expand an unaligned 32 or 64-bit integer store node.
2068 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2070 SDValue Value = SD->getValue(), Chain = SD->getChain();
2071 EVT VT = Value.getValueType();
2074 // (store val, baseptr) or
2075 // (truncstore val, baseptr)
2077 // (swl val, (add baseptr, 3))
2078 // (swr val, baseptr)
2079 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2080 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2082 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2085 assert(VT == MVT::i64);
2088 // (store val, baseptr)
2090 // (sdl val, (add baseptr, 7))
2091 // (sdr val, baseptr)
2092 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2093 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2096 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2097 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2098 SDValue Val = SD->getValue();
2100 if (Val.getOpcode() != ISD::FP_TO_SINT)
2103 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2104 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2107 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2108 SD->getPointerInfo(), SD->isVolatile(),
2109 SD->isNonTemporal(), SD->getAlignment());
2112 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2113 StoreSDNode *SD = cast<StoreSDNode>(Op);
2114 EVT MemVT = SD->getMemoryVT();
2116 // Lower unaligned integer stores.
2117 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2118 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2119 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2121 return lowerFP_TO_SINT_STORE(SD, DAG);
2124 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2125 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2126 || cast<ConstantSDNode>
2127 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2128 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2132 // (add (frameaddr 0), (frame_to_args_offset))
2133 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2134 // (add FrameObject, 0)
2135 // where FrameObject is a fixed StackObject with offset 0 which points to
2136 // the old stack pointer.
2137 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2138 EVT ValTy = Op->getValueType(0);
2139 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2140 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2141 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2142 DAG.getConstant(0, ValTy));
2145 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2146 SelectionDAG &DAG) const {
2147 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2148 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2150 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2153 //===----------------------------------------------------------------------===//
2154 // Calling Convention Implementation
2155 //===----------------------------------------------------------------------===//
2157 //===----------------------------------------------------------------------===//
2158 // TODO: Implement a generic logic using tblgen that can support this.
2159 // Mips O32 ABI rules:
2161 // i32 - Passed in A0, A1, A2, A3 and stack
2162 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2163 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2164 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2165 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2166 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2169 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2170 //===----------------------------------------------------------------------===//
2172 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2173 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2174 CCState &State, const uint16_t *F64Regs) {
2176 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2178 static const uint16_t IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2179 static const uint16_t F32Regs[] = { Mips::F12, Mips::F14 };
2181 // Do not process byval args here.
2182 if (ArgFlags.isByVal())
2185 // Promote i8 and i16
2186 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2188 if (ArgFlags.isSExt())
2189 LocInfo = CCValAssign::SExt;
2190 else if (ArgFlags.isZExt())
2191 LocInfo = CCValAssign::ZExt;
2193 LocInfo = CCValAssign::AExt;
2198 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2199 // is true: function is vararg, argument is 3rd or higher, there is previous
2200 // argument which is not f32 or f64.
2201 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2202 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2203 unsigned OrigAlign = ArgFlags.getOrigAlign();
2204 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2206 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2207 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2208 // If this is the first part of an i64 arg,
2209 // the allocated register must be either A0 or A2.
2210 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2211 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2213 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2214 // Allocate int register and shadow next int register. If first
2215 // available register is Mips::A1 or Mips::A3, shadow it too.
2216 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2217 if (Reg == Mips::A1 || Reg == Mips::A3)
2218 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2219 State.AllocateReg(IntRegs, IntRegsSize);
2221 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2222 // we are guaranteed to find an available float register
2223 if (ValVT == MVT::f32) {
2224 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2225 // Shadow int register
2226 State.AllocateReg(IntRegs, IntRegsSize);
2228 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2229 // Shadow int registers
2230 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2231 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2232 State.AllocateReg(IntRegs, IntRegsSize);
2233 State.AllocateReg(IntRegs, IntRegsSize);
2236 llvm_unreachable("Cannot handle this ValVT.");
2239 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2241 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2243 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2248 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2249 MVT LocVT, CCValAssign::LocInfo LocInfo,
2250 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2251 static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2253 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2256 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2257 MVT LocVT, CCValAssign::LocInfo LocInfo,
2258 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2259 static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2261 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2264 #include "MipsGenCallingConv.inc"
2266 //===----------------------------------------------------------------------===//
2267 // Call Calling Convention Implementation
2268 //===----------------------------------------------------------------------===//
2270 // Return next O32 integer argument register.
2271 static unsigned getNextIntArgReg(unsigned Reg) {
2272 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2273 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2277 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2278 SDValue Chain, SDValue Arg, SDLoc DL,
2279 bool IsTailCall, SelectionDAG &DAG) const {
2281 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2282 DAG.getIntPtrConstant(Offset));
2283 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2287 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2288 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2289 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2290 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2291 /*isVolatile=*/ true, false, 0);
2294 void MipsTargetLowering::
2295 getOpndList(SmallVectorImpl<SDValue> &Ops,
2296 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2297 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2298 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2299 // Insert node "GP copy globalreg" before call to function.
2301 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2302 // in PIC mode) allow symbols to be resolved via lazy binding.
2303 // The lazy binding stub requires GP to point to the GOT.
2304 if (IsPICCall && !InternalLinkage) {
2305 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2306 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2307 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2310 // Build a sequence of copy-to-reg nodes chained together with token
2311 // chain and flag operands which copy the outgoing args into registers.
2312 // The InFlag in necessary since all emitted instructions must be
2316 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2317 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2318 RegsToPass[i].second, InFlag);
2319 InFlag = Chain.getValue(1);
2322 // Add argument registers to the end of the list so that they are
2323 // known live into the call.
2324 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2325 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2326 RegsToPass[i].second.getValueType()));
2328 // Add a register mask operand representing the call-preserved registers.
2329 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2330 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2331 assert(Mask && "Missing call preserved mask for calling convention");
2332 if (Subtarget->inMips16HardFloat()) {
2333 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2334 llvm::StringRef Sym = G->getGlobal()->getName();
2335 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2336 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
2337 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2341 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2343 if (InFlag.getNode())
2344 Ops.push_back(InFlag);
2347 /// LowerCall - functions arguments are copied from virtual regs to
2348 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2350 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2351 SmallVectorImpl<SDValue> &InVals) const {
2352 SelectionDAG &DAG = CLI.DAG;
2354 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2355 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2356 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2357 SDValue Chain = CLI.Chain;
2358 SDValue Callee = CLI.Callee;
2359 bool &IsTailCall = CLI.IsTailCall;
2360 CallingConv::ID CallConv = CLI.CallConv;
2361 bool IsVarArg = CLI.IsVarArg;
2363 MachineFunction &MF = DAG.getMachineFunction();
2364 MachineFrameInfo *MFI = MF.getFrameInfo();
2365 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2366 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2367 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2369 // Analyze operands of the call, assigning locations to each operand.
2370 SmallVector<CCValAssign, 16> ArgLocs;
2371 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2372 getTargetMachine(), ArgLocs, *DAG.getContext());
2373 MipsCC::SpecialCallingConvType SpecialCallingConv =
2374 getSpecialCallingConv(Callee);
2375 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2376 SpecialCallingConv);
2378 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2379 Subtarget->mipsSEUsesSoftFloat(),
2380 Callee.getNode(), CLI.Args);
2382 // Get a count of how many bytes are to be pushed on the stack.
2383 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2385 // Check if it's really possible to do a tail call.
2388 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2389 *MF.getInfo<MipsFunctionInfo>());
2394 // Chain is the output chain of the last Load/Store or CopyToReg node.
2395 // ByValChain is the output chain of the last Memcpy node created for copying
2396 // byval arguments to the stack.
2397 unsigned StackAlignment = TFL->getStackAlignment();
2398 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2399 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2402 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2404 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2405 IsN64 ? Mips::SP_64 : Mips::SP,
2408 // With EABI is it possible to have 16 args on registers.
2409 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2410 SmallVector<SDValue, 8> MemOpChains;
2411 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2413 // Walk the register/memloc assignments, inserting copies/loads.
2414 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2415 SDValue Arg = OutVals[i];
2416 CCValAssign &VA = ArgLocs[i];
2417 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2418 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2421 if (Flags.isByVal()) {
2422 assert(Flags.getByValSize() &&
2423 "ByVal args of size 0 should have been ignored by front-end.");
2424 assert(ByValArg != MipsCCInfo.byval_end());
2425 assert(!IsTailCall &&
2426 "Do not tail-call optimize if there is a byval argument.");
2427 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2428 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2433 // Promote the value if needed.
2434 switch (VA.getLocInfo()) {
2435 default: llvm_unreachable("Unknown loc info!");
2436 case CCValAssign::Full:
2437 if (VA.isRegLoc()) {
2438 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2439 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2440 (ValVT == MVT::i64 && LocVT == MVT::f64))
2441 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2442 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2443 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2444 Arg, DAG.getConstant(0, MVT::i32));
2445 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2446 Arg, DAG.getConstant(1, MVT::i32));
2447 if (!Subtarget->isLittle())
2449 unsigned LocRegLo = VA.getLocReg();
2450 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2451 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2452 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2457 case CCValAssign::SExt:
2458 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2460 case CCValAssign::ZExt:
2461 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2463 case CCValAssign::AExt:
2464 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2468 // Arguments that can be passed on register must be kept at
2469 // RegsToPass vector
2470 if (VA.isRegLoc()) {
2471 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2475 // Register can't get to this point...
2476 assert(VA.isMemLoc());
2478 // emit ISD::STORE whichs stores the
2479 // parameter value to a stack Location
2480 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2481 Chain, Arg, DL, IsTailCall, DAG));
2484 // Transform all store nodes into one single node because all store
2485 // nodes are independent of each other.
2486 if (!MemOpChains.empty())
2487 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2488 &MemOpChains[0], MemOpChains.size());
2490 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2491 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2492 // node so that legalize doesn't hack it.
2493 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2494 bool GlobalOrExternal = false, InternalLinkage = false;
2496 EVT Ty = Callee.getValueType();
2498 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2500 const GlobalValue *Val = G->getGlobal();
2501 InternalLinkage = Val->hasInternalLinkage();
2503 if (InternalLinkage)
2504 Callee = getAddrLocal(G, Ty, DAG, HasMips64);
2506 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2507 MipsII::MO_CALL_LO16, Chain,
2508 FuncInfo->callPtrInfo(Val));
2510 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2511 FuncInfo->callPtrInfo(Val));
2513 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2514 MipsII::MO_NO_FLAG);
2515 GlobalOrExternal = true;
2517 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2518 const char *Sym = S->getSymbol();
2520 if (!IsN64 && !IsPIC) // !N64 && static
2521 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2522 MipsII::MO_NO_FLAG);
2524 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2525 MipsII::MO_CALL_LO16, Chain,
2526 FuncInfo->callPtrInfo(Sym));
2528 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2529 FuncInfo->callPtrInfo(Sym));
2531 GlobalOrExternal = true;
2534 SmallVector<SDValue, 8> Ops(1, Chain);
2535 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2537 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2538 CLI, Callee, Chain);
2541 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2543 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2544 SDValue InFlag = Chain.getValue(1);
2546 // Create the CALLSEQ_END node.
2547 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2548 DAG.getIntPtrConstant(0, true), InFlag, DL);
2549 InFlag = Chain.getValue(1);
2551 // Handle result values, copying them out of physregs into vregs that we
2553 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2554 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2557 /// LowerCallResult - Lower the result values of a call into the
2558 /// appropriate copies out of appropriate physical registers.
2560 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2561 CallingConv::ID CallConv, bool IsVarArg,
2562 const SmallVectorImpl<ISD::InputArg> &Ins,
2563 SDLoc DL, SelectionDAG &DAG,
2564 SmallVectorImpl<SDValue> &InVals,
2565 const SDNode *CallNode,
2566 const Type *RetTy) const {
2567 // Assign locations to each value returned by this call.
2568 SmallVector<CCValAssign, 16> RVLocs;
2569 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2570 getTargetMachine(), RVLocs, *DAG.getContext());
2571 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2573 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2576 // Copy all of the result registers out of their specified physreg.
2577 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2578 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2579 RVLocs[i].getLocVT(), InFlag);
2580 Chain = Val.getValue(1);
2581 InFlag = Val.getValue(2);
2583 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2584 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2586 InVals.push_back(Val);
2592 //===----------------------------------------------------------------------===//
2593 // Formal Arguments Calling Convention Implementation
2594 //===----------------------------------------------------------------------===//
2595 /// LowerFormalArguments - transform physical registers into virtual registers
2596 /// and generate load operations for arguments places on the stack.
2598 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2599 CallingConv::ID CallConv,
2601 const SmallVectorImpl<ISD::InputArg> &Ins,
2602 SDLoc DL, SelectionDAG &DAG,
2603 SmallVectorImpl<SDValue> &InVals)
2605 MachineFunction &MF = DAG.getMachineFunction();
2606 MachineFrameInfo *MFI = MF.getFrameInfo();
2607 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2609 MipsFI->setVarArgsFrameIndex(0);
2611 // Used with vargs to acumulate store chains.
2612 std::vector<SDValue> OutChains;
2614 // Assign locations to all of the incoming arguments.
2615 SmallVector<CCValAssign, 16> ArgLocs;
2616 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2617 getTargetMachine(), ArgLocs, *DAG.getContext());
2618 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2619 Function::const_arg_iterator FuncArg =
2620 DAG.getMachineFunction().getFunction()->arg_begin();
2621 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2623 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2624 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2625 MipsCCInfo.hasByValArg());
2627 unsigned CurArgIdx = 0;
2628 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2630 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2631 CCValAssign &VA = ArgLocs[i];
2632 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2633 CurArgIdx = Ins[i].OrigArgIndex;
2634 EVT ValVT = VA.getValVT();
2635 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2636 bool IsRegLoc = VA.isRegLoc();
2638 if (Flags.isByVal()) {
2639 assert(Flags.getByValSize() &&
2640 "ByVal args of size 0 should have been ignored by front-end.");
2641 assert(ByValArg != MipsCCInfo.byval_end());
2642 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2643 MipsCCInfo, *ByValArg);
2648 // Arguments stored on registers
2650 MVT RegVT = VA.getLocVT();
2651 unsigned ArgReg = VA.getLocReg();
2652 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2654 // Transform the arguments stored on
2655 // physical registers into virtual ones
2656 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2657 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2659 // If this is an 8 or 16-bit value, it has been passed promoted
2660 // to 32 bits. Insert an assert[sz]ext to capture this, then
2661 // truncate to the right size.
2662 if (VA.getLocInfo() != CCValAssign::Full) {
2663 unsigned Opcode = 0;
2664 if (VA.getLocInfo() == CCValAssign::SExt)
2665 Opcode = ISD::AssertSext;
2666 else if (VA.getLocInfo() == CCValAssign::ZExt)
2667 Opcode = ISD::AssertZext;
2669 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2670 DAG.getValueType(ValVT));
2671 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2674 // Handle floating point arguments passed in integer registers and
2675 // long double arguments passed in floating point registers.
2676 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2677 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2678 (RegVT == MVT::f64 && ValVT == MVT::i64))
2679 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2680 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2681 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2682 getNextIntArgReg(ArgReg), RC);
2683 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2684 if (!Subtarget->isLittle())
2685 std::swap(ArgValue, ArgValue2);
2686 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2687 ArgValue, ArgValue2);
2690 InVals.push_back(ArgValue);
2691 } else { // VA.isRegLoc()
2694 assert(VA.isMemLoc());
2696 // The stack pointer offset is relative to the caller stack frame.
2697 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2698 VA.getLocMemOffset(), true);
2700 // Create load nodes to retrieve arguments from the stack
2701 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2702 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2703 MachinePointerInfo::getFixedStack(FI),
2704 false, false, false, 0);
2705 InVals.push_back(Load);
2706 OutChains.push_back(Load.getValue(1));
2710 // The mips ABIs for returning structs by value requires that we copy
2711 // the sret argument into $v0 for the return. Save the argument into
2712 // a virtual register so that we can access it from the return points.
2713 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2714 unsigned Reg = MipsFI->getSRetReturnReg();
2716 Reg = MF.getRegInfo().
2717 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2718 MipsFI->setSRetReturnReg(Reg);
2720 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2721 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2725 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2727 // All stores are grouped in one node to allow the matching between
2728 // the size of Ins and InVals. This only happens when on varg functions
2729 if (!OutChains.empty()) {
2730 OutChains.push_back(Chain);
2731 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2732 &OutChains[0], OutChains.size());
2738 //===----------------------------------------------------------------------===//
2739 // Return Value Calling Convention Implementation
2740 //===----------------------------------------------------------------------===//
2743 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2744 MachineFunction &MF, bool IsVarArg,
2745 const SmallVectorImpl<ISD::OutputArg> &Outs,
2746 LLVMContext &Context) const {
2747 SmallVector<CCValAssign, 16> RVLocs;
2748 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2750 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2754 MipsTargetLowering::LowerReturn(SDValue Chain,
2755 CallingConv::ID CallConv, bool IsVarArg,
2756 const SmallVectorImpl<ISD::OutputArg> &Outs,
2757 const SmallVectorImpl<SDValue> &OutVals,
2758 SDLoc DL, SelectionDAG &DAG) const {
2759 // CCValAssign - represent the assignment of
2760 // the return value to a location
2761 SmallVector<CCValAssign, 16> RVLocs;
2762 MachineFunction &MF = DAG.getMachineFunction();
2764 // CCState - Info about the registers and stack slot.
2765 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2767 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2769 // Analyze return values.
2770 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2771 MF.getFunction()->getReturnType());
2774 SmallVector<SDValue, 4> RetOps(1, Chain);
2776 // Copy the result values into the output registers.
2777 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2778 SDValue Val = OutVals[i];
2779 CCValAssign &VA = RVLocs[i];
2780 assert(VA.isRegLoc() && "Can only return in registers!");
2782 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2783 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2785 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2787 // Guarantee that all emitted copies are stuck together with flags.
2788 Flag = Chain.getValue(1);
2789 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2792 // The mips ABIs for returning structs by value requires that we copy
2793 // the sret argument into $v0 for the return. We saved the argument into
2794 // a virtual register in the entry block, so now we copy the value out
2796 if (MF.getFunction()->hasStructRetAttr()) {
2797 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2798 unsigned Reg = MipsFI->getSRetReturnReg();
2801 llvm_unreachable("sret virtual register not created in the entry block");
2802 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2803 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2805 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2806 Flag = Chain.getValue(1);
2807 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2810 RetOps[0] = Chain; // Update chain.
2812 // Add the flag if we have it.
2814 RetOps.push_back(Flag);
2816 // Return on Mips is always a "jr $ra"
2817 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2820 //===----------------------------------------------------------------------===//
2821 // Mips Inline Assembly Support
2822 //===----------------------------------------------------------------------===//
2824 /// getConstraintType - Given a constraint letter, return the type of
2825 /// constraint it is for this target.
2826 MipsTargetLowering::ConstraintType MipsTargetLowering::
2827 getConstraintType(const std::string &Constraint) const
2829 // Mips specific constraints
2830 // GCC config/mips/constraints.md
2832 // 'd' : An address register. Equivalent to r
2833 // unless generating MIPS16 code.
2834 // 'y' : Equivalent to r; retained for
2835 // backwards compatibility.
2836 // 'c' : A register suitable for use in an indirect
2837 // jump. This will always be $25 for -mabicalls.
2838 // 'l' : The lo register. 1 word storage.
2839 // 'x' : The hilo register pair. Double word storage.
2840 if (Constraint.size() == 1) {
2841 switch (Constraint[0]) {
2849 return C_RegisterClass;
2854 return TargetLowering::getConstraintType(Constraint);
2857 /// Examine constraint type and operand type and determine a weight value.
2858 /// This object must already have been set up with the operand type
2859 /// and the current alternative constraint selected.
2860 TargetLowering::ConstraintWeight
2861 MipsTargetLowering::getSingleConstraintMatchWeight(
2862 AsmOperandInfo &info, const char *constraint) const {
2863 ConstraintWeight weight = CW_Invalid;
2864 Value *CallOperandVal = info.CallOperandVal;
2865 // If we don't have a value, we can't do a match,
2866 // but allow it at the lowest weight.
2867 if (CallOperandVal == NULL)
2869 Type *type = CallOperandVal->getType();
2870 // Look at the constraint type.
2871 switch (*constraint) {
2873 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2877 if (type->isIntegerTy())
2878 weight = CW_Register;
2880 case 'f': // FPU or MSA register
2881 if (Subtarget->hasMSA() && type->isVectorTy() &&
2882 cast<VectorType>(type)->getBitWidth() == 128)
2883 weight = CW_Register;
2884 else if (type->isFloatTy())
2885 weight = CW_Register;
2887 case 'c': // $25 for indirect jumps
2888 case 'l': // lo register
2889 case 'x': // hilo register pair
2890 if (type->isIntegerTy())
2891 weight = CW_SpecificReg;
2893 case 'I': // signed 16 bit immediate
2894 case 'J': // integer zero
2895 case 'K': // unsigned 16 bit immediate
2896 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2897 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2898 case 'O': // signed 15 bit immediate (+- 16383)
2899 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2900 if (isa<ConstantInt>(CallOperandVal))
2901 weight = CW_Constant;
2910 /// This is a helper function to parse a physical register string and split it
2911 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2912 /// that is returned indicates whether parsing was successful. The second flag
2913 /// is true if the numeric part exists.
2914 static std::pair<bool, bool>
2915 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2916 unsigned long long &Reg) {
2917 if (C.front() != '{' || C.back() != '}')
2918 return std::make_pair(false, false);
2920 // Search for the first numeric character.
2921 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2922 I = std::find_if(B, E, std::ptr_fun(isdigit));
2924 Prefix.assign(B, I - B);
2926 // The second flag is set to false if no numeric characters were found.
2928 return std::make_pair(true, false);
2930 // Parse the numeric characters.
2931 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2935 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2936 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2937 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2938 const TargetRegisterClass *RC;
2940 unsigned long long Reg;
2942 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2945 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2947 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2948 // No numeric characters follow "hi" or "lo".
2950 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2952 RC = TRI->getRegClass(Prefix == "hi" ?
2953 Mips::HI32RegClassID : Mips::LO32RegClassID);
2954 return std::make_pair(*(RC->begin()), RC);
2955 } else if (Prefix.compare(0, 4, "$msa") == 0) {
2956 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
2958 // No numeric characters follow the name.
2960 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2962 Reg = StringSwitch<unsigned long long>(Prefix)
2963 .Case("$msair", Mips::MSAIR)
2964 .Case("$msacsr", Mips::MSACSR)
2965 .Case("$msaaccess", Mips::MSAAccess)
2966 .Case("$msasave", Mips::MSASave)
2967 .Case("$msamodify", Mips::MSAModify)
2968 .Case("$msarequest", Mips::MSARequest)
2969 .Case("$msamap", Mips::MSAMap)
2970 .Case("$msaunmap", Mips::MSAUnmap)
2974 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2976 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
2977 return std::make_pair(Reg, RC);
2981 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2983 if (Prefix == "$f") { // Parse $f0-$f31.
2984 // If the size of FP registers is 64-bit or Reg is an even number, select
2985 // the 64-bit register class. Otherwise, select the 32-bit register class.
2986 if (VT == MVT::Other)
2987 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2989 RC = getRegClassFor(VT);
2991 if (RC == &Mips::AFGR64RegClass) {
2992 assert(Reg % 2 == 0);
2995 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
2996 RC = TRI->getRegClass(Mips::FCCRegClassID);
2997 else if (Prefix == "$w") { // Parse $w0-$w31.
2998 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
2999 } else { // Parse $0-$31.
3000 assert(Prefix == "$");
3001 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3004 assert(Reg < RC->getNumRegs());
3005 return std::make_pair(*(RC->begin() + Reg), RC);
3008 /// Given a register class constraint, like 'r', if this corresponds directly
3009 /// to an LLVM register class, return a register of 0 and the register class
3011 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3012 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3014 if (Constraint.size() == 1) {
3015 switch (Constraint[0]) {
3016 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3017 case 'y': // Same as 'r'. Exists for compatibility.
3019 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3020 if (Subtarget->inMips16Mode())
3021 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3022 return std::make_pair(0U, &Mips::GPR32RegClass);
3024 if (VT == MVT::i64 && !HasMips64)
3025 return std::make_pair(0U, &Mips::GPR32RegClass);
3026 if (VT == MVT::i64 && HasMips64)
3027 return std::make_pair(0U, &Mips::GPR64RegClass);
3028 // This will generate an error message
3029 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3030 case 'f': // FPU or MSA register
3031 if (VT == MVT::v16i8)
3032 return std::make_pair(0U, &Mips::MSA128BRegClass);
3033 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3034 return std::make_pair(0U, &Mips::MSA128HRegClass);
3035 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3036 return std::make_pair(0U, &Mips::MSA128WRegClass);
3037 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3038 return std::make_pair(0U, &Mips::MSA128DRegClass);
3039 else if (VT == MVT::f32)
3040 return std::make_pair(0U, &Mips::FGR32RegClass);
3041 else if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3042 if (Subtarget->isFP64bit())
3043 return std::make_pair(0U, &Mips::FGR64RegClass);
3044 return std::make_pair(0U, &Mips::AFGR64RegClass);
3047 case 'c': // register suitable for indirect jump
3049 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3050 assert(VT == MVT::i64 && "Unexpected type.");
3051 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3052 case 'l': // register suitable for indirect jump
3054 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3055 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3056 case 'x': // register suitable for indirect jump
3057 // Fixme: Not triggering the use of both hi and low
3058 // This will generate an error message
3059 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3063 std::pair<unsigned, const TargetRegisterClass *> R;
3064 R = parseRegForInlineAsmConstraint(Constraint, VT);
3069 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3072 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3073 /// vector. If it is invalid, don't add anything to Ops.
3074 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3075 std::string &Constraint,
3076 std::vector<SDValue>&Ops,
3077 SelectionDAG &DAG) const {
3078 SDValue Result(0, 0);
3080 // Only support length 1 constraints for now.
3081 if (Constraint.length() > 1) return;
3083 char ConstraintLetter = Constraint[0];
3084 switch (ConstraintLetter) {
3085 default: break; // This will fall through to the generic implementation
3086 case 'I': // Signed 16 bit constant
3087 // If this fails, the parent routine will give an error
3088 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3089 EVT Type = Op.getValueType();
3090 int64_t Val = C->getSExtValue();
3091 if (isInt<16>(Val)) {
3092 Result = DAG.getTargetConstant(Val, Type);
3097 case 'J': // integer zero
3098 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3099 EVT Type = Op.getValueType();
3100 int64_t Val = C->getZExtValue();
3102 Result = DAG.getTargetConstant(0, Type);
3107 case 'K': // unsigned 16 bit immediate
3108 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3109 EVT Type = Op.getValueType();
3110 uint64_t Val = (uint64_t)C->getZExtValue();
3111 if (isUInt<16>(Val)) {
3112 Result = DAG.getTargetConstant(Val, Type);
3117 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3118 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3119 EVT Type = Op.getValueType();
3120 int64_t Val = C->getSExtValue();
3121 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3122 Result = DAG.getTargetConstant(Val, Type);
3127 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3128 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3129 EVT Type = Op.getValueType();
3130 int64_t Val = C->getSExtValue();
3131 if ((Val >= -65535) && (Val <= -1)) {
3132 Result = DAG.getTargetConstant(Val, Type);
3137 case 'O': // signed 15 bit immediate
3138 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3139 EVT Type = Op.getValueType();
3140 int64_t Val = C->getSExtValue();
3141 if ((isInt<15>(Val))) {
3142 Result = DAG.getTargetConstant(Val, Type);
3147 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3148 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3149 EVT Type = Op.getValueType();
3150 int64_t Val = C->getSExtValue();
3151 if ((Val <= 65535) && (Val >= 1)) {
3152 Result = DAG.getTargetConstant(Val, Type);
3159 if (Result.getNode()) {
3160 Ops.push_back(Result);
3164 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3167 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3169 // No global is ever allowed as a base.
3174 case 0: // "r+i" or just "i", depending on HasBaseReg.
3177 if (!AM.HasBaseReg) // allow "r+i".
3179 return false; // disallow "r+r" or "r+r+i".
3188 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3189 // The Mips target isn't yet aware of offsets.
3193 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3195 bool IsMemset, bool ZeroMemset,
3197 MachineFunction &MF) const {
3198 if (Subtarget->hasMips64())
3204 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3205 if (VT != MVT::f32 && VT != MVT::f64)
3207 if (Imm.isNegZero())
3209 return Imm.isZero();
3212 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3214 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3216 return TargetLowering::getJumpTableEncoding();
3219 /// This function returns true if CallSym is a long double emulation routine.
3220 static bool isF128SoftLibCall(const char *CallSym) {
3221 const char *const LibCalls[] =
3222 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3223 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3224 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3225 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3226 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3227 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3228 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3229 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3232 const char *const *End = LibCalls + array_lengthof(LibCalls);
3234 // Check that LibCalls is sorted alphabetically.
3235 MipsTargetLowering::LTStr Comp;
3238 for (const char *const *I = LibCalls; I < End - 1; ++I)
3239 assert(Comp(*I, *(I + 1)));
3242 return std::binary_search(LibCalls, End, CallSym, Comp);
3245 /// This function returns true if Ty is fp128 or i128 which was originally a
3247 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3248 if (Ty->isFP128Ty())
3251 const ExternalSymbolSDNode *ES =
3252 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3254 // If the Ty is i128 and the function being called is a long double emulation
3255 // routine, then the original type is f128.
3256 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3259 MipsTargetLowering::MipsCC::SpecialCallingConvType
3260 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3261 MipsCC::SpecialCallingConvType SpecialCallingConv =
3262 MipsCC::NoSpecialCallingConv;;
3263 if (Subtarget->inMips16HardFloat()) {
3264 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3265 llvm::StringRef Sym = G->getGlobal()->getName();
3266 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3267 if (F && F->hasFnAttribute("__Mips16RetHelper")) {
3268 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3272 return SpecialCallingConv;
3275 MipsTargetLowering::MipsCC::MipsCC(
3276 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3277 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3278 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3279 SpecialCallingConv(SpecialCallingConv_){
3280 // Pre-allocate reserved argument area.
3281 CCInfo.AllocateStack(reservedArgArea(), 1);
3285 void MipsTargetLowering::MipsCC::
3286 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3287 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3288 std::vector<ArgListEntry> &FuncArgs) {
3289 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3290 "CallingConv::Fast shouldn't be used for vararg functions.");
3292 unsigned NumOpnds = Args.size();
3293 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3295 for (unsigned I = 0; I != NumOpnds; ++I) {
3296 MVT ArgVT = Args[I].VT;
3297 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3300 if (ArgFlags.isByVal()) {
3301 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3305 if (IsVarArg && !Args[I].IsFixed)
3306 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3308 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3310 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3315 dbgs() << "Call operand #" << I << " has unhandled type "
3316 << EVT(ArgVT).getEVTString();
3318 llvm_unreachable(0);
3323 void MipsTargetLowering::MipsCC::
3324 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3325 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3326 unsigned NumArgs = Args.size();
3327 llvm::CCAssignFn *FixedFn = fixedArgFn();
3328 unsigned CurArgIdx = 0;
3330 for (unsigned I = 0; I != NumArgs; ++I) {
3331 MVT ArgVT = Args[I].VT;
3332 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3333 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3334 CurArgIdx = Args[I].OrigArgIndex;
3336 if (ArgFlags.isByVal()) {
3337 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3341 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3343 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3347 dbgs() << "Formal Arg #" << I << " has unhandled type "
3348 << EVT(ArgVT).getEVTString();
3350 llvm_unreachable(0);
3354 template<typename Ty>
3355 void MipsTargetLowering::MipsCC::
3356 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3357 const SDNode *CallNode, const Type *RetTy) const {
3360 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3361 Fn = RetCC_F128Soft;
3365 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3366 MVT VT = RetVals[I].VT;
3367 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3368 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3370 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3372 dbgs() << "Call result #" << I << " has unhandled type "
3373 << EVT(VT).getEVTString() << '\n';
3375 llvm_unreachable(0);
3380 void MipsTargetLowering::MipsCC::
3381 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3382 const SDNode *CallNode, const Type *RetTy) const {
3383 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3386 void MipsTargetLowering::MipsCC::
3387 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3388 const Type *RetTy) const {
3389 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3392 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3394 CCValAssign::LocInfo LocInfo,
3395 ISD::ArgFlagsTy ArgFlags) {
3396 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3398 struct ByValArgInfo ByVal;
3399 unsigned RegSize = regSize();
3400 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3401 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3404 if (useRegsForByval())
3405 allocateRegs(ByVal, ByValSize, Align);
3407 // Allocate space on caller's stack.
3408 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3410 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3412 ByValArgs.push_back(ByVal);
3415 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3416 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3419 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3420 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3423 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3424 return IsO32 ? O32IntRegs : Mips64IntRegs;
3427 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3428 if (CallConv == CallingConv::Fast)
3429 return CC_Mips_FastCC;
3431 if (SpecialCallingConv == Mips16RetHelperConv)
3432 return CC_Mips16RetHelper;
3433 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3436 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3437 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3440 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3441 return IsO32 ? O32IntRegs : Mips64DPRegs;
3444 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3447 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3448 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3449 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3450 "Byval argument's size and alignment should be a multiple of"
3453 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3455 // If Align > RegSize, the first arg register must be even.
3456 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3457 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3461 // Mark the registers allocated.
3462 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3463 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3464 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3467 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3468 const SDNode *CallNode,
3469 bool IsSoftFloat) const {
3470 if (IsSoftFloat || IsO32)
3473 // Check if the original type was fp128.
3474 if (originalTypeIsF128(OrigTy, CallNode)) {
3475 assert(VT == MVT::i64);
3482 void MipsTargetLowering::
3483 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3484 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3485 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3486 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3487 MachineFunction &MF = DAG.getMachineFunction();
3488 MachineFrameInfo *MFI = MF.getFrameInfo();
3489 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3490 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3494 FrameObjOffset = (int)CC.reservedArgArea() -
3495 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3497 FrameObjOffset = ByVal.Address;
3499 // Create frame object.
3500 EVT PtrTy = getPointerTy();
3501 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3502 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3503 InVals.push_back(FIN);
3508 // Copy arg registers.
3509 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3510 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3512 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3513 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3514 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3515 unsigned Offset = I * CC.regSize();
3516 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3517 DAG.getConstant(Offset, PtrTy));
3518 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3519 StorePtr, MachinePointerInfo(FuncArg, Offset),
3521 OutChains.push_back(Store);
3525 // Copy byVal arg to registers and stack.
3526 void MipsTargetLowering::
3527 passByValArg(SDValue Chain, SDLoc DL,
3528 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3529 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3530 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3531 const MipsCC &CC, const ByValArgInfo &ByVal,
3532 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3533 unsigned ByValSize = Flags.getByValSize();
3534 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3535 unsigned RegSize = CC.regSize();
3536 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3537 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3539 if (ByVal.NumRegs) {
3540 const uint16_t *ArgRegs = CC.intArgRegs();
3541 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3544 // Copy words to registers.
3545 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3546 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3547 DAG.getConstant(Offset, PtrTy));
3548 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3549 MachinePointerInfo(), false, false, false,
3551 MemOpChains.push_back(LoadVal.getValue(1));
3552 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3553 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3556 // Return if the struct has been fully copied.
3557 if (ByValSize == Offset)
3560 // Copy the remainder of the byval argument with sub-word loads and shifts.
3561 if (LeftoverBytes) {
3562 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3563 "Size of the remainder should be smaller than RegSize.");
3566 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3567 Offset < ByValSize; LoadSize /= 2) {
3568 unsigned RemSize = ByValSize - Offset;
3570 if (RemSize < LoadSize)
3574 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3575 DAG.getConstant(Offset, PtrTy));
3577 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3578 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3579 false, false, Alignment);
3580 MemOpChains.push_back(LoadVal.getValue(1));
3582 // Shift the loaded value.
3586 Shamt = TotalSizeLoaded;
3588 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3590 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3591 DAG.getConstant(Shamt, MVT::i32));
3594 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3599 TotalSizeLoaded += LoadSize;
3600 Alignment = std::min(Alignment, LoadSize);
3603 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3604 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3609 // Copy remainder of byval arg to it with memcpy.
3610 unsigned MemCpySize = ByValSize - Offset;
3611 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3612 DAG.getConstant(Offset, PtrTy));
3613 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3614 DAG.getIntPtrConstant(ByVal.Address));
3615 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3616 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3617 MachinePointerInfo(0), MachinePointerInfo(0));
3618 MemOpChains.push_back(Chain);
3621 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3622 const MipsCC &CC, SDValue Chain,
3623 SDLoc DL, SelectionDAG &DAG) const {
3624 unsigned NumRegs = CC.numIntArgRegs();
3625 const uint16_t *ArgRegs = CC.intArgRegs();
3626 const CCState &CCInfo = CC.getCCInfo();
3627 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3628 unsigned RegSize = CC.regSize();
3629 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3630 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3631 MachineFunction &MF = DAG.getMachineFunction();
3632 MachineFrameInfo *MFI = MF.getFrameInfo();
3633 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3635 // Offset of the first variable argument from stack pointer.
3639 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3641 VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3643 // Record the frame index of the first variable argument
3644 // which is a value necessary to VASTART.
3645 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3646 MipsFI->setVarArgsFrameIndex(FI);
3648 // Copy the integer registers that have not been used for argument passing
3649 // to the argument register save area. For O32, the save area is allocated
3650 // in the caller's stack frame, while for N32/64, it is allocated in the
3651 // callee's stack frame.
3652 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3653 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3654 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3655 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3656 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3657 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3658 MachinePointerInfo(), false, false, 0);
3659 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3660 OutChains.push_back(Store);