1 //===-- MipsISelLowering.cpp - Mips DAG Lowering Implementation -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines the interfaces that Mips uses to lower LLVM code into a
13 //===----------------------------------------------------------------------===//
14 #define DEBUG_TYPE "mips-lower"
15 #include "MipsISelLowering.h"
16 #include "InstPrinter/MipsInstPrinter.h"
17 #include "MCTargetDesc/MipsBaseInfo.h"
18 #include "MipsMachineFunction.h"
19 #include "MipsSubtarget.h"
20 #include "MipsTargetMachine.h"
21 #include "MipsTargetObjectFile.h"
22 #include "llvm/ADT/Statistic.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/CodeGen/CallingConvLower.h"
25 #include "llvm/CodeGen/MachineFrameInfo.h"
26 #include "llvm/CodeGen/MachineFunction.h"
27 #include "llvm/CodeGen/MachineInstrBuilder.h"
28 #include "llvm/CodeGen/MachineRegisterInfo.h"
29 #include "llvm/CodeGen/SelectionDAGISel.h"
30 #include "llvm/CodeGen/ValueTypes.h"
31 #include "llvm/IR/CallingConv.h"
32 #include "llvm/IR/DerivedTypes.h"
33 #include "llvm/IR/GlobalVariable.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
42 STATISTIC(NumTailCalls, "Number of tail calls");
45 LargeGOT("mxgot", cl::Hidden,
46 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
49 NoZeroDivCheck("mno-check-zero-division", cl::Hidden,
50 cl::desc("MIPS: Don't trap on integer division by zero."),
53 static const uint16_t O32IntRegs[4] = {
54 Mips::A0, Mips::A1, Mips::A2, Mips::A3
57 static const uint16_t Mips64IntRegs[8] = {
58 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
59 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
62 static const uint16_t Mips64DPRegs[8] = {
63 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
64 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
67 // If I is a shifted mask, set the size (Size) and the first bit of the
68 // mask (Pos), and return true.
69 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
70 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
71 if (!isShiftedMask_64(I))
74 Size = CountPopulation_64(I);
75 Pos = countTrailingZeros(I);
79 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
80 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
81 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
84 SDValue MipsTargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
86 unsigned Flag) const {
87 return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty, 0, Flag);
90 SDValue MipsTargetLowering::getTargetNode(ExternalSymbolSDNode *N, EVT Ty,
92 unsigned Flag) const {
93 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
96 SDValue MipsTargetLowering::getTargetNode(BlockAddressSDNode *N, EVT Ty,
98 unsigned Flag) const {
99 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
102 SDValue MipsTargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
104 unsigned Flag) const {
105 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
108 SDValue MipsTargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
110 unsigned Flag) const {
111 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
112 N->getOffset(), Flag);
115 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
117 case MipsISD::JmpLink: return "MipsISD::JmpLink";
118 case MipsISD::TailCall: return "MipsISD::TailCall";
119 case MipsISD::Hi: return "MipsISD::Hi";
120 case MipsISD::Lo: return "MipsISD::Lo";
121 case MipsISD::GPRel: return "MipsISD::GPRel";
122 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
123 case MipsISD::Ret: return "MipsISD::Ret";
124 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
125 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
126 case MipsISD::FPCmp: return "MipsISD::FPCmp";
127 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
128 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
129 case MipsISD::TruncIntFP: return "MipsISD::TruncIntFP";
130 case MipsISD::MFHI: return "MipsISD::MFHI";
131 case MipsISD::MFLO: return "MipsISD::MFLO";
132 case MipsISD::MTLOHI: return "MipsISD::MTLOHI";
133 case MipsISD::Mult: return "MipsISD::Mult";
134 case MipsISD::Multu: return "MipsISD::Multu";
135 case MipsISD::MAdd: return "MipsISD::MAdd";
136 case MipsISD::MAddu: return "MipsISD::MAddu";
137 case MipsISD::MSub: return "MipsISD::MSub";
138 case MipsISD::MSubu: return "MipsISD::MSubu";
139 case MipsISD::DivRem: return "MipsISD::DivRem";
140 case MipsISD::DivRemU: return "MipsISD::DivRemU";
141 case MipsISD::DivRem16: return "MipsISD::DivRem16";
142 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
143 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
144 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
145 case MipsISD::Wrapper: return "MipsISD::Wrapper";
146 case MipsISD::Sync: return "MipsISD::Sync";
147 case MipsISD::Ext: return "MipsISD::Ext";
148 case MipsISD::Ins: return "MipsISD::Ins";
149 case MipsISD::LWL: return "MipsISD::LWL";
150 case MipsISD::LWR: return "MipsISD::LWR";
151 case MipsISD::SWL: return "MipsISD::SWL";
152 case MipsISD::SWR: return "MipsISD::SWR";
153 case MipsISD::LDL: return "MipsISD::LDL";
154 case MipsISD::LDR: return "MipsISD::LDR";
155 case MipsISD::SDL: return "MipsISD::SDL";
156 case MipsISD::SDR: return "MipsISD::SDR";
157 case MipsISD::EXTP: return "MipsISD::EXTP";
158 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
159 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
160 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
161 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
162 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
163 case MipsISD::SHILO: return "MipsISD::SHILO";
164 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
165 case MipsISD::MULT: return "MipsISD::MULT";
166 case MipsISD::MULTU: return "MipsISD::MULTU";
167 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
168 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
169 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
170 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
171 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
172 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
173 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
174 case MipsISD::SETCC_DSP: return "MipsISD::SETCC_DSP";
175 case MipsISD::SELECT_CC_DSP: return "MipsISD::SELECT_CC_DSP";
176 case MipsISD::VALL_ZERO: return "MipsISD::VALL_ZERO";
177 case MipsISD::VANY_ZERO: return "MipsISD::VANY_ZERO";
178 case MipsISD::VALL_NONZERO: return "MipsISD::VALL_NONZERO";
179 case MipsISD::VANY_NONZERO: return "MipsISD::VANY_NONZERO";
180 case MipsISD::VCEQ: return "MipsISD::VCEQ";
181 case MipsISD::VCLE_S: return "MipsISD::VCLE_S";
182 case MipsISD::VCLE_U: return "MipsISD::VCLE_U";
183 case MipsISD::VCLT_S: return "MipsISD::VCLT_S";
184 case MipsISD::VCLT_U: return "MipsISD::VCLT_U";
185 case MipsISD::VSMAX: return "MipsISD::VSMAX";
186 case MipsISD::VSMIN: return "MipsISD::VSMIN";
187 case MipsISD::VUMAX: return "MipsISD::VUMAX";
188 case MipsISD::VUMIN: return "MipsISD::VUMIN";
189 case MipsISD::VEXTRACT_SEXT_ELT: return "MipsISD::VEXTRACT_SEXT_ELT";
190 case MipsISD::VEXTRACT_ZEXT_ELT: return "MipsISD::VEXTRACT_ZEXT_ELT";
191 case MipsISD::VNOR: return "MipsISD::VNOR";
192 case MipsISD::VSHF: return "MipsISD::VSHF";
193 case MipsISD::SHF: return "MipsISD::SHF";
194 case MipsISD::ILVEV: return "MipsISD::ILVEV";
195 case MipsISD::ILVOD: return "MipsISD::ILVOD";
196 case MipsISD::ILVL: return "MipsISD::ILVL";
197 case MipsISD::ILVR: return "MipsISD::ILVR";
198 case MipsISD::PCKEV: return "MipsISD::PCKEV";
199 case MipsISD::PCKOD: return "MipsISD::PCKOD";
200 default: return NULL;
205 MipsTargetLowering(MipsTargetMachine &TM)
206 : TargetLowering(TM, new MipsTargetObjectFile()),
207 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
208 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
209 IsO32(Subtarget->isABI_O32()) {
210 // Mips does not have i1 type, so use i32 for
211 // setcc operations results (slt, sgt, ...).
212 setBooleanContents(ZeroOrOneBooleanContent);
213 setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
215 // Load extented operations for i1 types must be promoted
216 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
217 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
218 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
220 // MIPS doesn't have extending float->double load/store
221 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
222 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
224 // Used by legalize types to correctly generate the setcc result.
225 // Without this, every float setcc comes with a AND/OR with the result,
226 // we don't want this, since the fpcmp result goes to a flag register,
227 // which is used implicitly by brcond and select operations.
228 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
230 // Mips Custom Operations
231 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
232 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
233 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
234 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
235 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
236 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
237 setOperationAction(ISD::SELECT, MVT::f32, Custom);
238 setOperationAction(ISD::SELECT, MVT::f64, Custom);
239 setOperationAction(ISD::SELECT, MVT::i32, Custom);
240 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
241 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
242 setOperationAction(ISD::SETCC, MVT::f32, Custom);
243 setOperationAction(ISD::SETCC, MVT::f64, Custom);
244 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
245 setOperationAction(ISD::VASTART, MVT::Other, Custom);
246 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
247 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
248 setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
250 if (!TM.Options.NoNaNsFPMath) {
251 setOperationAction(ISD::FABS, MVT::f32, Custom);
252 setOperationAction(ISD::FABS, MVT::f64, Custom);
256 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
257 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
258 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
259 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
260 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
261 setOperationAction(ISD::SELECT, MVT::i64, Custom);
262 setOperationAction(ISD::LOAD, MVT::i64, Custom);
263 setOperationAction(ISD::STORE, MVT::i64, Custom);
264 setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
268 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
269 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
270 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
273 setOperationAction(ISD::ADD, MVT::i32, Custom);
275 setOperationAction(ISD::ADD, MVT::i64, Custom);
277 setOperationAction(ISD::SDIV, MVT::i32, Expand);
278 setOperationAction(ISD::SREM, MVT::i32, Expand);
279 setOperationAction(ISD::UDIV, MVT::i32, Expand);
280 setOperationAction(ISD::UREM, MVT::i32, Expand);
281 setOperationAction(ISD::SDIV, MVT::i64, Expand);
282 setOperationAction(ISD::SREM, MVT::i64, Expand);
283 setOperationAction(ISD::UDIV, MVT::i64, Expand);
284 setOperationAction(ISD::UREM, MVT::i64, Expand);
286 // Operations not directly supported by Mips.
287 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
288 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
289 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
290 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
291 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
292 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
293 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
294 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
295 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
296 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
297 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
298 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
299 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
300 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
301 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
302 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
303 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
304 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
305 setOperationAction(ISD::ROTL, MVT::i32, Expand);
306 setOperationAction(ISD::ROTL, MVT::i64, Expand);
307 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
308 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
310 if (!Subtarget->hasMips32r2())
311 setOperationAction(ISD::ROTR, MVT::i32, Expand);
313 if (!Subtarget->hasMips64r2())
314 setOperationAction(ISD::ROTR, MVT::i64, Expand);
316 setOperationAction(ISD::FSIN, MVT::f32, Expand);
317 setOperationAction(ISD::FSIN, MVT::f64, Expand);
318 setOperationAction(ISD::FCOS, MVT::f32, Expand);
319 setOperationAction(ISD::FCOS, MVT::f64, Expand);
320 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
321 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
322 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
323 setOperationAction(ISD::FPOW, MVT::f32, Expand);
324 setOperationAction(ISD::FPOW, MVT::f64, Expand);
325 setOperationAction(ISD::FLOG, MVT::f32, Expand);
326 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
327 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
328 setOperationAction(ISD::FEXP, MVT::f32, Expand);
329 setOperationAction(ISD::FMA, MVT::f32, Expand);
330 setOperationAction(ISD::FMA, MVT::f64, Expand);
331 setOperationAction(ISD::FREM, MVT::f32, Expand);
332 setOperationAction(ISD::FREM, MVT::f64, Expand);
334 if (!TM.Options.NoNaNsFPMath) {
335 setOperationAction(ISD::FNEG, MVT::f32, Expand);
336 setOperationAction(ISD::FNEG, MVT::f64, Expand);
339 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
341 setOperationAction(ISD::VAARG, MVT::Other, Expand);
342 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
343 setOperationAction(ISD::VAEND, MVT::Other, Expand);
345 // Use the default for now
346 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
347 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
349 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
350 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
351 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
352 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
354 setInsertFencesForAtomic(true);
356 if (!Subtarget->hasSEInReg()) {
357 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
358 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
361 if (!Subtarget->hasBitCount()) {
362 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
363 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
366 if (!Subtarget->hasSwap()) {
367 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
368 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
372 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
373 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
374 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
375 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
378 setOperationAction(ISD::TRAP, MVT::Other, Legal);
380 setTargetDAGCombine(ISD::SDIVREM);
381 setTargetDAGCombine(ISD::UDIVREM);
382 setTargetDAGCombine(ISD::SELECT);
383 setTargetDAGCombine(ISD::AND);
384 setTargetDAGCombine(ISD::OR);
385 setTargetDAGCombine(ISD::ADD);
387 setMinFunctionAlignment(HasMips64 ? 3 : 2);
389 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
391 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
392 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
394 MaxStoresPerMemcpy = 16;
397 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
398 if (TM.getSubtargetImpl()->inMips16Mode())
399 return llvm::createMips16TargetLowering(TM);
401 return llvm::createMipsSETargetLowering(TM);
404 EVT MipsTargetLowering::getSetCCResultType(LLVMContext &, EVT VT) const {
407 return VT.changeVectorElementTypeToInteger();
410 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
411 TargetLowering::DAGCombinerInfo &DCI,
412 const MipsSubtarget *Subtarget) {
413 if (DCI.isBeforeLegalizeOps())
416 EVT Ty = N->getValueType(0);
417 unsigned LO = (Ty == MVT::i32) ? Mips::LO0 : Mips::LO0_64;
418 unsigned HI = (Ty == MVT::i32) ? Mips::HI0 : Mips::HI0_64;
419 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
423 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
424 N->getOperand(0), N->getOperand(1));
425 SDValue InChain = DAG.getEntryNode();
426 SDValue InGlue = DivRem;
429 if (N->hasAnyUseOfValue(0)) {
430 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
432 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
433 InChain = CopyFromLo.getValue(1);
434 InGlue = CopyFromLo.getValue(2);
438 if (N->hasAnyUseOfValue(1)) {
439 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
441 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
447 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
449 default: llvm_unreachable("Unknown fp condition code!");
451 case ISD::SETOEQ: return Mips::FCOND_OEQ;
452 case ISD::SETUNE: return Mips::FCOND_UNE;
454 case ISD::SETOLT: return Mips::FCOND_OLT;
456 case ISD::SETOGT: return Mips::FCOND_OGT;
458 case ISD::SETOLE: return Mips::FCOND_OLE;
460 case ISD::SETOGE: return Mips::FCOND_OGE;
461 case ISD::SETULT: return Mips::FCOND_ULT;
462 case ISD::SETULE: return Mips::FCOND_ULE;
463 case ISD::SETUGT: return Mips::FCOND_UGT;
464 case ISD::SETUGE: return Mips::FCOND_UGE;
465 case ISD::SETUO: return Mips::FCOND_UN;
466 case ISD::SETO: return Mips::FCOND_OR;
468 case ISD::SETONE: return Mips::FCOND_ONE;
469 case ISD::SETUEQ: return Mips::FCOND_UEQ;
474 /// This function returns true if the floating point conditional branches and
475 /// conditional moves which use condition code CC should be inverted.
476 static bool invertFPCondCodeUser(Mips::CondCode CC) {
477 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
480 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
481 "Illegal Condition Code");
486 // Creates and returns an FPCmp node from a setcc node.
487 // Returns Op if setcc is not a floating point comparison.
488 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
489 // must be a SETCC node
490 if (Op.getOpcode() != ISD::SETCC)
493 SDValue LHS = Op.getOperand(0);
495 if (!LHS.getValueType().isFloatingPoint())
498 SDValue RHS = Op.getOperand(1);
501 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
502 // node if necessary.
503 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
505 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
506 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
509 // Creates and returns a CMovFPT/F node.
510 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
511 SDValue False, SDLoc DL) {
512 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
513 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
514 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
516 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
517 True.getValueType(), True, FCC0, False, Cond);
520 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
521 TargetLowering::DAGCombinerInfo &DCI,
522 const MipsSubtarget *Subtarget) {
523 if (DCI.isBeforeLegalizeOps())
526 SDValue SetCC = N->getOperand(0);
528 if ((SetCC.getOpcode() != ISD::SETCC) ||
529 !SetCC.getOperand(0).getValueType().isInteger())
532 SDValue False = N->getOperand(2);
533 EVT FalseTy = False.getValueType();
535 if (!FalseTy.isInteger())
538 ConstantSDNode *FalseC = dyn_cast<ConstantSDNode>(False);
540 // If the RHS (False) is 0, we swap the order of the operands
541 // of ISD::SELECT (obviously also inverting the condition) so that we can
542 // take advantage of conditional moves using the $0 register.
544 // return (a != 0) ? x : 0;
552 if (!FalseC->getZExtValue()) {
553 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
554 SDValue True = N->getOperand(1);
556 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
557 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
559 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
562 // If both operands are integer constants there's a possibility that we
563 // can do some interesting optimizations.
564 SDValue True = N->getOperand(1);
565 ConstantSDNode *TrueC = dyn_cast<ConstantSDNode>(True);
567 if (!TrueC || !True.getValueType().isInteger())
570 // We'll also ignore MVT::i64 operands as this optimizations proves
571 // to be ineffective because of the required sign extensions as the result
572 // of a SETCC operator is always MVT::i32 for non-vector types.
573 if (True.getValueType() == MVT::i64)
576 int64_t Diff = TrueC->getSExtValue() - FalseC->getSExtValue();
578 // 1) (a < x) ? y : y-1
580 // addiu $reg2, $reg1, y-1
582 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, False);
584 // 2) (a < x) ? y-1 : y
586 // xor $reg1, $reg1, 1
587 // addiu $reg2, $reg1, y-1
589 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
590 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
591 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
592 return DAG.getNode(ISD::ADD, DL, SetCC.getValueType(), SetCC, True);
595 // Couldn't optimize.
599 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
600 TargetLowering::DAGCombinerInfo &DCI,
601 const MipsSubtarget *Subtarget) {
602 // Pattern match EXT.
603 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
604 // => ext $dst, $src, size, pos
605 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
608 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
609 unsigned ShiftRightOpc = ShiftRight.getOpcode();
611 // Op's first operand must be a shift right.
612 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
615 // The second operand of the shift must be an immediate.
617 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
620 uint64_t Pos = CN->getZExtValue();
621 uint64_t SMPos, SMSize;
623 // Op's second operand must be a shifted mask.
624 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
625 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
628 // Return if the shifted mask does not start at bit 0 or the sum of its size
629 // and Pos exceeds the word's size.
630 EVT ValTy = N->getValueType(0);
631 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
634 return DAG.getNode(MipsISD::Ext, SDLoc(N), ValTy,
635 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
636 DAG.getConstant(SMSize, MVT::i32));
639 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
640 TargetLowering::DAGCombinerInfo &DCI,
641 const MipsSubtarget *Subtarget) {
642 // Pattern match INS.
643 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
644 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
645 // => ins $dst, $src, size, pos, $src1
646 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasExtractInsert())
649 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
650 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
653 // See if Op's first operand matches (and $src1 , mask0).
654 if (And0.getOpcode() != ISD::AND)
657 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
658 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
661 // See if Op's second operand matches (and (shl $src, pos), mask1).
662 if (And1.getOpcode() != ISD::AND)
665 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
666 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
669 // The shift masks must have the same position and size.
670 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
673 SDValue Shl = And1.getOperand(0);
674 if (Shl.getOpcode() != ISD::SHL)
677 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
680 unsigned Shamt = CN->getZExtValue();
682 // Return if the shift amount and the first bit position of mask are not the
684 EVT ValTy = N->getValueType(0);
685 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
688 return DAG.getNode(MipsISD::Ins, SDLoc(N), ValTy, Shl.getOperand(0),
689 DAG.getConstant(SMPos0, MVT::i32),
690 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
693 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
694 TargetLowering::DAGCombinerInfo &DCI,
695 const MipsSubtarget *Subtarget) {
696 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
698 if (DCI.isBeforeLegalizeOps())
701 SDValue Add = N->getOperand(1);
703 if (Add.getOpcode() != ISD::ADD)
706 SDValue Lo = Add.getOperand(1);
708 if ((Lo.getOpcode() != MipsISD::Lo) ||
709 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
712 EVT ValTy = N->getValueType(0);
715 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
717 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
720 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
722 SelectionDAG &DAG = DCI.DAG;
723 unsigned Opc = N->getOpcode();
729 return performDivRemCombine(N, DAG, DCI, Subtarget);
731 return performSELECTCombine(N, DAG, DCI, Subtarget);
733 return performANDCombine(N, DAG, DCI, Subtarget);
735 return performORCombine(N, DAG, DCI, Subtarget);
737 return performADDCombine(N, DAG, DCI, Subtarget);
744 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
745 SmallVectorImpl<SDValue> &Results,
746 SelectionDAG &DAG) const {
747 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
749 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
750 Results.push_back(Res.getValue(I));
754 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
755 SmallVectorImpl<SDValue> &Results,
756 SelectionDAG &DAG) const {
757 return LowerOperationWrapper(N, Results, DAG);
760 SDValue MipsTargetLowering::
761 LowerOperation(SDValue Op, SelectionDAG &DAG) const
763 switch (Op.getOpcode())
765 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
766 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
767 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
768 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
769 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
770 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
771 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
772 case ISD::SELECT: return lowerSELECT(Op, DAG);
773 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
774 case ISD::SETCC: return lowerSETCC(Op, DAG);
775 case ISD::VASTART: return lowerVASTART(Op, DAG);
776 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
777 case ISD::FABS: return lowerFABS(Op, DAG);
778 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
779 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
780 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
781 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
782 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
783 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
784 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
785 case ISD::LOAD: return lowerLOAD(Op, DAG);
786 case ISD::STORE: return lowerSTORE(Op, DAG);
787 case ISD::ADD: return lowerADD(Op, DAG);
788 case ISD::FP_TO_SINT: return lowerFP_TO_SINT(Op, DAG);
793 //===----------------------------------------------------------------------===//
794 // Lower helper functions
795 //===----------------------------------------------------------------------===//
797 // addLiveIn - This helper function adds the specified physical register to the
798 // MachineFunction as a live in value. It also creates a corresponding
799 // virtual register for it.
801 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
803 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
804 MF.getRegInfo().addLiveIn(PReg, VReg);
808 static MachineBasicBlock *expandPseudoDIV(MachineInstr *MI,
809 MachineBasicBlock &MBB,
810 const TargetInstrInfo &TII,
815 // Insert instruction "teq $divisor_reg, $zero, 7".
816 MachineBasicBlock::iterator I(MI);
817 MachineInstrBuilder MIB;
818 MachineOperand &Divisor = MI->getOperand(2);
819 MIB = BuildMI(MBB, llvm::next(I), MI->getDebugLoc(), TII.get(Mips::TEQ))
820 .addReg(Divisor.getReg(), getKillRegState(Divisor.isKill()))
821 .addReg(Mips::ZERO).addImm(7);
823 // Use the 32-bit sub-register if this is a 64-bit division.
825 MIB->getOperand(0).setSubReg(Mips::sub_32);
827 // Clear Divisor's kill flag.
828 Divisor.setIsKill(false);
833 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
834 MachineBasicBlock *BB) const {
835 switch (MI->getOpcode()) {
837 llvm_unreachable("Unexpected instr type to insert");
838 case Mips::ATOMIC_LOAD_ADD_I8:
839 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
840 case Mips::ATOMIC_LOAD_ADD_I16:
841 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
842 case Mips::ATOMIC_LOAD_ADD_I32:
843 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
844 case Mips::ATOMIC_LOAD_ADD_I64:
845 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
847 case Mips::ATOMIC_LOAD_AND_I8:
848 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
849 case Mips::ATOMIC_LOAD_AND_I16:
850 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
851 case Mips::ATOMIC_LOAD_AND_I32:
852 return emitAtomicBinary(MI, BB, 4, Mips::AND);
853 case Mips::ATOMIC_LOAD_AND_I64:
854 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
856 case Mips::ATOMIC_LOAD_OR_I8:
857 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
858 case Mips::ATOMIC_LOAD_OR_I16:
859 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
860 case Mips::ATOMIC_LOAD_OR_I32:
861 return emitAtomicBinary(MI, BB, 4, Mips::OR);
862 case Mips::ATOMIC_LOAD_OR_I64:
863 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
865 case Mips::ATOMIC_LOAD_XOR_I8:
866 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
867 case Mips::ATOMIC_LOAD_XOR_I16:
868 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
869 case Mips::ATOMIC_LOAD_XOR_I32:
870 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
871 case Mips::ATOMIC_LOAD_XOR_I64:
872 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
874 case Mips::ATOMIC_LOAD_NAND_I8:
875 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
876 case Mips::ATOMIC_LOAD_NAND_I16:
877 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
878 case Mips::ATOMIC_LOAD_NAND_I32:
879 return emitAtomicBinary(MI, BB, 4, 0, true);
880 case Mips::ATOMIC_LOAD_NAND_I64:
881 return emitAtomicBinary(MI, BB, 8, 0, true);
883 case Mips::ATOMIC_LOAD_SUB_I8:
884 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
885 case Mips::ATOMIC_LOAD_SUB_I16:
886 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
887 case Mips::ATOMIC_LOAD_SUB_I32:
888 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
889 case Mips::ATOMIC_LOAD_SUB_I64:
890 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
892 case Mips::ATOMIC_SWAP_I8:
893 return emitAtomicBinaryPartword(MI, BB, 1, 0);
894 case Mips::ATOMIC_SWAP_I16:
895 return emitAtomicBinaryPartword(MI, BB, 2, 0);
896 case Mips::ATOMIC_SWAP_I32:
897 return emitAtomicBinary(MI, BB, 4, 0);
898 case Mips::ATOMIC_SWAP_I64:
899 return emitAtomicBinary(MI, BB, 8, 0);
901 case Mips::ATOMIC_CMP_SWAP_I8:
902 return emitAtomicCmpSwapPartword(MI, BB, 1);
903 case Mips::ATOMIC_CMP_SWAP_I16:
904 return emitAtomicCmpSwapPartword(MI, BB, 2);
905 case Mips::ATOMIC_CMP_SWAP_I32:
906 return emitAtomicCmpSwap(MI, BB, 4);
907 case Mips::ATOMIC_CMP_SWAP_I64:
908 return emitAtomicCmpSwap(MI, BB, 8);
909 case Mips::PseudoSDIV:
910 case Mips::PseudoUDIV:
911 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), false);
912 case Mips::PseudoDSDIV:
913 case Mips::PseudoDUDIV:
914 return expandPseudoDIV(MI, *BB, *getTargetMachine().getInstrInfo(), true);
918 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
919 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
921 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
922 unsigned Size, unsigned BinOpcode,
924 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
926 MachineFunction *MF = BB->getParent();
927 MachineRegisterInfo &RegInfo = MF->getRegInfo();
928 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
929 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
930 DebugLoc DL = MI->getDebugLoc();
931 unsigned LL, SC, AND, NOR, ZERO, BEQ;
946 ZERO = Mips::ZERO_64;
950 unsigned OldVal = MI->getOperand(0).getReg();
951 unsigned Ptr = MI->getOperand(1).getReg();
952 unsigned Incr = MI->getOperand(2).getReg();
954 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
955 unsigned AndRes = RegInfo.createVirtualRegister(RC);
956 unsigned Success = RegInfo.createVirtualRegister(RC);
958 // insert new blocks after the current block
959 const BasicBlock *LLVM_BB = BB->getBasicBlock();
960 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
961 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
962 MachineFunction::iterator It = BB;
964 MF->insert(It, loopMBB);
965 MF->insert(It, exitMBB);
967 // Transfer the remainder of BB and its successor edges to exitMBB.
968 exitMBB->splice(exitMBB->begin(), BB,
969 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
970 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
974 // fallthrough --> loopMBB
975 BB->addSuccessor(loopMBB);
976 loopMBB->addSuccessor(loopMBB);
977 loopMBB->addSuccessor(exitMBB);
981 // <binop> storeval, oldval, incr
982 // sc success, storeval, 0(ptr)
983 // beq success, $0, loopMBB
985 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
987 // and andres, oldval, incr
988 // nor storeval, $0, andres
989 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
990 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
991 } else if (BinOpcode) {
992 // <binop> storeval, oldval, incr
993 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
997 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
998 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1000 MI->eraseFromParent(); // The instruction is gone now.
1006 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
1007 MachineBasicBlock *BB,
1008 unsigned Size, unsigned BinOpcode,
1010 assert((Size == 1 || Size == 2) &&
1011 "Unsupported size for EmitAtomicBinaryPartial.");
1013 MachineFunction *MF = BB->getParent();
1014 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1015 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1016 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1017 DebugLoc DL = MI->getDebugLoc();
1019 unsigned Dest = MI->getOperand(0).getReg();
1020 unsigned Ptr = MI->getOperand(1).getReg();
1021 unsigned Incr = MI->getOperand(2).getReg();
1023 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1024 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1025 unsigned Mask = RegInfo.createVirtualRegister(RC);
1026 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1027 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1028 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1029 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1030 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1031 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1032 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1033 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1034 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1035 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1036 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1037 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1038 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1039 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1040 unsigned Success = RegInfo.createVirtualRegister(RC);
1042 // insert new blocks after the current block
1043 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1044 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1045 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1046 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1047 MachineFunction::iterator It = BB;
1049 MF->insert(It, loopMBB);
1050 MF->insert(It, sinkMBB);
1051 MF->insert(It, exitMBB);
1053 // Transfer the remainder of BB and its successor edges to exitMBB.
1054 exitMBB->splice(exitMBB->begin(), BB,
1055 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1056 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1058 BB->addSuccessor(loopMBB);
1059 loopMBB->addSuccessor(loopMBB);
1060 loopMBB->addSuccessor(sinkMBB);
1061 sinkMBB->addSuccessor(exitMBB);
1064 // addiu masklsb2,$0,-4 # 0xfffffffc
1065 // and alignedaddr,ptr,masklsb2
1066 // andi ptrlsb2,ptr,3
1067 // sll shiftamt,ptrlsb2,3
1068 // ori maskupper,$0,255 # 0xff
1069 // sll mask,maskupper,shiftamt
1070 // nor mask2,$0,mask
1071 // sll incr2,incr,shiftamt
1073 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1074 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1075 .addReg(Mips::ZERO).addImm(-4);
1076 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1077 .addReg(Ptr).addReg(MaskLSB2);
1078 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1079 if (Subtarget->isLittle()) {
1080 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1082 unsigned Off = RegInfo.createVirtualRegister(RC);
1083 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1084 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1085 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1087 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1088 .addReg(Mips::ZERO).addImm(MaskImm);
1089 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1090 .addReg(MaskUpper).addReg(ShiftAmt);
1091 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1092 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(Incr).addReg(ShiftAmt);
1094 // atomic.load.binop
1096 // ll oldval,0(alignedaddr)
1097 // binop binopres,oldval,incr2
1098 // and newval,binopres,mask
1099 // and maskedoldval0,oldval,mask2
1100 // or storeval,maskedoldval0,newval
1101 // sc success,storeval,0(alignedaddr)
1102 // beq success,$0,loopMBB
1106 // ll oldval,0(alignedaddr)
1107 // and newval,incr2,mask
1108 // and maskedoldval0,oldval,mask2
1109 // or storeval,maskedoldval0,newval
1110 // sc success,storeval,0(alignedaddr)
1111 // beq success,$0,loopMBB
1114 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1116 // and andres, oldval, incr2
1117 // nor binopres, $0, andres
1118 // and newval, binopres, mask
1119 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1120 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1121 .addReg(Mips::ZERO).addReg(AndRes);
1122 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1123 } else if (BinOpcode) {
1124 // <binop> binopres, oldval, incr2
1125 // and newval, binopres, mask
1126 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1127 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1128 } else { // atomic.swap
1129 // and newval, incr2, mask
1130 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1133 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1134 .addReg(OldVal).addReg(Mask2);
1135 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1136 .addReg(MaskedOldVal0).addReg(NewVal);
1137 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1138 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1139 BuildMI(BB, DL, TII->get(Mips::BEQ))
1140 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1143 // and maskedoldval1,oldval,mask
1144 // srl srlres,maskedoldval1,shiftamt
1145 // sll sllres,srlres,24
1146 // sra dest,sllres,24
1148 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1150 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1151 .addReg(OldVal).addReg(Mask);
1152 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1153 .addReg(MaskedOldVal1).addReg(ShiftAmt);
1154 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1155 .addReg(SrlRes).addImm(ShiftImm);
1156 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1157 .addReg(SllRes).addImm(ShiftImm);
1159 MI->eraseFromParent(); // The instruction is gone now.
1164 MachineBasicBlock * MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1165 MachineBasicBlock *BB,
1166 unsigned Size) const {
1167 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1169 MachineFunction *MF = BB->getParent();
1170 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1171 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1172 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1173 DebugLoc DL = MI->getDebugLoc();
1174 unsigned LL, SC, ZERO, BNE, BEQ;
1185 ZERO = Mips::ZERO_64;
1190 unsigned Dest = MI->getOperand(0).getReg();
1191 unsigned Ptr = MI->getOperand(1).getReg();
1192 unsigned OldVal = MI->getOperand(2).getReg();
1193 unsigned NewVal = MI->getOperand(3).getReg();
1195 unsigned Success = RegInfo.createVirtualRegister(RC);
1197 // insert new blocks after the current block
1198 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1199 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1200 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1201 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1202 MachineFunction::iterator It = BB;
1204 MF->insert(It, loop1MBB);
1205 MF->insert(It, loop2MBB);
1206 MF->insert(It, exitMBB);
1208 // Transfer the remainder of BB and its successor edges to exitMBB.
1209 exitMBB->splice(exitMBB->begin(), BB,
1210 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1211 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1215 // fallthrough --> loop1MBB
1216 BB->addSuccessor(loop1MBB);
1217 loop1MBB->addSuccessor(exitMBB);
1218 loop1MBB->addSuccessor(loop2MBB);
1219 loop2MBB->addSuccessor(loop1MBB);
1220 loop2MBB->addSuccessor(exitMBB);
1224 // bne dest, oldval, exitMBB
1226 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1227 BuildMI(BB, DL, TII->get(BNE))
1228 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1231 // sc success, newval, 0(ptr)
1232 // beq success, $0, loop1MBB
1234 BuildMI(BB, DL, TII->get(SC), Success)
1235 .addReg(NewVal).addReg(Ptr).addImm(0);
1236 BuildMI(BB, DL, TII->get(BEQ))
1237 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1239 MI->eraseFromParent(); // The instruction is gone now.
1245 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1246 MachineBasicBlock *BB,
1247 unsigned Size) const {
1248 assert((Size == 1 || Size == 2) &&
1249 "Unsupported size for EmitAtomicCmpSwapPartial.");
1251 MachineFunction *MF = BB->getParent();
1252 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1253 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1254 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1255 DebugLoc DL = MI->getDebugLoc();
1257 unsigned Dest = MI->getOperand(0).getReg();
1258 unsigned Ptr = MI->getOperand(1).getReg();
1259 unsigned CmpVal = MI->getOperand(2).getReg();
1260 unsigned NewVal = MI->getOperand(3).getReg();
1262 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1263 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1264 unsigned Mask = RegInfo.createVirtualRegister(RC);
1265 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1266 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1267 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1268 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1269 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1270 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1271 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1272 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1273 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1274 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1275 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1276 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1277 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1278 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1279 unsigned Success = RegInfo.createVirtualRegister(RC);
1281 // insert new blocks after the current block
1282 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1283 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1284 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1285 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1286 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1287 MachineFunction::iterator It = BB;
1289 MF->insert(It, loop1MBB);
1290 MF->insert(It, loop2MBB);
1291 MF->insert(It, sinkMBB);
1292 MF->insert(It, exitMBB);
1294 // Transfer the remainder of BB and its successor edges to exitMBB.
1295 exitMBB->splice(exitMBB->begin(), BB,
1296 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1297 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1299 BB->addSuccessor(loop1MBB);
1300 loop1MBB->addSuccessor(sinkMBB);
1301 loop1MBB->addSuccessor(loop2MBB);
1302 loop2MBB->addSuccessor(loop1MBB);
1303 loop2MBB->addSuccessor(sinkMBB);
1304 sinkMBB->addSuccessor(exitMBB);
1306 // FIXME: computation of newval2 can be moved to loop2MBB.
1308 // addiu masklsb2,$0,-4 # 0xfffffffc
1309 // and alignedaddr,ptr,masklsb2
1310 // andi ptrlsb2,ptr,3
1311 // sll shiftamt,ptrlsb2,3
1312 // ori maskupper,$0,255 # 0xff
1313 // sll mask,maskupper,shiftamt
1314 // nor mask2,$0,mask
1315 // andi maskedcmpval,cmpval,255
1316 // sll shiftedcmpval,maskedcmpval,shiftamt
1317 // andi maskednewval,newval,255
1318 // sll shiftednewval,maskednewval,shiftamt
1319 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1320 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1321 .addReg(Mips::ZERO).addImm(-4);
1322 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1323 .addReg(Ptr).addReg(MaskLSB2);
1324 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1325 if (Subtarget->isLittle()) {
1326 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1328 unsigned Off = RegInfo.createVirtualRegister(RC);
1329 BuildMI(BB, DL, TII->get(Mips::XORi), Off)
1330 .addReg(PtrLSB2).addImm((Size == 1) ? 3 : 2);
1331 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(Off).addImm(3);
1333 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1334 .addReg(Mips::ZERO).addImm(MaskImm);
1335 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1336 .addReg(MaskUpper).addReg(ShiftAmt);
1337 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1338 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1339 .addReg(CmpVal).addImm(MaskImm);
1340 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1341 .addReg(MaskedCmpVal).addReg(ShiftAmt);
1342 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1343 .addReg(NewVal).addImm(MaskImm);
1344 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1345 .addReg(MaskedNewVal).addReg(ShiftAmt);
1348 // ll oldval,0(alginedaddr)
1349 // and maskedoldval0,oldval,mask
1350 // bne maskedoldval0,shiftedcmpval,sinkMBB
1352 BuildMI(BB, DL, TII->get(Mips::LL), OldVal).addReg(AlignedAddr).addImm(0);
1353 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1354 .addReg(OldVal).addReg(Mask);
1355 BuildMI(BB, DL, TII->get(Mips::BNE))
1356 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1359 // and maskedoldval1,oldval,mask2
1360 // or storeval,maskedoldval1,shiftednewval
1361 // sc success,storeval,0(alignedaddr)
1362 // beq success,$0,loop1MBB
1364 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1365 .addReg(OldVal).addReg(Mask2);
1366 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1367 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1368 BuildMI(BB, DL, TII->get(Mips::SC), Success)
1369 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1370 BuildMI(BB, DL, TII->get(Mips::BEQ))
1371 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1374 // srl srlres,maskedoldval0,shiftamt
1375 // sll sllres,srlres,24
1376 // sra dest,sllres,24
1378 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1380 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1381 .addReg(MaskedOldVal0).addReg(ShiftAmt);
1382 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1383 .addReg(SrlRes).addImm(ShiftImm);
1384 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1385 .addReg(SllRes).addImm(ShiftImm);
1387 MI->eraseFromParent(); // The instruction is gone now.
1392 //===----------------------------------------------------------------------===//
1393 // Misc Lower Operation implementation
1394 //===----------------------------------------------------------------------===//
1395 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1396 SDValue Chain = Op.getOperand(0);
1397 SDValue Table = Op.getOperand(1);
1398 SDValue Index = Op.getOperand(2);
1400 EVT PTy = getPointerTy();
1401 unsigned EntrySize =
1402 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1404 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1405 DAG.getConstant(EntrySize, PTy));
1406 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1408 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1409 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1410 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1412 Chain = Addr.getValue(1);
1414 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1415 // For PIC, the sequence is:
1416 // BRIND(load(Jumptable + index) + RelocBase)
1417 // RelocBase can be JumpTable, GOT or some sort of global base.
1418 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1419 getPICJumpTableRelocBase(Table, DAG));
1422 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1425 SDValue MipsTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
1426 // The first operand is the chain, the second is the condition, the third is
1427 // the block to branch to if the condition is true.
1428 SDValue Chain = Op.getOperand(0);
1429 SDValue Dest = Op.getOperand(2);
1432 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1434 // Return if flag is not set by a floating point comparison.
1435 if (CondRes.getOpcode() != MipsISD::FPCmp)
1438 SDValue CCNode = CondRes.getOperand(2);
1440 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1441 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1442 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1443 SDValue FCC0 = DAG.getRegister(Mips::FCC0, MVT::i32);
1444 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1445 FCC0, Dest, CondRes);
1448 SDValue MipsTargetLowering::
1449 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1451 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1453 // Return if flag is not set by a floating point comparison.
1454 if (Cond.getOpcode() != MipsISD::FPCmp)
1457 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1461 SDValue MipsTargetLowering::
1462 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1465 EVT Ty = Op.getOperand(0).getValueType();
1466 SDValue Cond = DAG.getNode(ISD::SETCC, DL,
1467 getSetCCResultType(*DAG.getContext(), Ty),
1468 Op.getOperand(0), Op.getOperand(1),
1471 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1475 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1476 SDValue Cond = createFPCmp(DAG, Op);
1478 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1479 "Floating point operand expected.");
1481 SDValue True = DAG.getConstant(1, MVT::i32);
1482 SDValue False = DAG.getConstant(0, MVT::i32);
1484 return createCMovFP(DAG, Cond, True, False, SDLoc(Op));
1487 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1488 SelectionDAG &DAG) const {
1489 // FIXME there isn't actually debug info here
1491 EVT Ty = Op.getValueType();
1492 GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
1493 const GlobalValue *GV = N->getGlobal();
1495 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1496 const MipsTargetObjectFile &TLOF =
1497 (const MipsTargetObjectFile&)getObjFileLowering();
1499 // %gp_rel relocation
1500 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1501 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1503 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1504 DAG.getVTList(MVT::i32), &GA, 1);
1505 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1506 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1509 // %hi/%lo relocation
1510 return getAddrNonPIC(N, Ty, DAG);
1513 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1514 return getAddrLocal(N, Ty, DAG, HasMips64);
1517 return getAddrGlobalLargeGOT(N, Ty, DAG, MipsII::MO_GOT_HI16,
1518 MipsII::MO_GOT_LO16, DAG.getEntryNode(),
1519 MachinePointerInfo::getGOT());
1521 return getAddrGlobal(N, Ty, DAG,
1522 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16,
1523 DAG.getEntryNode(), MachinePointerInfo::getGOT());
1526 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1527 SelectionDAG &DAG) const {
1528 BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
1529 EVT Ty = Op.getValueType();
1531 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1532 return getAddrNonPIC(N, Ty, DAG);
1534 return getAddrLocal(N, Ty, DAG, HasMips64);
1537 SDValue MipsTargetLowering::
1538 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1540 // If the relocation model is PIC, use the General Dynamic TLS Model or
1541 // Local Dynamic TLS model, otherwise use the Initial Exec or
1542 // Local Exec TLS Model.
1544 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1546 const GlobalValue *GV = GA->getGlobal();
1547 EVT PtrVT = getPointerTy();
1549 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1551 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1552 // General Dynamic and Local Dynamic TLS Model.
1553 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1556 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1557 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1558 getGlobalReg(DAG, PtrVT), TGA);
1559 unsigned PtrSize = PtrVT.getSizeInBits();
1560 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1562 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1566 Entry.Node = Argument;
1568 Args.push_back(Entry);
1570 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1571 false, false, false, false, 0, CallingConv::C,
1572 /*IsTailCall=*/false, /*doesNotRet=*/false,
1573 /*isReturnValueUsed=*/true,
1574 TlsGetAddr, Args, DAG, DL);
1575 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1577 SDValue Ret = CallResult.first;
1579 if (model != TLSModel::LocalDynamic)
1582 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1583 MipsII::MO_DTPREL_HI);
1584 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1585 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1586 MipsII::MO_DTPREL_LO);
1587 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1588 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1589 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1593 if (model == TLSModel::InitialExec) {
1594 // Initial Exec TLS Model
1595 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1596 MipsII::MO_GOTTPREL);
1597 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1599 Offset = DAG.getLoad(PtrVT, DL,
1600 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1601 false, false, false, 0);
1603 // Local Exec TLS Model
1604 assert(model == TLSModel::LocalExec);
1605 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1606 MipsII::MO_TPREL_HI);
1607 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1608 MipsII::MO_TPREL_LO);
1609 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1610 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1611 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1614 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1615 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1618 SDValue MipsTargetLowering::
1619 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1621 JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
1622 EVT Ty = Op.getValueType();
1624 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1625 return getAddrNonPIC(N, Ty, DAG);
1627 return getAddrLocal(N, Ty, DAG, HasMips64);
1630 SDValue MipsTargetLowering::
1631 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1633 // gp_rel relocation
1634 // FIXME: we should reference the constant pool using small data sections,
1635 // but the asm printer currently doesn't support this feature without
1636 // hacking it. This feature should come soon so we can uncomment the
1638 //if (IsInSmallSection(C->getType())) {
1639 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1640 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1641 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1642 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1643 EVT Ty = Op.getValueType();
1645 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1646 return getAddrNonPIC(N, Ty, DAG);
1648 return getAddrLocal(N, Ty, DAG, HasMips64);
1651 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1652 MachineFunction &MF = DAG.getMachineFunction();
1653 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1656 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1659 // vastart just stores the address of the VarArgsFrameIndex slot into the
1660 // memory location argument.
1661 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1662 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1663 MachinePointerInfo(SV), false, false, 0);
1666 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG,
1667 bool HasExtractInsert) {
1668 EVT TyX = Op.getOperand(0).getValueType();
1669 EVT TyY = Op.getOperand(1).getValueType();
1670 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1671 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1675 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1677 SDValue X = (TyX == MVT::f32) ?
1678 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1679 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1681 SDValue Y = (TyY == MVT::f32) ?
1682 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1683 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1686 if (HasExtractInsert) {
1687 // ext E, Y, 31, 1 ; extract bit31 of Y
1688 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1689 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1690 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1693 // srl SrlX, SllX, 1
1695 // sll SllY, SrlX, 31
1696 // or Or, SrlX, SllY
1697 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1698 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1699 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1700 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1701 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1704 if (TyX == MVT::f32)
1705 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1707 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1708 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1709 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1712 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG,
1713 bool HasExtractInsert) {
1714 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1715 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1716 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1717 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1720 // Bitcast to integer nodes.
1721 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1722 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1724 if (HasExtractInsert) {
1725 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1726 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1727 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1728 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1730 if (WidthX > WidthY)
1731 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1732 else if (WidthY > WidthX)
1733 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1735 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1736 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1737 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1740 // (d)sll SllX, X, 1
1741 // (d)srl SrlX, SllX, 1
1742 // (d)srl SrlY, Y, width(Y)-1
1743 // (d)sll SllY, SrlX, width(Y)-1
1744 // or Or, SrlX, SllY
1745 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1746 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1747 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1748 DAG.getConstant(WidthY - 1, MVT::i32));
1750 if (WidthX > WidthY)
1751 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1752 else if (WidthY > WidthX)
1753 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1755 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1756 DAG.getConstant(WidthX - 1, MVT::i32));
1757 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1758 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1762 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1763 if (Subtarget->hasMips64())
1764 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasExtractInsert());
1766 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasExtractInsert());
1769 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG,
1770 bool HasExtractInsert) {
1771 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1774 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1776 SDValue X = (Op.getValueType() == MVT::f32) ?
1777 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1778 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1782 if (HasExtractInsert)
1783 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1784 DAG.getRegister(Mips::ZERO, MVT::i32),
1785 DAG.getConstant(31, MVT::i32), Const1, X);
1787 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1788 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1791 if (Op.getValueType() == MVT::f32)
1792 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1794 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1795 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1796 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1799 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG,
1800 bool HasExtractInsert) {
1801 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1804 // Bitcast to integer node.
1805 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1808 if (HasExtractInsert)
1809 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1810 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1811 DAG.getConstant(63, MVT::i32), Const1, X);
1813 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1814 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1817 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1821 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1822 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1823 return lowerFABS64(Op, DAG, Subtarget->hasExtractInsert());
1825 return lowerFABS32(Op, DAG, Subtarget->hasExtractInsert());
1828 SDValue MipsTargetLowering::
1829 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1831 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1832 "Frame address can only be determined for current frame.");
1834 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1835 MFI->setFrameAddressIsTaken(true);
1836 EVT VT = Op.getValueType();
1838 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1839 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1843 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1844 SelectionDAG &DAG) const {
1846 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1847 "Return address can be determined only for current frame.");
1849 MachineFunction &MF = DAG.getMachineFunction();
1850 MachineFrameInfo *MFI = MF.getFrameInfo();
1851 MVT VT = Op.getSimpleValueType();
1852 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1853 MFI->setReturnAddressIsTaken(true);
1855 // Return RA, which contains the return address. Mark it an implicit live-in.
1856 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1857 return DAG.getCopyFromReg(DAG.getEntryNode(), SDLoc(Op), Reg, VT);
1860 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1861 // generated from __builtin_eh_return (offset, handler)
1862 // The effect of this is to adjust the stack pointer by "offset"
1863 // and then branch to "handler".
1864 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1866 MachineFunction &MF = DAG.getMachineFunction();
1867 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1869 MipsFI->setCallsEhReturn();
1870 SDValue Chain = Op.getOperand(0);
1871 SDValue Offset = Op.getOperand(1);
1872 SDValue Handler = Op.getOperand(2);
1874 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1876 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1877 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1878 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1879 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1880 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1881 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1882 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1883 DAG.getRegister(OffsetReg, Ty),
1884 DAG.getRegister(AddrReg, getPointerTy()),
1888 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1889 SelectionDAG &DAG) const {
1890 // FIXME: Need pseudo-fence for 'singlethread' fences
1891 // FIXME: Set SType for weaker fences where supported/appropriate.
1894 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1895 DAG.getConstant(SType, MVT::i32));
1898 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1899 SelectionDAG &DAG) const {
1901 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1902 SDValue Shamt = Op.getOperand(2);
1905 // lo = (shl lo, shamt)
1906 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1909 // hi = (shl lo, shamt[4:0])
1910 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1911 DAG.getConstant(-1, MVT::i32));
1912 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1913 DAG.getConstant(1, MVT::i32));
1914 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1916 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1917 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1918 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1919 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1920 DAG.getConstant(0x20, MVT::i32));
1921 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1922 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1923 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1925 SDValue Ops[2] = {Lo, Hi};
1926 return DAG.getMergeValues(Ops, 2, DL);
1929 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1932 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1933 SDValue Shamt = Op.getOperand(2);
1936 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1938 // hi = (sra hi, shamt)
1940 // hi = (srl hi, shamt)
1943 // lo = (sra hi, shamt[4:0])
1944 // hi = (sra hi, 31)
1946 // lo = (srl hi, shamt[4:0])
1948 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1949 DAG.getConstant(-1, MVT::i32));
1950 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1951 DAG.getConstant(1, MVT::i32));
1952 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1953 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1954 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1955 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1957 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1958 DAG.getConstant(0x20, MVT::i32));
1959 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1960 DAG.getConstant(31, MVT::i32));
1961 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1962 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1963 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1966 SDValue Ops[2] = {Lo, Hi};
1967 return DAG.getMergeValues(Ops, 2, DL);
1970 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1971 SDValue Chain, SDValue Src, unsigned Offset) {
1972 SDValue Ptr = LD->getBasePtr();
1973 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1974 EVT BasePtrVT = Ptr.getValueType();
1976 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1979 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1980 DAG.getConstant(Offset, BasePtrVT));
1982 SDValue Ops[] = { Chain, Ptr, Src };
1983 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1984 LD->getMemOperand());
1987 // Expand an unaligned 32 or 64-bit integer load node.
1988 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1989 LoadSDNode *LD = cast<LoadSDNode>(Op);
1990 EVT MemVT = LD->getMemoryVT();
1992 // Return if load is aligned or if MemVT is neither i32 nor i64.
1993 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1994 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1997 bool IsLittle = Subtarget->isLittle();
1998 EVT VT = Op.getValueType();
1999 ISD::LoadExtType ExtType = LD->getExtensionType();
2000 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2002 assert((VT == MVT::i32) || (VT == MVT::i64));
2005 // (set dst, (i64 (load baseptr)))
2007 // (set tmp, (ldl (add baseptr, 7), undef))
2008 // (set dst, (ldr baseptr, tmp))
2009 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2010 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2012 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2016 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2018 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2022 // (set dst, (i32 (load baseptr))) or
2023 // (set dst, (i64 (sextload baseptr))) or
2024 // (set dst, (i64 (extload baseptr)))
2026 // (set tmp, (lwl (add baseptr, 3), undef))
2027 // (set dst, (lwr baseptr, tmp))
2028 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2029 (ExtType == ISD::EXTLOAD))
2032 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2035 // (set dst, (i64 (zextload baseptr)))
2037 // (set tmp0, (lwl (add baseptr, 3), undef))
2038 // (set tmp1, (lwr baseptr, tmp0))
2039 // (set tmp2, (shl tmp1, 32))
2040 // (set dst, (srl tmp2, 32))
2042 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2043 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2044 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2045 SDValue Ops[] = { SRL, LWR.getValue(1) };
2046 return DAG.getMergeValues(Ops, 2, DL);
2049 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2050 SDValue Chain, unsigned Offset) {
2051 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2052 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2054 SDVTList VTList = DAG.getVTList(MVT::Other);
2057 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2058 DAG.getConstant(Offset, BasePtrVT));
2060 SDValue Ops[] = { Chain, Value, Ptr };
2061 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2062 SD->getMemOperand());
2065 // Expand an unaligned 32 or 64-bit integer store node.
2066 static SDValue lowerUnalignedIntStore(StoreSDNode *SD, SelectionDAG &DAG,
2068 SDValue Value = SD->getValue(), Chain = SD->getChain();
2069 EVT VT = Value.getValueType();
2072 // (store val, baseptr) or
2073 // (truncstore val, baseptr)
2075 // (swl val, (add baseptr, 3))
2076 // (swr val, baseptr)
2077 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2078 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2080 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2083 assert(VT == MVT::i64);
2086 // (store val, baseptr)
2088 // (sdl val, (add baseptr, 7))
2089 // (sdr val, baseptr)
2090 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2091 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2094 // Lower (store (fp_to_sint $fp) $ptr) to (store (TruncIntFP $fp), $ptr).
2095 static SDValue lowerFP_TO_SINT_STORE(StoreSDNode *SD, SelectionDAG &DAG) {
2096 SDValue Val = SD->getValue();
2098 if (Val.getOpcode() != ISD::FP_TO_SINT)
2101 EVT FPTy = EVT::getFloatingPointVT(Val.getValueSizeInBits());
2102 SDValue Tr = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Val), FPTy,
2105 return DAG.getStore(SD->getChain(), SDLoc(SD), Tr, SD->getBasePtr(),
2106 SD->getPointerInfo(), SD->isVolatile(),
2107 SD->isNonTemporal(), SD->getAlignment());
2110 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2111 StoreSDNode *SD = cast<StoreSDNode>(Op);
2112 EVT MemVT = SD->getMemoryVT();
2114 // Lower unaligned integer stores.
2115 if ((SD->getAlignment() < MemVT.getSizeInBits() / 8) &&
2116 ((MemVT == MVT::i32) || (MemVT == MVT::i64)))
2117 return lowerUnalignedIntStore(SD, DAG, Subtarget->isLittle());
2119 return lowerFP_TO_SINT_STORE(SD, DAG);
2122 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2123 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2124 || cast<ConstantSDNode>
2125 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2126 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2130 // (add (frameaddr 0), (frame_to_args_offset))
2131 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2132 // (add FrameObject, 0)
2133 // where FrameObject is a fixed StackObject with offset 0 which points to
2134 // the old stack pointer.
2135 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2136 EVT ValTy = Op->getValueType(0);
2137 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2138 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2139 return DAG.getNode(ISD::ADD, SDLoc(Op), ValTy, InArgsAddr,
2140 DAG.getConstant(0, ValTy));
2143 SDValue MipsTargetLowering::lowerFP_TO_SINT(SDValue Op,
2144 SelectionDAG &DAG) const {
2145 EVT FPTy = EVT::getFloatingPointVT(Op.getValueSizeInBits());
2146 SDValue Trunc = DAG.getNode(MipsISD::TruncIntFP, SDLoc(Op), FPTy,
2148 return DAG.getNode(ISD::BITCAST, SDLoc(Op), Op.getValueType(), Trunc);
2151 //===----------------------------------------------------------------------===//
2152 // Calling Convention Implementation
2153 //===----------------------------------------------------------------------===//
2155 //===----------------------------------------------------------------------===//
2156 // TODO: Implement a generic logic using tblgen that can support this.
2157 // Mips O32 ABI rules:
2159 // i32 - Passed in A0, A1, A2, A3 and stack
2160 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2161 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2162 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2163 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2164 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2167 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2168 //===----------------------------------------------------------------------===//
2170 static bool CC_MipsO32(unsigned ValNo, MVT ValVT, MVT LocVT,
2171 CCValAssign::LocInfo LocInfo, ISD::ArgFlagsTy ArgFlags,
2172 CCState &State, const uint16_t *F64Regs) {
2174 static const unsigned IntRegsSize = 4, FloatRegsSize = 2;
2176 static const uint16_t IntRegs[] = { Mips::A0, Mips::A1, Mips::A2, Mips::A3 };
2177 static const uint16_t F32Regs[] = { Mips::F12, Mips::F14 };
2179 // Do not process byval args here.
2180 if (ArgFlags.isByVal())
2183 // Promote i8 and i16
2184 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2186 if (ArgFlags.isSExt())
2187 LocInfo = CCValAssign::SExt;
2188 else if (ArgFlags.isZExt())
2189 LocInfo = CCValAssign::ZExt;
2191 LocInfo = CCValAssign::AExt;
2196 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2197 // is true: function is vararg, argument is 3rd or higher, there is previous
2198 // argument which is not f32 or f64.
2199 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2200 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2201 unsigned OrigAlign = ArgFlags.getOrigAlign();
2202 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2204 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2205 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2206 // If this is the first part of an i64 arg,
2207 // the allocated register must be either A0 or A2.
2208 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2209 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2211 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2212 // Allocate int register and shadow next int register. If first
2213 // available register is Mips::A1 or Mips::A3, shadow it too.
2214 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2215 if (Reg == Mips::A1 || Reg == Mips::A3)
2216 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2217 State.AllocateReg(IntRegs, IntRegsSize);
2219 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2220 // we are guaranteed to find an available float register
2221 if (ValVT == MVT::f32) {
2222 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2223 // Shadow int register
2224 State.AllocateReg(IntRegs, IntRegsSize);
2226 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2227 // Shadow int registers
2228 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2229 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2230 State.AllocateReg(IntRegs, IntRegsSize);
2231 State.AllocateReg(IntRegs, IntRegsSize);
2234 llvm_unreachable("Cannot handle this ValVT.");
2237 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2239 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2241 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2246 static bool CC_MipsO32_FP32(unsigned ValNo, MVT ValVT,
2247 MVT LocVT, CCValAssign::LocInfo LocInfo,
2248 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2249 static const uint16_t F64Regs[] = { Mips::D6, Mips::D7 };
2251 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2254 static bool CC_MipsO32_FP64(unsigned ValNo, MVT ValVT,
2255 MVT LocVT, CCValAssign::LocInfo LocInfo,
2256 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2257 static const uint16_t F64Regs[] = { Mips::D12_64, Mips::D14_64 };
2259 return CC_MipsO32(ValNo, ValVT, LocVT, LocInfo, ArgFlags, State, F64Regs);
2262 #include "MipsGenCallingConv.inc"
2264 //===----------------------------------------------------------------------===//
2265 // Call Calling Convention Implementation
2266 //===----------------------------------------------------------------------===//
2268 // Return next O32 integer argument register.
2269 static unsigned getNextIntArgReg(unsigned Reg) {
2270 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2271 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2275 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2276 SDValue Chain, SDValue Arg, SDLoc DL,
2277 bool IsTailCall, SelectionDAG &DAG) const {
2279 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2280 DAG.getIntPtrConstant(Offset));
2281 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2285 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2286 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2287 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2288 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2289 /*isVolatile=*/ true, false, 0);
2292 void MipsTargetLowering::
2293 getOpndList(SmallVectorImpl<SDValue> &Ops,
2294 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2295 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2296 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2297 // Insert node "GP copy globalreg" before call to function.
2299 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2300 // in PIC mode) allow symbols to be resolved via lazy binding.
2301 // The lazy binding stub requires GP to point to the GOT.
2302 if (IsPICCall && !InternalLinkage) {
2303 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2304 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2305 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2308 // Build a sequence of copy-to-reg nodes chained together with token
2309 // chain and flag operands which copy the outgoing args into registers.
2310 // The InFlag in necessary since all emitted instructions must be
2314 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2315 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2316 RegsToPass[i].second, InFlag);
2317 InFlag = Chain.getValue(1);
2320 // Add argument registers to the end of the list so that they are
2321 // known live into the call.
2322 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2323 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2324 RegsToPass[i].second.getValueType()));
2326 // Add a register mask operand representing the call-preserved registers.
2327 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2328 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2329 assert(Mask && "Missing call preserved mask for calling convention");
2330 if (Subtarget->inMips16HardFloat()) {
2331 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(CLI.Callee)) {
2332 llvm::StringRef Sym = G->getGlobal()->getName();
2333 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
2334 if (F->hasFnAttribute("__Mips16RetHelper")) {
2335 Mask = MipsRegisterInfo::getMips16RetHelperMask();
2339 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2341 if (InFlag.getNode())
2342 Ops.push_back(InFlag);
2345 /// LowerCall - functions arguments are copied from virtual regs to
2346 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2348 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2349 SmallVectorImpl<SDValue> &InVals) const {
2350 SelectionDAG &DAG = CLI.DAG;
2352 SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
2353 SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
2354 SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
2355 SDValue Chain = CLI.Chain;
2356 SDValue Callee = CLI.Callee;
2357 bool &IsTailCall = CLI.IsTailCall;
2358 CallingConv::ID CallConv = CLI.CallConv;
2359 bool IsVarArg = CLI.IsVarArg;
2361 MachineFunction &MF = DAG.getMachineFunction();
2362 MachineFrameInfo *MFI = MF.getFrameInfo();
2363 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2364 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
2365 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2367 // Analyze operands of the call, assigning locations to each operand.
2368 SmallVector<CCValAssign, 16> ArgLocs;
2369 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2370 getTargetMachine(), ArgLocs, *DAG.getContext());
2371 MipsCC::SpecialCallingConvType SpecialCallingConv =
2372 getSpecialCallingConv(Callee);
2373 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo,
2374 SpecialCallingConv);
2376 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2377 Subtarget->mipsSEUsesSoftFloat(),
2378 Callee.getNode(), CLI.Args);
2380 // Get a count of how many bytes are to be pushed on the stack.
2381 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2383 // Check if it's really possible to do a tail call.
2386 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2387 *MF.getInfo<MipsFunctionInfo>());
2392 // Chain is the output chain of the last Load/Store or CopyToReg node.
2393 // ByValChain is the output chain of the last Memcpy node created for copying
2394 // byval arguments to the stack.
2395 unsigned StackAlignment = TFL->getStackAlignment();
2396 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2397 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2400 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal, DL);
2402 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2403 IsN64 ? Mips::SP_64 : Mips::SP,
2406 // With EABI is it possible to have 16 args on registers.
2407 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2408 SmallVector<SDValue, 8> MemOpChains;
2409 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2411 // Walk the register/memloc assignments, inserting copies/loads.
2412 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2413 SDValue Arg = OutVals[i];
2414 CCValAssign &VA = ArgLocs[i];
2415 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2416 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2419 if (Flags.isByVal()) {
2420 assert(Flags.getByValSize() &&
2421 "ByVal args of size 0 should have been ignored by front-end.");
2422 assert(ByValArg != MipsCCInfo.byval_end());
2423 assert(!IsTailCall &&
2424 "Do not tail-call optimize if there is a byval argument.");
2425 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2426 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2431 // Promote the value if needed.
2432 switch (VA.getLocInfo()) {
2433 default: llvm_unreachable("Unknown loc info!");
2434 case CCValAssign::Full:
2435 if (VA.isRegLoc()) {
2436 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2437 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2438 (ValVT == MVT::i64 && LocVT == MVT::f64))
2439 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2440 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2441 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2442 Arg, DAG.getConstant(0, MVT::i32));
2443 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2444 Arg, DAG.getConstant(1, MVT::i32));
2445 if (!Subtarget->isLittle())
2447 unsigned LocRegLo = VA.getLocReg();
2448 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2449 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2450 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2455 case CCValAssign::SExt:
2456 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2458 case CCValAssign::ZExt:
2459 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2461 case CCValAssign::AExt:
2462 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2466 // Arguments that can be passed on register must be kept at
2467 // RegsToPass vector
2468 if (VA.isRegLoc()) {
2469 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2473 // Register can't get to this point...
2474 assert(VA.isMemLoc());
2476 // emit ISD::STORE whichs stores the
2477 // parameter value to a stack Location
2478 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2479 Chain, Arg, DL, IsTailCall, DAG));
2482 // Transform all store nodes into one single node because all store
2483 // nodes are independent of each other.
2484 if (!MemOpChains.empty())
2485 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2486 &MemOpChains[0], MemOpChains.size());
2488 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2489 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2490 // node so that legalize doesn't hack it.
2491 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2492 bool GlobalOrExternal = false, InternalLinkage = false;
2494 EVT Ty = Callee.getValueType();
2496 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2498 const GlobalValue *Val = G->getGlobal();
2499 InternalLinkage = Val->hasInternalLinkage();
2501 if (InternalLinkage)
2502 Callee = getAddrLocal(G, Ty, DAG, HasMips64);
2504 Callee = getAddrGlobalLargeGOT(G, Ty, DAG, MipsII::MO_CALL_HI16,
2505 MipsII::MO_CALL_LO16, Chain,
2506 FuncInfo->callPtrInfo(Val));
2508 Callee = getAddrGlobal(G, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2509 FuncInfo->callPtrInfo(Val));
2511 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2512 MipsII::MO_NO_FLAG);
2513 GlobalOrExternal = true;
2515 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2516 const char *Sym = S->getSymbol();
2518 if (!IsN64 && !IsPIC) // !N64 && static
2519 Callee = DAG.getTargetExternalSymbol(Sym, getPointerTy(),
2520 MipsII::MO_NO_FLAG);
2522 Callee = getAddrGlobalLargeGOT(S, Ty, DAG, MipsII::MO_CALL_HI16,
2523 MipsII::MO_CALL_LO16, Chain,
2524 FuncInfo->callPtrInfo(Sym));
2526 Callee = getAddrGlobal(S, Ty, DAG, MipsII::MO_GOT_CALL, Chain,
2527 FuncInfo->callPtrInfo(Sym));
2529 GlobalOrExternal = true;
2532 SmallVector<SDValue, 8> Ops(1, Chain);
2533 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2535 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2536 CLI, Callee, Chain);
2539 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2541 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2542 SDValue InFlag = Chain.getValue(1);
2544 // Create the CALLSEQ_END node.
2545 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2546 DAG.getIntPtrConstant(0, true), InFlag, DL);
2547 InFlag = Chain.getValue(1);
2549 // Handle result values, copying them out of physregs into vregs that we
2551 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2552 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2555 /// LowerCallResult - Lower the result values of a call into the
2556 /// appropriate copies out of appropriate physical registers.
2558 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2559 CallingConv::ID CallConv, bool IsVarArg,
2560 const SmallVectorImpl<ISD::InputArg> &Ins,
2561 SDLoc DL, SelectionDAG &DAG,
2562 SmallVectorImpl<SDValue> &InVals,
2563 const SDNode *CallNode,
2564 const Type *RetTy) const {
2565 // Assign locations to each value returned by this call.
2566 SmallVector<CCValAssign, 16> RVLocs;
2567 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2568 getTargetMachine(), RVLocs, *DAG.getContext());
2569 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2571 MipsCCInfo.analyzeCallResult(Ins, Subtarget->mipsSEUsesSoftFloat(),
2574 // Copy all of the result registers out of their specified physreg.
2575 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2576 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2577 RVLocs[i].getLocVT(), InFlag);
2578 Chain = Val.getValue(1);
2579 InFlag = Val.getValue(2);
2581 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2582 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2584 InVals.push_back(Val);
2590 //===----------------------------------------------------------------------===//
2591 // Formal Arguments Calling Convention Implementation
2592 //===----------------------------------------------------------------------===//
2593 /// LowerFormalArguments - transform physical registers into virtual registers
2594 /// and generate load operations for arguments places on the stack.
2596 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2597 CallingConv::ID CallConv,
2599 const SmallVectorImpl<ISD::InputArg> &Ins,
2600 SDLoc DL, SelectionDAG &DAG,
2601 SmallVectorImpl<SDValue> &InVals)
2603 MachineFunction &MF = DAG.getMachineFunction();
2604 MachineFrameInfo *MFI = MF.getFrameInfo();
2605 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2607 MipsFI->setVarArgsFrameIndex(0);
2609 // Used with vargs to acumulate store chains.
2610 std::vector<SDValue> OutChains;
2612 // Assign locations to all of the incoming arguments.
2613 SmallVector<CCValAssign, 16> ArgLocs;
2614 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2615 getTargetMachine(), ArgLocs, *DAG.getContext());
2616 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2617 Function::const_arg_iterator FuncArg =
2618 DAG.getMachineFunction().getFunction()->arg_begin();
2619 bool UseSoftFloat = Subtarget->mipsSEUsesSoftFloat();
2621 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2622 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2623 MipsCCInfo.hasByValArg());
2625 unsigned CurArgIdx = 0;
2626 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2628 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2629 CCValAssign &VA = ArgLocs[i];
2630 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2631 CurArgIdx = Ins[i].OrigArgIndex;
2632 EVT ValVT = VA.getValVT();
2633 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2634 bool IsRegLoc = VA.isRegLoc();
2636 if (Flags.isByVal()) {
2637 assert(Flags.getByValSize() &&
2638 "ByVal args of size 0 should have been ignored by front-end.");
2639 assert(ByValArg != MipsCCInfo.byval_end());
2640 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2641 MipsCCInfo, *ByValArg);
2646 // Arguments stored on registers
2648 MVT RegVT = VA.getLocVT();
2649 unsigned ArgReg = VA.getLocReg();
2650 const TargetRegisterClass *RC = getRegClassFor(RegVT);
2652 // Transform the arguments stored on
2653 // physical registers into virtual ones
2654 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2655 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2657 // If this is an 8 or 16-bit value, it has been passed promoted
2658 // to 32 bits. Insert an assert[sz]ext to capture this, then
2659 // truncate to the right size.
2660 if (VA.getLocInfo() != CCValAssign::Full) {
2661 unsigned Opcode = 0;
2662 if (VA.getLocInfo() == CCValAssign::SExt)
2663 Opcode = ISD::AssertSext;
2664 else if (VA.getLocInfo() == CCValAssign::ZExt)
2665 Opcode = ISD::AssertZext;
2667 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2668 DAG.getValueType(ValVT));
2669 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2672 // Handle floating point arguments passed in integer registers and
2673 // long double arguments passed in floating point registers.
2674 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2675 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2676 (RegVT == MVT::f64 && ValVT == MVT::i64))
2677 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2678 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2679 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2680 getNextIntArgReg(ArgReg), RC);
2681 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2682 if (!Subtarget->isLittle())
2683 std::swap(ArgValue, ArgValue2);
2684 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2685 ArgValue, ArgValue2);
2688 InVals.push_back(ArgValue);
2689 } else { // VA.isRegLoc()
2692 assert(VA.isMemLoc());
2694 // The stack pointer offset is relative to the caller stack frame.
2695 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2696 VA.getLocMemOffset(), true);
2698 // Create load nodes to retrieve arguments from the stack
2699 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2700 SDValue Load = DAG.getLoad(ValVT, DL, Chain, FIN,
2701 MachinePointerInfo::getFixedStack(FI),
2702 false, false, false, 0);
2703 InVals.push_back(Load);
2704 OutChains.push_back(Load.getValue(1));
2708 // The mips ABIs for returning structs by value requires that we copy
2709 // the sret argument into $v0 for the return. Save the argument into
2710 // a virtual register so that we can access it from the return points.
2711 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2712 unsigned Reg = MipsFI->getSRetReturnReg();
2714 Reg = MF.getRegInfo().
2715 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2716 MipsFI->setSRetReturnReg(Reg);
2718 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2719 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2723 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2725 // All stores are grouped in one node to allow the matching between
2726 // the size of Ins and InVals. This only happens when on varg functions
2727 if (!OutChains.empty()) {
2728 OutChains.push_back(Chain);
2729 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2730 &OutChains[0], OutChains.size());
2736 //===----------------------------------------------------------------------===//
2737 // Return Value Calling Convention Implementation
2738 //===----------------------------------------------------------------------===//
2741 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2742 MachineFunction &MF, bool IsVarArg,
2743 const SmallVectorImpl<ISD::OutputArg> &Outs,
2744 LLVMContext &Context) const {
2745 SmallVector<CCValAssign, 16> RVLocs;
2746 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2748 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2752 MipsTargetLowering::LowerReturn(SDValue Chain,
2753 CallingConv::ID CallConv, bool IsVarArg,
2754 const SmallVectorImpl<ISD::OutputArg> &Outs,
2755 const SmallVectorImpl<SDValue> &OutVals,
2756 SDLoc DL, SelectionDAG &DAG) const {
2757 // CCValAssign - represent the assignment of
2758 // the return value to a location
2759 SmallVector<CCValAssign, 16> RVLocs;
2760 MachineFunction &MF = DAG.getMachineFunction();
2762 // CCState - Info about the registers and stack slot.
2763 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2765 MipsCC MipsCCInfo(CallConv, IsO32, Subtarget->isFP64bit(), CCInfo);
2767 // Analyze return values.
2768 MipsCCInfo.analyzeReturn(Outs, Subtarget->mipsSEUsesSoftFloat(),
2769 MF.getFunction()->getReturnType());
2772 SmallVector<SDValue, 4> RetOps(1, Chain);
2774 // Copy the result values into the output registers.
2775 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2776 SDValue Val = OutVals[i];
2777 CCValAssign &VA = RVLocs[i];
2778 assert(VA.isRegLoc() && "Can only return in registers!");
2780 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2781 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2783 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2785 // Guarantee that all emitted copies are stuck together with flags.
2786 Flag = Chain.getValue(1);
2787 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2790 // The mips ABIs for returning structs by value requires that we copy
2791 // the sret argument into $v0 for the return. We saved the argument into
2792 // a virtual register in the entry block, so now we copy the value out
2794 if (MF.getFunction()->hasStructRetAttr()) {
2795 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2796 unsigned Reg = MipsFI->getSRetReturnReg();
2799 llvm_unreachable("sret virtual register not created in the entry block");
2800 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2801 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2803 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2804 Flag = Chain.getValue(1);
2805 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2808 RetOps[0] = Chain; // Update chain.
2810 // Add the flag if we have it.
2812 RetOps.push_back(Flag);
2814 // Return on Mips is always a "jr $ra"
2815 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2818 //===----------------------------------------------------------------------===//
2819 // Mips Inline Assembly Support
2820 //===----------------------------------------------------------------------===//
2822 /// getConstraintType - Given a constraint letter, return the type of
2823 /// constraint it is for this target.
2824 MipsTargetLowering::ConstraintType MipsTargetLowering::
2825 getConstraintType(const std::string &Constraint) const
2827 // Mips specific constraints
2828 // GCC config/mips/constraints.md
2830 // 'd' : An address register. Equivalent to r
2831 // unless generating MIPS16 code.
2832 // 'y' : Equivalent to r; retained for
2833 // backwards compatibility.
2834 // 'c' : A register suitable for use in an indirect
2835 // jump. This will always be $25 for -mabicalls.
2836 // 'l' : The lo register. 1 word storage.
2837 // 'x' : The hilo register pair. Double word storage.
2838 if (Constraint.size() == 1) {
2839 switch (Constraint[0]) {
2847 return C_RegisterClass;
2852 return TargetLowering::getConstraintType(Constraint);
2855 /// Examine constraint type and operand type and determine a weight value.
2856 /// This object must already have been set up with the operand type
2857 /// and the current alternative constraint selected.
2858 TargetLowering::ConstraintWeight
2859 MipsTargetLowering::getSingleConstraintMatchWeight(
2860 AsmOperandInfo &info, const char *constraint) const {
2861 ConstraintWeight weight = CW_Invalid;
2862 Value *CallOperandVal = info.CallOperandVal;
2863 // If we don't have a value, we can't do a match,
2864 // but allow it at the lowest weight.
2865 if (CallOperandVal == NULL)
2867 Type *type = CallOperandVal->getType();
2868 // Look at the constraint type.
2869 switch (*constraint) {
2871 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2875 if (type->isIntegerTy())
2876 weight = CW_Register;
2878 case 'f': // FPU or MSA register
2879 if (Subtarget->hasMSA() && type->isVectorTy() &&
2880 cast<VectorType>(type)->getBitWidth() == 128)
2881 weight = CW_Register;
2882 else if (type->isFloatTy())
2883 weight = CW_Register;
2885 case 'c': // $25 for indirect jumps
2886 case 'l': // lo register
2887 case 'x': // hilo register pair
2888 if (type->isIntegerTy())
2889 weight = CW_SpecificReg;
2891 case 'I': // signed 16 bit immediate
2892 case 'J': // integer zero
2893 case 'K': // unsigned 16 bit immediate
2894 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2895 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2896 case 'O': // signed 15 bit immediate (+- 16383)
2897 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2898 if (isa<ConstantInt>(CallOperandVal))
2899 weight = CW_Constant;
2908 /// This is a helper function to parse a physical register string and split it
2909 /// into non-numeric and numeric parts (Prefix and Reg). The first boolean flag
2910 /// that is returned indicates whether parsing was successful. The second flag
2911 /// is true if the numeric part exists.
2912 static std::pair<bool, bool>
2913 parsePhysicalReg(const StringRef &C, std::string &Prefix,
2914 unsigned long long &Reg) {
2915 if (C.front() != '{' || C.back() != '}')
2916 return std::make_pair(false, false);
2918 // Search for the first numeric character.
2919 StringRef::const_iterator I, B = C.begin() + 1, E = C.end() - 1;
2920 I = std::find_if(B, E, std::ptr_fun(isdigit));
2922 Prefix.assign(B, I - B);
2924 // The second flag is set to false if no numeric characters were found.
2926 return std::make_pair(true, false);
2928 // Parse the numeric characters.
2929 return std::make_pair(!getAsUnsignedInteger(StringRef(I, E - I), 10, Reg),
2933 std::pair<unsigned, const TargetRegisterClass *> MipsTargetLowering::
2934 parseRegForInlineAsmConstraint(const StringRef &C, MVT VT) const {
2935 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2936 const TargetRegisterClass *RC;
2938 unsigned long long Reg;
2940 std::pair<bool, bool> R = parsePhysicalReg(C, Prefix, Reg);
2943 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2945 if ((Prefix == "hi" || Prefix == "lo")) { // Parse hi/lo.
2946 // No numeric characters follow "hi" or "lo".
2948 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2950 RC = TRI->getRegClass(Prefix == "hi" ?
2951 Mips::HI32RegClassID : Mips::LO32RegClassID);
2952 return std::make_pair(*(RC->begin()), RC);
2953 } else if (Prefix.compare(0, 4, "$msa") == 0) {
2954 // Parse $msa(ir|csr|access|save|modify|request|map|unmap)
2956 // No numeric characters follow the name.
2958 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2960 Reg = StringSwitch<unsigned long long>(Prefix)
2961 .Case("$msair", Mips::MSAIR)
2962 .Case("$msacsr", Mips::MSACSR)
2963 .Case("$msaaccess", Mips::MSAAccess)
2964 .Case("$msasave", Mips::MSASave)
2965 .Case("$msamodify", Mips::MSAModify)
2966 .Case("$msarequest", Mips::MSARequest)
2967 .Case("$msamap", Mips::MSAMap)
2968 .Case("$msaunmap", Mips::MSAUnmap)
2972 return std::make_pair((unsigned)0, (const TargetRegisterClass *)0);
2974 RC = TRI->getRegClass(Mips::MSACtrlRegClassID);
2975 return std::make_pair(Reg, RC);
2979 return std::make_pair((unsigned)0, (const TargetRegisterClass*)0);
2981 if (Prefix == "$f") { // Parse $f0-$f31.
2982 // If the size of FP registers is 64-bit or Reg is an even number, select
2983 // the 64-bit register class. Otherwise, select the 32-bit register class.
2984 if (VT == MVT::Other)
2985 VT = (Subtarget->isFP64bit() || !(Reg % 2)) ? MVT::f64 : MVT::f32;
2987 RC = getRegClassFor(VT);
2989 if (RC == &Mips::AFGR64RegClass) {
2990 assert(Reg % 2 == 0);
2993 } else if (Prefix == "$fcc") // Parse $fcc0-$fcc7.
2994 RC = TRI->getRegClass(Mips::FCCRegClassID);
2995 else if (Prefix == "$w") { // Parse $w0-$w31.
2996 RC = getRegClassFor((VT == MVT::Other) ? MVT::v16i8 : VT);
2997 } else { // Parse $0-$31.
2998 assert(Prefix == "$");
2999 RC = getRegClassFor((VT == MVT::Other) ? MVT::i32 : VT);
3002 assert(Reg < RC->getNumRegs());
3003 return std::make_pair(*(RC->begin() + Reg), RC);
3006 /// Given a register class constraint, like 'r', if this corresponds directly
3007 /// to an LLVM register class, return a register of 0 and the register class
3009 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3010 getRegForInlineAsmConstraint(const std::string &Constraint, MVT VT) const
3012 if (Constraint.size() == 1) {
3013 switch (Constraint[0]) {
3014 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3015 case 'y': // Same as 'r'. Exists for compatibility.
3017 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
3018 if (Subtarget->inMips16Mode())
3019 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
3020 return std::make_pair(0U, &Mips::GPR32RegClass);
3022 if (VT == MVT::i64 && !HasMips64)
3023 return std::make_pair(0U, &Mips::GPR32RegClass);
3024 if (VT == MVT::i64 && HasMips64)
3025 return std::make_pair(0U, &Mips::GPR64RegClass);
3026 // This will generate an error message
3027 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3028 case 'f': // FPU or MSA register
3029 if (VT == MVT::v16i8)
3030 return std::make_pair(0U, &Mips::MSA128BRegClass);
3031 else if (VT == MVT::v8i16 || VT == MVT::v8f16)
3032 return std::make_pair(0U, &Mips::MSA128HRegClass);
3033 else if (VT == MVT::v4i32 || VT == MVT::v4f32)
3034 return std::make_pair(0U, &Mips::MSA128WRegClass);
3035 else if (VT == MVT::v2i64 || VT == MVT::v2f64)
3036 return std::make_pair(0U, &Mips::MSA128DRegClass);
3037 else if (VT == MVT::f32)
3038 return std::make_pair(0U, &Mips::FGR32RegClass);
3039 else if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3040 if (Subtarget->isFP64bit())
3041 return std::make_pair(0U, &Mips::FGR64RegClass);
3042 return std::make_pair(0U, &Mips::AFGR64RegClass);
3045 case 'c': // register suitable for indirect jump
3047 return std::make_pair((unsigned)Mips::T9, &Mips::GPR32RegClass);
3048 assert(VT == MVT::i64 && "Unexpected type.");
3049 return std::make_pair((unsigned)Mips::T9_64, &Mips::GPR64RegClass);
3050 case 'l': // register suitable for indirect jump
3052 return std::make_pair((unsigned)Mips::LO0, &Mips::LO32RegClass);
3053 return std::make_pair((unsigned)Mips::LO0_64, &Mips::LO64RegClass);
3054 case 'x': // register suitable for indirect jump
3055 // Fixme: Not triggering the use of both hi and low
3056 // This will generate an error message
3057 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3061 std::pair<unsigned, const TargetRegisterClass *> R;
3062 R = parseRegForInlineAsmConstraint(Constraint, VT);
3067 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3070 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3071 /// vector. If it is invalid, don't add anything to Ops.
3072 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3073 std::string &Constraint,
3074 std::vector<SDValue>&Ops,
3075 SelectionDAG &DAG) const {
3076 SDValue Result(0, 0);
3078 // Only support length 1 constraints for now.
3079 if (Constraint.length() > 1) return;
3081 char ConstraintLetter = Constraint[0];
3082 switch (ConstraintLetter) {
3083 default: break; // This will fall through to the generic implementation
3084 case 'I': // Signed 16 bit constant
3085 // If this fails, the parent routine will give an error
3086 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3087 EVT Type = Op.getValueType();
3088 int64_t Val = C->getSExtValue();
3089 if (isInt<16>(Val)) {
3090 Result = DAG.getTargetConstant(Val, Type);
3095 case 'J': // integer zero
3096 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3097 EVT Type = Op.getValueType();
3098 int64_t Val = C->getZExtValue();
3100 Result = DAG.getTargetConstant(0, Type);
3105 case 'K': // unsigned 16 bit immediate
3106 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3107 EVT Type = Op.getValueType();
3108 uint64_t Val = (uint64_t)C->getZExtValue();
3109 if (isUInt<16>(Val)) {
3110 Result = DAG.getTargetConstant(Val, Type);
3115 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3116 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3117 EVT Type = Op.getValueType();
3118 int64_t Val = C->getSExtValue();
3119 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3120 Result = DAG.getTargetConstant(Val, Type);
3125 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3126 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3127 EVT Type = Op.getValueType();
3128 int64_t Val = C->getSExtValue();
3129 if ((Val >= -65535) && (Val <= -1)) {
3130 Result = DAG.getTargetConstant(Val, Type);
3135 case 'O': // signed 15 bit immediate
3136 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3137 EVT Type = Op.getValueType();
3138 int64_t Val = C->getSExtValue();
3139 if ((isInt<15>(Val))) {
3140 Result = DAG.getTargetConstant(Val, Type);
3145 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3146 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3147 EVT Type = Op.getValueType();
3148 int64_t Val = C->getSExtValue();
3149 if ((Val <= 65535) && (Val >= 1)) {
3150 Result = DAG.getTargetConstant(Val, Type);
3157 if (Result.getNode()) {
3158 Ops.push_back(Result);
3162 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3165 bool MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM,
3167 // No global is ever allowed as a base.
3172 case 0: // "r+i" or just "i", depending on HasBaseReg.
3175 if (!AM.HasBaseReg) // allow "r+i".
3177 return false; // disallow "r+r" or "r+r+i".
3186 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3187 // The Mips target isn't yet aware of offsets.
3191 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3193 bool IsMemset, bool ZeroMemset,
3195 MachineFunction &MF) const {
3196 if (Subtarget->hasMips64())
3202 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3203 if (VT != MVT::f32 && VT != MVT::f64)
3205 if (Imm.isNegZero())
3207 return Imm.isZero();
3210 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3212 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3214 return TargetLowering::getJumpTableEncoding();
3217 /// This function returns true if CallSym is a long double emulation routine.
3218 static bool isF128SoftLibCall(const char *CallSym) {
3219 const char *const LibCalls[] =
3220 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
3221 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
3222 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
3223 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3224 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3225 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3226 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3227 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3230 const char *const *End = LibCalls + array_lengthof(LibCalls);
3232 // Check that LibCalls is sorted alphabetically.
3233 MipsTargetLowering::LTStr Comp;
3236 for (const char *const *I = LibCalls; I < End - 1; ++I)
3237 assert(Comp(*I, *(I + 1)));
3240 return std::binary_search(LibCalls, End, CallSym, Comp);
3243 /// This function returns true if Ty is fp128 or i128 which was originally a
3245 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3246 if (Ty->isFP128Ty())
3249 const ExternalSymbolSDNode *ES =
3250 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3252 // If the Ty is i128 and the function being called is a long double emulation
3253 // routine, then the original type is f128.
3254 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3257 MipsTargetLowering::MipsCC::SpecialCallingConvType
3258 MipsTargetLowering::getSpecialCallingConv(SDValue Callee) const {
3259 MipsCC::SpecialCallingConvType SpecialCallingConv =
3260 MipsCC::NoSpecialCallingConv;;
3261 if (Subtarget->inMips16HardFloat()) {
3262 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
3263 llvm::StringRef Sym = G->getGlobal()->getName();
3264 Function *F = G->getGlobal()->getParent()->getFunction(Sym);
3265 if (F->hasFnAttribute("__Mips16RetHelper")) {
3266 SpecialCallingConv = MipsCC::Mips16RetHelperConv;
3270 return SpecialCallingConv;
3273 MipsTargetLowering::MipsCC::MipsCC(
3274 CallingConv::ID CC, bool IsO32_, bool IsFP64_, CCState &Info,
3275 MipsCC::SpecialCallingConvType SpecialCallingConv_)
3276 : CCInfo(Info), CallConv(CC), IsO32(IsO32_), IsFP64(IsFP64_),
3277 SpecialCallingConv(SpecialCallingConv_){
3278 // Pre-allocate reserved argument area.
3279 CCInfo.AllocateStack(reservedArgArea(), 1);
3283 void MipsTargetLowering::MipsCC::
3284 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3285 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3286 std::vector<ArgListEntry> &FuncArgs) {
3287 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3288 "CallingConv::Fast shouldn't be used for vararg functions.");
3290 unsigned NumOpnds = Args.size();
3291 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3293 for (unsigned I = 0; I != NumOpnds; ++I) {
3294 MVT ArgVT = Args[I].VT;
3295 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3298 if (ArgFlags.isByVal()) {
3299 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3303 if (IsVarArg && !Args[I].IsFixed)
3304 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3306 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3308 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3313 dbgs() << "Call operand #" << I << " has unhandled type "
3314 << EVT(ArgVT).getEVTString();
3316 llvm_unreachable(0);
3321 void MipsTargetLowering::MipsCC::
3322 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3323 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3324 unsigned NumArgs = Args.size();
3325 llvm::CCAssignFn *FixedFn = fixedArgFn();
3326 unsigned CurArgIdx = 0;
3328 for (unsigned I = 0; I != NumArgs; ++I) {
3329 MVT ArgVT = Args[I].VT;
3330 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3331 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3332 CurArgIdx = Args[I].OrigArgIndex;
3334 if (ArgFlags.isByVal()) {
3335 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3339 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3341 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3345 dbgs() << "Formal Arg #" << I << " has unhandled type "
3346 << EVT(ArgVT).getEVTString();
3348 llvm_unreachable(0);
3352 template<typename Ty>
3353 void MipsTargetLowering::MipsCC::
3354 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3355 const SDNode *CallNode, const Type *RetTy) const {
3358 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3359 Fn = RetCC_F128Soft;
3363 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3364 MVT VT = RetVals[I].VT;
3365 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3366 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3368 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3370 dbgs() << "Call result #" << I << " has unhandled type "
3371 << EVT(VT).getEVTString() << '\n';
3373 llvm_unreachable(0);
3378 void MipsTargetLowering::MipsCC::
3379 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3380 const SDNode *CallNode, const Type *RetTy) const {
3381 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3384 void MipsTargetLowering::MipsCC::
3385 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3386 const Type *RetTy) const {
3387 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3390 void MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3392 CCValAssign::LocInfo LocInfo,
3393 ISD::ArgFlagsTy ArgFlags) {
3394 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3396 struct ByValArgInfo ByVal;
3397 unsigned RegSize = regSize();
3398 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3399 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3402 if (useRegsForByval())
3403 allocateRegs(ByVal, ByValSize, Align);
3405 // Allocate space on caller's stack.
3406 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3408 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3410 ByValArgs.push_back(ByVal);
3413 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3414 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3417 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3418 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3421 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3422 return IsO32 ? O32IntRegs : Mips64IntRegs;
3425 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3426 if (CallConv == CallingConv::Fast)
3427 return CC_Mips_FastCC;
3429 if (SpecialCallingConv == Mips16RetHelperConv)
3430 return CC_Mips16RetHelper;
3431 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN;
3434 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3435 return IsO32 ? (IsFP64 ? CC_MipsO32_FP64 : CC_MipsO32_FP32) : CC_MipsN_VarArg;
3438 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3439 return IsO32 ? O32IntRegs : Mips64DPRegs;
3442 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3445 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3446 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3447 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3448 "Byval argument's size and alignment should be a multiple of"
3451 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3453 // If Align > RegSize, the first arg register must be even.
3454 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3455 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3459 // Mark the registers allocated.
3460 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3461 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3462 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3465 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3466 const SDNode *CallNode,
3467 bool IsSoftFloat) const {
3468 if (IsSoftFloat || IsO32)
3471 // Check if the original type was fp128.
3472 if (originalTypeIsF128(OrigTy, CallNode)) {
3473 assert(VT == MVT::i64);
3480 void MipsTargetLowering::
3481 copyByValRegs(SDValue Chain, SDLoc DL, std::vector<SDValue> &OutChains,
3482 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3483 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3484 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3485 MachineFunction &MF = DAG.getMachineFunction();
3486 MachineFrameInfo *MFI = MF.getFrameInfo();
3487 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3488 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3492 FrameObjOffset = (int)CC.reservedArgArea() -
3493 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3495 FrameObjOffset = ByVal.Address;
3497 // Create frame object.
3498 EVT PtrTy = getPointerTy();
3499 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3500 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3501 InVals.push_back(FIN);
3506 // Copy arg registers.
3507 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3508 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3510 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3511 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3512 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3513 unsigned Offset = I * CC.regSize();
3514 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3515 DAG.getConstant(Offset, PtrTy));
3516 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3517 StorePtr, MachinePointerInfo(FuncArg, Offset),
3519 OutChains.push_back(Store);
3523 // Copy byVal arg to registers and stack.
3524 void MipsTargetLowering::
3525 passByValArg(SDValue Chain, SDLoc DL,
3526 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3527 SmallVectorImpl<SDValue> &MemOpChains, SDValue StackPtr,
3528 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3529 const MipsCC &CC, const ByValArgInfo &ByVal,
3530 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3531 unsigned ByValSize = Flags.getByValSize();
3532 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3533 unsigned RegSize = CC.regSize();
3534 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3535 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3537 if (ByVal.NumRegs) {
3538 const uint16_t *ArgRegs = CC.intArgRegs();
3539 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3542 // Copy words to registers.
3543 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3544 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3545 DAG.getConstant(Offset, PtrTy));
3546 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3547 MachinePointerInfo(), false, false, false,
3549 MemOpChains.push_back(LoadVal.getValue(1));
3550 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3551 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3554 // Return if the struct has been fully copied.
3555 if (ByValSize == Offset)
3558 // Copy the remainder of the byval argument with sub-word loads and shifts.
3559 if (LeftoverBytes) {
3560 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3561 "Size of the remainder should be smaller than RegSize.");
3564 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3565 Offset < ByValSize; LoadSize /= 2) {
3566 unsigned RemSize = ByValSize - Offset;
3568 if (RemSize < LoadSize)
3572 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3573 DAG.getConstant(Offset, PtrTy));
3575 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3576 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3577 false, false, Alignment);
3578 MemOpChains.push_back(LoadVal.getValue(1));
3580 // Shift the loaded value.
3584 Shamt = TotalSizeLoaded;
3586 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3588 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3589 DAG.getConstant(Shamt, MVT::i32));
3592 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3597 TotalSizeLoaded += LoadSize;
3598 Alignment = std::min(Alignment, LoadSize);
3601 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3602 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3607 // Copy remainder of byval arg to it with memcpy.
3608 unsigned MemCpySize = ByValSize - Offset;
3609 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3610 DAG.getConstant(Offset, PtrTy));
3611 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3612 DAG.getIntPtrConstant(ByVal.Address));
3613 Chain = DAG.getMemcpy(Chain, DL, Dst, Src, DAG.getConstant(MemCpySize, PtrTy),
3614 Alignment, /*isVolatile=*/false, /*AlwaysInline=*/false,
3615 MachinePointerInfo(0), MachinePointerInfo(0));
3616 MemOpChains.push_back(Chain);
3619 void MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3620 const MipsCC &CC, SDValue Chain,
3621 SDLoc DL, SelectionDAG &DAG) const {
3622 unsigned NumRegs = CC.numIntArgRegs();
3623 const uint16_t *ArgRegs = CC.intArgRegs();
3624 const CCState &CCInfo = CC.getCCInfo();
3625 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3626 unsigned RegSize = CC.regSize();
3627 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3628 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3629 MachineFunction &MF = DAG.getMachineFunction();
3630 MachineFrameInfo *MFI = MF.getFrameInfo();
3631 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3633 // Offset of the first variable argument from stack pointer.
3637 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3639 VaArgOffset = (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3641 // Record the frame index of the first variable argument
3642 // which is a value necessary to VASTART.
3643 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3644 MipsFI->setVarArgsFrameIndex(FI);
3646 // Copy the integer registers that have not been used for argument passing
3647 // to the argument register save area. For O32, the save area is allocated
3648 // in the caller's stack frame, while for N32/64, it is allocated in the
3649 // callee's stack frame.
3650 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3651 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3652 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3653 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3654 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3655 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3656 MachinePointerInfo(), false, false, 0);
3657 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3658 OutChains.push_back(Store);