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/CodeGen/CallingConvLower.h"
24 #include "llvm/CodeGen/MachineFrameInfo.h"
25 #include "llvm/CodeGen/MachineFunction.h"
26 #include "llvm/CodeGen/MachineInstrBuilder.h"
27 #include "llvm/CodeGen/MachineRegisterInfo.h"
28 #include "llvm/CodeGen/SelectionDAGISel.h"
29 #include "llvm/CodeGen/ValueTypes.h"
30 #include "llvm/IR/CallingConv.h"
31 #include "llvm/IR/DerivedTypes.h"
32 #include "llvm/IR/GlobalVariable.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/ErrorHandling.h"
36 #include "llvm/Support/raw_ostream.h"
40 STATISTIC(NumTailCalls, "Number of tail calls");
43 LargeGOT("mxgot", cl::Hidden,
44 cl::desc("MIPS: Enable GOT larger than 64k."), cl::init(false));
46 static const uint16_t O32IntRegs[4] = {
47 Mips::A0, Mips::A1, Mips::A2, Mips::A3
50 static const uint16_t Mips64IntRegs[8] = {
51 Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
52 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64
55 static const uint16_t Mips64DPRegs[8] = {
56 Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
57 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64
60 // If I is a shifted mask, set the size (Size) and the first bit of the
61 // mask (Pos), and return true.
62 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
63 static bool isShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
64 if (!isShiftedMask_64(I))
67 Size = CountPopulation_64(I);
68 Pos = CountTrailingZeros_64(I);
72 SDValue MipsTargetLowering::getGlobalReg(SelectionDAG &DAG, EVT Ty) const {
73 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
74 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
77 static SDValue getTargetNode(SDValue Op, SelectionDAG &DAG, unsigned Flag) {
78 EVT Ty = Op.getValueType();
80 if (GlobalAddressSDNode *N = dyn_cast<GlobalAddressSDNode>(Op))
81 return DAG.getTargetGlobalAddress(N->getGlobal(), Op.getDebugLoc(), Ty, 0,
83 if (ExternalSymbolSDNode *N = dyn_cast<ExternalSymbolSDNode>(Op))
84 return DAG.getTargetExternalSymbol(N->getSymbol(), Ty, Flag);
85 if (BlockAddressSDNode *N = dyn_cast<BlockAddressSDNode>(Op))
86 return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
87 if (JumpTableSDNode *N = dyn_cast<JumpTableSDNode>(Op))
88 return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
89 if (ConstantPoolSDNode *N = dyn_cast<ConstantPoolSDNode>(Op))
90 return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlignment(),
91 N->getOffset(), Flag);
93 llvm_unreachable("Unexpected node type.");
97 static SDValue getAddrNonPIC(SDValue Op, SelectionDAG &DAG) {
98 DebugLoc DL = Op.getDebugLoc();
99 EVT Ty = Op.getValueType();
100 SDValue Hi = getTargetNode(Op, DAG, MipsII::MO_ABS_HI);
101 SDValue Lo = getTargetNode(Op, DAG, MipsII::MO_ABS_LO);
102 return DAG.getNode(ISD::ADD, DL, Ty,
103 DAG.getNode(MipsISD::Hi, DL, Ty, Hi),
104 DAG.getNode(MipsISD::Lo, DL, Ty, Lo));
107 SDValue MipsTargetLowering::getAddrLocal(SDValue Op, SelectionDAG &DAG,
108 bool HasMips64) const {
109 DebugLoc DL = Op.getDebugLoc();
110 EVT Ty = Op.getValueType();
111 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
112 SDValue GOT = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
113 getTargetNode(Op, DAG, GOTFlag));
114 SDValue Load = DAG.getLoad(Ty, DL, DAG.getEntryNode(), GOT,
115 MachinePointerInfo::getGOT(), false, false, false,
117 unsigned LoFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
118 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, Ty, getTargetNode(Op, DAG, LoFlag));
119 return DAG.getNode(ISD::ADD, DL, Ty, Load, Lo);
122 SDValue MipsTargetLowering::getAddrGlobal(SDValue Op, SelectionDAG &DAG,
123 unsigned Flag) const {
124 DebugLoc DL = Op.getDebugLoc();
125 EVT Ty = Op.getValueType();
126 SDValue Tgt = DAG.getNode(MipsISD::Wrapper, DL, Ty, getGlobalReg(DAG, Ty),
127 getTargetNode(Op, DAG, Flag));
128 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Tgt,
129 MachinePointerInfo::getGOT(), false, false, false, 0);
132 SDValue MipsTargetLowering::getAddrGlobalLargeGOT(SDValue Op, SelectionDAG &DAG,
134 unsigned LoFlag) const {
135 DebugLoc DL = Op.getDebugLoc();
136 EVT Ty = Op.getValueType();
137 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, Ty, getTargetNode(Op, DAG, HiFlag));
138 Hi = DAG.getNode(ISD::ADD, DL, Ty, Hi, getGlobalReg(DAG, Ty));
139 SDValue Wrapper = DAG.getNode(MipsISD::Wrapper, DL, Ty, Hi,
140 getTargetNode(Op, DAG, LoFlag));
141 return DAG.getLoad(Ty, DL, DAG.getEntryNode(), Wrapper,
142 MachinePointerInfo::getGOT(), false, false, false, 0);
145 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
147 case MipsISD::JmpLink: return "MipsISD::JmpLink";
148 case MipsISD::TailCall: return "MipsISD::TailCall";
149 case MipsISD::Hi: return "MipsISD::Hi";
150 case MipsISD::Lo: return "MipsISD::Lo";
151 case MipsISD::GPRel: return "MipsISD::GPRel";
152 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
153 case MipsISD::Ret: return "MipsISD::Ret";
154 case MipsISD::EH_RETURN: return "MipsISD::EH_RETURN";
155 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
156 case MipsISD::FPCmp: return "MipsISD::FPCmp";
157 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
158 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
159 case MipsISD::FPRound: return "MipsISD::FPRound";
160 case MipsISD::ExtractLOHI: return "MipsISD::ExtractLOHI";
161 case MipsISD::InsertLOHI: return "MipsISD::InsertLOHI";
162 case MipsISD::Mult: return "MipsISD::Mult";
163 case MipsISD::Multu: return "MipsISD::Multu";
164 case MipsISD::MAdd: return "MipsISD::MAdd";
165 case MipsISD::MAddu: return "MipsISD::MAddu";
166 case MipsISD::MSub: return "MipsISD::MSub";
167 case MipsISD::MSubu: return "MipsISD::MSubu";
168 case MipsISD::DivRem: return "MipsISD::DivRem";
169 case MipsISD::DivRemU: return "MipsISD::DivRemU";
170 case MipsISD::DivRem16: return "MipsISD::DivRem16";
171 case MipsISD::DivRemU16: return "MipsISD::DivRemU16";
172 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
173 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
174 case MipsISD::Wrapper: return "MipsISD::Wrapper";
175 case MipsISD::Sync: return "MipsISD::Sync";
176 case MipsISD::Ext: return "MipsISD::Ext";
177 case MipsISD::Ins: return "MipsISD::Ins";
178 case MipsISD::LWL: return "MipsISD::LWL";
179 case MipsISD::LWR: return "MipsISD::LWR";
180 case MipsISD::SWL: return "MipsISD::SWL";
181 case MipsISD::SWR: return "MipsISD::SWR";
182 case MipsISD::LDL: return "MipsISD::LDL";
183 case MipsISD::LDR: return "MipsISD::LDR";
184 case MipsISD::SDL: return "MipsISD::SDL";
185 case MipsISD::SDR: return "MipsISD::SDR";
186 case MipsISD::EXTP: return "MipsISD::EXTP";
187 case MipsISD::EXTPDP: return "MipsISD::EXTPDP";
188 case MipsISD::EXTR_S_H: return "MipsISD::EXTR_S_H";
189 case MipsISD::EXTR_W: return "MipsISD::EXTR_W";
190 case MipsISD::EXTR_R_W: return "MipsISD::EXTR_R_W";
191 case MipsISD::EXTR_RS_W: return "MipsISD::EXTR_RS_W";
192 case MipsISD::SHILO: return "MipsISD::SHILO";
193 case MipsISD::MTHLIP: return "MipsISD::MTHLIP";
194 case MipsISD::MULT: return "MipsISD::MULT";
195 case MipsISD::MULTU: return "MipsISD::MULTU";
196 case MipsISD::MADD_DSP: return "MipsISD::MADD_DSP";
197 case MipsISD::MADDU_DSP: return "MipsISD::MADDU_DSP";
198 case MipsISD::MSUB_DSP: return "MipsISD::MSUB_DSP";
199 case MipsISD::MSUBU_DSP: return "MipsISD::MSUBU_DSP";
200 case MipsISD::SHLL_DSP: return "MipsISD::SHLL_DSP";
201 case MipsISD::SHRA_DSP: return "MipsISD::SHRA_DSP";
202 case MipsISD::SHRL_DSP: return "MipsISD::SHRL_DSP";
203 default: return NULL;
208 MipsTargetLowering(MipsTargetMachine &TM)
209 : TargetLowering(TM, new MipsTargetObjectFile()),
210 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
211 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
212 IsO32(Subtarget->isABI_O32()) {
213 // Mips does not have i1 type, so use i32 for
214 // setcc operations results (slt, sgt, ...).
215 setBooleanContents(ZeroOrOneBooleanContent);
216 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
218 // Load extented operations for i1 types must be promoted
219 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
220 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
221 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
223 // MIPS doesn't have extending float->double load/store
224 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
225 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
227 // Used by legalize types to correctly generate the setcc result.
228 // Without this, every float setcc comes with a AND/OR with the result,
229 // we don't want this, since the fpcmp result goes to a flag register,
230 // which is used implicitly by brcond and select operations.
231 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
233 // Mips Custom Operations
234 setOperationAction(ISD::BR_JT, MVT::Other, Custom);
235 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
236 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
237 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
238 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
239 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
240 setOperationAction(ISD::SELECT, MVT::f32, Custom);
241 setOperationAction(ISD::SELECT, MVT::f64, Custom);
242 setOperationAction(ISD::SELECT, MVT::i32, Custom);
243 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
244 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
245 setOperationAction(ISD::SETCC, MVT::f32, Custom);
246 setOperationAction(ISD::SETCC, MVT::f64, Custom);
247 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
248 setOperationAction(ISD::VASTART, MVT::Other, Custom);
249 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
250 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
252 if (!TM.Options.NoNaNsFPMath) {
253 setOperationAction(ISD::FABS, MVT::f32, Custom);
254 setOperationAction(ISD::FABS, MVT::f64, Custom);
258 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
259 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
260 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
261 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
262 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
263 setOperationAction(ISD::SELECT, MVT::i64, Custom);
264 setOperationAction(ISD::LOAD, MVT::i64, Custom);
265 setOperationAction(ISD::STORE, MVT::i64, Custom);
269 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
270 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
271 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
274 setOperationAction(ISD::ADD, MVT::i32, Custom);
276 setOperationAction(ISD::ADD, MVT::i64, Custom);
278 setOperationAction(ISD::SDIV, MVT::i32, Expand);
279 setOperationAction(ISD::SREM, MVT::i32, Expand);
280 setOperationAction(ISD::UDIV, MVT::i32, Expand);
281 setOperationAction(ISD::UREM, MVT::i32, Expand);
282 setOperationAction(ISD::SDIV, MVT::i64, Expand);
283 setOperationAction(ISD::SREM, MVT::i64, Expand);
284 setOperationAction(ISD::UDIV, MVT::i64, Expand);
285 setOperationAction(ISD::UREM, MVT::i64, Expand);
287 // Operations not directly supported by Mips.
288 setOperationAction(ISD::BR_CC, MVT::f32, Expand);
289 setOperationAction(ISD::BR_CC, MVT::f64, Expand);
290 setOperationAction(ISD::BR_CC, MVT::i32, Expand);
291 setOperationAction(ISD::BR_CC, MVT::i64, Expand);
292 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
293 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
294 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
295 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
296 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
297 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
298 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
299 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
300 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
301 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
302 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
303 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
304 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
305 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
306 setOperationAction(ISD::ROTL, MVT::i32, Expand);
307 setOperationAction(ISD::ROTL, MVT::i64, Expand);
308 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Expand);
309 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
311 if (!Subtarget->hasMips32r2())
312 setOperationAction(ISD::ROTR, MVT::i32, Expand);
314 if (!Subtarget->hasMips64r2())
315 setOperationAction(ISD::ROTR, MVT::i64, Expand);
317 setOperationAction(ISD::FSIN, MVT::f32, Expand);
318 setOperationAction(ISD::FSIN, MVT::f64, Expand);
319 setOperationAction(ISD::FCOS, MVT::f32, Expand);
320 setOperationAction(ISD::FCOS, MVT::f64, Expand);
321 setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
322 setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
323 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
324 setOperationAction(ISD::FPOW, MVT::f32, Expand);
325 setOperationAction(ISD::FPOW, MVT::f64, Expand);
326 setOperationAction(ISD::FLOG, MVT::f32, Expand);
327 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
328 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
329 setOperationAction(ISD::FEXP, MVT::f32, Expand);
330 setOperationAction(ISD::FMA, MVT::f32, Expand);
331 setOperationAction(ISD::FMA, MVT::f64, Expand);
332 setOperationAction(ISD::FREM, MVT::f32, Expand);
333 setOperationAction(ISD::FREM, MVT::f64, Expand);
335 if (!TM.Options.NoNaNsFPMath) {
336 setOperationAction(ISD::FNEG, MVT::f32, Expand);
337 setOperationAction(ISD::FNEG, MVT::f64, Expand);
340 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
341 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
342 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
343 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
345 setOperationAction(ISD::EH_RETURN, MVT::Other, Custom);
347 setOperationAction(ISD::VAARG, MVT::Other, Expand);
348 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
349 setOperationAction(ISD::VAEND, MVT::Other, Expand);
351 // Use the default for now
352 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
353 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
355 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
356 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
357 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
358 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
360 setInsertFencesForAtomic(true);
362 if (!Subtarget->hasSEInReg()) {
363 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
364 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
367 if (!Subtarget->hasBitCount()) {
368 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
369 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
372 if (!Subtarget->hasSwap()) {
373 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
374 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
378 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
379 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
380 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
381 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
384 setTargetDAGCombine(ISD::SDIVREM);
385 setTargetDAGCombine(ISD::UDIVREM);
386 setTargetDAGCombine(ISD::SELECT);
387 setTargetDAGCombine(ISD::AND);
388 setTargetDAGCombine(ISD::OR);
389 setTargetDAGCombine(ISD::ADD);
391 setMinFunctionAlignment(HasMips64 ? 3 : 2);
393 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
395 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
396 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
398 MaxStoresPerMemcpy = 16;
401 const MipsTargetLowering *MipsTargetLowering::create(MipsTargetMachine &TM) {
402 if (TM.getSubtargetImpl()->inMips16Mode())
403 return llvm::createMips16TargetLowering(TM);
405 return llvm::createMipsSETargetLowering(TM);
408 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
411 return VT.changeVectorElementTypeToInteger();
414 static SDValue performDivRemCombine(SDNode *N, SelectionDAG &DAG,
415 TargetLowering::DAGCombinerInfo &DCI,
416 const MipsSubtarget *Subtarget) {
417 if (DCI.isBeforeLegalizeOps())
420 EVT Ty = N->getValueType(0);
421 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
422 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
423 unsigned Opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem16 :
425 DebugLoc DL = N->getDebugLoc();
427 SDValue DivRem = DAG.getNode(Opc, DL, MVT::Glue,
428 N->getOperand(0), N->getOperand(1));
429 SDValue InChain = DAG.getEntryNode();
430 SDValue InGlue = DivRem;
433 if (N->hasAnyUseOfValue(0)) {
434 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, DL, LO, Ty,
436 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
437 InChain = CopyFromLo.getValue(1);
438 InGlue = CopyFromLo.getValue(2);
442 if (N->hasAnyUseOfValue(1)) {
443 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, DL,
445 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
451 static Mips::CondCode condCodeToFCC(ISD::CondCode CC) {
453 default: llvm_unreachable("Unknown fp condition code!");
455 case ISD::SETOEQ: return Mips::FCOND_OEQ;
456 case ISD::SETUNE: return Mips::FCOND_UNE;
458 case ISD::SETOLT: return Mips::FCOND_OLT;
460 case ISD::SETOGT: return Mips::FCOND_OGT;
462 case ISD::SETOLE: return Mips::FCOND_OLE;
464 case ISD::SETOGE: return Mips::FCOND_OGE;
465 case ISD::SETULT: return Mips::FCOND_ULT;
466 case ISD::SETULE: return Mips::FCOND_ULE;
467 case ISD::SETUGT: return Mips::FCOND_UGT;
468 case ISD::SETUGE: return Mips::FCOND_UGE;
469 case ISD::SETUO: return Mips::FCOND_UN;
470 case ISD::SETO: return Mips::FCOND_OR;
472 case ISD::SETONE: return Mips::FCOND_ONE;
473 case ISD::SETUEQ: return Mips::FCOND_UEQ;
478 /// This function returns true if the floating point conditional branches and
479 /// conditional moves which use condition code CC should be inverted.
480 static bool invertFPCondCodeUser(Mips::CondCode CC) {
481 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
484 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
485 "Illegal Condition Code");
490 // Creates and returns an FPCmp node from a setcc node.
491 // Returns Op if setcc is not a floating point comparison.
492 static SDValue createFPCmp(SelectionDAG &DAG, const SDValue &Op) {
493 // must be a SETCC node
494 if (Op.getOpcode() != ISD::SETCC)
497 SDValue LHS = Op.getOperand(0);
499 if (!LHS.getValueType().isFloatingPoint())
502 SDValue RHS = Op.getOperand(1);
503 DebugLoc DL = Op.getDebugLoc();
505 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
506 // node if necessary.
507 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
509 return DAG.getNode(MipsISD::FPCmp, DL, MVT::Glue, LHS, RHS,
510 DAG.getConstant(condCodeToFCC(CC), MVT::i32));
513 // Creates and returns a CMovFPT/F node.
514 static SDValue createCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
515 SDValue False, DebugLoc DL) {
516 ConstantSDNode *CC = cast<ConstantSDNode>(Cond.getOperand(2));
517 bool invert = invertFPCondCodeUser((Mips::CondCode)CC->getSExtValue());
519 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
520 True.getValueType(), True, False, Cond);
523 static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
524 TargetLowering::DAGCombinerInfo &DCI,
525 const MipsSubtarget *Subtarget) {
526 if (DCI.isBeforeLegalizeOps())
529 SDValue SetCC = N->getOperand(0);
531 if ((SetCC.getOpcode() != ISD::SETCC) ||
532 !SetCC.getOperand(0).getValueType().isInteger())
535 SDValue False = N->getOperand(2);
536 EVT FalseTy = False.getValueType();
538 if (!FalseTy.isInteger())
541 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
543 if (!CN || CN->getZExtValue())
546 const DebugLoc DL = N->getDebugLoc();
547 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
548 SDValue True = N->getOperand(1);
550 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
551 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
553 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
556 static SDValue performANDCombine(SDNode *N, SelectionDAG &DAG,
557 TargetLowering::DAGCombinerInfo &DCI,
558 const MipsSubtarget *Subtarget) {
559 // Pattern match EXT.
560 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
561 // => ext $dst, $src, size, pos
562 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
565 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
566 unsigned ShiftRightOpc = ShiftRight.getOpcode();
568 // Op's first operand must be a shift right.
569 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
572 // The second operand of the shift must be an immediate.
574 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
577 uint64_t Pos = CN->getZExtValue();
578 uint64_t SMPos, SMSize;
580 // Op's second operand must be a shifted mask.
581 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
582 !isShiftedMask(CN->getZExtValue(), SMPos, SMSize))
585 // Return if the shifted mask does not start at bit 0 or the sum of its size
586 // and Pos exceeds the word's size.
587 EVT ValTy = N->getValueType(0);
588 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
591 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
592 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
593 DAG.getConstant(SMSize, MVT::i32));
596 static SDValue performORCombine(SDNode *N, SelectionDAG &DAG,
597 TargetLowering::DAGCombinerInfo &DCI,
598 const MipsSubtarget *Subtarget) {
599 // Pattern match INS.
600 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
601 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
602 // => ins $dst, $src, size, pos, $src1
603 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
606 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
607 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
610 // See if Op's first operand matches (and $src1 , mask0).
611 if (And0.getOpcode() != ISD::AND)
614 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
615 !isShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
618 // See if Op's second operand matches (and (shl $src, pos), mask1).
619 if (And1.getOpcode() != ISD::AND)
622 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
623 !isShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
626 // The shift masks must have the same position and size.
627 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
630 SDValue Shl = And1.getOperand(0);
631 if (Shl.getOpcode() != ISD::SHL)
634 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
637 unsigned Shamt = CN->getZExtValue();
639 // Return if the shift amount and the first bit position of mask are not the
641 EVT ValTy = N->getValueType(0);
642 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
645 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
646 DAG.getConstant(SMPos0, MVT::i32),
647 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
650 static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
651 TargetLowering::DAGCombinerInfo &DCI,
652 const MipsSubtarget *Subtarget) {
653 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
655 if (DCI.isBeforeLegalizeOps())
658 SDValue Add = N->getOperand(1);
660 if (Add.getOpcode() != ISD::ADD)
663 SDValue Lo = Add.getOperand(1);
665 if ((Lo.getOpcode() != MipsISD::Lo) ||
666 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
669 EVT ValTy = N->getValueType(0);
670 DebugLoc DL = N->getDebugLoc();
672 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
674 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
677 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
679 SelectionDAG &DAG = DCI.DAG;
680 unsigned Opc = N->getOpcode();
686 return performDivRemCombine(N, DAG, DCI, Subtarget);
688 return performSELECTCombine(N, DAG, DCI, Subtarget);
690 return performANDCombine(N, DAG, DCI, Subtarget);
692 return performORCombine(N, DAG, DCI, Subtarget);
694 return performADDCombine(N, DAG, DCI, Subtarget);
701 MipsTargetLowering::LowerOperationWrapper(SDNode *N,
702 SmallVectorImpl<SDValue> &Results,
703 SelectionDAG &DAG) const {
704 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
706 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
707 Results.push_back(Res.getValue(I));
711 MipsTargetLowering::ReplaceNodeResults(SDNode *N,
712 SmallVectorImpl<SDValue> &Results,
713 SelectionDAG &DAG) const {
714 SDValue Res = LowerOperation(SDValue(N, 0), DAG);
716 for (unsigned I = 0, E = Res->getNumValues(); I != E; ++I)
717 Results.push_back(Res.getValue(I));
720 SDValue MipsTargetLowering::
721 LowerOperation(SDValue Op, SelectionDAG &DAG) const
723 switch (Op.getOpcode())
725 case ISD::BR_JT: return lowerBR_JT(Op, DAG);
726 case ISD::BRCOND: return lowerBRCOND(Op, DAG);
727 case ISD::ConstantPool: return lowerConstantPool(Op, DAG);
728 case ISD::GlobalAddress: return lowerGlobalAddress(Op, DAG);
729 case ISD::BlockAddress: return lowerBlockAddress(Op, DAG);
730 case ISD::GlobalTLSAddress: return lowerGlobalTLSAddress(Op, DAG);
731 case ISD::JumpTable: return lowerJumpTable(Op, DAG);
732 case ISD::SELECT: return lowerSELECT(Op, DAG);
733 case ISD::SELECT_CC: return lowerSELECT_CC(Op, DAG);
734 case ISD::SETCC: return lowerSETCC(Op, DAG);
735 case ISD::VASTART: return lowerVASTART(Op, DAG);
736 case ISD::FCOPYSIGN: return lowerFCOPYSIGN(Op, DAG);
737 case ISD::FABS: return lowerFABS(Op, DAG);
738 case ISD::FRAMEADDR: return lowerFRAMEADDR(Op, DAG);
739 case ISD::RETURNADDR: return lowerRETURNADDR(Op, DAG);
740 case ISD::EH_RETURN: return lowerEH_RETURN(Op, DAG);
741 case ISD::ATOMIC_FENCE: return lowerATOMIC_FENCE(Op, DAG);
742 case ISD::SHL_PARTS: return lowerShiftLeftParts(Op, DAG);
743 case ISD::SRA_PARTS: return lowerShiftRightParts(Op, DAG, true);
744 case ISD::SRL_PARTS: return lowerShiftRightParts(Op, DAG, false);
745 case ISD::LOAD: return lowerLOAD(Op, DAG);
746 case ISD::STORE: return lowerSTORE(Op, DAG);
747 case ISD::ADD: return lowerADD(Op, DAG);
752 //===----------------------------------------------------------------------===//
753 // Lower helper functions
754 //===----------------------------------------------------------------------===//
756 // addLiveIn - This helper function adds the specified physical register to the
757 // MachineFunction as a live in value. It also creates a corresponding
758 // virtual register for it.
760 addLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
762 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
763 MF.getRegInfo().addLiveIn(PReg, VReg);
768 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
769 MachineBasicBlock *BB) const {
770 switch (MI->getOpcode()) {
772 llvm_unreachable("Unexpected instr type to insert");
773 case Mips::ATOMIC_LOAD_ADD_I8:
774 case Mips::ATOMIC_LOAD_ADD_I8_P8:
775 return emitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
776 case Mips::ATOMIC_LOAD_ADD_I16:
777 case Mips::ATOMIC_LOAD_ADD_I16_P8:
778 return emitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
779 case Mips::ATOMIC_LOAD_ADD_I32:
780 case Mips::ATOMIC_LOAD_ADD_I32_P8:
781 return emitAtomicBinary(MI, BB, 4, Mips::ADDu);
782 case Mips::ATOMIC_LOAD_ADD_I64:
783 case Mips::ATOMIC_LOAD_ADD_I64_P8:
784 return emitAtomicBinary(MI, BB, 8, Mips::DADDu);
786 case Mips::ATOMIC_LOAD_AND_I8:
787 case Mips::ATOMIC_LOAD_AND_I8_P8:
788 return emitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
789 case Mips::ATOMIC_LOAD_AND_I16:
790 case Mips::ATOMIC_LOAD_AND_I16_P8:
791 return emitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
792 case Mips::ATOMIC_LOAD_AND_I32:
793 case Mips::ATOMIC_LOAD_AND_I32_P8:
794 return emitAtomicBinary(MI, BB, 4, Mips::AND);
795 case Mips::ATOMIC_LOAD_AND_I64:
796 case Mips::ATOMIC_LOAD_AND_I64_P8:
797 return emitAtomicBinary(MI, BB, 8, Mips::AND64);
799 case Mips::ATOMIC_LOAD_OR_I8:
800 case Mips::ATOMIC_LOAD_OR_I8_P8:
801 return emitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
802 case Mips::ATOMIC_LOAD_OR_I16:
803 case Mips::ATOMIC_LOAD_OR_I16_P8:
804 return emitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
805 case Mips::ATOMIC_LOAD_OR_I32:
806 case Mips::ATOMIC_LOAD_OR_I32_P8:
807 return emitAtomicBinary(MI, BB, 4, Mips::OR);
808 case Mips::ATOMIC_LOAD_OR_I64:
809 case Mips::ATOMIC_LOAD_OR_I64_P8:
810 return emitAtomicBinary(MI, BB, 8, Mips::OR64);
812 case Mips::ATOMIC_LOAD_XOR_I8:
813 case Mips::ATOMIC_LOAD_XOR_I8_P8:
814 return emitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
815 case Mips::ATOMIC_LOAD_XOR_I16:
816 case Mips::ATOMIC_LOAD_XOR_I16_P8:
817 return emitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
818 case Mips::ATOMIC_LOAD_XOR_I32:
819 case Mips::ATOMIC_LOAD_XOR_I32_P8:
820 return emitAtomicBinary(MI, BB, 4, Mips::XOR);
821 case Mips::ATOMIC_LOAD_XOR_I64:
822 case Mips::ATOMIC_LOAD_XOR_I64_P8:
823 return emitAtomicBinary(MI, BB, 8, Mips::XOR64);
825 case Mips::ATOMIC_LOAD_NAND_I8:
826 case Mips::ATOMIC_LOAD_NAND_I8_P8:
827 return emitAtomicBinaryPartword(MI, BB, 1, 0, true);
828 case Mips::ATOMIC_LOAD_NAND_I16:
829 case Mips::ATOMIC_LOAD_NAND_I16_P8:
830 return emitAtomicBinaryPartword(MI, BB, 2, 0, true);
831 case Mips::ATOMIC_LOAD_NAND_I32:
832 case Mips::ATOMIC_LOAD_NAND_I32_P8:
833 return emitAtomicBinary(MI, BB, 4, 0, true);
834 case Mips::ATOMIC_LOAD_NAND_I64:
835 case Mips::ATOMIC_LOAD_NAND_I64_P8:
836 return emitAtomicBinary(MI, BB, 8, 0, true);
838 case Mips::ATOMIC_LOAD_SUB_I8:
839 case Mips::ATOMIC_LOAD_SUB_I8_P8:
840 return emitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
841 case Mips::ATOMIC_LOAD_SUB_I16:
842 case Mips::ATOMIC_LOAD_SUB_I16_P8:
843 return emitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
844 case Mips::ATOMIC_LOAD_SUB_I32:
845 case Mips::ATOMIC_LOAD_SUB_I32_P8:
846 return emitAtomicBinary(MI, BB, 4, Mips::SUBu);
847 case Mips::ATOMIC_LOAD_SUB_I64:
848 case Mips::ATOMIC_LOAD_SUB_I64_P8:
849 return emitAtomicBinary(MI, BB, 8, Mips::DSUBu);
851 case Mips::ATOMIC_SWAP_I8:
852 case Mips::ATOMIC_SWAP_I8_P8:
853 return emitAtomicBinaryPartword(MI, BB, 1, 0);
854 case Mips::ATOMIC_SWAP_I16:
855 case Mips::ATOMIC_SWAP_I16_P8:
856 return emitAtomicBinaryPartword(MI, BB, 2, 0);
857 case Mips::ATOMIC_SWAP_I32:
858 case Mips::ATOMIC_SWAP_I32_P8:
859 return emitAtomicBinary(MI, BB, 4, 0);
860 case Mips::ATOMIC_SWAP_I64:
861 case Mips::ATOMIC_SWAP_I64_P8:
862 return emitAtomicBinary(MI, BB, 8, 0);
864 case Mips::ATOMIC_CMP_SWAP_I8:
865 case Mips::ATOMIC_CMP_SWAP_I8_P8:
866 return emitAtomicCmpSwapPartword(MI, BB, 1);
867 case Mips::ATOMIC_CMP_SWAP_I16:
868 case Mips::ATOMIC_CMP_SWAP_I16_P8:
869 return emitAtomicCmpSwapPartword(MI, BB, 2);
870 case Mips::ATOMIC_CMP_SWAP_I32:
871 case Mips::ATOMIC_CMP_SWAP_I32_P8:
872 return emitAtomicCmpSwap(MI, BB, 4);
873 case Mips::ATOMIC_CMP_SWAP_I64:
874 case Mips::ATOMIC_CMP_SWAP_I64_P8:
875 return emitAtomicCmpSwap(MI, BB, 8);
879 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
880 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
882 MipsTargetLowering::emitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
883 unsigned Size, unsigned BinOpcode,
885 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
887 MachineFunction *MF = BB->getParent();
888 MachineRegisterInfo &RegInfo = MF->getRegInfo();
889 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
890 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
891 DebugLoc DL = MI->getDebugLoc();
892 unsigned LL, SC, AND, NOR, ZERO, BEQ;
895 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
896 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
903 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
904 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
907 ZERO = Mips::ZERO_64;
911 unsigned OldVal = MI->getOperand(0).getReg();
912 unsigned Ptr = MI->getOperand(1).getReg();
913 unsigned Incr = MI->getOperand(2).getReg();
915 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
916 unsigned AndRes = RegInfo.createVirtualRegister(RC);
917 unsigned Success = RegInfo.createVirtualRegister(RC);
919 // insert new blocks after the current block
920 const BasicBlock *LLVM_BB = BB->getBasicBlock();
921 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
922 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
923 MachineFunction::iterator It = BB;
925 MF->insert(It, loopMBB);
926 MF->insert(It, exitMBB);
928 // Transfer the remainder of BB and its successor edges to exitMBB.
929 exitMBB->splice(exitMBB->begin(), BB,
930 llvm::next(MachineBasicBlock::iterator(MI)),
932 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
936 // fallthrough --> loopMBB
937 BB->addSuccessor(loopMBB);
938 loopMBB->addSuccessor(loopMBB);
939 loopMBB->addSuccessor(exitMBB);
943 // <binop> storeval, oldval, incr
944 // sc success, storeval, 0(ptr)
945 // beq success, $0, loopMBB
947 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
949 // and andres, oldval, incr
950 // nor storeval, $0, andres
951 BuildMI(BB, DL, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
952 BuildMI(BB, DL, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
953 } else if (BinOpcode) {
954 // <binop> storeval, oldval, incr
955 BuildMI(BB, DL, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
959 BuildMI(BB, DL, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
960 BuildMI(BB, DL, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
962 MI->eraseFromParent(); // The instruction is gone now.
968 MipsTargetLowering::emitAtomicBinaryPartword(MachineInstr *MI,
969 MachineBasicBlock *BB,
970 unsigned Size, unsigned BinOpcode,
972 assert((Size == 1 || Size == 2) &&
973 "Unsupported size for EmitAtomicBinaryPartial.");
975 MachineFunction *MF = BB->getParent();
976 MachineRegisterInfo &RegInfo = MF->getRegInfo();
977 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
978 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
979 DebugLoc DL = MI->getDebugLoc();
980 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
981 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
983 unsigned Dest = MI->getOperand(0).getReg();
984 unsigned Ptr = MI->getOperand(1).getReg();
985 unsigned Incr = MI->getOperand(2).getReg();
987 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
988 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
989 unsigned Mask = RegInfo.createVirtualRegister(RC);
990 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
991 unsigned NewVal = RegInfo.createVirtualRegister(RC);
992 unsigned OldVal = RegInfo.createVirtualRegister(RC);
993 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
994 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
995 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
996 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
997 unsigned AndRes = RegInfo.createVirtualRegister(RC);
998 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
999 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1000 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1001 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1002 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1003 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1004 unsigned Success = RegInfo.createVirtualRegister(RC);
1006 // insert new blocks after the current block
1007 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1008 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1009 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1010 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1011 MachineFunction::iterator It = BB;
1013 MF->insert(It, loopMBB);
1014 MF->insert(It, sinkMBB);
1015 MF->insert(It, exitMBB);
1017 // Transfer the remainder of BB and its successor edges to exitMBB.
1018 exitMBB->splice(exitMBB->begin(), BB,
1019 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1020 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1022 BB->addSuccessor(loopMBB);
1023 loopMBB->addSuccessor(loopMBB);
1024 loopMBB->addSuccessor(sinkMBB);
1025 sinkMBB->addSuccessor(exitMBB);
1028 // addiu masklsb2,$0,-4 # 0xfffffffc
1029 // and alignedaddr,ptr,masklsb2
1030 // andi ptrlsb2,ptr,3
1031 // sll shiftamt,ptrlsb2,3
1032 // ori maskupper,$0,255 # 0xff
1033 // sll mask,maskupper,shiftamt
1034 // nor mask2,$0,mask
1035 // sll incr2,incr,shiftamt
1037 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1038 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1039 .addReg(Mips::ZERO).addImm(-4);
1040 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1041 .addReg(Ptr).addReg(MaskLSB2);
1042 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1043 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1044 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1045 .addReg(Mips::ZERO).addImm(MaskImm);
1046 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1047 .addReg(ShiftAmt).addReg(MaskUpper);
1048 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1049 BuildMI(BB, DL, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1051 // atomic.load.binop
1053 // ll oldval,0(alignedaddr)
1054 // binop binopres,oldval,incr2
1055 // and newval,binopres,mask
1056 // and maskedoldval0,oldval,mask2
1057 // or storeval,maskedoldval0,newval
1058 // sc success,storeval,0(alignedaddr)
1059 // beq success,$0,loopMBB
1063 // ll oldval,0(alignedaddr)
1064 // and newval,incr2,mask
1065 // and maskedoldval0,oldval,mask2
1066 // or storeval,maskedoldval0,newval
1067 // sc success,storeval,0(alignedaddr)
1068 // beq success,$0,loopMBB
1071 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1073 // and andres, oldval, incr2
1074 // nor binopres, $0, andres
1075 // and newval, binopres, mask
1076 BuildMI(BB, DL, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1077 BuildMI(BB, DL, TII->get(Mips::NOR), BinOpRes)
1078 .addReg(Mips::ZERO).addReg(AndRes);
1079 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1080 } else if (BinOpcode) {
1081 // <binop> binopres, oldval, incr2
1082 // and newval, binopres, mask
1083 BuildMI(BB, DL, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1084 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1085 } else {// atomic.swap
1086 // and newval, incr2, mask
1087 BuildMI(BB, DL, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1090 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1091 .addReg(OldVal).addReg(Mask2);
1092 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1093 .addReg(MaskedOldVal0).addReg(NewVal);
1094 BuildMI(BB, DL, TII->get(SC), Success)
1095 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1096 BuildMI(BB, DL, TII->get(Mips::BEQ))
1097 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1100 // and maskedoldval1,oldval,mask
1101 // srl srlres,maskedoldval1,shiftamt
1102 // sll sllres,srlres,24
1103 // sra dest,sllres,24
1105 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1107 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1108 .addReg(OldVal).addReg(Mask);
1109 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1110 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1111 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1112 .addReg(SrlRes).addImm(ShiftImm);
1113 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1114 .addReg(SllRes).addImm(ShiftImm);
1116 MI->eraseFromParent(); // The instruction is gone now.
1122 MipsTargetLowering::emitAtomicCmpSwap(MachineInstr *MI,
1123 MachineBasicBlock *BB,
1124 unsigned Size) const {
1125 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1127 MachineFunction *MF = BB->getParent();
1128 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1129 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1130 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1131 DebugLoc DL = MI->getDebugLoc();
1132 unsigned LL, SC, ZERO, BNE, BEQ;
1135 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1136 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1142 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1143 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1144 ZERO = Mips::ZERO_64;
1149 unsigned Dest = MI->getOperand(0).getReg();
1150 unsigned Ptr = MI->getOperand(1).getReg();
1151 unsigned OldVal = MI->getOperand(2).getReg();
1152 unsigned NewVal = MI->getOperand(3).getReg();
1154 unsigned Success = RegInfo.createVirtualRegister(RC);
1156 // insert new blocks after the current block
1157 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1158 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1159 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1160 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1161 MachineFunction::iterator It = BB;
1163 MF->insert(It, loop1MBB);
1164 MF->insert(It, loop2MBB);
1165 MF->insert(It, exitMBB);
1167 // Transfer the remainder of BB and its successor edges to exitMBB.
1168 exitMBB->splice(exitMBB->begin(), BB,
1169 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1170 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1174 // fallthrough --> loop1MBB
1175 BB->addSuccessor(loop1MBB);
1176 loop1MBB->addSuccessor(exitMBB);
1177 loop1MBB->addSuccessor(loop2MBB);
1178 loop2MBB->addSuccessor(loop1MBB);
1179 loop2MBB->addSuccessor(exitMBB);
1183 // bne dest, oldval, exitMBB
1185 BuildMI(BB, DL, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1186 BuildMI(BB, DL, TII->get(BNE))
1187 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1190 // sc success, newval, 0(ptr)
1191 // beq success, $0, loop1MBB
1193 BuildMI(BB, DL, TII->get(SC), Success)
1194 .addReg(NewVal).addReg(Ptr).addImm(0);
1195 BuildMI(BB, DL, TII->get(BEQ))
1196 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1198 MI->eraseFromParent(); // The instruction is gone now.
1204 MipsTargetLowering::emitAtomicCmpSwapPartword(MachineInstr *MI,
1205 MachineBasicBlock *BB,
1206 unsigned Size) const {
1207 assert((Size == 1 || Size == 2) &&
1208 "Unsupported size for EmitAtomicCmpSwapPartial.");
1210 MachineFunction *MF = BB->getParent();
1211 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1212 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1213 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1214 DebugLoc DL = MI->getDebugLoc();
1215 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1216 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1218 unsigned Dest = MI->getOperand(0).getReg();
1219 unsigned Ptr = MI->getOperand(1).getReg();
1220 unsigned CmpVal = MI->getOperand(2).getReg();
1221 unsigned NewVal = MI->getOperand(3).getReg();
1223 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1224 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1225 unsigned Mask = RegInfo.createVirtualRegister(RC);
1226 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1227 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1228 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1229 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1230 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1231 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1232 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1233 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1234 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1235 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1236 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1237 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1238 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1239 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1240 unsigned Success = RegInfo.createVirtualRegister(RC);
1242 // insert new blocks after the current block
1243 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1244 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1245 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1246 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1247 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1248 MachineFunction::iterator It = BB;
1250 MF->insert(It, loop1MBB);
1251 MF->insert(It, loop2MBB);
1252 MF->insert(It, sinkMBB);
1253 MF->insert(It, exitMBB);
1255 // Transfer the remainder of BB and its successor edges to exitMBB.
1256 exitMBB->splice(exitMBB->begin(), BB,
1257 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1258 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1260 BB->addSuccessor(loop1MBB);
1261 loop1MBB->addSuccessor(sinkMBB);
1262 loop1MBB->addSuccessor(loop2MBB);
1263 loop2MBB->addSuccessor(loop1MBB);
1264 loop2MBB->addSuccessor(sinkMBB);
1265 sinkMBB->addSuccessor(exitMBB);
1267 // FIXME: computation of newval2 can be moved to loop2MBB.
1269 // addiu masklsb2,$0,-4 # 0xfffffffc
1270 // and alignedaddr,ptr,masklsb2
1271 // andi ptrlsb2,ptr,3
1272 // sll shiftamt,ptrlsb2,3
1273 // ori maskupper,$0,255 # 0xff
1274 // sll mask,maskupper,shiftamt
1275 // nor mask2,$0,mask
1276 // andi maskedcmpval,cmpval,255
1277 // sll shiftedcmpval,maskedcmpval,shiftamt
1278 // andi maskednewval,newval,255
1279 // sll shiftednewval,maskednewval,shiftamt
1280 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1281 BuildMI(BB, DL, TII->get(Mips::ADDiu), MaskLSB2)
1282 .addReg(Mips::ZERO).addImm(-4);
1283 BuildMI(BB, DL, TII->get(Mips::AND), AlignedAddr)
1284 .addReg(Ptr).addReg(MaskLSB2);
1285 BuildMI(BB, DL, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1286 BuildMI(BB, DL, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1287 BuildMI(BB, DL, TII->get(Mips::ORi), MaskUpper)
1288 .addReg(Mips::ZERO).addImm(MaskImm);
1289 BuildMI(BB, DL, TII->get(Mips::SLLV), Mask)
1290 .addReg(ShiftAmt).addReg(MaskUpper);
1291 BuildMI(BB, DL, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1292 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedCmpVal)
1293 .addReg(CmpVal).addImm(MaskImm);
1294 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedCmpVal)
1295 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1296 BuildMI(BB, DL, TII->get(Mips::ANDi), MaskedNewVal)
1297 .addReg(NewVal).addImm(MaskImm);
1298 BuildMI(BB, DL, TII->get(Mips::SLLV), ShiftedNewVal)
1299 .addReg(ShiftAmt).addReg(MaskedNewVal);
1302 // ll oldval,0(alginedaddr)
1303 // and maskedoldval0,oldval,mask
1304 // bne maskedoldval0,shiftedcmpval,sinkMBB
1306 BuildMI(BB, DL, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1307 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal0)
1308 .addReg(OldVal).addReg(Mask);
1309 BuildMI(BB, DL, TII->get(Mips::BNE))
1310 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1313 // and maskedoldval1,oldval,mask2
1314 // or storeval,maskedoldval1,shiftednewval
1315 // sc success,storeval,0(alignedaddr)
1316 // beq success,$0,loop1MBB
1318 BuildMI(BB, DL, TII->get(Mips::AND), MaskedOldVal1)
1319 .addReg(OldVal).addReg(Mask2);
1320 BuildMI(BB, DL, TII->get(Mips::OR), StoreVal)
1321 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1322 BuildMI(BB, DL, TII->get(SC), Success)
1323 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1324 BuildMI(BB, DL, TII->get(Mips::BEQ))
1325 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1328 // srl srlres,maskedoldval0,shiftamt
1329 // sll sllres,srlres,24
1330 // sra dest,sllres,24
1332 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1334 BuildMI(BB, DL, TII->get(Mips::SRLV), SrlRes)
1335 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1336 BuildMI(BB, DL, TII->get(Mips::SLL), SllRes)
1337 .addReg(SrlRes).addImm(ShiftImm);
1338 BuildMI(BB, DL, TII->get(Mips::SRA), Dest)
1339 .addReg(SllRes).addImm(ShiftImm);
1341 MI->eraseFromParent(); // The instruction is gone now.
1346 //===----------------------------------------------------------------------===//
1347 // Misc Lower Operation implementation
1348 //===----------------------------------------------------------------------===//
1349 SDValue MipsTargetLowering::lowerBR_JT(SDValue Op, SelectionDAG &DAG) const {
1350 SDValue Chain = Op.getOperand(0);
1351 SDValue Table = Op.getOperand(1);
1352 SDValue Index = Op.getOperand(2);
1353 DebugLoc DL = Op.getDebugLoc();
1354 EVT PTy = getPointerTy();
1355 unsigned EntrySize =
1356 DAG.getMachineFunction().getJumpTableInfo()->getEntrySize(*getDataLayout());
1358 Index = DAG.getNode(ISD::MUL, DL, PTy, Index,
1359 DAG.getConstant(EntrySize, PTy));
1360 SDValue Addr = DAG.getNode(ISD::ADD, DL, PTy, Index, Table);
1362 EVT MemVT = EVT::getIntegerVT(*DAG.getContext(), EntrySize * 8);
1363 Addr = DAG.getExtLoad(ISD::SEXTLOAD, DL, PTy, Chain, Addr,
1364 MachinePointerInfo::getJumpTable(), MemVT, false, false,
1366 Chain = Addr.getValue(1);
1368 if ((getTargetMachine().getRelocationModel() == Reloc::PIC_) || IsN64) {
1369 // For PIC, the sequence is:
1370 // BRIND(load(Jumptable + index) + RelocBase)
1371 // RelocBase can be JumpTable, GOT or some sort of global base.
1372 Addr = DAG.getNode(ISD::ADD, DL, PTy, Addr,
1373 getPICJumpTableRelocBase(Table, DAG));
1376 return DAG.getNode(ISD::BRIND, DL, MVT::Other, Chain, Addr);
1379 SDValue MipsTargetLowering::
1380 lowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1382 // The first operand is the chain, the second is the condition, the third is
1383 // the block to branch to if the condition is true.
1384 SDValue Chain = Op.getOperand(0);
1385 SDValue Dest = Op.getOperand(2);
1386 DebugLoc DL = Op.getDebugLoc();
1388 SDValue CondRes = createFPCmp(DAG, Op.getOperand(1));
1390 // Return if flag is not set by a floating point comparison.
1391 if (CondRes.getOpcode() != MipsISD::FPCmp)
1394 SDValue CCNode = CondRes.getOperand(2);
1396 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1397 unsigned Opc = invertFPCondCodeUser(CC) ? Mips::BRANCH_F : Mips::BRANCH_T;
1398 SDValue BrCode = DAG.getConstant(Opc, MVT::i32);
1399 return DAG.getNode(MipsISD::FPBrcond, DL, Op.getValueType(), Chain, BrCode,
1403 SDValue MipsTargetLowering::
1404 lowerSELECT(SDValue Op, SelectionDAG &DAG) const
1406 SDValue Cond = createFPCmp(DAG, Op.getOperand(0));
1408 // Return if flag is not set by a floating point comparison.
1409 if (Cond.getOpcode() != MipsISD::FPCmp)
1412 return createCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1416 SDValue MipsTargetLowering::
1417 lowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1419 DebugLoc DL = Op.getDebugLoc();
1420 EVT Ty = Op.getOperand(0).getValueType();
1421 SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1422 Op.getOperand(0), Op.getOperand(1),
1425 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1429 SDValue MipsTargetLowering::lowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1430 SDValue Cond = createFPCmp(DAG, Op);
1432 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1433 "Floating point operand expected.");
1435 SDValue True = DAG.getConstant(1, MVT::i32);
1436 SDValue False = DAG.getConstant(0, MVT::i32);
1438 return createCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1441 SDValue MipsTargetLowering::lowerGlobalAddress(SDValue Op,
1442 SelectionDAG &DAG) const {
1443 // FIXME there isn't actually debug info here
1444 DebugLoc DL = Op.getDebugLoc();
1445 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1447 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1448 const MipsTargetObjectFile &TLOF =
1449 (const MipsTargetObjectFile&)getObjFileLowering();
1451 // %gp_rel relocation
1452 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1453 SDValue GA = DAG.getTargetGlobalAddress(GV, DL, MVT::i32, 0,
1455 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, DL,
1456 DAG.getVTList(MVT::i32), &GA, 1);
1457 SDValue GPReg = DAG.getRegister(Mips::GP, MVT::i32);
1458 return DAG.getNode(ISD::ADD, DL, MVT::i32, GPReg, GPRelNode);
1461 // %hi/%lo relocation
1462 return getAddrNonPIC(Op, DAG);
1465 if (GV->hasInternalLinkage() || (GV->hasLocalLinkage() && !isa<Function>(GV)))
1466 return getAddrLocal(Op, DAG, HasMips64);
1469 return getAddrGlobalLargeGOT(Op, DAG, MipsII::MO_GOT_HI16,
1470 MipsII::MO_GOT_LO16);
1472 return getAddrGlobal(Op, DAG,
1473 HasMips64 ? MipsII::MO_GOT_DISP : MipsII::MO_GOT16);
1476 SDValue MipsTargetLowering::lowerBlockAddress(SDValue Op,
1477 SelectionDAG &DAG) const {
1478 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1479 return getAddrNonPIC(Op, DAG);
1481 return getAddrLocal(Op, DAG, HasMips64);
1484 SDValue MipsTargetLowering::
1485 lowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1487 // If the relocation model is PIC, use the General Dynamic TLS Model or
1488 // Local Dynamic TLS model, otherwise use the Initial Exec or
1489 // Local Exec TLS Model.
1491 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1492 DebugLoc DL = GA->getDebugLoc();
1493 const GlobalValue *GV = GA->getGlobal();
1494 EVT PtrVT = getPointerTy();
1496 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1498 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1499 // General Dynamic and Local Dynamic TLS Model.
1500 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1503 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, Flag);
1504 SDValue Argument = DAG.getNode(MipsISD::Wrapper, DL, PtrVT,
1505 getGlobalReg(DAG, PtrVT), TGA);
1506 unsigned PtrSize = PtrVT.getSizeInBits();
1507 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1509 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1513 Entry.Node = Argument;
1515 Args.push_back(Entry);
1517 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1518 false, false, false, false, 0, CallingConv::C,
1519 /*IsTailCall=*/false, /*doesNotRet=*/false,
1520 /*isReturnValueUsed=*/true,
1521 TlsGetAddr, Args, DAG, DL);
1522 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1524 SDValue Ret = CallResult.first;
1526 if (model != TLSModel::LocalDynamic)
1529 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1530 MipsII::MO_DTPREL_HI);
1531 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1532 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1533 MipsII::MO_DTPREL_LO);
1534 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1535 SDValue Add = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Ret);
1536 return DAG.getNode(ISD::ADD, DL, PtrVT, Add, Lo);
1540 if (model == TLSModel::InitialExec) {
1541 // Initial Exec TLS Model
1542 SDValue TGA = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1543 MipsII::MO_GOTTPREL);
1544 TGA = DAG.getNode(MipsISD::Wrapper, DL, PtrVT, getGlobalReg(DAG, PtrVT),
1546 Offset = DAG.getLoad(PtrVT, DL,
1547 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1548 false, false, false, 0);
1550 // Local Exec TLS Model
1551 assert(model == TLSModel::LocalExec);
1552 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1553 MipsII::MO_TPREL_HI);
1554 SDValue TGALo = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0,
1555 MipsII::MO_TPREL_LO);
1556 SDValue Hi = DAG.getNode(MipsISD::Hi, DL, PtrVT, TGAHi);
1557 SDValue Lo = DAG.getNode(MipsISD::Lo, DL, PtrVT, TGALo);
1558 Offset = DAG.getNode(ISD::ADD, DL, PtrVT, Hi, Lo);
1561 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, DL, PtrVT);
1562 return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadPointer, Offset);
1565 SDValue MipsTargetLowering::
1566 lowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1568 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1569 return getAddrNonPIC(Op, DAG);
1571 return getAddrLocal(Op, DAG, HasMips64);
1574 SDValue MipsTargetLowering::
1575 lowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1577 // gp_rel relocation
1578 // FIXME: we should reference the constant pool using small data sections,
1579 // but the asm printer currently doesn't support this feature without
1580 // hacking it. This feature should come soon so we can uncomment the
1582 //if (IsInSmallSection(C->getType())) {
1583 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1584 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1585 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1587 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64)
1588 return getAddrNonPIC(Op, DAG);
1590 return getAddrLocal(Op, DAG, HasMips64);
1593 SDValue MipsTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1594 MachineFunction &MF = DAG.getMachineFunction();
1595 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1597 DebugLoc DL = Op.getDebugLoc();
1598 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1601 // vastart just stores the address of the VarArgsFrameIndex slot into the
1602 // memory location argument.
1603 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1604 return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
1605 MachinePointerInfo(SV), false, false, 0);
1608 static SDValue lowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1609 EVT TyX = Op.getOperand(0).getValueType();
1610 EVT TyY = Op.getOperand(1).getValueType();
1611 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1612 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1613 DebugLoc DL = Op.getDebugLoc();
1616 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1618 SDValue X = (TyX == MVT::f32) ?
1619 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1620 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1622 SDValue Y = (TyY == MVT::f32) ?
1623 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1624 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1628 // ext E, Y, 31, 1 ; extract bit31 of Y
1629 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1630 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1631 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1634 // srl SrlX, SllX, 1
1636 // sll SllY, SrlX, 31
1637 // or Or, SrlX, SllY
1638 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1639 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1640 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1641 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1642 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1645 if (TyX == MVT::f32)
1646 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1648 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1649 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1650 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1653 static SDValue lowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1654 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1655 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1656 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1657 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1658 DebugLoc DL = Op.getDebugLoc();
1660 // Bitcast to integer nodes.
1661 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1662 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1665 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1666 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1667 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1668 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1670 if (WidthX > WidthY)
1671 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1672 else if (WidthY > WidthX)
1673 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1675 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1676 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1677 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1680 // (d)sll SllX, X, 1
1681 // (d)srl SrlX, SllX, 1
1682 // (d)srl SrlY, Y, width(Y)-1
1683 // (d)sll SllY, SrlX, width(Y)-1
1684 // or Or, SrlX, SllY
1685 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1686 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1687 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1688 DAG.getConstant(WidthY - 1, MVT::i32));
1690 if (WidthX > WidthY)
1691 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1692 else if (WidthY > WidthX)
1693 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1695 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1696 DAG.getConstant(WidthX - 1, MVT::i32));
1697 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1698 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1702 MipsTargetLowering::lowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1703 if (Subtarget->hasMips64())
1704 return lowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1706 return lowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1709 static SDValue lowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1710 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1711 DebugLoc DL = Op.getDebugLoc();
1713 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1715 SDValue X = (Op.getValueType() == MVT::f32) ?
1716 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1717 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1722 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1723 DAG.getRegister(Mips::ZERO, MVT::i32),
1724 DAG.getConstant(31, MVT::i32), Const1, X);
1726 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1727 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1730 if (Op.getValueType() == MVT::f32)
1731 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1733 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1734 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1735 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1738 static SDValue lowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1739 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1740 DebugLoc DL = Op.getDebugLoc();
1742 // Bitcast to integer node.
1743 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1747 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1748 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1749 DAG.getConstant(63, MVT::i32), Const1, X);
1751 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1752 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
1755 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
1759 MipsTargetLowering::lowerFABS(SDValue Op, SelectionDAG &DAG) const {
1760 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
1761 return lowerFABS64(Op, DAG, Subtarget->hasMips32r2());
1763 return lowerFABS32(Op, DAG, Subtarget->hasMips32r2());
1766 SDValue MipsTargetLowering::
1767 lowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
1769 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1770 "Frame address can only be determined for current frame.");
1772 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
1773 MFI->setFrameAddressIsTaken(true);
1774 EVT VT = Op.getValueType();
1775 DebugLoc DL = Op.getDebugLoc();
1776 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL,
1777 IsN64 ? Mips::FP_64 : Mips::FP, VT);
1781 SDValue MipsTargetLowering::lowerRETURNADDR(SDValue Op,
1782 SelectionDAG &DAG) const {
1784 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
1785 "Return address can be determined only for current frame.");
1787 MachineFunction &MF = DAG.getMachineFunction();
1788 MachineFrameInfo *MFI = MF.getFrameInfo();
1789 MVT VT = Op.getSimpleValueType();
1790 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
1791 MFI->setReturnAddressIsTaken(true);
1793 // Return RA, which contains the return address. Mark it an implicit live-in.
1794 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
1795 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
1798 // An EH_RETURN is the result of lowering llvm.eh.return which in turn is
1799 // generated from __builtin_eh_return (offset, handler)
1800 // The effect of this is to adjust the stack pointer by "offset"
1801 // and then branch to "handler".
1802 SDValue MipsTargetLowering::lowerEH_RETURN(SDValue Op, SelectionDAG &DAG)
1804 MachineFunction &MF = DAG.getMachineFunction();
1805 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1807 MipsFI->setCallsEhReturn();
1808 SDValue Chain = Op.getOperand(0);
1809 SDValue Offset = Op.getOperand(1);
1810 SDValue Handler = Op.getOperand(2);
1811 DebugLoc DL = Op.getDebugLoc();
1812 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
1814 // Store stack offset in V1, store jump target in V0. Glue CopyToReg and
1815 // EH_RETURN nodes, so that instructions are emitted back-to-back.
1816 unsigned OffsetReg = IsN64 ? Mips::V1_64 : Mips::V1;
1817 unsigned AddrReg = IsN64 ? Mips::V0_64 : Mips::V0;
1818 Chain = DAG.getCopyToReg(Chain, DL, OffsetReg, Offset, SDValue());
1819 Chain = DAG.getCopyToReg(Chain, DL, AddrReg, Handler, Chain.getValue(1));
1820 return DAG.getNode(MipsISD::EH_RETURN, DL, MVT::Other, Chain,
1821 DAG.getRegister(OffsetReg, Ty),
1822 DAG.getRegister(AddrReg, getPointerTy()),
1826 SDValue MipsTargetLowering::lowerATOMIC_FENCE(SDValue Op,
1827 SelectionDAG &DAG) const {
1828 // FIXME: Need pseudo-fence for 'singlethread' fences
1829 // FIXME: Set SType for weaker fences where supported/appropriate.
1831 DebugLoc DL = Op.getDebugLoc();
1832 return DAG.getNode(MipsISD::Sync, DL, MVT::Other, Op.getOperand(0),
1833 DAG.getConstant(SType, MVT::i32));
1836 SDValue MipsTargetLowering::lowerShiftLeftParts(SDValue Op,
1837 SelectionDAG &DAG) const {
1838 DebugLoc DL = Op.getDebugLoc();
1839 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1840 SDValue Shamt = Op.getOperand(2);
1843 // lo = (shl lo, shamt)
1844 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
1847 // hi = (shl lo, shamt[4:0])
1848 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1849 DAG.getConstant(-1, MVT::i32));
1850 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
1851 DAG.getConstant(1, MVT::i32));
1852 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
1854 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
1855 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1856 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
1857 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1858 DAG.getConstant(0x20, MVT::i32));
1859 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1860 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
1861 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
1863 SDValue Ops[2] = {Lo, Hi};
1864 return DAG.getMergeValues(Ops, 2, DL);
1867 SDValue MipsTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
1869 DebugLoc DL = Op.getDebugLoc();
1870 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
1871 SDValue Shamt = Op.getOperand(2);
1874 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
1876 // hi = (sra hi, shamt)
1878 // hi = (srl hi, shamt)
1881 // lo = (sra hi, shamt[4:0])
1882 // hi = (sra hi, 31)
1884 // lo = (srl hi, shamt[4:0])
1886 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
1887 DAG.getConstant(-1, MVT::i32));
1888 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
1889 DAG.getConstant(1, MVT::i32));
1890 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
1891 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
1892 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
1893 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
1895 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
1896 DAG.getConstant(0x20, MVT::i32));
1897 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
1898 DAG.getConstant(31, MVT::i32));
1899 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
1900 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
1901 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
1904 SDValue Ops[2] = {Lo, Hi};
1905 return DAG.getMergeValues(Ops, 2, DL);
1908 static SDValue createLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
1909 SDValue Chain, SDValue Src, unsigned Offset) {
1910 SDValue Ptr = LD->getBasePtr();
1911 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
1912 EVT BasePtrVT = Ptr.getValueType();
1913 DebugLoc DL = LD->getDebugLoc();
1914 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
1917 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1918 DAG.getConstant(Offset, BasePtrVT));
1920 SDValue Ops[] = { Chain, Ptr, Src };
1921 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
1922 LD->getMemOperand());
1925 // Expand an unaligned 32 or 64-bit integer load node.
1926 SDValue MipsTargetLowering::lowerLOAD(SDValue Op, SelectionDAG &DAG) const {
1927 LoadSDNode *LD = cast<LoadSDNode>(Op);
1928 EVT MemVT = LD->getMemoryVT();
1930 // Return if load is aligned or if MemVT is neither i32 nor i64.
1931 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
1932 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
1935 bool IsLittle = Subtarget->isLittle();
1936 EVT VT = Op.getValueType();
1937 ISD::LoadExtType ExtType = LD->getExtensionType();
1938 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
1940 assert((VT == MVT::i32) || (VT == MVT::i64));
1943 // (set dst, (i64 (load baseptr)))
1945 // (set tmp, (ldl (add baseptr, 7), undef))
1946 // (set dst, (ldr baseptr, tmp))
1947 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
1948 SDValue LDL = createLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
1950 return createLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
1954 SDValue LWL = createLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
1956 SDValue LWR = createLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
1960 // (set dst, (i32 (load baseptr))) or
1961 // (set dst, (i64 (sextload baseptr))) or
1962 // (set dst, (i64 (extload baseptr)))
1964 // (set tmp, (lwl (add baseptr, 3), undef))
1965 // (set dst, (lwr baseptr, tmp))
1966 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
1967 (ExtType == ISD::EXTLOAD))
1970 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
1973 // (set dst, (i64 (zextload baseptr)))
1975 // (set tmp0, (lwl (add baseptr, 3), undef))
1976 // (set tmp1, (lwr baseptr, tmp0))
1977 // (set tmp2, (shl tmp1, 32))
1978 // (set dst, (srl tmp2, 32))
1979 DebugLoc DL = LD->getDebugLoc();
1980 SDValue Const32 = DAG.getConstant(32, MVT::i32);
1981 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
1982 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
1983 SDValue Ops[] = { SRL, LWR.getValue(1) };
1984 return DAG.getMergeValues(Ops, 2, DL);
1987 static SDValue createStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
1988 SDValue Chain, unsigned Offset) {
1989 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
1990 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
1991 DebugLoc DL = SD->getDebugLoc();
1992 SDVTList VTList = DAG.getVTList(MVT::Other);
1995 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
1996 DAG.getConstant(Offset, BasePtrVT));
1998 SDValue Ops[] = { Chain, Value, Ptr };
1999 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2000 SD->getMemOperand());
2003 // Expand an unaligned 32 or 64-bit integer store node.
2004 SDValue MipsTargetLowering::lowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2005 StoreSDNode *SD = cast<StoreSDNode>(Op);
2006 EVT MemVT = SD->getMemoryVT();
2008 // Return if store is aligned or if MemVT is neither i32 nor i64.
2009 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2010 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2013 bool IsLittle = Subtarget->isLittle();
2014 SDValue Value = SD->getValue(), Chain = SD->getChain();
2015 EVT VT = Value.getValueType();
2018 // (store val, baseptr) or
2019 // (truncstore val, baseptr)
2021 // (swl val, (add baseptr, 3))
2022 // (swr val, baseptr)
2023 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2024 SDValue SWL = createStoreLR(MipsISD::SWL, DAG, SD, Chain,
2026 return createStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2029 assert(VT == MVT::i64);
2032 // (store val, baseptr)
2034 // (sdl val, (add baseptr, 7))
2035 // (sdr val, baseptr)
2036 SDValue SDL = createStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2037 return createStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2040 SDValue MipsTargetLowering::lowerADD(SDValue Op, SelectionDAG &DAG) const {
2041 if (Op->getOperand(0).getOpcode() != ISD::FRAMEADDR
2042 || cast<ConstantSDNode>
2043 (Op->getOperand(0).getOperand(0))->getZExtValue() != 0
2044 || Op->getOperand(1).getOpcode() != ISD::FRAME_TO_ARGS_OFFSET)
2048 // (add (frameaddr 0), (frame_to_args_offset))
2049 // results from lowering llvm.eh.dwarf.cfa intrinsic. Transform it to
2050 // (add FrameObject, 0)
2051 // where FrameObject is a fixed StackObject with offset 0 which points to
2052 // the old stack pointer.
2053 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2054 EVT ValTy = Op->getValueType(0);
2055 int FI = MFI->CreateFixedObject(Op.getValueSizeInBits() / 8, 0, false);
2056 SDValue InArgsAddr = DAG.getFrameIndex(FI, ValTy);
2057 return DAG.getNode(ISD::ADD, Op->getDebugLoc(), ValTy, InArgsAddr,
2058 DAG.getConstant(0, ValTy));
2061 //===----------------------------------------------------------------------===//
2062 // Calling Convention Implementation
2063 //===----------------------------------------------------------------------===//
2065 //===----------------------------------------------------------------------===//
2066 // TODO: Implement a generic logic using tblgen that can support this.
2067 // Mips O32 ABI rules:
2069 // i32 - Passed in A0, A1, A2, A3 and stack
2070 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2071 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2072 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2073 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2074 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2077 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2078 //===----------------------------------------------------------------------===//
2080 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2081 MVT LocVT, CCValAssign::LocInfo LocInfo,
2082 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2084 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2086 static const uint16_t IntRegs[] = {
2087 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2089 static const uint16_t F32Regs[] = {
2090 Mips::F12, Mips::F14
2092 static const uint16_t F64Regs[] = {
2096 // Do not process byval args here.
2097 if (ArgFlags.isByVal())
2100 // Promote i8 and i16
2101 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2103 if (ArgFlags.isSExt())
2104 LocInfo = CCValAssign::SExt;
2105 else if (ArgFlags.isZExt())
2106 LocInfo = CCValAssign::ZExt;
2108 LocInfo = CCValAssign::AExt;
2113 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2114 // is true: function is vararg, argument is 3rd or higher, there is previous
2115 // argument which is not f32 or f64.
2116 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2117 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2118 unsigned OrigAlign = ArgFlags.getOrigAlign();
2119 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2121 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2122 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2123 // If this is the first part of an i64 arg,
2124 // the allocated register must be either A0 or A2.
2125 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2126 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2128 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2129 // Allocate int register and shadow next int register. If first
2130 // available register is Mips::A1 or Mips::A3, shadow it too.
2131 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2132 if (Reg == Mips::A1 || Reg == Mips::A3)
2133 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2134 State.AllocateReg(IntRegs, IntRegsSize);
2136 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2137 // we are guaranteed to find an available float register
2138 if (ValVT == MVT::f32) {
2139 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2140 // Shadow int register
2141 State.AllocateReg(IntRegs, IntRegsSize);
2143 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2144 // Shadow int registers
2145 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2146 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2147 State.AllocateReg(IntRegs, IntRegsSize);
2148 State.AllocateReg(IntRegs, IntRegsSize);
2151 llvm_unreachable("Cannot handle this ValVT.");
2154 unsigned Offset = State.AllocateStack(ValVT.getSizeInBits() >> 3,
2156 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2158 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2163 #include "MipsGenCallingConv.inc"
2165 //===----------------------------------------------------------------------===//
2166 // Call Calling Convention Implementation
2167 //===----------------------------------------------------------------------===//
2169 static const unsigned O32IntRegsSize = 4;
2171 // Return next O32 integer argument register.
2172 static unsigned getNextIntArgReg(unsigned Reg) {
2173 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2174 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2178 MipsTargetLowering::passArgOnStack(SDValue StackPtr, unsigned Offset,
2179 SDValue Chain, SDValue Arg, DebugLoc DL,
2180 bool IsTailCall, SelectionDAG &DAG) const {
2182 SDValue PtrOff = DAG.getNode(ISD::ADD, DL, getPointerTy(), StackPtr,
2183 DAG.getIntPtrConstant(Offset));
2184 return DAG.getStore(Chain, DL, Arg, PtrOff, MachinePointerInfo(), false,
2188 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2189 int FI = MFI->CreateFixedObject(Arg.getValueSizeInBits() / 8, Offset, false);
2190 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2191 return DAG.getStore(Chain, DL, Arg, FIN, MachinePointerInfo(),
2192 /*isVolatile=*/ true, false, 0);
2195 void MipsTargetLowering::
2196 getOpndList(SmallVectorImpl<SDValue> &Ops,
2197 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
2198 bool IsPICCall, bool GlobalOrExternal, bool InternalLinkage,
2199 CallLoweringInfo &CLI, SDValue Callee, SDValue Chain) const {
2200 // Insert node "GP copy globalreg" before call to function.
2202 // R_MIPS_CALL* operators (emitted when non-internal functions are called
2203 // in PIC mode) allow symbols to be resolved via lazy binding.
2204 // The lazy binding stub requires GP to point to the GOT.
2205 if (IsPICCall && !InternalLinkage) {
2206 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2207 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2208 RegsToPass.push_back(std::make_pair(GPReg, getGlobalReg(CLI.DAG, Ty)));
2211 // Build a sequence of copy-to-reg nodes chained together with token
2212 // chain and flag operands which copy the outgoing args into registers.
2213 // The InFlag in necessary since all emitted instructions must be
2217 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2218 Chain = CLI.DAG.getCopyToReg(Chain, CLI.DL, RegsToPass[i].first,
2219 RegsToPass[i].second, InFlag);
2220 InFlag = Chain.getValue(1);
2223 // Add argument registers to the end of the list so that they are
2224 // known live into the call.
2225 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2226 Ops.push_back(CLI.DAG.getRegister(RegsToPass[i].first,
2227 RegsToPass[i].second.getValueType()));
2229 // Add a register mask operand representing the call-preserved registers.
2230 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2231 const uint32_t *Mask = TRI->getCallPreservedMask(CLI.CallConv);
2232 assert(Mask && "Missing call preserved mask for calling convention");
2233 Ops.push_back(CLI.DAG.getRegisterMask(Mask));
2235 if (InFlag.getNode())
2236 Ops.push_back(InFlag);
2239 /// LowerCall - functions arguments are copied from virtual regs to
2240 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2242 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2243 SmallVectorImpl<SDValue> &InVals) const {
2244 SelectionDAG &DAG = CLI.DAG;
2245 DebugLoc &DL = CLI.DL;
2246 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2247 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2248 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2249 SDValue Chain = CLI.Chain;
2250 SDValue Callee = CLI.Callee;
2251 bool &IsTailCall = CLI.IsTailCall;
2252 CallingConv::ID CallConv = CLI.CallConv;
2253 bool IsVarArg = CLI.IsVarArg;
2255 MachineFunction &MF = DAG.getMachineFunction();
2256 MachineFrameInfo *MFI = MF.getFrameInfo();
2257 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2258 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2260 // Analyze operands of the call, assigning locations to each operand.
2261 SmallVector<CCValAssign, 16> ArgLocs;
2262 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2263 getTargetMachine(), ArgLocs, *DAG.getContext());
2264 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2266 MipsCCInfo.analyzeCallOperands(Outs, IsVarArg,
2267 getTargetMachine().Options.UseSoftFloat,
2268 Callee.getNode(), CLI.Args);
2270 // Get a count of how many bytes are to be pushed on the stack.
2271 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2273 // Check if it's really possible to do a tail call.
2276 isEligibleForTailCallOptimization(MipsCCInfo, NextStackOffset,
2277 *MF.getInfo<MipsFunctionInfo>());
2282 // Chain is the output chain of the last Load/Store or CopyToReg node.
2283 // ByValChain is the output chain of the last Memcpy node created for copying
2284 // byval arguments to the stack.
2285 unsigned StackAlignment = TFL->getStackAlignment();
2286 NextStackOffset = RoundUpToAlignment(NextStackOffset, StackAlignment);
2287 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2290 Chain = DAG.getCALLSEQ_START(Chain, NextStackOffsetVal);
2292 SDValue StackPtr = DAG.getCopyFromReg(Chain, DL,
2293 IsN64 ? Mips::SP_64 : Mips::SP,
2296 // With EABI is it possible to have 16 args on registers.
2297 std::deque< std::pair<unsigned, SDValue> > RegsToPass;
2298 SmallVector<SDValue, 8> MemOpChains;
2299 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2301 // Walk the register/memloc assignments, inserting copies/loads.
2302 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2303 SDValue Arg = OutVals[i];
2304 CCValAssign &VA = ArgLocs[i];
2305 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2306 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2309 if (Flags.isByVal()) {
2310 assert(Flags.getByValSize() &&
2311 "ByVal args of size 0 should have been ignored by front-end.");
2312 assert(ByValArg != MipsCCInfo.byval_end());
2313 assert(!IsTailCall &&
2314 "Do not tail-call optimize if there is a byval argument.");
2315 passByValArg(Chain, DL, RegsToPass, MemOpChains, StackPtr, MFI, DAG, Arg,
2316 MipsCCInfo, *ByValArg, Flags, Subtarget->isLittle());
2321 // Promote the value if needed.
2322 switch (VA.getLocInfo()) {
2323 default: llvm_unreachable("Unknown loc info!");
2324 case CCValAssign::Full:
2325 if (VA.isRegLoc()) {
2326 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2327 (ValVT == MVT::f64 && LocVT == MVT::i64) ||
2328 (ValVT == MVT::i64 && LocVT == MVT::f64))
2329 Arg = DAG.getNode(ISD::BITCAST, DL, LocVT, Arg);
2330 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2331 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2332 Arg, DAG.getConstant(0, MVT::i32));
2333 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
2334 Arg, DAG.getConstant(1, MVT::i32));
2335 if (!Subtarget->isLittle())
2337 unsigned LocRegLo = VA.getLocReg();
2338 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2339 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2340 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2345 case CCValAssign::SExt:
2346 Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, LocVT, Arg);
2348 case CCValAssign::ZExt:
2349 Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, LocVT, Arg);
2351 case CCValAssign::AExt:
2352 Arg = DAG.getNode(ISD::ANY_EXTEND, DL, LocVT, Arg);
2356 // Arguments that can be passed on register must be kept at
2357 // RegsToPass vector
2358 if (VA.isRegLoc()) {
2359 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2363 // Register can't get to this point...
2364 assert(VA.isMemLoc());
2366 // emit ISD::STORE whichs stores the
2367 // parameter value to a stack Location
2368 MemOpChains.push_back(passArgOnStack(StackPtr, VA.getLocMemOffset(),
2369 Chain, Arg, DL, IsTailCall, DAG));
2372 // Transform all store nodes into one single node because all store
2373 // nodes are independent of each other.
2374 if (!MemOpChains.empty())
2375 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2376 &MemOpChains[0], MemOpChains.size());
2378 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2379 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2380 // node so that legalize doesn't hack it.
2381 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2382 bool GlobalOrExternal = false, InternalLinkage = false;
2385 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2387 InternalLinkage = G->getGlobal()->hasInternalLinkage();
2389 if (InternalLinkage)
2390 Callee = getAddrLocal(Callee, DAG, HasMips64);
2392 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2393 MipsII::MO_CALL_LO16);
2395 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2397 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), DL, getPointerTy(), 0,
2398 MipsII::MO_NO_FLAG);
2399 GlobalOrExternal = true;
2401 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2402 if (!IsN64 && !IsPIC) // !N64 && static
2403 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2404 MipsII::MO_NO_FLAG);
2406 Callee = getAddrGlobalLargeGOT(Callee, DAG, MipsII::MO_CALL_HI16,
2407 MipsII::MO_CALL_LO16);
2409 Callee = getAddrGlobal(Callee, DAG, MipsII::MO_GOT_CALL);
2411 GlobalOrExternal = true;
2414 SmallVector<SDValue, 8> Ops(1, Chain);
2415 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2417 getOpndList(Ops, RegsToPass, IsPICCall, GlobalOrExternal, InternalLinkage,
2418 CLI, Callee, Chain);
2421 return DAG.getNode(MipsISD::TailCall, DL, MVT::Other, &Ops[0], Ops.size());
2423 Chain = DAG.getNode(MipsISD::JmpLink, DL, NodeTys, &Ops[0], Ops.size());
2424 SDValue InFlag = Chain.getValue(1);
2426 // Create the CALLSEQ_END node.
2427 Chain = DAG.getCALLSEQ_END(Chain, NextStackOffsetVal,
2428 DAG.getIntPtrConstant(0, true), InFlag);
2429 InFlag = Chain.getValue(1);
2431 // Handle result values, copying them out of physregs into vregs that we
2433 return LowerCallResult(Chain, InFlag, CallConv, IsVarArg,
2434 Ins, DL, DAG, InVals, CLI.Callee.getNode(), CLI.RetTy);
2437 /// LowerCallResult - Lower the result values of a call into the
2438 /// appropriate copies out of appropriate physical registers.
2440 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2441 CallingConv::ID CallConv, bool IsVarArg,
2442 const SmallVectorImpl<ISD::InputArg> &Ins,
2443 DebugLoc DL, SelectionDAG &DAG,
2444 SmallVectorImpl<SDValue> &InVals,
2445 const SDNode *CallNode,
2446 const Type *RetTy) const {
2447 // Assign locations to each value returned by this call.
2448 SmallVector<CCValAssign, 16> RVLocs;
2449 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2450 getTargetMachine(), RVLocs, *DAG.getContext());
2451 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2453 MipsCCInfo.analyzeCallResult(Ins, getTargetMachine().Options.UseSoftFloat,
2456 // Copy all of the result registers out of their specified physreg.
2457 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2458 SDValue Val = DAG.getCopyFromReg(Chain, DL, RVLocs[i].getLocReg(),
2459 RVLocs[i].getLocVT(), InFlag);
2460 Chain = Val.getValue(1);
2461 InFlag = Val.getValue(2);
2463 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2464 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getValVT(), Val);
2466 InVals.push_back(Val);
2472 //===----------------------------------------------------------------------===//
2473 // Formal Arguments Calling Convention Implementation
2474 //===----------------------------------------------------------------------===//
2475 /// LowerFormalArguments - transform physical registers into virtual registers
2476 /// and generate load operations for arguments places on the stack.
2478 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
2479 CallingConv::ID CallConv,
2481 const SmallVectorImpl<ISD::InputArg> &Ins,
2482 DebugLoc DL, SelectionDAG &DAG,
2483 SmallVectorImpl<SDValue> &InVals)
2485 MachineFunction &MF = DAG.getMachineFunction();
2486 MachineFrameInfo *MFI = MF.getFrameInfo();
2487 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2489 MipsFI->setVarArgsFrameIndex(0);
2491 // Used with vargs to acumulate store chains.
2492 std::vector<SDValue> OutChains;
2494 // Assign locations to all of the incoming arguments.
2495 SmallVector<CCValAssign, 16> ArgLocs;
2496 CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(),
2497 getTargetMachine(), ArgLocs, *DAG.getContext());
2498 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2499 Function::const_arg_iterator FuncArg =
2500 DAG.getMachineFunction().getFunction()->arg_begin();
2501 bool UseSoftFloat = getTargetMachine().Options.UseSoftFloat;
2503 MipsCCInfo.analyzeFormalArguments(Ins, UseSoftFloat, FuncArg);
2504 MipsFI->setFormalArgInfo(CCInfo.getNextStackOffset(),
2505 MipsCCInfo.hasByValArg());
2507 unsigned CurArgIdx = 0;
2508 MipsCC::byval_iterator ByValArg = MipsCCInfo.byval_begin();
2510 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2511 CCValAssign &VA = ArgLocs[i];
2512 std::advance(FuncArg, Ins[i].OrigArgIndex - CurArgIdx);
2513 CurArgIdx = Ins[i].OrigArgIndex;
2514 EVT ValVT = VA.getValVT();
2515 ISD::ArgFlagsTy Flags = Ins[i].Flags;
2516 bool IsRegLoc = VA.isRegLoc();
2518 if (Flags.isByVal()) {
2519 assert(Flags.getByValSize() &&
2520 "ByVal args of size 0 should have been ignored by front-end.");
2521 assert(ByValArg != MipsCCInfo.byval_end());
2522 copyByValRegs(Chain, DL, OutChains, DAG, Flags, InVals, &*FuncArg,
2523 MipsCCInfo, *ByValArg);
2528 // Arguments stored on registers
2530 EVT RegVT = VA.getLocVT();
2531 unsigned ArgReg = VA.getLocReg();
2532 const TargetRegisterClass *RC;
2534 if (RegVT == MVT::i32)
2535 RC = Subtarget->inMips16Mode()? &Mips::CPU16RegsRegClass :
2536 &Mips::CPURegsRegClass;
2537 else if (RegVT == MVT::i64)
2538 RC = &Mips::CPU64RegsRegClass;
2539 else if (RegVT == MVT::f32)
2540 RC = &Mips::FGR32RegClass;
2541 else if (RegVT == MVT::f64)
2542 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
2544 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
2546 // Transform the arguments stored on
2547 // physical registers into virtual ones
2548 unsigned Reg = addLiveIn(DAG.getMachineFunction(), ArgReg, RC);
2549 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
2551 // If this is an 8 or 16-bit value, it has been passed promoted
2552 // to 32 bits. Insert an assert[sz]ext to capture this, then
2553 // truncate to the right size.
2554 if (VA.getLocInfo() != CCValAssign::Full) {
2555 unsigned Opcode = 0;
2556 if (VA.getLocInfo() == CCValAssign::SExt)
2557 Opcode = ISD::AssertSext;
2558 else if (VA.getLocInfo() == CCValAssign::ZExt)
2559 Opcode = ISD::AssertZext;
2561 ArgValue = DAG.getNode(Opcode, DL, RegVT, ArgValue,
2562 DAG.getValueType(ValVT));
2563 ArgValue = DAG.getNode(ISD::TRUNCATE, DL, ValVT, ArgValue);
2566 // Handle floating point arguments passed in integer registers and
2567 // long double arguments passed in floating point registers.
2568 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
2569 (RegVT == MVT::i64 && ValVT == MVT::f64) ||
2570 (RegVT == MVT::f64 && ValVT == MVT::i64))
2571 ArgValue = DAG.getNode(ISD::BITCAST, DL, ValVT, ArgValue);
2572 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
2573 unsigned Reg2 = addLiveIn(DAG.getMachineFunction(),
2574 getNextIntArgReg(ArgReg), RC);
2575 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, DL, Reg2, RegVT);
2576 if (!Subtarget->isLittle())
2577 std::swap(ArgValue, ArgValue2);
2578 ArgValue = DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64,
2579 ArgValue, ArgValue2);
2582 InVals.push_back(ArgValue);
2583 } else { // VA.isRegLoc()
2586 assert(VA.isMemLoc());
2588 // The stack pointer offset is relative to the caller stack frame.
2589 int FI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2590 VA.getLocMemOffset(), true);
2592 // Create load nodes to retrieve arguments from the stack
2593 SDValue FIN = DAG.getFrameIndex(FI, getPointerTy());
2594 InVals.push_back(DAG.getLoad(ValVT, DL, Chain, FIN,
2595 MachinePointerInfo::getFixedStack(FI),
2596 false, false, false, 0));
2600 // The mips ABIs for returning structs by value requires that we copy
2601 // the sret argument into $v0 for the return. Save the argument into
2602 // a virtual register so that we can access it from the return points.
2603 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
2604 unsigned Reg = MipsFI->getSRetReturnReg();
2606 Reg = MF.getRegInfo().
2607 createVirtualRegister(getRegClassFor(IsN64 ? MVT::i64 : MVT::i32));
2608 MipsFI->setSRetReturnReg(Reg);
2610 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[0]);
2611 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
2615 writeVarArgRegs(OutChains, MipsCCInfo, Chain, DL, DAG);
2617 // All stores are grouped in one node to allow the matching between
2618 // the size of Ins and InVals. This only happens when on varg functions
2619 if (!OutChains.empty()) {
2620 OutChains.push_back(Chain);
2621 Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
2622 &OutChains[0], OutChains.size());
2628 //===----------------------------------------------------------------------===//
2629 // Return Value Calling Convention Implementation
2630 //===----------------------------------------------------------------------===//
2633 MipsTargetLowering::CanLowerReturn(CallingConv::ID CallConv,
2634 MachineFunction &MF, bool IsVarArg,
2635 const SmallVectorImpl<ISD::OutputArg> &Outs,
2636 LLVMContext &Context) const {
2637 SmallVector<CCValAssign, 16> RVLocs;
2638 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(),
2640 return CCInfo.CheckReturn(Outs, RetCC_Mips);
2644 MipsTargetLowering::LowerReturn(SDValue Chain,
2645 CallingConv::ID CallConv, bool IsVarArg,
2646 const SmallVectorImpl<ISD::OutputArg> &Outs,
2647 const SmallVectorImpl<SDValue> &OutVals,
2648 DebugLoc DL, SelectionDAG &DAG) const {
2649 // CCValAssign - represent the assignment of
2650 // the return value to a location
2651 SmallVector<CCValAssign, 16> RVLocs;
2652 MachineFunction &MF = DAG.getMachineFunction();
2654 // CCState - Info about the registers and stack slot.
2655 CCState CCInfo(CallConv, IsVarArg, MF, getTargetMachine(), RVLocs,
2657 MipsCC MipsCCInfo(CallConv, IsO32, CCInfo);
2659 // Analyze return values.
2660 MipsCCInfo.analyzeReturn(Outs, getTargetMachine().Options.UseSoftFloat,
2661 MF.getFunction()->getReturnType());
2664 SmallVector<SDValue, 4> RetOps(1, Chain);
2666 // Copy the result values into the output registers.
2667 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2668 SDValue Val = OutVals[i];
2669 CCValAssign &VA = RVLocs[i];
2670 assert(VA.isRegLoc() && "Can only return in registers!");
2672 if (RVLocs[i].getValVT() != RVLocs[i].getLocVT())
2673 Val = DAG.getNode(ISD::BITCAST, DL, RVLocs[i].getLocVT(), Val);
2675 Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Flag);
2677 // Guarantee that all emitted copies are stuck together with flags.
2678 Flag = Chain.getValue(1);
2679 RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
2682 // The mips ABIs for returning structs by value requires that we copy
2683 // the sret argument into $v0 for the return. We saved the argument into
2684 // a virtual register in the entry block, so now we copy the value out
2686 if (MF.getFunction()->hasStructRetAttr()) {
2687 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2688 unsigned Reg = MipsFI->getSRetReturnReg();
2691 llvm_unreachable("sret virtual register not created in the entry block");
2692 SDValue Val = DAG.getCopyFromReg(Chain, DL, Reg, getPointerTy());
2693 unsigned V0 = IsN64 ? Mips::V0_64 : Mips::V0;
2695 Chain = DAG.getCopyToReg(Chain, DL, V0, Val, Flag);
2696 Flag = Chain.getValue(1);
2697 RetOps.push_back(DAG.getRegister(V0, getPointerTy()));
2700 RetOps[0] = Chain; // Update chain.
2702 // Add the flag if we have it.
2704 RetOps.push_back(Flag);
2706 // Return on Mips is always a "jr $ra"
2707 return DAG.getNode(MipsISD::Ret, DL, MVT::Other, &RetOps[0], RetOps.size());
2710 //===----------------------------------------------------------------------===//
2711 // Mips Inline Assembly Support
2712 //===----------------------------------------------------------------------===//
2714 /// getConstraintType - Given a constraint letter, return the type of
2715 /// constraint it is for this target.
2716 MipsTargetLowering::ConstraintType MipsTargetLowering::
2717 getConstraintType(const std::string &Constraint) const
2719 // Mips specific constrainy
2720 // GCC config/mips/constraints.md
2722 // 'd' : An address register. Equivalent to r
2723 // unless generating MIPS16 code.
2724 // 'y' : Equivalent to r; retained for
2725 // backwards compatibility.
2726 // 'c' : A register suitable for use in an indirect
2727 // jump. This will always be $25 for -mabicalls.
2728 // 'l' : The lo register. 1 word storage.
2729 // 'x' : The hilo register pair. Double word storage.
2730 if (Constraint.size() == 1) {
2731 switch (Constraint[0]) {
2739 return C_RegisterClass;
2744 return TargetLowering::getConstraintType(Constraint);
2747 /// Examine constraint type and operand type and determine a weight value.
2748 /// This object must already have been set up with the operand type
2749 /// and the current alternative constraint selected.
2750 TargetLowering::ConstraintWeight
2751 MipsTargetLowering::getSingleConstraintMatchWeight(
2752 AsmOperandInfo &info, const char *constraint) const {
2753 ConstraintWeight weight = CW_Invalid;
2754 Value *CallOperandVal = info.CallOperandVal;
2755 // If we don't have a value, we can't do a match,
2756 // but allow it at the lowest weight.
2757 if (CallOperandVal == NULL)
2759 Type *type = CallOperandVal->getType();
2760 // Look at the constraint type.
2761 switch (*constraint) {
2763 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
2767 if (type->isIntegerTy())
2768 weight = CW_Register;
2771 if (type->isFloatTy())
2772 weight = CW_Register;
2774 case 'c': // $25 for indirect jumps
2775 case 'l': // lo register
2776 case 'x': // hilo register pair
2777 if (type->isIntegerTy())
2778 weight = CW_SpecificReg;
2780 case 'I': // signed 16 bit immediate
2781 case 'J': // integer zero
2782 case 'K': // unsigned 16 bit immediate
2783 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2784 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2785 case 'O': // signed 15 bit immediate (+- 16383)
2786 case 'P': // immediate in the range of 65535 to 1 (inclusive)
2787 if (isa<ConstantInt>(CallOperandVal))
2788 weight = CW_Constant;
2797 /// Given a register class constraint, like 'r', if this corresponds directly
2798 /// to an LLVM register class, return a register of 0 and the register class
2800 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
2801 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
2803 if (Constraint.size() == 1) {
2804 switch (Constraint[0]) {
2805 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
2806 case 'y': // Same as 'r'. Exists for compatibility.
2808 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8) {
2809 if (Subtarget->inMips16Mode())
2810 return std::make_pair(0U, &Mips::CPU16RegsRegClass);
2811 return std::make_pair(0U, &Mips::CPURegsRegClass);
2813 if (VT == MVT::i64 && !HasMips64)
2814 return std::make_pair(0U, &Mips::CPURegsRegClass);
2815 if (VT == MVT::i64 && HasMips64)
2816 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
2817 // This will generate an error message
2818 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2821 return std::make_pair(0U, &Mips::FGR32RegClass);
2822 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
2823 if (Subtarget->isFP64bit())
2824 return std::make_pair(0U, &Mips::FGR64RegClass);
2825 return std::make_pair(0U, &Mips::AFGR64RegClass);
2828 case 'c': // register suitable for indirect jump
2830 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
2831 assert(VT == MVT::i64 && "Unexpected type.");
2832 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
2833 case 'l': // register suitable for indirect jump
2835 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
2836 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
2837 case 'x': // register suitable for indirect jump
2838 // Fixme: Not triggering the use of both hi and low
2839 // This will generate an error message
2840 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
2843 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
2846 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
2847 /// vector. If it is invalid, don't add anything to Ops.
2848 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
2849 std::string &Constraint,
2850 std::vector<SDValue>&Ops,
2851 SelectionDAG &DAG) const {
2852 SDValue Result(0, 0);
2854 // Only support length 1 constraints for now.
2855 if (Constraint.length() > 1) return;
2857 char ConstraintLetter = Constraint[0];
2858 switch (ConstraintLetter) {
2859 default: break; // This will fall through to the generic implementation
2860 case 'I': // Signed 16 bit constant
2861 // If this fails, the parent routine will give an error
2862 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2863 EVT Type = Op.getValueType();
2864 int64_t Val = C->getSExtValue();
2865 if (isInt<16>(Val)) {
2866 Result = DAG.getTargetConstant(Val, Type);
2871 case 'J': // integer zero
2872 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2873 EVT Type = Op.getValueType();
2874 int64_t Val = C->getZExtValue();
2876 Result = DAG.getTargetConstant(0, Type);
2881 case 'K': // unsigned 16 bit immediate
2882 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2883 EVT Type = Op.getValueType();
2884 uint64_t Val = (uint64_t)C->getZExtValue();
2885 if (isUInt<16>(Val)) {
2886 Result = DAG.getTargetConstant(Val, Type);
2891 case 'L': // signed 32 bit immediate where lower 16 bits are 0
2892 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2893 EVT Type = Op.getValueType();
2894 int64_t Val = C->getSExtValue();
2895 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
2896 Result = DAG.getTargetConstant(Val, Type);
2901 case 'N': // immediate in the range of -65535 to -1 (inclusive)
2902 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2903 EVT Type = Op.getValueType();
2904 int64_t Val = C->getSExtValue();
2905 if ((Val >= -65535) && (Val <= -1)) {
2906 Result = DAG.getTargetConstant(Val, Type);
2911 case 'O': // signed 15 bit immediate
2912 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2913 EVT Type = Op.getValueType();
2914 int64_t Val = C->getSExtValue();
2915 if ((isInt<15>(Val))) {
2916 Result = DAG.getTargetConstant(Val, Type);
2921 case 'P': // immediate in the range of 1 to 65535 (inclusive)
2922 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
2923 EVT Type = Op.getValueType();
2924 int64_t Val = C->getSExtValue();
2925 if ((Val <= 65535) && (Val >= 1)) {
2926 Result = DAG.getTargetConstant(Val, Type);
2933 if (Result.getNode()) {
2934 Ops.push_back(Result);
2938 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
2942 MipsTargetLowering::isLegalAddressingMode(const AddrMode &AM, Type *Ty) const {
2943 // No global is ever allowed as a base.
2948 case 0: // "r+i" or just "i", depending on HasBaseReg.
2951 if (!AM.HasBaseReg) // allow "r+i".
2953 return false; // disallow "r+r" or "r+r+i".
2962 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
2963 // The Mips target isn't yet aware of offsets.
2967 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
2969 bool IsMemset, bool ZeroMemset,
2971 MachineFunction &MF) const {
2972 if (Subtarget->hasMips64())
2978 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
2979 if (VT != MVT::f32 && VT != MVT::f64)
2981 if (Imm.isNegZero())
2983 return Imm.isZero();
2986 unsigned MipsTargetLowering::getJumpTableEncoding() const {
2988 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
2990 return TargetLowering::getJumpTableEncoding();
2993 /// This function returns true if CallSym is a long double emulation routine.
2994 static bool isF128SoftLibCall(const char *CallSym) {
2995 const char *const LibCalls[] =
2996 {"__addtf3", "__divtf3", "__eqtf2", "__extenddftf2", "__extendsftf2",
2997 "__fixtfdi", "__fixtfsi", "__fixtfti", "__fixunstfdi", "__fixunstfsi",
2998 "__fixunstfti", "__floatditf", "__floatsitf", "__floattitf",
2999 "__floatunditf", "__floatunsitf", "__floatuntitf", "__getf2", "__gttf2",
3000 "__letf2", "__lttf2", "__multf3", "__netf2", "__powitf2", "__subtf3",
3001 "__trunctfdf2", "__trunctfsf2", "__unordtf2",
3002 "ceill", "copysignl", "cosl", "exp2l", "expl", "floorl", "fmal", "fmodl",
3003 "log10l", "log2l", "logl", "nearbyintl", "powl", "rintl", "sinl", "sqrtl",
3006 const char * const *End = LibCalls + array_lengthof(LibCalls);
3008 // Check that LibCalls is sorted alphabetically.
3009 MipsTargetLowering::LTStr Comp;
3012 for (const char * const *I = LibCalls; I < End - 1; ++I)
3013 assert(Comp(*I, *(I + 1)));
3016 return std::binary_search(LibCalls, End, CallSym, Comp);
3019 /// This function returns true if Ty is fp128 or i128 which was originally a
3021 static bool originalTypeIsF128(const Type *Ty, const SDNode *CallNode) {
3022 if (Ty->isFP128Ty())
3025 const ExternalSymbolSDNode *ES =
3026 dyn_cast_or_null<const ExternalSymbolSDNode>(CallNode);
3028 // If the Ty is i128 and the function being called is a long double emulation
3029 // routine, then the original type is f128.
3030 return (ES && Ty->isIntegerTy(128) && isF128SoftLibCall(ES->getSymbol()));
3033 MipsTargetLowering::MipsCC::MipsCC(CallingConv::ID CC, bool IsO32_,
3035 : CCInfo(Info), CallConv(CC), IsO32(IsO32_) {
3036 // Pre-allocate reserved argument area.
3037 CCInfo.AllocateStack(reservedArgArea(), 1);
3040 void MipsTargetLowering::MipsCC::
3041 analyzeCallOperands(const SmallVectorImpl<ISD::OutputArg> &Args,
3042 bool IsVarArg, bool IsSoftFloat, const SDNode *CallNode,
3043 std::vector<ArgListEntry> &FuncArgs) {
3044 assert((CallConv != CallingConv::Fast || !IsVarArg) &&
3045 "CallingConv::Fast shouldn't be used for vararg functions.");
3047 unsigned NumOpnds = Args.size();
3048 llvm::CCAssignFn *FixedFn = fixedArgFn(), *VarFn = varArgFn();
3050 for (unsigned I = 0; I != NumOpnds; ++I) {
3051 MVT ArgVT = Args[I].VT;
3052 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3055 if (ArgFlags.isByVal()) {
3056 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3060 if (IsVarArg && !Args[I].IsFixed)
3061 R = VarFn(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
3063 MVT RegVT = getRegVT(ArgVT, FuncArgs[Args[I].OrigArgIndex].Ty, CallNode,
3065 R = FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo);
3070 dbgs() << "Call operand #" << I << " has unhandled type "
3071 << EVT(ArgVT).getEVTString();
3073 llvm_unreachable(0);
3078 void MipsTargetLowering::MipsCC::
3079 analyzeFormalArguments(const SmallVectorImpl<ISD::InputArg> &Args,
3080 bool IsSoftFloat, Function::const_arg_iterator FuncArg) {
3081 unsigned NumArgs = Args.size();
3082 llvm::CCAssignFn *FixedFn = fixedArgFn();
3083 unsigned CurArgIdx = 0;
3085 for (unsigned I = 0; I != NumArgs; ++I) {
3086 MVT ArgVT = Args[I].VT;
3087 ISD::ArgFlagsTy ArgFlags = Args[I].Flags;
3088 std::advance(FuncArg, Args[I].OrigArgIndex - CurArgIdx);
3089 CurArgIdx = Args[I].OrigArgIndex;
3091 if (ArgFlags.isByVal()) {
3092 handleByValArg(I, ArgVT, ArgVT, CCValAssign::Full, ArgFlags);
3096 MVT RegVT = getRegVT(ArgVT, FuncArg->getType(), 0, IsSoftFloat);
3098 if (!FixedFn(I, ArgVT, RegVT, CCValAssign::Full, ArgFlags, CCInfo))
3102 dbgs() << "Formal Arg #" << I << " has unhandled type "
3103 << EVT(ArgVT).getEVTString();
3105 llvm_unreachable(0);
3109 template<typename Ty>
3110 void MipsTargetLowering::MipsCC::
3111 analyzeReturn(const SmallVectorImpl<Ty> &RetVals, bool IsSoftFloat,
3112 const SDNode *CallNode, const Type *RetTy) const {
3115 if (IsSoftFloat && originalTypeIsF128(RetTy, CallNode))
3116 Fn = RetCC_F128Soft;
3120 for (unsigned I = 0, E = RetVals.size(); I < E; ++I) {
3121 MVT VT = RetVals[I].VT;
3122 ISD::ArgFlagsTy Flags = RetVals[I].Flags;
3123 MVT RegVT = this->getRegVT(VT, RetTy, CallNode, IsSoftFloat);
3125 if (Fn(I, VT, RegVT, CCValAssign::Full, Flags, this->CCInfo)) {
3127 dbgs() << "Call result #" << I << " has unhandled type "
3128 << EVT(VT).getEVTString() << '\n';
3130 llvm_unreachable(0);
3135 void MipsTargetLowering::MipsCC::
3136 analyzeCallResult(const SmallVectorImpl<ISD::InputArg> &Ins, bool IsSoftFloat,
3137 const SDNode *CallNode, const Type *RetTy) const {
3138 analyzeReturn(Ins, IsSoftFloat, CallNode, RetTy);
3141 void MipsTargetLowering::MipsCC::
3142 analyzeReturn(const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsSoftFloat,
3143 const Type *RetTy) const {
3144 analyzeReturn(Outs, IsSoftFloat, 0, RetTy);
3148 MipsTargetLowering::MipsCC::handleByValArg(unsigned ValNo, MVT ValVT,
3150 CCValAssign::LocInfo LocInfo,
3151 ISD::ArgFlagsTy ArgFlags) {
3152 assert(ArgFlags.getByValSize() && "Byval argument's size shouldn't be 0.");
3154 struct ByValArgInfo ByVal;
3155 unsigned RegSize = regSize();
3156 unsigned ByValSize = RoundUpToAlignment(ArgFlags.getByValSize(), RegSize);
3157 unsigned Align = std::min(std::max(ArgFlags.getByValAlign(), RegSize),
3160 if (useRegsForByval())
3161 allocateRegs(ByVal, ByValSize, Align);
3163 // Allocate space on caller's stack.
3164 ByVal.Address = CCInfo.AllocateStack(ByValSize - RegSize * ByVal.NumRegs,
3166 CCInfo.addLoc(CCValAssign::getMem(ValNo, ValVT, ByVal.Address, LocVT,
3168 ByValArgs.push_back(ByVal);
3171 unsigned MipsTargetLowering::MipsCC::numIntArgRegs() const {
3172 return IsO32 ? array_lengthof(O32IntRegs) : array_lengthof(Mips64IntRegs);
3175 unsigned MipsTargetLowering::MipsCC::reservedArgArea() const {
3176 return (IsO32 && (CallConv != CallingConv::Fast)) ? 16 : 0;
3179 const uint16_t *MipsTargetLowering::MipsCC::intArgRegs() const {
3180 return IsO32 ? O32IntRegs : Mips64IntRegs;
3183 llvm::CCAssignFn *MipsTargetLowering::MipsCC::fixedArgFn() const {
3184 if (CallConv == CallingConv::Fast)
3185 return CC_Mips_FastCC;
3187 return IsO32 ? CC_MipsO32 : CC_MipsN;
3190 llvm::CCAssignFn *MipsTargetLowering::MipsCC::varArgFn() const {
3191 return IsO32 ? CC_MipsO32 : CC_MipsN_VarArg;
3194 const uint16_t *MipsTargetLowering::MipsCC::shadowRegs() const {
3195 return IsO32 ? O32IntRegs : Mips64DPRegs;
3198 void MipsTargetLowering::MipsCC::allocateRegs(ByValArgInfo &ByVal,
3201 unsigned RegSize = regSize(), NumIntArgRegs = numIntArgRegs();
3202 const uint16_t *IntArgRegs = intArgRegs(), *ShadowRegs = shadowRegs();
3203 assert(!(ByValSize % RegSize) && !(Align % RegSize) &&
3204 "Byval argument's size and alignment should be a multiple of"
3207 ByVal.FirstIdx = CCInfo.getFirstUnallocated(IntArgRegs, NumIntArgRegs);
3209 // If Align > RegSize, the first arg register must be even.
3210 if ((Align > RegSize) && (ByVal.FirstIdx % 2)) {
3211 CCInfo.AllocateReg(IntArgRegs[ByVal.FirstIdx], ShadowRegs[ByVal.FirstIdx]);
3215 // Mark the registers allocated.
3216 for (unsigned I = ByVal.FirstIdx; ByValSize && (I < NumIntArgRegs);
3217 ByValSize -= RegSize, ++I, ++ByVal.NumRegs)
3218 CCInfo.AllocateReg(IntArgRegs[I], ShadowRegs[I]);
3221 MVT MipsTargetLowering::MipsCC::getRegVT(MVT VT, const Type *OrigTy,
3222 const SDNode *CallNode,
3223 bool IsSoftFloat) const {
3224 if (IsSoftFloat || IsO32)
3227 // Check if the original type was fp128.
3228 if (originalTypeIsF128(OrigTy, CallNode)) {
3229 assert(VT == MVT::i64);
3236 void MipsTargetLowering::
3237 copyByValRegs(SDValue Chain, DebugLoc DL, std::vector<SDValue> &OutChains,
3238 SelectionDAG &DAG, const ISD::ArgFlagsTy &Flags,
3239 SmallVectorImpl<SDValue> &InVals, const Argument *FuncArg,
3240 const MipsCC &CC, const ByValArgInfo &ByVal) const {
3241 MachineFunction &MF = DAG.getMachineFunction();
3242 MachineFrameInfo *MFI = MF.getFrameInfo();
3243 unsigned RegAreaSize = ByVal.NumRegs * CC.regSize();
3244 unsigned FrameObjSize = std::max(Flags.getByValSize(), RegAreaSize);
3248 FrameObjOffset = (int)CC.reservedArgArea() -
3249 (int)((CC.numIntArgRegs() - ByVal.FirstIdx) * CC.regSize());
3251 FrameObjOffset = ByVal.Address;
3253 // Create frame object.
3254 EVT PtrTy = getPointerTy();
3255 int FI = MFI->CreateFixedObject(FrameObjSize, FrameObjOffset, true);
3256 SDValue FIN = DAG.getFrameIndex(FI, PtrTy);
3257 InVals.push_back(FIN);
3262 // Copy arg registers.
3263 MVT RegTy = MVT::getIntegerVT(CC.regSize() * 8);
3264 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3266 for (unsigned I = 0; I < ByVal.NumRegs; ++I) {
3267 unsigned ArgReg = CC.intArgRegs()[ByVal.FirstIdx + I];
3268 unsigned VReg = addLiveIn(MF, ArgReg, RC);
3269 unsigned Offset = I * CC.regSize();
3270 SDValue StorePtr = DAG.getNode(ISD::ADD, DL, PtrTy, FIN,
3271 DAG.getConstant(Offset, PtrTy));
3272 SDValue Store = DAG.getStore(Chain, DL, DAG.getRegister(VReg, RegTy),
3273 StorePtr, MachinePointerInfo(FuncArg, Offset),
3275 OutChains.push_back(Store);
3279 // Copy byVal arg to registers and stack.
3280 void MipsTargetLowering::
3281 passByValArg(SDValue Chain, DebugLoc DL,
3282 std::deque< std::pair<unsigned, SDValue> > &RegsToPass,
3283 SmallVector<SDValue, 8> &MemOpChains, SDValue StackPtr,
3284 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
3285 const MipsCC &CC, const ByValArgInfo &ByVal,
3286 const ISD::ArgFlagsTy &Flags, bool isLittle) const {
3287 unsigned ByValSize = Flags.getByValSize();
3288 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
3289 unsigned RegSize = CC.regSize();
3290 unsigned Alignment = std::min(Flags.getByValAlign(), RegSize);
3291 EVT PtrTy = getPointerTy(), RegTy = MVT::getIntegerVT(RegSize * 8);
3293 if (ByVal.NumRegs) {
3294 const uint16_t *ArgRegs = CC.intArgRegs();
3295 bool LeftoverBytes = (ByVal.NumRegs * RegSize > ByValSize);
3298 // Copy words to registers.
3299 for (; I < ByVal.NumRegs - LeftoverBytes; ++I, Offset += RegSize) {
3300 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3301 DAG.getConstant(Offset, PtrTy));
3302 SDValue LoadVal = DAG.getLoad(RegTy, DL, Chain, LoadPtr,
3303 MachinePointerInfo(), false, false, false,
3305 MemOpChains.push_back(LoadVal.getValue(1));
3306 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3307 RegsToPass.push_back(std::make_pair(ArgReg, LoadVal));
3310 // Return if the struct has been fully copied.
3311 if (ByValSize == Offset)
3314 // Copy the remainder of the byval argument with sub-word loads and shifts.
3315 if (LeftoverBytes) {
3316 assert((ByValSize > Offset) && (ByValSize < Offset + RegSize) &&
3317 "Size of the remainder should be smaller than RegSize.");
3320 for (unsigned LoadSize = RegSize / 2, TotalSizeLoaded = 0;
3321 Offset < ByValSize; LoadSize /= 2) {
3322 unsigned RemSize = ByValSize - Offset;
3324 if (RemSize < LoadSize)
3328 SDValue LoadPtr = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3329 DAG.getConstant(Offset, PtrTy));
3331 DAG.getExtLoad(ISD::ZEXTLOAD, DL, RegTy, Chain, LoadPtr,
3332 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
3333 false, false, Alignment);
3334 MemOpChains.push_back(LoadVal.getValue(1));
3336 // Shift the loaded value.
3340 Shamt = TotalSizeLoaded;
3342 Shamt = (RegSize - (TotalSizeLoaded + LoadSize)) * 8;
3344 SDValue Shift = DAG.getNode(ISD::SHL, DL, RegTy, LoadVal,
3345 DAG.getConstant(Shamt, MVT::i32));
3348 Val = DAG.getNode(ISD::OR, DL, RegTy, Val, Shift);
3353 TotalSizeLoaded += LoadSize;
3354 Alignment = std::min(Alignment, LoadSize);
3357 unsigned ArgReg = ArgRegs[ByVal.FirstIdx + I];
3358 RegsToPass.push_back(std::make_pair(ArgReg, Val));
3363 // Copy remainder of byval arg to it with memcpy.
3364 unsigned MemCpySize = ByValSize - Offset;
3365 SDValue Src = DAG.getNode(ISD::ADD, DL, PtrTy, Arg,
3366 DAG.getConstant(Offset, PtrTy));
3367 SDValue Dst = DAG.getNode(ISD::ADD, DL, PtrTy, StackPtr,
3368 DAG.getIntPtrConstant(ByVal.Address));
3369 Chain = DAG.getMemcpy(Chain, DL, Dst, Src,
3370 DAG.getConstant(MemCpySize, PtrTy), Alignment,
3371 /*isVolatile=*/false, /*AlwaysInline=*/false,
3372 MachinePointerInfo(0), MachinePointerInfo(0));
3373 MemOpChains.push_back(Chain);
3377 MipsTargetLowering::writeVarArgRegs(std::vector<SDValue> &OutChains,
3378 const MipsCC &CC, SDValue Chain,
3379 DebugLoc DL, SelectionDAG &DAG) const {
3380 unsigned NumRegs = CC.numIntArgRegs();
3381 const uint16_t *ArgRegs = CC.intArgRegs();
3382 const CCState &CCInfo = CC.getCCInfo();
3383 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumRegs);
3384 unsigned RegSize = CC.regSize();
3385 MVT RegTy = MVT::getIntegerVT(RegSize * 8);
3386 const TargetRegisterClass *RC = getRegClassFor(RegTy);
3387 MachineFunction &MF = DAG.getMachineFunction();
3388 MachineFrameInfo *MFI = MF.getFrameInfo();
3389 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3391 // Offset of the first variable argument from stack pointer.
3395 VaArgOffset = RoundUpToAlignment(CCInfo.getNextStackOffset(), RegSize);
3398 (int)CC.reservedArgArea() - (int)(RegSize * (NumRegs - Idx));
3400 // Record the frame index of the first variable argument
3401 // which is a value necessary to VASTART.
3402 int FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3403 MipsFI->setVarArgsFrameIndex(FI);
3405 // Copy the integer registers that have not been used for argument passing
3406 // to the argument register save area. For O32, the save area is allocated
3407 // in the caller's stack frame, while for N32/64, it is allocated in the
3408 // callee's stack frame.
3409 for (unsigned I = Idx; I < NumRegs; ++I, VaArgOffset += RegSize) {
3410 unsigned Reg = addLiveIn(MF, ArgRegs[I], RC);
3411 SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegTy);
3412 FI = MFI->CreateFixedObject(RegSize, VaArgOffset, true);
3413 SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy());
3414 SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
3415 MachinePointerInfo(), false, false, 0);
3416 cast<StoreSDNode>(Store.getNode())->getMemOperand()->setValue(0);
3417 OutChains.push_back(Store);