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 //===----------------------------------------------------------------------===//
15 #define DEBUG_TYPE "mips-lower"
16 #include "MipsISelLowering.h"
17 #include "MipsMachineFunction.h"
18 #include "MipsTargetMachine.h"
19 #include "MipsTargetObjectFile.h"
20 #include "MipsSubtarget.h"
21 #include "InstPrinter/MipsInstPrinter.h"
22 #include "MCTargetDesc/MipsBaseInfo.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Function.h"
25 #include "llvm/GlobalVariable.h"
26 #include "llvm/Intrinsics.h"
27 #include "llvm/CallingConv.h"
28 #include "llvm/CodeGen/CallingConvLower.h"
29 #include "llvm/CodeGen/MachineFrameInfo.h"
30 #include "llvm/CodeGen/MachineFunction.h"
31 #include "llvm/CodeGen/MachineInstrBuilder.h"
32 #include "llvm/CodeGen/MachineRegisterInfo.h"
33 #include "llvm/CodeGen/SelectionDAGISel.h"
34 #include "llvm/CodeGen/ValueTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/ErrorHandling.h"
37 #include "llvm/Support/raw_ostream.h"
41 // If I is a shifted mask, set the size (Size) and the first bit of the
42 // mask (Pos), and return true.
43 // For example, if I is 0x003ff800, (Pos, Size) = (11, 11).
44 static bool IsShiftedMask(uint64_t I, uint64_t &Pos, uint64_t &Size) {
45 if (!isShiftedMask_64(I))
48 Size = CountPopulation_64(I);
49 Pos = CountTrailingZeros_64(I);
53 static SDValue GetGlobalReg(SelectionDAG &DAG, EVT Ty) {
54 MipsFunctionInfo *FI = DAG.getMachineFunction().getInfo<MipsFunctionInfo>();
55 return DAG.getRegister(FI->getGlobalBaseReg(), Ty);
58 const char *MipsTargetLowering::getTargetNodeName(unsigned Opcode) const {
60 case MipsISD::JmpLink: return "MipsISD::JmpLink";
61 case MipsISD::Hi: return "MipsISD::Hi";
62 case MipsISD::Lo: return "MipsISD::Lo";
63 case MipsISD::GPRel: return "MipsISD::GPRel";
64 case MipsISD::ThreadPointer: return "MipsISD::ThreadPointer";
65 case MipsISD::Ret: return "MipsISD::Ret";
66 case MipsISD::FPBrcond: return "MipsISD::FPBrcond";
67 case MipsISD::FPCmp: return "MipsISD::FPCmp";
68 case MipsISD::CMovFP_T: return "MipsISD::CMovFP_T";
69 case MipsISD::CMovFP_F: return "MipsISD::CMovFP_F";
70 case MipsISD::FPRound: return "MipsISD::FPRound";
71 case MipsISD::MAdd: return "MipsISD::MAdd";
72 case MipsISD::MAddu: return "MipsISD::MAddu";
73 case MipsISD::MSub: return "MipsISD::MSub";
74 case MipsISD::MSubu: return "MipsISD::MSubu";
75 case MipsISD::DivRem: return "MipsISD::DivRem";
76 case MipsISD::DivRemU: return "MipsISD::DivRemU";
77 case MipsISD::BuildPairF64: return "MipsISD::BuildPairF64";
78 case MipsISD::ExtractElementF64: return "MipsISD::ExtractElementF64";
79 case MipsISD::Wrapper: return "MipsISD::Wrapper";
80 case MipsISD::DynAlloc: return "MipsISD::DynAlloc";
81 case MipsISD::Sync: return "MipsISD::Sync";
82 case MipsISD::Ext: return "MipsISD::Ext";
83 case MipsISD::Ins: return "MipsISD::Ins";
84 case MipsISD::LWL: return "MipsISD::LWL";
85 case MipsISD::LWR: return "MipsISD::LWR";
86 case MipsISD::SWL: return "MipsISD::SWL";
87 case MipsISD::SWR: return "MipsISD::SWR";
88 case MipsISD::LDL: return "MipsISD::LDL";
89 case MipsISD::LDR: return "MipsISD::LDR";
90 case MipsISD::SDL: return "MipsISD::SDL";
91 case MipsISD::SDR: return "MipsISD::SDR";
97 MipsTargetLowering(MipsTargetMachine &TM)
98 : TargetLowering(TM, new MipsTargetObjectFile()),
99 Subtarget(&TM.getSubtarget<MipsSubtarget>()),
100 HasMips64(Subtarget->hasMips64()), IsN64(Subtarget->isABI_N64()),
101 IsO32(Subtarget->isABI_O32()) {
103 // Mips does not have i1 type, so use i32 for
104 // setcc operations results (slt, sgt, ...).
105 setBooleanContents(ZeroOrOneBooleanContent);
106 setBooleanVectorContents(ZeroOrOneBooleanContent); // FIXME: Is this correct?
108 // Set up the register classes
109 addRegisterClass(MVT::i32, &Mips::CPURegsRegClass);
112 addRegisterClass(MVT::i64, &Mips::CPU64RegsRegClass);
114 if (Subtarget->inMips16Mode()) {
115 addRegisterClass(MVT::i32, &Mips::CPU16RegsRegClass);
116 addRegisterClass(MVT::i32, &Mips::CPURARegRegClass);
119 if (!TM.Options.UseSoftFloat) {
120 addRegisterClass(MVT::f32, &Mips::FGR32RegClass);
122 // When dealing with single precision only, use libcalls
123 if (!Subtarget->isSingleFloat()) {
125 addRegisterClass(MVT::f64, &Mips::FGR64RegClass);
127 addRegisterClass(MVT::f64, &Mips::AFGR64RegClass);
131 // Load extented operations for i1 types must be promoted
132 setLoadExtAction(ISD::EXTLOAD, MVT::i1, Promote);
133 setLoadExtAction(ISD::ZEXTLOAD, MVT::i1, Promote);
134 setLoadExtAction(ISD::SEXTLOAD, MVT::i1, Promote);
136 // MIPS doesn't have extending float->double load/store
137 setLoadExtAction(ISD::EXTLOAD, MVT::f32, Expand);
138 setTruncStoreAction(MVT::f64, MVT::f32, Expand);
140 // Used by legalize types to correctly generate the setcc result.
141 // Without this, every float setcc comes with a AND/OR with the result,
142 // we don't want this, since the fpcmp result goes to a flag register,
143 // which is used implicitly by brcond and select operations.
144 AddPromotedToType(ISD::SETCC, MVT::i1, MVT::i32);
146 // Mips Custom Operations
147 setOperationAction(ISD::GlobalAddress, MVT::i32, Custom);
148 setOperationAction(ISD::BlockAddress, MVT::i32, Custom);
149 setOperationAction(ISD::GlobalTLSAddress, MVT::i32, Custom);
150 setOperationAction(ISD::JumpTable, MVT::i32, Custom);
151 setOperationAction(ISD::ConstantPool, MVT::i32, Custom);
152 setOperationAction(ISD::SELECT, MVT::f32, Custom);
153 setOperationAction(ISD::SELECT, MVT::f64, Custom);
154 setOperationAction(ISD::SELECT, MVT::i32, Custom);
155 setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
156 setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
157 setOperationAction(ISD::SETCC, MVT::f32, Custom);
158 setOperationAction(ISD::SETCC, MVT::f64, Custom);
159 setOperationAction(ISD::BRCOND, MVT::Other, Custom);
160 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i32, Custom);
161 setOperationAction(ISD::VASTART, MVT::Other, Custom);
162 setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
163 setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
164 setOperationAction(ISD::MEMBARRIER, MVT::Other, Custom);
165 setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
166 setOperationAction(ISD::LOAD, MVT::i32, Custom);
167 setOperationAction(ISD::STORE, MVT::i32, Custom);
169 if (!TM.Options.NoNaNsFPMath) {
170 setOperationAction(ISD::FABS, MVT::f32, Custom);
171 setOperationAction(ISD::FABS, MVT::f64, Custom);
175 setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
176 setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
177 setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
178 setOperationAction(ISD::JumpTable, MVT::i64, Custom);
179 setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
180 setOperationAction(ISD::SELECT, MVT::i64, Custom);
181 setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
182 setOperationAction(ISD::LOAD, MVT::i64, Custom);
183 setOperationAction(ISD::STORE, MVT::i64, Custom);
187 setOperationAction(ISD::SHL_PARTS, MVT::i32, Custom);
188 setOperationAction(ISD::SRA_PARTS, MVT::i32, Custom);
189 setOperationAction(ISD::SRL_PARTS, MVT::i32, Custom);
192 setOperationAction(ISD::SDIV, MVT::i32, Expand);
193 setOperationAction(ISD::SREM, MVT::i32, Expand);
194 setOperationAction(ISD::UDIV, MVT::i32, Expand);
195 setOperationAction(ISD::UREM, MVT::i32, Expand);
196 setOperationAction(ISD::SDIV, MVT::i64, Expand);
197 setOperationAction(ISD::SREM, MVT::i64, Expand);
198 setOperationAction(ISD::UDIV, MVT::i64, Expand);
199 setOperationAction(ISD::UREM, MVT::i64, Expand);
201 // Operations not directly supported by Mips.
202 setOperationAction(ISD::BR_JT, MVT::Other, Expand);
203 setOperationAction(ISD::BR_CC, MVT::Other, Expand);
204 setOperationAction(ISD::SELECT_CC, MVT::Other, Expand);
205 setOperationAction(ISD::UINT_TO_FP, MVT::i32, Expand);
206 setOperationAction(ISD::UINT_TO_FP, MVT::i64, Expand);
207 setOperationAction(ISD::FP_TO_UINT, MVT::i32, Expand);
208 setOperationAction(ISD::FP_TO_UINT, MVT::i64, Expand);
209 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
210 setOperationAction(ISD::CTPOP, MVT::i32, Expand);
211 setOperationAction(ISD::CTPOP, MVT::i64, Expand);
212 setOperationAction(ISD::CTTZ, MVT::i32, Expand);
213 setOperationAction(ISD::CTTZ, MVT::i64, Expand);
214 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i32, Expand);
215 setOperationAction(ISD::CTTZ_ZERO_UNDEF, MVT::i64, Expand);
216 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i32, Expand);
217 setOperationAction(ISD::CTLZ_ZERO_UNDEF, MVT::i64, Expand);
218 setOperationAction(ISD::ROTL, MVT::i32, Expand);
219 setOperationAction(ISD::ROTL, MVT::i64, Expand);
221 if (!Subtarget->hasMips32r2())
222 setOperationAction(ISD::ROTR, MVT::i32, Expand);
224 if (!Subtarget->hasMips64r2())
225 setOperationAction(ISD::ROTR, MVT::i64, Expand);
227 setOperationAction(ISD::FSIN, MVT::f32, Expand);
228 setOperationAction(ISD::FSIN, MVT::f64, Expand);
229 setOperationAction(ISD::FCOS, MVT::f32, Expand);
230 setOperationAction(ISD::FCOS, MVT::f64, Expand);
231 setOperationAction(ISD::FPOWI, MVT::f32, Expand);
232 setOperationAction(ISD::FPOW, MVT::f32, Expand);
233 setOperationAction(ISD::FPOW, MVT::f64, Expand);
234 setOperationAction(ISD::FLOG, MVT::f32, Expand);
235 setOperationAction(ISD::FLOG2, MVT::f32, Expand);
236 setOperationAction(ISD::FLOG10, MVT::f32, Expand);
237 setOperationAction(ISD::FEXP, MVT::f32, Expand);
238 setOperationAction(ISD::FMA, MVT::f32, Expand);
239 setOperationAction(ISD::FMA, MVT::f64, Expand);
240 setOperationAction(ISD::FREM, MVT::f32, Expand);
241 setOperationAction(ISD::FREM, MVT::f64, Expand);
243 if (!TM.Options.NoNaNsFPMath) {
244 setOperationAction(ISD::FNEG, MVT::f32, Expand);
245 setOperationAction(ISD::FNEG, MVT::f64, Expand);
248 setOperationAction(ISD::EXCEPTIONADDR, MVT::i32, Expand);
249 setOperationAction(ISD::EXCEPTIONADDR, MVT::i64, Expand);
250 setOperationAction(ISD::EHSELECTION, MVT::i32, Expand);
251 setOperationAction(ISD::EHSELECTION, MVT::i64, Expand);
253 setOperationAction(ISD::VAARG, MVT::Other, Expand);
254 setOperationAction(ISD::VACOPY, MVT::Other, Expand);
255 setOperationAction(ISD::VAEND, MVT::Other, Expand);
257 // Use the default for now
258 setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
259 setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
261 setOperationAction(ISD::ATOMIC_LOAD, MVT::i32, Expand);
262 setOperationAction(ISD::ATOMIC_LOAD, MVT::i64, Expand);
263 setOperationAction(ISD::ATOMIC_STORE, MVT::i32, Expand);
264 setOperationAction(ISD::ATOMIC_STORE, MVT::i64, Expand);
266 setInsertFencesForAtomic(true);
268 if (!Subtarget->hasSEInReg()) {
269 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i8, Expand);
270 setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i16, Expand);
273 if (!Subtarget->hasBitCount()) {
274 setOperationAction(ISD::CTLZ, MVT::i32, Expand);
275 setOperationAction(ISD::CTLZ, MVT::i64, Expand);
278 if (!Subtarget->hasSwap()) {
279 setOperationAction(ISD::BSWAP, MVT::i32, Expand);
280 setOperationAction(ISD::BSWAP, MVT::i64, Expand);
284 setLoadExtAction(ISD::SEXTLOAD, MVT::i32, Custom);
285 setLoadExtAction(ISD::ZEXTLOAD, MVT::i32, Custom);
286 setLoadExtAction(ISD::EXTLOAD, MVT::i32, Custom);
287 setTruncStoreAction(MVT::i64, MVT::i32, Custom);
290 setTargetDAGCombine(ISD::ADDE);
291 setTargetDAGCombine(ISD::SUBE);
292 setTargetDAGCombine(ISD::SDIVREM);
293 setTargetDAGCombine(ISD::UDIVREM);
294 setTargetDAGCombine(ISD::SELECT);
295 setTargetDAGCombine(ISD::AND);
296 setTargetDAGCombine(ISD::OR);
297 setTargetDAGCombine(ISD::ADD);
299 setMinFunctionAlignment(HasMips64 ? 3 : 2);
301 setStackPointerRegisterToSaveRestore(IsN64 ? Mips::SP_64 : Mips::SP);
302 computeRegisterProperties();
304 setExceptionPointerRegister(IsN64 ? Mips::A0_64 : Mips::A0);
305 setExceptionSelectorRegister(IsN64 ? Mips::A1_64 : Mips::A1);
307 maxStoresPerMemcpy = 16;
310 bool MipsTargetLowering::allowsUnalignedMemoryAccesses(EVT VT) const {
311 MVT::SimpleValueType SVT = VT.getSimpleVT().SimpleTy;
318 return Subtarget->hasMips32r2Or64();
324 EVT MipsTargetLowering::getSetCCResultType(EVT VT) const {
329 // Transforms a subgraph in CurDAG if the following pattern is found:
330 // (addc multLo, Lo0), (adde multHi, Hi0),
332 // multHi/Lo: product of multiplication
333 // Lo0: initial value of Lo register
334 // Hi0: initial value of Hi register
335 // Return true if pattern matching was successful.
336 static bool SelectMadd(SDNode *ADDENode, SelectionDAG *CurDAG) {
337 // ADDENode's second operand must be a flag output of an ADDC node in order
338 // for the matching to be successful.
339 SDNode *ADDCNode = ADDENode->getOperand(2).getNode();
341 if (ADDCNode->getOpcode() != ISD::ADDC)
344 SDValue MultHi = ADDENode->getOperand(0);
345 SDValue MultLo = ADDCNode->getOperand(0);
346 SDNode *MultNode = MultHi.getNode();
347 unsigned MultOpc = MultHi.getOpcode();
349 // MultHi and MultLo must be generated by the same node,
350 if (MultLo.getNode() != MultNode)
353 // and it must be a multiplication.
354 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
357 // MultLo amd MultHi must be the first and second output of MultNode
359 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
362 // Transform this to a MADD only if ADDENode and ADDCNode are the only users
363 // of the values of MultNode, in which case MultNode will be removed in later
365 // If there exist users other than ADDENode or ADDCNode, this function returns
366 // here, which will result in MultNode being mapped to a single MULT
367 // instruction node rather than a pair of MULT and MADD instructions being
369 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
372 SDValue Chain = CurDAG->getEntryNode();
373 DebugLoc dl = ADDENode->getDebugLoc();
375 // create MipsMAdd(u) node
376 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MAddu : MipsISD::MAdd;
378 SDValue MAdd = CurDAG->getNode(MultOpc, dl, MVT::Glue,
379 MultNode->getOperand(0),// Factor 0
380 MultNode->getOperand(1),// Factor 1
381 ADDCNode->getOperand(1),// Lo0
382 ADDENode->getOperand(1));// Hi0
384 // create CopyFromReg nodes
385 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
387 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
389 CopyFromLo.getValue(2));
391 // replace uses of adde and addc here
392 if (!SDValue(ADDCNode, 0).use_empty())
393 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDCNode, 0), CopyFromLo);
395 if (!SDValue(ADDENode, 0).use_empty())
396 CurDAG->ReplaceAllUsesOfValueWith(SDValue(ADDENode, 0), CopyFromHi);
402 // Transforms a subgraph in CurDAG if the following pattern is found:
403 // (addc Lo0, multLo), (sube Hi0, multHi),
405 // multHi/Lo: product of multiplication
406 // Lo0: initial value of Lo register
407 // Hi0: initial value of Hi register
408 // Return true if pattern matching was successful.
409 static bool SelectMsub(SDNode *SUBENode, SelectionDAG *CurDAG) {
410 // SUBENode's second operand must be a flag output of an SUBC node in order
411 // for the matching to be successful.
412 SDNode *SUBCNode = SUBENode->getOperand(2).getNode();
414 if (SUBCNode->getOpcode() != ISD::SUBC)
417 SDValue MultHi = SUBENode->getOperand(1);
418 SDValue MultLo = SUBCNode->getOperand(1);
419 SDNode *MultNode = MultHi.getNode();
420 unsigned MultOpc = MultHi.getOpcode();
422 // MultHi and MultLo must be generated by the same node,
423 if (MultLo.getNode() != MultNode)
426 // and it must be a multiplication.
427 if (MultOpc != ISD::SMUL_LOHI && MultOpc != ISD::UMUL_LOHI)
430 // MultLo amd MultHi must be the first and second output of MultNode
432 if (MultHi.getResNo() != 1 || MultLo.getResNo() != 0)
435 // Transform this to a MSUB only if SUBENode and SUBCNode are the only users
436 // of the values of MultNode, in which case MultNode will be removed in later
438 // If there exist users other than SUBENode or SUBCNode, this function returns
439 // here, which will result in MultNode being mapped to a single MULT
440 // instruction node rather than a pair of MULT and MSUB instructions being
442 if (!MultHi.hasOneUse() || !MultLo.hasOneUse())
445 SDValue Chain = CurDAG->getEntryNode();
446 DebugLoc dl = SUBENode->getDebugLoc();
448 // create MipsSub(u) node
449 MultOpc = MultOpc == ISD::UMUL_LOHI ? MipsISD::MSubu : MipsISD::MSub;
451 SDValue MSub = CurDAG->getNode(MultOpc, dl, MVT::Glue,
452 MultNode->getOperand(0),// Factor 0
453 MultNode->getOperand(1),// Factor 1
454 SUBCNode->getOperand(0),// Lo0
455 SUBENode->getOperand(0));// Hi0
457 // create CopyFromReg nodes
458 SDValue CopyFromLo = CurDAG->getCopyFromReg(Chain, dl, Mips::LO, MVT::i32,
460 SDValue CopyFromHi = CurDAG->getCopyFromReg(CopyFromLo.getValue(1), dl,
462 CopyFromLo.getValue(2));
464 // replace uses of sube and subc here
465 if (!SDValue(SUBCNode, 0).use_empty())
466 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBCNode, 0), CopyFromLo);
468 if (!SDValue(SUBENode, 0).use_empty())
469 CurDAG->ReplaceAllUsesOfValueWith(SDValue(SUBENode, 0), CopyFromHi);
474 static SDValue PerformADDECombine(SDNode *N, SelectionDAG &DAG,
475 TargetLowering::DAGCombinerInfo &DCI,
476 const MipsSubtarget *Subtarget) {
477 if (DCI.isBeforeLegalize())
480 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
482 return SDValue(N, 0);
487 static SDValue PerformSUBECombine(SDNode *N, SelectionDAG &DAG,
488 TargetLowering::DAGCombinerInfo &DCI,
489 const MipsSubtarget *Subtarget) {
490 if (DCI.isBeforeLegalize())
493 if (Subtarget->hasMips32() && N->getValueType(0) == MVT::i32 &&
495 return SDValue(N, 0);
500 static SDValue PerformDivRemCombine(SDNode *N, SelectionDAG &DAG,
501 TargetLowering::DAGCombinerInfo &DCI,
502 const MipsSubtarget *Subtarget) {
503 if (DCI.isBeforeLegalizeOps())
506 EVT Ty = N->getValueType(0);
507 unsigned LO = (Ty == MVT::i32) ? Mips::LO : Mips::LO64;
508 unsigned HI = (Ty == MVT::i32) ? Mips::HI : Mips::HI64;
509 unsigned opc = N->getOpcode() == ISD::SDIVREM ? MipsISD::DivRem :
511 DebugLoc dl = N->getDebugLoc();
513 SDValue DivRem = DAG.getNode(opc, dl, MVT::Glue,
514 N->getOperand(0), N->getOperand(1));
515 SDValue InChain = DAG.getEntryNode();
516 SDValue InGlue = DivRem;
519 if (N->hasAnyUseOfValue(0)) {
520 SDValue CopyFromLo = DAG.getCopyFromReg(InChain, dl, LO, Ty,
522 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), CopyFromLo);
523 InChain = CopyFromLo.getValue(1);
524 InGlue = CopyFromLo.getValue(2);
528 if (N->hasAnyUseOfValue(1)) {
529 SDValue CopyFromHi = DAG.getCopyFromReg(InChain, dl,
531 DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), CopyFromHi);
537 static Mips::CondCode FPCondCCodeToFCC(ISD::CondCode CC) {
539 default: llvm_unreachable("Unknown fp condition code!");
541 case ISD::SETOEQ: return Mips::FCOND_OEQ;
542 case ISD::SETUNE: return Mips::FCOND_UNE;
544 case ISD::SETOLT: return Mips::FCOND_OLT;
546 case ISD::SETOGT: return Mips::FCOND_OGT;
548 case ISD::SETOLE: return Mips::FCOND_OLE;
550 case ISD::SETOGE: return Mips::FCOND_OGE;
551 case ISD::SETULT: return Mips::FCOND_ULT;
552 case ISD::SETULE: return Mips::FCOND_ULE;
553 case ISD::SETUGT: return Mips::FCOND_UGT;
554 case ISD::SETUGE: return Mips::FCOND_UGE;
555 case ISD::SETUO: return Mips::FCOND_UN;
556 case ISD::SETO: return Mips::FCOND_OR;
558 case ISD::SETONE: return Mips::FCOND_ONE;
559 case ISD::SETUEQ: return Mips::FCOND_UEQ;
564 // Returns true if condition code has to be inverted.
565 static bool InvertFPCondCode(Mips::CondCode CC) {
566 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
569 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
570 "Illegal Condition Code");
575 // Creates and returns an FPCmp node from a setcc node.
576 // Returns Op if setcc is not a floating point comparison.
577 static SDValue CreateFPCmp(SelectionDAG &DAG, const SDValue &Op) {
578 // must be a SETCC node
579 if (Op.getOpcode() != ISD::SETCC)
582 SDValue LHS = Op.getOperand(0);
584 if (!LHS.getValueType().isFloatingPoint())
587 SDValue RHS = Op.getOperand(1);
588 DebugLoc dl = Op.getDebugLoc();
590 // Assume the 3rd operand is a CondCodeSDNode. Add code to check the type of
591 // node if necessary.
592 ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
594 return DAG.getNode(MipsISD::FPCmp, dl, MVT::Glue, LHS, RHS,
595 DAG.getConstant(FPCondCCodeToFCC(CC), MVT::i32));
598 // Creates and returns a CMovFPT/F node.
599 static SDValue CreateCMovFP(SelectionDAG &DAG, SDValue Cond, SDValue True,
600 SDValue False, DebugLoc DL) {
601 bool invert = InvertFPCondCode((Mips::CondCode)
602 cast<ConstantSDNode>(Cond.getOperand(2))
605 return DAG.getNode((invert ? MipsISD::CMovFP_F : MipsISD::CMovFP_T), DL,
606 True.getValueType(), True, False, Cond);
609 static SDValue PerformSELECTCombine(SDNode *N, SelectionDAG &DAG,
610 TargetLowering::DAGCombinerInfo &DCI,
611 const MipsSubtarget *Subtarget) {
612 if (DCI.isBeforeLegalizeOps())
615 SDValue SetCC = N->getOperand(0);
617 if ((SetCC.getOpcode() != ISD::SETCC) ||
618 !SetCC.getOperand(0).getValueType().isInteger())
621 SDValue False = N->getOperand(2);
622 EVT FalseTy = False.getValueType();
624 if (!FalseTy.isInteger())
627 ConstantSDNode *CN = dyn_cast<ConstantSDNode>(False);
629 if (!CN || CN->getZExtValue())
632 const DebugLoc DL = N->getDebugLoc();
633 ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
634 SDValue True = N->getOperand(1);
636 SetCC = DAG.getSetCC(DL, SetCC.getValueType(), SetCC.getOperand(0),
637 SetCC.getOperand(1), ISD::getSetCCInverse(CC, true));
639 return DAG.getNode(ISD::SELECT, DL, FalseTy, SetCC, False, True);
642 static SDValue PerformANDCombine(SDNode *N, SelectionDAG &DAG,
643 TargetLowering::DAGCombinerInfo &DCI,
644 const MipsSubtarget *Subtarget) {
645 // Pattern match EXT.
646 // $dst = and ((sra or srl) $src , pos), (2**size - 1)
647 // => ext $dst, $src, size, pos
648 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
651 SDValue ShiftRight = N->getOperand(0), Mask = N->getOperand(1);
652 unsigned ShiftRightOpc = ShiftRight.getOpcode();
654 // Op's first operand must be a shift right.
655 if (ShiftRightOpc != ISD::SRA && ShiftRightOpc != ISD::SRL)
658 // The second operand of the shift must be an immediate.
660 if (!(CN = dyn_cast<ConstantSDNode>(ShiftRight.getOperand(1))))
663 uint64_t Pos = CN->getZExtValue();
664 uint64_t SMPos, SMSize;
666 // Op's second operand must be a shifted mask.
667 if (!(CN = dyn_cast<ConstantSDNode>(Mask)) ||
668 !IsShiftedMask(CN->getZExtValue(), SMPos, SMSize))
671 // Return if the shifted mask does not start at bit 0 or the sum of its size
672 // and Pos exceeds the word's size.
673 EVT ValTy = N->getValueType(0);
674 if (SMPos != 0 || Pos + SMSize > ValTy.getSizeInBits())
677 return DAG.getNode(MipsISD::Ext, N->getDebugLoc(), ValTy,
678 ShiftRight.getOperand(0), DAG.getConstant(Pos, MVT::i32),
679 DAG.getConstant(SMSize, MVT::i32));
682 static SDValue PerformORCombine(SDNode *N, SelectionDAG &DAG,
683 TargetLowering::DAGCombinerInfo &DCI,
684 const MipsSubtarget *Subtarget) {
685 // Pattern match INS.
686 // $dst = or (and $src1 , mask0), (and (shl $src, pos), mask1),
687 // where mask1 = (2**size - 1) << pos, mask0 = ~mask1
688 // => ins $dst, $src, size, pos, $src1
689 if (DCI.isBeforeLegalizeOps() || !Subtarget->hasMips32r2())
692 SDValue And0 = N->getOperand(0), And1 = N->getOperand(1);
693 uint64_t SMPos0, SMSize0, SMPos1, SMSize1;
696 // See if Op's first operand matches (and $src1 , mask0).
697 if (And0.getOpcode() != ISD::AND)
700 if (!(CN = dyn_cast<ConstantSDNode>(And0.getOperand(1))) ||
701 !IsShiftedMask(~CN->getSExtValue(), SMPos0, SMSize0))
704 // See if Op's second operand matches (and (shl $src, pos), mask1).
705 if (And1.getOpcode() != ISD::AND)
708 if (!(CN = dyn_cast<ConstantSDNode>(And1.getOperand(1))) ||
709 !IsShiftedMask(CN->getZExtValue(), SMPos1, SMSize1))
712 // The shift masks must have the same position and size.
713 if (SMPos0 != SMPos1 || SMSize0 != SMSize1)
716 SDValue Shl = And1.getOperand(0);
717 if (Shl.getOpcode() != ISD::SHL)
720 if (!(CN = dyn_cast<ConstantSDNode>(Shl.getOperand(1))))
723 unsigned Shamt = CN->getZExtValue();
725 // Return if the shift amount and the first bit position of mask are not the
727 EVT ValTy = N->getValueType(0);
728 if ((Shamt != SMPos0) || (SMPos0 + SMSize0 > ValTy.getSizeInBits()))
731 return DAG.getNode(MipsISD::Ins, N->getDebugLoc(), ValTy, Shl.getOperand(0),
732 DAG.getConstant(SMPos0, MVT::i32),
733 DAG.getConstant(SMSize0, MVT::i32), And0.getOperand(0));
736 static SDValue PerformADDCombine(SDNode *N, SelectionDAG &DAG,
737 TargetLowering::DAGCombinerInfo &DCI,
738 const MipsSubtarget *Subtarget) {
739 // (add v0, (add v1, abs_lo(tjt))) => (add (add v0, v1), abs_lo(tjt))
741 if (DCI.isBeforeLegalizeOps())
744 SDValue Add = N->getOperand(1);
746 if (Add.getOpcode() != ISD::ADD)
749 SDValue Lo = Add.getOperand(1);
751 if ((Lo.getOpcode() != MipsISD::Lo) ||
752 (Lo.getOperand(0).getOpcode() != ISD::TargetJumpTable))
755 EVT ValTy = N->getValueType(0);
756 DebugLoc DL = N->getDebugLoc();
758 SDValue Add1 = DAG.getNode(ISD::ADD, DL, ValTy, N->getOperand(0),
760 return DAG.getNode(ISD::ADD, DL, ValTy, Add1, Lo);
763 SDValue MipsTargetLowering::PerformDAGCombine(SDNode *N, DAGCombinerInfo &DCI)
765 SelectionDAG &DAG = DCI.DAG;
766 unsigned opc = N->getOpcode();
771 return PerformADDECombine(N, DAG, DCI, Subtarget);
773 return PerformSUBECombine(N, DAG, DCI, Subtarget);
776 return PerformDivRemCombine(N, DAG, DCI, Subtarget);
778 return PerformSELECTCombine(N, DAG, DCI, Subtarget);
780 return PerformANDCombine(N, DAG, DCI, Subtarget);
782 return PerformORCombine(N, DAG, DCI, Subtarget);
784 return PerformADDCombine(N, DAG, DCI, Subtarget);
790 SDValue MipsTargetLowering::
791 LowerOperation(SDValue Op, SelectionDAG &DAG) const
793 switch (Op.getOpcode())
795 case ISD::BRCOND: return LowerBRCOND(Op, DAG);
796 case ISD::ConstantPool: return LowerConstantPool(Op, DAG);
797 case ISD::DYNAMIC_STACKALLOC: return LowerDYNAMIC_STACKALLOC(Op, DAG);
798 case ISD::GlobalAddress: return LowerGlobalAddress(Op, DAG);
799 case ISD::BlockAddress: return LowerBlockAddress(Op, DAG);
800 case ISD::GlobalTLSAddress: return LowerGlobalTLSAddress(Op, DAG);
801 case ISD::JumpTable: return LowerJumpTable(Op, DAG);
802 case ISD::SELECT: return LowerSELECT(Op, DAG);
803 case ISD::SELECT_CC: return LowerSELECT_CC(Op, DAG);
804 case ISD::SETCC: return LowerSETCC(Op, DAG);
805 case ISD::VASTART: return LowerVASTART(Op, DAG);
806 case ISD::FCOPYSIGN: return LowerFCOPYSIGN(Op, DAG);
807 case ISD::FABS: return LowerFABS(Op, DAG);
808 case ISD::FRAMEADDR: return LowerFRAMEADDR(Op, DAG);
809 case ISD::RETURNADDR: return LowerRETURNADDR(Op, DAG);
810 case ISD::MEMBARRIER: return LowerMEMBARRIER(Op, DAG);
811 case ISD::ATOMIC_FENCE: return LowerATOMIC_FENCE(Op, DAG);
812 case ISD::SHL_PARTS: return LowerShiftLeftParts(Op, DAG);
813 case ISD::SRA_PARTS: return LowerShiftRightParts(Op, DAG, true);
814 case ISD::SRL_PARTS: return LowerShiftRightParts(Op, DAG, false);
815 case ISD::LOAD: return LowerLOAD(Op, DAG);
816 case ISD::STORE: return LowerSTORE(Op, DAG);
821 //===----------------------------------------------------------------------===//
822 // Lower helper functions
823 //===----------------------------------------------------------------------===//
825 // AddLiveIn - This helper function adds the specified physical register to the
826 // MachineFunction as a live in value. It also creates a corresponding
827 // virtual register for it.
829 AddLiveIn(MachineFunction &MF, unsigned PReg, const TargetRegisterClass *RC)
831 assert(RC->contains(PReg) && "Not the correct regclass!");
832 unsigned VReg = MF.getRegInfo().createVirtualRegister(RC);
833 MF.getRegInfo().addLiveIn(PReg, VReg);
837 // Get fp branch code (not opcode) from condition code.
838 static Mips::FPBranchCode GetFPBranchCodeFromCond(Mips::CondCode CC) {
839 if (CC >= Mips::FCOND_F && CC <= Mips::FCOND_NGT)
840 return Mips::BRANCH_T;
842 assert((CC >= Mips::FCOND_T && CC <= Mips::FCOND_GT) &&
843 "Invalid CondCode.");
845 return Mips::BRANCH_F;
849 static MachineBasicBlock* ExpandCondMov(MachineInstr *MI, MachineBasicBlock *BB,
851 const MipsSubtarget *Subtarget,
852 const TargetInstrInfo *TII,
853 bool isFPCmp, unsigned Opc) {
854 // There is no need to expand CMov instructions if target has
855 // conditional moves.
856 if (Subtarget->hasCondMov())
859 // To "insert" a SELECT_CC instruction, we actually have to insert the
860 // diamond control-flow pattern. The incoming instruction knows the
861 // destination vreg to set, the condition code register to branch on, the
862 // true/false values to select between, and a branch opcode to use.
863 const BasicBlock *LLVM_BB = BB->getBasicBlock();
864 MachineFunction::iterator It = BB;
871 // bNE r1, r0, copy1MBB
872 // fallthrough --> copy0MBB
873 MachineBasicBlock *thisMBB = BB;
874 MachineFunction *F = BB->getParent();
875 MachineBasicBlock *copy0MBB = F->CreateMachineBasicBlock(LLVM_BB);
876 MachineBasicBlock *sinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
877 F->insert(It, copy0MBB);
878 F->insert(It, sinkMBB);
880 // Transfer the remainder of BB and its successor edges to sinkMBB.
881 sinkMBB->splice(sinkMBB->begin(), BB,
882 llvm::next(MachineBasicBlock::iterator(MI)),
884 sinkMBB->transferSuccessorsAndUpdatePHIs(BB);
886 // Next, add the true and fallthrough blocks as its successors.
887 BB->addSuccessor(copy0MBB);
888 BB->addSuccessor(sinkMBB);
890 // Emit the right instruction according to the type of the operands compared
892 BuildMI(BB, dl, TII->get(Opc)).addMBB(sinkMBB);
894 BuildMI(BB, dl, TII->get(Opc)).addReg(MI->getOperand(2).getReg())
895 .addReg(Mips::ZERO).addMBB(sinkMBB);
899 // # fallthrough to sinkMBB
902 // Update machine-CFG edges
903 BB->addSuccessor(sinkMBB);
906 // %Result = phi [ %TrueValue, thisMBB ], [ %FalseValue, copy0MBB ]
911 BuildMI(*BB, BB->begin(), dl,
912 TII->get(Mips::PHI), MI->getOperand(0).getReg())
913 .addReg(MI->getOperand(2).getReg()).addMBB(thisMBB)
914 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
916 BuildMI(*BB, BB->begin(), dl,
917 TII->get(Mips::PHI), MI->getOperand(0).getReg())
918 .addReg(MI->getOperand(3).getReg()).addMBB(thisMBB)
919 .addReg(MI->getOperand(1).getReg()).addMBB(copy0MBB);
921 MI->eraseFromParent(); // The pseudo instruction is gone now.
926 MipsTargetLowering::EmitInstrWithCustomInserter(MachineInstr *MI,
927 MachineBasicBlock *BB) const {
928 switch (MI->getOpcode()) {
929 default: llvm_unreachable("Unexpected instr type to insert");
930 case Mips::ATOMIC_LOAD_ADD_I8:
931 case Mips::ATOMIC_LOAD_ADD_I8_P8:
932 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::ADDu);
933 case Mips::ATOMIC_LOAD_ADD_I16:
934 case Mips::ATOMIC_LOAD_ADD_I16_P8:
935 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::ADDu);
936 case Mips::ATOMIC_LOAD_ADD_I32:
937 case Mips::ATOMIC_LOAD_ADD_I32_P8:
938 return EmitAtomicBinary(MI, BB, 4, Mips::ADDu);
939 case Mips::ATOMIC_LOAD_ADD_I64:
940 case Mips::ATOMIC_LOAD_ADD_I64_P8:
941 return EmitAtomicBinary(MI, BB, 8, Mips::DADDu);
943 case Mips::ATOMIC_LOAD_AND_I8:
944 case Mips::ATOMIC_LOAD_AND_I8_P8:
945 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::AND);
946 case Mips::ATOMIC_LOAD_AND_I16:
947 case Mips::ATOMIC_LOAD_AND_I16_P8:
948 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::AND);
949 case Mips::ATOMIC_LOAD_AND_I32:
950 case Mips::ATOMIC_LOAD_AND_I32_P8:
951 return EmitAtomicBinary(MI, BB, 4, Mips::AND);
952 case Mips::ATOMIC_LOAD_AND_I64:
953 case Mips::ATOMIC_LOAD_AND_I64_P8:
954 return EmitAtomicBinary(MI, BB, 8, Mips::AND64);
956 case Mips::ATOMIC_LOAD_OR_I8:
957 case Mips::ATOMIC_LOAD_OR_I8_P8:
958 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::OR);
959 case Mips::ATOMIC_LOAD_OR_I16:
960 case Mips::ATOMIC_LOAD_OR_I16_P8:
961 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::OR);
962 case Mips::ATOMIC_LOAD_OR_I32:
963 case Mips::ATOMIC_LOAD_OR_I32_P8:
964 return EmitAtomicBinary(MI, BB, 4, Mips::OR);
965 case Mips::ATOMIC_LOAD_OR_I64:
966 case Mips::ATOMIC_LOAD_OR_I64_P8:
967 return EmitAtomicBinary(MI, BB, 8, Mips::OR64);
969 case Mips::ATOMIC_LOAD_XOR_I8:
970 case Mips::ATOMIC_LOAD_XOR_I8_P8:
971 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::XOR);
972 case Mips::ATOMIC_LOAD_XOR_I16:
973 case Mips::ATOMIC_LOAD_XOR_I16_P8:
974 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::XOR);
975 case Mips::ATOMIC_LOAD_XOR_I32:
976 case Mips::ATOMIC_LOAD_XOR_I32_P8:
977 return EmitAtomicBinary(MI, BB, 4, Mips::XOR);
978 case Mips::ATOMIC_LOAD_XOR_I64:
979 case Mips::ATOMIC_LOAD_XOR_I64_P8:
980 return EmitAtomicBinary(MI, BB, 8, Mips::XOR64);
982 case Mips::ATOMIC_LOAD_NAND_I8:
983 case Mips::ATOMIC_LOAD_NAND_I8_P8:
984 return EmitAtomicBinaryPartword(MI, BB, 1, 0, true);
985 case Mips::ATOMIC_LOAD_NAND_I16:
986 case Mips::ATOMIC_LOAD_NAND_I16_P8:
987 return EmitAtomicBinaryPartword(MI, BB, 2, 0, true);
988 case Mips::ATOMIC_LOAD_NAND_I32:
989 case Mips::ATOMIC_LOAD_NAND_I32_P8:
990 return EmitAtomicBinary(MI, BB, 4, 0, true);
991 case Mips::ATOMIC_LOAD_NAND_I64:
992 case Mips::ATOMIC_LOAD_NAND_I64_P8:
993 return EmitAtomicBinary(MI, BB, 8, 0, true);
995 case Mips::ATOMIC_LOAD_SUB_I8:
996 case Mips::ATOMIC_LOAD_SUB_I8_P8:
997 return EmitAtomicBinaryPartword(MI, BB, 1, Mips::SUBu);
998 case Mips::ATOMIC_LOAD_SUB_I16:
999 case Mips::ATOMIC_LOAD_SUB_I16_P8:
1000 return EmitAtomicBinaryPartword(MI, BB, 2, Mips::SUBu);
1001 case Mips::ATOMIC_LOAD_SUB_I32:
1002 case Mips::ATOMIC_LOAD_SUB_I32_P8:
1003 return EmitAtomicBinary(MI, BB, 4, Mips::SUBu);
1004 case Mips::ATOMIC_LOAD_SUB_I64:
1005 case Mips::ATOMIC_LOAD_SUB_I64_P8:
1006 return EmitAtomicBinary(MI, BB, 8, Mips::DSUBu);
1008 case Mips::ATOMIC_SWAP_I8:
1009 case Mips::ATOMIC_SWAP_I8_P8:
1010 return EmitAtomicBinaryPartword(MI, BB, 1, 0);
1011 case Mips::ATOMIC_SWAP_I16:
1012 case Mips::ATOMIC_SWAP_I16_P8:
1013 return EmitAtomicBinaryPartword(MI, BB, 2, 0);
1014 case Mips::ATOMIC_SWAP_I32:
1015 case Mips::ATOMIC_SWAP_I32_P8:
1016 return EmitAtomicBinary(MI, BB, 4, 0);
1017 case Mips::ATOMIC_SWAP_I64:
1018 case Mips::ATOMIC_SWAP_I64_P8:
1019 return EmitAtomicBinary(MI, BB, 8, 0);
1021 case Mips::ATOMIC_CMP_SWAP_I8:
1022 case Mips::ATOMIC_CMP_SWAP_I8_P8:
1023 return EmitAtomicCmpSwapPartword(MI, BB, 1);
1024 case Mips::ATOMIC_CMP_SWAP_I16:
1025 case Mips::ATOMIC_CMP_SWAP_I16_P8:
1026 return EmitAtomicCmpSwapPartword(MI, BB, 2);
1027 case Mips::ATOMIC_CMP_SWAP_I32:
1028 case Mips::ATOMIC_CMP_SWAP_I32_P8:
1029 return EmitAtomicCmpSwap(MI, BB, 4);
1030 case Mips::ATOMIC_CMP_SWAP_I64:
1031 case Mips::ATOMIC_CMP_SWAP_I64_P8:
1032 return EmitAtomicCmpSwap(MI, BB, 8);
1036 // This function also handles Mips::ATOMIC_SWAP_I32 (when BinOpcode == 0), and
1037 // Mips::ATOMIC_LOAD_NAND_I32 (when Nand == true)
1039 MipsTargetLowering::EmitAtomicBinary(MachineInstr *MI, MachineBasicBlock *BB,
1040 unsigned Size, unsigned BinOpcode,
1042 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicBinary.");
1044 MachineFunction *MF = BB->getParent();
1045 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1046 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1047 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1048 DebugLoc dl = MI->getDebugLoc();
1049 unsigned LL, SC, AND, NOR, ZERO, BEQ;
1052 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1053 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1060 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1061 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1064 ZERO = Mips::ZERO_64;
1068 unsigned OldVal = MI->getOperand(0).getReg();
1069 unsigned Ptr = MI->getOperand(1).getReg();
1070 unsigned Incr = MI->getOperand(2).getReg();
1072 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1073 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1074 unsigned Success = RegInfo.createVirtualRegister(RC);
1076 // insert new blocks after the current block
1077 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1078 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1079 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1080 MachineFunction::iterator It = BB;
1082 MF->insert(It, loopMBB);
1083 MF->insert(It, exitMBB);
1085 // Transfer the remainder of BB and its successor edges to exitMBB.
1086 exitMBB->splice(exitMBB->begin(), BB,
1087 llvm::next(MachineBasicBlock::iterator(MI)),
1089 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1093 // fallthrough --> loopMBB
1094 BB->addSuccessor(loopMBB);
1095 loopMBB->addSuccessor(loopMBB);
1096 loopMBB->addSuccessor(exitMBB);
1099 // ll oldval, 0(ptr)
1100 // <binop> storeval, oldval, incr
1101 // sc success, storeval, 0(ptr)
1102 // beq success, $0, loopMBB
1104 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(Ptr).addImm(0);
1106 // and andres, oldval, incr
1107 // nor storeval, $0, andres
1108 BuildMI(BB, dl, TII->get(AND), AndRes).addReg(OldVal).addReg(Incr);
1109 BuildMI(BB, dl, TII->get(NOR), StoreVal).addReg(ZERO).addReg(AndRes);
1110 } else if (BinOpcode) {
1111 // <binop> storeval, oldval, incr
1112 BuildMI(BB, dl, TII->get(BinOpcode), StoreVal).addReg(OldVal).addReg(Incr);
1116 BuildMI(BB, dl, TII->get(SC), Success).addReg(StoreVal).addReg(Ptr).addImm(0);
1117 BuildMI(BB, dl, TII->get(BEQ)).addReg(Success).addReg(ZERO).addMBB(loopMBB);
1119 MI->eraseFromParent(); // The instruction is gone now.
1125 MipsTargetLowering::EmitAtomicBinaryPartword(MachineInstr *MI,
1126 MachineBasicBlock *BB,
1127 unsigned Size, unsigned BinOpcode,
1129 assert((Size == 1 || Size == 2) &&
1130 "Unsupported size for EmitAtomicBinaryPartial.");
1132 MachineFunction *MF = BB->getParent();
1133 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1134 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1135 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1136 DebugLoc dl = MI->getDebugLoc();
1137 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1138 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1140 unsigned Dest = MI->getOperand(0).getReg();
1141 unsigned Ptr = MI->getOperand(1).getReg();
1142 unsigned Incr = MI->getOperand(2).getReg();
1144 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1145 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1146 unsigned Mask = RegInfo.createVirtualRegister(RC);
1147 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1148 unsigned NewVal = RegInfo.createVirtualRegister(RC);
1149 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1150 unsigned Incr2 = RegInfo.createVirtualRegister(RC);
1151 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1152 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1153 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1154 unsigned AndRes = RegInfo.createVirtualRegister(RC);
1155 unsigned BinOpRes = RegInfo.createVirtualRegister(RC);
1156 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1157 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1158 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1159 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1160 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1161 unsigned Success = RegInfo.createVirtualRegister(RC);
1163 // insert new blocks after the current block
1164 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1165 MachineBasicBlock *loopMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1166 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1167 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1168 MachineFunction::iterator It = BB;
1170 MF->insert(It, loopMBB);
1171 MF->insert(It, sinkMBB);
1172 MF->insert(It, exitMBB);
1174 // Transfer the remainder of BB and its successor edges to exitMBB.
1175 exitMBB->splice(exitMBB->begin(), BB,
1176 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1177 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1179 BB->addSuccessor(loopMBB);
1180 loopMBB->addSuccessor(loopMBB);
1181 loopMBB->addSuccessor(sinkMBB);
1182 sinkMBB->addSuccessor(exitMBB);
1185 // addiu masklsb2,$0,-4 # 0xfffffffc
1186 // and alignedaddr,ptr,masklsb2
1187 // andi ptrlsb2,ptr,3
1188 // sll shiftamt,ptrlsb2,3
1189 // ori maskupper,$0,255 # 0xff
1190 // sll mask,maskupper,shiftamt
1191 // nor mask2,$0,mask
1192 // sll incr2,incr,shiftamt
1194 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1195 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1196 .addReg(Mips::ZERO).addImm(-4);
1197 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1198 .addReg(Ptr).addReg(MaskLSB2);
1199 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1200 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1201 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1202 .addReg(Mips::ZERO).addImm(MaskImm);
1203 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1204 .addReg(ShiftAmt).addReg(MaskUpper);
1205 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1206 BuildMI(BB, dl, TII->get(Mips::SLLV), Incr2).addReg(ShiftAmt).addReg(Incr);
1208 // atomic.load.binop
1210 // ll oldval,0(alignedaddr)
1211 // binop binopres,oldval,incr2
1212 // and newval,binopres,mask
1213 // and maskedoldval0,oldval,mask2
1214 // or storeval,maskedoldval0,newval
1215 // sc success,storeval,0(alignedaddr)
1216 // beq success,$0,loopMBB
1220 // ll oldval,0(alignedaddr)
1221 // and newval,incr2,mask
1222 // and maskedoldval0,oldval,mask2
1223 // or storeval,maskedoldval0,newval
1224 // sc success,storeval,0(alignedaddr)
1225 // beq success,$0,loopMBB
1228 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1230 // and andres, oldval, incr2
1231 // nor binopres, $0, andres
1232 // and newval, binopres, mask
1233 BuildMI(BB, dl, TII->get(Mips::AND), AndRes).addReg(OldVal).addReg(Incr2);
1234 BuildMI(BB, dl, TII->get(Mips::NOR), BinOpRes)
1235 .addReg(Mips::ZERO).addReg(AndRes);
1236 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1237 } else if (BinOpcode) {
1238 // <binop> binopres, oldval, incr2
1239 // and newval, binopres, mask
1240 BuildMI(BB, dl, TII->get(BinOpcode), BinOpRes).addReg(OldVal).addReg(Incr2);
1241 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(BinOpRes).addReg(Mask);
1242 } else {// atomic.swap
1243 // and newval, incr2, mask
1244 BuildMI(BB, dl, TII->get(Mips::AND), NewVal).addReg(Incr2).addReg(Mask);
1247 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1248 .addReg(OldVal).addReg(Mask2);
1249 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1250 .addReg(MaskedOldVal0).addReg(NewVal);
1251 BuildMI(BB, dl, TII->get(SC), Success)
1252 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1253 BuildMI(BB, dl, TII->get(Mips::BEQ))
1254 .addReg(Success).addReg(Mips::ZERO).addMBB(loopMBB);
1257 // and maskedoldval1,oldval,mask
1258 // srl srlres,maskedoldval1,shiftamt
1259 // sll sllres,srlres,24
1260 // sra dest,sllres,24
1262 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1264 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1265 .addReg(OldVal).addReg(Mask);
1266 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1267 .addReg(ShiftAmt).addReg(MaskedOldVal1);
1268 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1269 .addReg(SrlRes).addImm(ShiftImm);
1270 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1271 .addReg(SllRes).addImm(ShiftImm);
1273 MI->eraseFromParent(); // The instruction is gone now.
1279 MipsTargetLowering::EmitAtomicCmpSwap(MachineInstr *MI,
1280 MachineBasicBlock *BB,
1281 unsigned Size) const {
1282 assert((Size == 4 || Size == 8) && "Unsupported size for EmitAtomicCmpSwap.");
1284 MachineFunction *MF = BB->getParent();
1285 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1286 const TargetRegisterClass *RC = getRegClassFor(MVT::getIntegerVT(Size * 8));
1287 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1288 DebugLoc dl = MI->getDebugLoc();
1289 unsigned LL, SC, ZERO, BNE, BEQ;
1292 LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1293 SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1299 LL = IsN64 ? Mips::LLD_P8 : Mips::LLD;
1300 SC = IsN64 ? Mips::SCD_P8 : Mips::SCD;
1301 ZERO = Mips::ZERO_64;
1306 unsigned Dest = MI->getOperand(0).getReg();
1307 unsigned Ptr = MI->getOperand(1).getReg();
1308 unsigned OldVal = MI->getOperand(2).getReg();
1309 unsigned NewVal = MI->getOperand(3).getReg();
1311 unsigned Success = RegInfo.createVirtualRegister(RC);
1313 // insert new blocks after the current block
1314 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1315 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1316 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1317 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1318 MachineFunction::iterator It = BB;
1320 MF->insert(It, loop1MBB);
1321 MF->insert(It, loop2MBB);
1322 MF->insert(It, exitMBB);
1324 // Transfer the remainder of BB and its successor edges to exitMBB.
1325 exitMBB->splice(exitMBB->begin(), BB,
1326 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1327 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1331 // fallthrough --> loop1MBB
1332 BB->addSuccessor(loop1MBB);
1333 loop1MBB->addSuccessor(exitMBB);
1334 loop1MBB->addSuccessor(loop2MBB);
1335 loop2MBB->addSuccessor(loop1MBB);
1336 loop2MBB->addSuccessor(exitMBB);
1340 // bne dest, oldval, exitMBB
1342 BuildMI(BB, dl, TII->get(LL), Dest).addReg(Ptr).addImm(0);
1343 BuildMI(BB, dl, TII->get(BNE))
1344 .addReg(Dest).addReg(OldVal).addMBB(exitMBB);
1347 // sc success, newval, 0(ptr)
1348 // beq success, $0, loop1MBB
1350 BuildMI(BB, dl, TII->get(SC), Success)
1351 .addReg(NewVal).addReg(Ptr).addImm(0);
1352 BuildMI(BB, dl, TII->get(BEQ))
1353 .addReg(Success).addReg(ZERO).addMBB(loop1MBB);
1355 MI->eraseFromParent(); // The instruction is gone now.
1361 MipsTargetLowering::EmitAtomicCmpSwapPartword(MachineInstr *MI,
1362 MachineBasicBlock *BB,
1363 unsigned Size) const {
1364 assert((Size == 1 || Size == 2) &&
1365 "Unsupported size for EmitAtomicCmpSwapPartial.");
1367 MachineFunction *MF = BB->getParent();
1368 MachineRegisterInfo &RegInfo = MF->getRegInfo();
1369 const TargetRegisterClass *RC = getRegClassFor(MVT::i32);
1370 const TargetInstrInfo *TII = getTargetMachine().getInstrInfo();
1371 DebugLoc dl = MI->getDebugLoc();
1372 unsigned LL = IsN64 ? Mips::LL_P8 : Mips::LL;
1373 unsigned SC = IsN64 ? Mips::SC_P8 : Mips::SC;
1375 unsigned Dest = MI->getOperand(0).getReg();
1376 unsigned Ptr = MI->getOperand(1).getReg();
1377 unsigned CmpVal = MI->getOperand(2).getReg();
1378 unsigned NewVal = MI->getOperand(3).getReg();
1380 unsigned AlignedAddr = RegInfo.createVirtualRegister(RC);
1381 unsigned ShiftAmt = RegInfo.createVirtualRegister(RC);
1382 unsigned Mask = RegInfo.createVirtualRegister(RC);
1383 unsigned Mask2 = RegInfo.createVirtualRegister(RC);
1384 unsigned ShiftedCmpVal = RegInfo.createVirtualRegister(RC);
1385 unsigned OldVal = RegInfo.createVirtualRegister(RC);
1386 unsigned MaskedOldVal0 = RegInfo.createVirtualRegister(RC);
1387 unsigned ShiftedNewVal = RegInfo.createVirtualRegister(RC);
1388 unsigned MaskLSB2 = RegInfo.createVirtualRegister(RC);
1389 unsigned PtrLSB2 = RegInfo.createVirtualRegister(RC);
1390 unsigned MaskUpper = RegInfo.createVirtualRegister(RC);
1391 unsigned MaskedCmpVal = RegInfo.createVirtualRegister(RC);
1392 unsigned MaskedNewVal = RegInfo.createVirtualRegister(RC);
1393 unsigned MaskedOldVal1 = RegInfo.createVirtualRegister(RC);
1394 unsigned StoreVal = RegInfo.createVirtualRegister(RC);
1395 unsigned SrlRes = RegInfo.createVirtualRegister(RC);
1396 unsigned SllRes = RegInfo.createVirtualRegister(RC);
1397 unsigned Success = RegInfo.createVirtualRegister(RC);
1399 // insert new blocks after the current block
1400 const BasicBlock *LLVM_BB = BB->getBasicBlock();
1401 MachineBasicBlock *loop1MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1402 MachineBasicBlock *loop2MBB = MF->CreateMachineBasicBlock(LLVM_BB);
1403 MachineBasicBlock *sinkMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1404 MachineBasicBlock *exitMBB = MF->CreateMachineBasicBlock(LLVM_BB);
1405 MachineFunction::iterator It = BB;
1407 MF->insert(It, loop1MBB);
1408 MF->insert(It, loop2MBB);
1409 MF->insert(It, sinkMBB);
1410 MF->insert(It, exitMBB);
1412 // Transfer the remainder of BB and its successor edges to exitMBB.
1413 exitMBB->splice(exitMBB->begin(), BB,
1414 llvm::next(MachineBasicBlock::iterator(MI)), BB->end());
1415 exitMBB->transferSuccessorsAndUpdatePHIs(BB);
1417 BB->addSuccessor(loop1MBB);
1418 loop1MBB->addSuccessor(sinkMBB);
1419 loop1MBB->addSuccessor(loop2MBB);
1420 loop2MBB->addSuccessor(loop1MBB);
1421 loop2MBB->addSuccessor(sinkMBB);
1422 sinkMBB->addSuccessor(exitMBB);
1424 // FIXME: computation of newval2 can be moved to loop2MBB.
1426 // addiu masklsb2,$0,-4 # 0xfffffffc
1427 // and alignedaddr,ptr,masklsb2
1428 // andi ptrlsb2,ptr,3
1429 // sll shiftamt,ptrlsb2,3
1430 // ori maskupper,$0,255 # 0xff
1431 // sll mask,maskupper,shiftamt
1432 // nor mask2,$0,mask
1433 // andi maskedcmpval,cmpval,255
1434 // sll shiftedcmpval,maskedcmpval,shiftamt
1435 // andi maskednewval,newval,255
1436 // sll shiftednewval,maskednewval,shiftamt
1437 int64_t MaskImm = (Size == 1) ? 255 : 65535;
1438 BuildMI(BB, dl, TII->get(Mips::ADDiu), MaskLSB2)
1439 .addReg(Mips::ZERO).addImm(-4);
1440 BuildMI(BB, dl, TII->get(Mips::AND), AlignedAddr)
1441 .addReg(Ptr).addReg(MaskLSB2);
1442 BuildMI(BB, dl, TII->get(Mips::ANDi), PtrLSB2).addReg(Ptr).addImm(3);
1443 BuildMI(BB, dl, TII->get(Mips::SLL), ShiftAmt).addReg(PtrLSB2).addImm(3);
1444 BuildMI(BB, dl, TII->get(Mips::ORi), MaskUpper)
1445 .addReg(Mips::ZERO).addImm(MaskImm);
1446 BuildMI(BB, dl, TII->get(Mips::SLLV), Mask)
1447 .addReg(ShiftAmt).addReg(MaskUpper);
1448 BuildMI(BB, dl, TII->get(Mips::NOR), Mask2).addReg(Mips::ZERO).addReg(Mask);
1449 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedCmpVal)
1450 .addReg(CmpVal).addImm(MaskImm);
1451 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedCmpVal)
1452 .addReg(ShiftAmt).addReg(MaskedCmpVal);
1453 BuildMI(BB, dl, TII->get(Mips::ANDi), MaskedNewVal)
1454 .addReg(NewVal).addImm(MaskImm);
1455 BuildMI(BB, dl, TII->get(Mips::SLLV), ShiftedNewVal)
1456 .addReg(ShiftAmt).addReg(MaskedNewVal);
1459 // ll oldval,0(alginedaddr)
1460 // and maskedoldval0,oldval,mask
1461 // bne maskedoldval0,shiftedcmpval,sinkMBB
1463 BuildMI(BB, dl, TII->get(LL), OldVal).addReg(AlignedAddr).addImm(0);
1464 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal0)
1465 .addReg(OldVal).addReg(Mask);
1466 BuildMI(BB, dl, TII->get(Mips::BNE))
1467 .addReg(MaskedOldVal0).addReg(ShiftedCmpVal).addMBB(sinkMBB);
1470 // and maskedoldval1,oldval,mask2
1471 // or storeval,maskedoldval1,shiftednewval
1472 // sc success,storeval,0(alignedaddr)
1473 // beq success,$0,loop1MBB
1475 BuildMI(BB, dl, TII->get(Mips::AND), MaskedOldVal1)
1476 .addReg(OldVal).addReg(Mask2);
1477 BuildMI(BB, dl, TII->get(Mips::OR), StoreVal)
1478 .addReg(MaskedOldVal1).addReg(ShiftedNewVal);
1479 BuildMI(BB, dl, TII->get(SC), Success)
1480 .addReg(StoreVal).addReg(AlignedAddr).addImm(0);
1481 BuildMI(BB, dl, TII->get(Mips::BEQ))
1482 .addReg(Success).addReg(Mips::ZERO).addMBB(loop1MBB);
1485 // srl srlres,maskedoldval0,shiftamt
1486 // sll sllres,srlres,24
1487 // sra dest,sllres,24
1489 int64_t ShiftImm = (Size == 1) ? 24 : 16;
1491 BuildMI(BB, dl, TII->get(Mips::SRLV), SrlRes)
1492 .addReg(ShiftAmt).addReg(MaskedOldVal0);
1493 BuildMI(BB, dl, TII->get(Mips::SLL), SllRes)
1494 .addReg(SrlRes).addImm(ShiftImm);
1495 BuildMI(BB, dl, TII->get(Mips::SRA), Dest)
1496 .addReg(SllRes).addImm(ShiftImm);
1498 MI->eraseFromParent(); // The instruction is gone now.
1503 //===----------------------------------------------------------------------===//
1504 // Misc Lower Operation implementation
1505 //===----------------------------------------------------------------------===//
1506 SDValue MipsTargetLowering::
1507 LowerDYNAMIC_STACKALLOC(SDValue Op, SelectionDAG &DAG) const
1509 MachineFunction &MF = DAG.getMachineFunction();
1510 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
1511 unsigned SP = IsN64 ? Mips::SP_64 : Mips::SP;
1513 assert(getTargetMachine().getFrameLowering()->getStackAlignment() >=
1514 cast<ConstantSDNode>(Op.getOperand(2).getNode())->getZExtValue() &&
1515 "Cannot lower if the alignment of the allocated space is larger than \
1516 that of the stack.");
1518 SDValue Chain = Op.getOperand(0);
1519 SDValue Size = Op.getOperand(1);
1520 DebugLoc dl = Op.getDebugLoc();
1522 // Get a reference from Mips stack pointer
1523 SDValue StackPointer = DAG.getCopyFromReg(Chain, dl, SP, getPointerTy());
1525 // Subtract the dynamic size from the actual stack size to
1526 // obtain the new stack size.
1527 SDValue Sub = DAG.getNode(ISD::SUB, dl, getPointerTy(), StackPointer, Size);
1529 // The Sub result contains the new stack start address, so it
1530 // must be placed in the stack pointer register.
1531 Chain = DAG.getCopyToReg(StackPointer.getValue(1), dl, SP, Sub, SDValue());
1533 // This node always has two return values: a new stack pointer
1534 // value and a chain
1535 SDVTList VTLs = DAG.getVTList(getPointerTy(), MVT::Other);
1536 SDValue Ptr = DAG.getFrameIndex(MipsFI->getDynAllocFI(), getPointerTy());
1537 SDValue Ops[] = { Chain, Ptr, Chain.getValue(1) };
1539 return DAG.getNode(MipsISD::DynAlloc, dl, VTLs, Ops, 3);
1542 SDValue MipsTargetLowering::
1543 LowerBRCOND(SDValue Op, SelectionDAG &DAG) const
1545 // The first operand is the chain, the second is the condition, the third is
1546 // the block to branch to if the condition is true.
1547 SDValue Chain = Op.getOperand(0);
1548 SDValue Dest = Op.getOperand(2);
1549 DebugLoc dl = Op.getDebugLoc();
1551 SDValue CondRes = CreateFPCmp(DAG, Op.getOperand(1));
1553 // Return if flag is not set by a floating point comparison.
1554 if (CondRes.getOpcode() != MipsISD::FPCmp)
1557 SDValue CCNode = CondRes.getOperand(2);
1559 (Mips::CondCode)cast<ConstantSDNode>(CCNode)->getZExtValue();
1560 SDValue BrCode = DAG.getConstant(GetFPBranchCodeFromCond(CC), MVT::i32);
1562 return DAG.getNode(MipsISD::FPBrcond, dl, Op.getValueType(), Chain, BrCode,
1566 SDValue MipsTargetLowering::
1567 LowerSELECT(SDValue Op, SelectionDAG &DAG) const
1569 SDValue Cond = CreateFPCmp(DAG, Op.getOperand(0));
1571 // Return if flag is not set by a floating point comparison.
1572 if (Cond.getOpcode() != MipsISD::FPCmp)
1575 return CreateCMovFP(DAG, Cond, Op.getOperand(1), Op.getOperand(2),
1579 SDValue MipsTargetLowering::
1580 LowerSELECT_CC(SDValue Op, SelectionDAG &DAG) const
1582 DebugLoc DL = Op.getDebugLoc();
1583 EVT Ty = Op.getOperand(0).getValueType();
1584 SDValue Cond = DAG.getNode(ISD::SETCC, DL, getSetCCResultType(Ty),
1585 Op.getOperand(0), Op.getOperand(1),
1588 return DAG.getNode(ISD::SELECT, DL, Op.getValueType(), Cond, Op.getOperand(2),
1592 SDValue MipsTargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
1593 SDValue Cond = CreateFPCmp(DAG, Op);
1595 assert(Cond.getOpcode() == MipsISD::FPCmp &&
1596 "Floating point operand expected.");
1598 SDValue True = DAG.getConstant(1, MVT::i32);
1599 SDValue False = DAG.getConstant(0, MVT::i32);
1601 return CreateCMovFP(DAG, Cond, True, False, Op.getDebugLoc());
1604 SDValue MipsTargetLowering::LowerGlobalAddress(SDValue Op,
1605 SelectionDAG &DAG) const {
1606 // FIXME there isn't actually debug info here
1607 DebugLoc dl = Op.getDebugLoc();
1608 const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
1610 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1611 SDVTList VTs = DAG.getVTList(MVT::i32);
1613 MipsTargetObjectFile &TLOF = (MipsTargetObjectFile&)getObjFileLowering();
1615 // %gp_rel relocation
1616 if (TLOF.IsGlobalInSmallSection(GV, getTargetMachine())) {
1617 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1619 SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, dl, VTs, &GA, 1);
1620 SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1621 return DAG.getNode(ISD::ADD, dl, MVT::i32, GOT, GPRelNode);
1623 // %hi/%lo relocation
1624 SDValue GAHi = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1626 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, MVT::i32, 0,
1628 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, VTs, &GAHi, 1);
1629 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, GALo);
1630 return DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1633 EVT ValTy = Op.getValueType();
1634 bool HasGotOfst = (GV->hasInternalLinkage() ||
1635 (GV->hasLocalLinkage() && !isa<Function>(GV)));
1636 unsigned GotFlag = HasMips64 ?
1637 (HasGotOfst ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT_DISP) :
1638 (HasGotOfst ? MipsII::MO_GOT : MipsII::MO_GOT16);
1639 SDValue GA = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0, GotFlag);
1640 GA = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), GA);
1641 SDValue ResNode = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), GA,
1642 MachinePointerInfo(), false, false, false, 0);
1643 // On functions and global targets not internal linked only
1644 // a load from got/GP is necessary for PIC to work.
1647 SDValue GALo = DAG.getTargetGlobalAddress(GV, dl, ValTy, 0,
1648 HasMips64 ? MipsII::MO_GOT_OFST :
1650 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, GALo);
1651 return DAG.getNode(ISD::ADD, dl, ValTy, ResNode, Lo);
1654 SDValue MipsTargetLowering::LowerBlockAddress(SDValue Op,
1655 SelectionDAG &DAG) const {
1656 const BlockAddress *BA = cast<BlockAddressSDNode>(Op)->getBlockAddress();
1657 // FIXME there isn't actually debug info here
1658 DebugLoc dl = Op.getDebugLoc();
1660 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1661 // %hi/%lo relocation
1662 SDValue BAHi = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_HI);
1663 SDValue BALo = DAG.getBlockAddress(BA, MVT::i32, true, MipsII::MO_ABS_LO);
1664 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, MVT::i32, BAHi);
1665 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, BALo);
1666 return DAG.getNode(ISD::ADD, dl, MVT::i32, Hi, Lo);
1669 EVT ValTy = Op.getValueType();
1670 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1671 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1672 SDValue BAGOTOffset = DAG.getBlockAddress(BA, ValTy, true, GOTFlag);
1673 BAGOTOffset = DAG.getNode(MipsISD::Wrapper, dl, ValTy,
1674 GetGlobalReg(DAG, ValTy), BAGOTOffset);
1675 SDValue BALOOffset = DAG.getBlockAddress(BA, ValTy, true, OFSTFlag);
1676 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), BAGOTOffset,
1677 MachinePointerInfo(), false, false, false, 0);
1678 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, BALOOffset);
1679 return DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1682 SDValue MipsTargetLowering::
1683 LowerGlobalTLSAddress(SDValue Op, SelectionDAG &DAG) const
1685 // If the relocation model is PIC, use the General Dynamic TLS Model or
1686 // Local Dynamic TLS model, otherwise use the Initial Exec or
1687 // Local Exec TLS Model.
1689 GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
1690 DebugLoc dl = GA->getDebugLoc();
1691 const GlobalValue *GV = GA->getGlobal();
1692 EVT PtrVT = getPointerTy();
1694 TLSModel::Model model = getTargetMachine().getTLSModel(GV);
1696 if (model == TLSModel::GeneralDynamic || model == TLSModel::LocalDynamic) {
1697 // General Dynamic and Local Dynamic TLS Model.
1698 unsigned Flag = (model == TLSModel::LocalDynamic) ? MipsII::MO_TLSLDM
1701 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0, Flag);
1702 SDValue Argument = DAG.getNode(MipsISD::Wrapper, dl, PtrVT,
1703 GetGlobalReg(DAG, PtrVT), TGA);
1704 unsigned PtrSize = PtrVT.getSizeInBits();
1705 IntegerType *PtrTy = Type::getIntNTy(*DAG.getContext(), PtrSize);
1707 SDValue TlsGetAddr = DAG.getExternalSymbol("__tls_get_addr", PtrVT);
1711 Entry.Node = Argument;
1713 Args.push_back(Entry);
1715 TargetLowering::CallLoweringInfo CLI(DAG.getEntryNode(), PtrTy,
1716 false, false, false, false, 0, CallingConv::C,
1717 /*isTailCall=*/false, /*doesNotRet=*/false,
1718 /*isReturnValueUsed=*/true,
1719 TlsGetAddr, Args, DAG, dl);
1720 std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
1722 SDValue Ret = CallResult.first;
1724 if (model != TLSModel::LocalDynamic)
1727 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1728 MipsII::MO_DTPREL_HI);
1729 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1730 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1731 MipsII::MO_DTPREL_LO);
1732 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1733 SDValue Add = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Ret);
1734 return DAG.getNode(ISD::ADD, dl, PtrVT, Add, Lo);
1738 if (model == TLSModel::InitialExec) {
1739 // Initial Exec TLS Model
1740 SDValue TGA = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1741 MipsII::MO_GOTTPREL);
1742 TGA = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1744 Offset = DAG.getLoad(PtrVT, dl,
1745 DAG.getEntryNode(), TGA, MachinePointerInfo(),
1746 false, false, false, 0);
1748 // Local Exec TLS Model
1749 assert(model == TLSModel::LocalExec);
1750 SDValue TGAHi = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1751 MipsII::MO_TPREL_HI);
1752 SDValue TGALo = DAG.getTargetGlobalAddress(GV, dl, PtrVT, 0,
1753 MipsII::MO_TPREL_LO);
1754 SDValue Hi = DAG.getNode(MipsISD::Hi, dl, PtrVT, TGAHi);
1755 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, TGALo);
1756 Offset = DAG.getNode(ISD::ADD, dl, PtrVT, Hi, Lo);
1759 SDValue ThreadPointer = DAG.getNode(MipsISD::ThreadPointer, dl, PtrVT);
1760 return DAG.getNode(ISD::ADD, dl, PtrVT, ThreadPointer, Offset);
1763 SDValue MipsTargetLowering::
1764 LowerJumpTable(SDValue Op, SelectionDAG &DAG) const
1766 SDValue HiPart, JTI, JTILo;
1767 // FIXME there isn't actually debug info here
1768 DebugLoc dl = Op.getDebugLoc();
1769 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
1770 EVT PtrVT = Op.getValueType();
1771 JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
1773 if (!IsPIC && !IsN64) {
1774 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_HI);
1775 HiPart = DAG.getNode(MipsISD::Hi, dl, PtrVT, JTI);
1776 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, MipsII::MO_ABS_LO);
1777 } else {// Emit Load from Global Pointer
1778 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1779 unsigned OfstFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1780 JTI = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, GOTFlag);
1781 JTI = DAG.getNode(MipsISD::Wrapper, dl, PtrVT, GetGlobalReg(DAG, PtrVT),
1783 HiPart = DAG.getLoad(PtrVT, dl, DAG.getEntryNode(), JTI,
1784 MachinePointerInfo(), false, false, false, 0);
1785 JTILo = DAG.getTargetJumpTable(JT->getIndex(), PtrVT, OfstFlag);
1788 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, PtrVT, JTILo);
1789 return DAG.getNode(ISD::ADD, dl, PtrVT, HiPart, Lo);
1792 SDValue MipsTargetLowering::
1793 LowerConstantPool(SDValue Op, SelectionDAG &DAG) const
1796 ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
1797 const Constant *C = N->getConstVal();
1798 // FIXME there isn't actually debug info here
1799 DebugLoc dl = Op.getDebugLoc();
1801 // gp_rel relocation
1802 // FIXME: we should reference the constant pool using small data sections,
1803 // but the asm printer currently doesn't support this feature without
1804 // hacking it. This feature should come soon so we can uncomment the
1806 //if (IsInSmallSection(C->getType())) {
1807 // SDValue GPRelNode = DAG.getNode(MipsISD::GPRel, MVT::i32, CP);
1808 // SDValue GOT = DAG.getGLOBAL_OFFSET_TABLE(MVT::i32);
1809 // ResNode = DAG.getNode(ISD::ADD, MVT::i32, GOT, GPRelNode);
1811 if (getTargetMachine().getRelocationModel() != Reloc::PIC_ && !IsN64) {
1812 SDValue CPHi = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1813 N->getOffset(), MipsII::MO_ABS_HI);
1814 SDValue CPLo = DAG.getTargetConstantPool(C, MVT::i32, N->getAlignment(),
1815 N->getOffset(), MipsII::MO_ABS_LO);
1816 SDValue HiPart = DAG.getNode(MipsISD::Hi, dl, MVT::i32, CPHi);
1817 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, MVT::i32, CPLo);
1818 ResNode = DAG.getNode(ISD::ADD, dl, MVT::i32, HiPart, Lo);
1820 EVT ValTy = Op.getValueType();
1821 unsigned GOTFlag = HasMips64 ? MipsII::MO_GOT_PAGE : MipsII::MO_GOT;
1822 unsigned OFSTFlag = HasMips64 ? MipsII::MO_GOT_OFST : MipsII::MO_ABS_LO;
1823 SDValue CP = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1824 N->getOffset(), GOTFlag);
1825 CP = DAG.getNode(MipsISD::Wrapper, dl, ValTy, GetGlobalReg(DAG, ValTy), CP);
1826 SDValue Load = DAG.getLoad(ValTy, dl, DAG.getEntryNode(), CP,
1827 MachinePointerInfo::getConstantPool(), false,
1829 SDValue CPLo = DAG.getTargetConstantPool(C, ValTy, N->getAlignment(),
1830 N->getOffset(), OFSTFlag);
1831 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, ValTy, CPLo);
1832 ResNode = DAG.getNode(ISD::ADD, dl, ValTy, Load, Lo);
1838 SDValue MipsTargetLowering::LowerVASTART(SDValue Op, SelectionDAG &DAG) const {
1839 MachineFunction &MF = DAG.getMachineFunction();
1840 MipsFunctionInfo *FuncInfo = MF.getInfo<MipsFunctionInfo>();
1842 DebugLoc dl = Op.getDebugLoc();
1843 SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
1846 // vastart just stores the address of the VarArgsFrameIndex slot into the
1847 // memory location argument.
1848 const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
1849 return DAG.getStore(Op.getOperand(0), dl, FI, Op.getOperand(1),
1850 MachinePointerInfo(SV), false, false, 0);
1853 static SDValue LowerFCOPYSIGN32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1854 EVT TyX = Op.getOperand(0).getValueType();
1855 EVT TyY = Op.getOperand(1).getValueType();
1856 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1857 SDValue Const31 = DAG.getConstant(31, MVT::i32);
1858 DebugLoc DL = Op.getDebugLoc();
1861 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1863 SDValue X = (TyX == MVT::f32) ?
1864 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1865 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1867 SDValue Y = (TyY == MVT::f32) ?
1868 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(1)) :
1869 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(1),
1873 // ext E, Y, 31, 1 ; extract bit31 of Y
1874 // ins X, E, 31, 1 ; insert extracted bit at bit31 of X
1875 SDValue E = DAG.getNode(MipsISD::Ext, DL, MVT::i32, Y, Const31, Const1);
1876 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32, E, Const31, Const1, X);
1879 // srl SrlX, SllX, 1
1881 // sll SllY, SrlX, 31
1882 // or Or, SrlX, SllY
1883 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1884 SDValue SrlX = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1885 SDValue SrlY = DAG.getNode(ISD::SRL, DL, MVT::i32, Y, Const31);
1886 SDValue SllY = DAG.getNode(ISD::SHL, DL, MVT::i32, SrlY, Const31);
1887 Res = DAG.getNode(ISD::OR, DL, MVT::i32, SrlX, SllY);
1890 if (TyX == MVT::f32)
1891 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Res);
1893 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1894 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1895 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1898 static SDValue LowerFCOPYSIGN64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1899 unsigned WidthX = Op.getOperand(0).getValueSizeInBits();
1900 unsigned WidthY = Op.getOperand(1).getValueSizeInBits();
1901 EVT TyX = MVT::getIntegerVT(WidthX), TyY = MVT::getIntegerVT(WidthY);
1902 SDValue Const1 = DAG.getConstant(1, MVT::i32);
1903 DebugLoc DL = Op.getDebugLoc();
1905 // Bitcast to integer nodes.
1906 SDValue X = DAG.getNode(ISD::BITCAST, DL, TyX, Op.getOperand(0));
1907 SDValue Y = DAG.getNode(ISD::BITCAST, DL, TyY, Op.getOperand(1));
1910 // ext E, Y, width(Y) - 1, 1 ; extract bit width(Y)-1 of Y
1911 // ins X, E, width(X) - 1, 1 ; insert extracted bit at bit width(X)-1 of X
1912 SDValue E = DAG.getNode(MipsISD::Ext, DL, TyY, Y,
1913 DAG.getConstant(WidthY - 1, MVT::i32), Const1);
1915 if (WidthX > WidthY)
1916 E = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, E);
1917 else if (WidthY > WidthX)
1918 E = DAG.getNode(ISD::TRUNCATE, DL, TyX, E);
1920 SDValue I = DAG.getNode(MipsISD::Ins, DL, TyX, E,
1921 DAG.getConstant(WidthX - 1, MVT::i32), Const1, X);
1922 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), I);
1925 // (d)sll SllX, X, 1
1926 // (d)srl SrlX, SllX, 1
1927 // (d)srl SrlY, Y, width(Y)-1
1928 // (d)sll SllY, SrlX, width(Y)-1
1929 // or Or, SrlX, SllY
1930 SDValue SllX = DAG.getNode(ISD::SHL, DL, TyX, X, Const1);
1931 SDValue SrlX = DAG.getNode(ISD::SRL, DL, TyX, SllX, Const1);
1932 SDValue SrlY = DAG.getNode(ISD::SRL, DL, TyY, Y,
1933 DAG.getConstant(WidthY - 1, MVT::i32));
1935 if (WidthX > WidthY)
1936 SrlY = DAG.getNode(ISD::ZERO_EXTEND, DL, TyX, SrlY);
1937 else if (WidthY > WidthX)
1938 SrlY = DAG.getNode(ISD::TRUNCATE, DL, TyX, SrlY);
1940 SDValue SllY = DAG.getNode(ISD::SHL, DL, TyX, SrlY,
1941 DAG.getConstant(WidthX - 1, MVT::i32));
1942 SDValue Or = DAG.getNode(ISD::OR, DL, TyX, SrlX, SllY);
1943 return DAG.getNode(ISD::BITCAST, DL, Op.getOperand(0).getValueType(), Or);
1947 MipsTargetLowering::LowerFCOPYSIGN(SDValue Op, SelectionDAG &DAG) const {
1948 if (Subtarget->hasMips64())
1949 return LowerFCOPYSIGN64(Op, DAG, Subtarget->hasMips32r2());
1951 return LowerFCOPYSIGN32(Op, DAG, Subtarget->hasMips32r2());
1954 static SDValue LowerFABS32(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1955 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1956 DebugLoc DL = Op.getDebugLoc();
1958 // If operand is of type f64, extract the upper 32-bit. Otherwise, bitcast it
1960 SDValue X = (Op.getValueType() == MVT::f32) ?
1961 DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op.getOperand(0)) :
1962 DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32, Op.getOperand(0),
1967 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i32,
1968 DAG.getRegister(Mips::ZERO, MVT::i32),
1969 DAG.getConstant(31, MVT::i32), Const1, X);
1971 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i32, X, Const1);
1972 Res = DAG.getNode(ISD::SRL, DL, MVT::i32, SllX, Const1);
1975 if (Op.getValueType() == MVT::f32)
1976 return DAG.getNode(ISD::BITCAST, DL, MVT::f32, Res);
1978 SDValue LowX = DAG.getNode(MipsISD::ExtractElementF64, DL, MVT::i32,
1979 Op.getOperand(0), DAG.getConstant(0, MVT::i32));
1980 return DAG.getNode(MipsISD::BuildPairF64, DL, MVT::f64, LowX, Res);
1983 static SDValue LowerFABS64(SDValue Op, SelectionDAG &DAG, bool HasR2) {
1984 SDValue Res, Const1 = DAG.getConstant(1, MVT::i32);
1985 DebugLoc DL = Op.getDebugLoc();
1987 // Bitcast to integer node.
1988 SDValue X = DAG.getNode(ISD::BITCAST, DL, MVT::i64, Op.getOperand(0));
1992 Res = DAG.getNode(MipsISD::Ins, DL, MVT::i64,
1993 DAG.getRegister(Mips::ZERO_64, MVT::i64),
1994 DAG.getConstant(63, MVT::i32), Const1, X);
1996 SDValue SllX = DAG.getNode(ISD::SHL, DL, MVT::i64, X, Const1);
1997 Res = DAG.getNode(ISD::SRL, DL, MVT::i64, SllX, Const1);
2000 return DAG.getNode(ISD::BITCAST, DL, MVT::f64, Res);
2004 MipsTargetLowering::LowerFABS(SDValue Op, SelectionDAG &DAG) const {
2005 if (Subtarget->hasMips64() && (Op.getValueType() == MVT::f64))
2006 return LowerFABS64(Op, DAG, Subtarget->hasMips32r2());
2008 return LowerFABS32(Op, DAG, Subtarget->hasMips32r2());
2011 SDValue MipsTargetLowering::
2012 LowerFRAMEADDR(SDValue Op, SelectionDAG &DAG) const {
2014 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2015 "Frame address can only be determined for current frame.");
2017 MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
2018 MFI->setFrameAddressIsTaken(true);
2019 EVT VT = Op.getValueType();
2020 DebugLoc dl = Op.getDebugLoc();
2021 SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), dl,
2022 IsN64 ? Mips::FP_64 : Mips::FP, VT);
2026 SDValue MipsTargetLowering::LowerRETURNADDR(SDValue Op,
2027 SelectionDAG &DAG) const {
2029 assert((cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue() == 0) &&
2030 "Return address can be determined only for current frame.");
2032 MachineFunction &MF = DAG.getMachineFunction();
2033 MachineFrameInfo *MFI = MF.getFrameInfo();
2034 EVT VT = Op.getValueType();
2035 unsigned RA = IsN64 ? Mips::RA_64 : Mips::RA;
2036 MFI->setReturnAddressIsTaken(true);
2038 // Return RA, which contains the return address. Mark it an implicit live-in.
2039 unsigned Reg = MF.addLiveIn(RA, getRegClassFor(VT));
2040 return DAG.getCopyFromReg(DAG.getEntryNode(), Op.getDebugLoc(), Reg, VT);
2043 // TODO: set SType according to the desired memory barrier behavior.
2045 MipsTargetLowering::LowerMEMBARRIER(SDValue Op, SelectionDAG &DAG) const {
2047 DebugLoc dl = Op.getDebugLoc();
2048 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2049 DAG.getConstant(SType, MVT::i32));
2052 SDValue MipsTargetLowering::LowerATOMIC_FENCE(SDValue Op,
2053 SelectionDAG &DAG) const {
2054 // FIXME: Need pseudo-fence for 'singlethread' fences
2055 // FIXME: Set SType for weaker fences where supported/appropriate.
2057 DebugLoc dl = Op.getDebugLoc();
2058 return DAG.getNode(MipsISD::Sync, dl, MVT::Other, Op.getOperand(0),
2059 DAG.getConstant(SType, MVT::i32));
2062 SDValue MipsTargetLowering::LowerShiftLeftParts(SDValue Op,
2063 SelectionDAG &DAG) const {
2064 DebugLoc DL = Op.getDebugLoc();
2065 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2066 SDValue Shamt = Op.getOperand(2);
2069 // lo = (shl lo, shamt)
2070 // hi = (or (shl hi, shamt) (srl (srl lo, 1), ~shamt))
2073 // hi = (shl lo, shamt[4:0])
2074 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2075 DAG.getConstant(-1, MVT::i32));
2076 SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo,
2077 DAG.getConstant(1, MVT::i32));
2078 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, ShiftRight1Lo,
2080 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi, Shamt);
2081 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2082 SDValue ShiftLeftLo = DAG.getNode(ISD::SHL, DL, MVT::i32, Lo, Shamt);
2083 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2084 DAG.getConstant(0x20, MVT::i32));
2085 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2086 DAG.getConstant(0, MVT::i32), ShiftLeftLo);
2087 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftLeftLo, Or);
2089 SDValue Ops[2] = {Lo, Hi};
2090 return DAG.getMergeValues(Ops, 2, DL);
2093 SDValue MipsTargetLowering::LowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
2095 DebugLoc DL = Op.getDebugLoc();
2096 SDValue Lo = Op.getOperand(0), Hi = Op.getOperand(1);
2097 SDValue Shamt = Op.getOperand(2);
2100 // lo = (or (shl (shl hi, 1), ~shamt) (srl lo, shamt))
2102 // hi = (sra hi, shamt)
2104 // hi = (srl hi, shamt)
2107 // lo = (sra hi, shamt[4:0])
2108 // hi = (sra hi, 31)
2110 // lo = (srl hi, shamt[4:0])
2112 SDValue Not = DAG.getNode(ISD::XOR, DL, MVT::i32, Shamt,
2113 DAG.getConstant(-1, MVT::i32));
2114 SDValue ShiftLeft1Hi = DAG.getNode(ISD::SHL, DL, MVT::i32, Hi,
2115 DAG.getConstant(1, MVT::i32));
2116 SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, MVT::i32, ShiftLeft1Hi, Not);
2117 SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, MVT::i32, Lo, Shamt);
2118 SDValue Or = DAG.getNode(ISD::OR, DL, MVT::i32, ShiftLeftHi, ShiftRightLo);
2119 SDValue ShiftRightHi = DAG.getNode(IsSRA ? ISD::SRA : ISD::SRL, DL, MVT::i32,
2121 SDValue Cond = DAG.getNode(ISD::AND, DL, MVT::i32, Shamt,
2122 DAG.getConstant(0x20, MVT::i32));
2123 SDValue Shift31 = DAG.getNode(ISD::SRA, DL, MVT::i32, Hi,
2124 DAG.getConstant(31, MVT::i32));
2125 Lo = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond, ShiftRightHi, Or);
2126 Hi = DAG.getNode(ISD::SELECT, DL, MVT::i32, Cond,
2127 IsSRA ? Shift31 : DAG.getConstant(0, MVT::i32),
2130 SDValue Ops[2] = {Lo, Hi};
2131 return DAG.getMergeValues(Ops, 2, DL);
2134 static SDValue CreateLoadLR(unsigned Opc, SelectionDAG &DAG, LoadSDNode *LD,
2135 SDValue Chain, SDValue Src, unsigned Offset) {
2136 SDValue Ptr = LD->getBasePtr();
2137 EVT VT = LD->getValueType(0), MemVT = LD->getMemoryVT();
2138 EVT BasePtrVT = Ptr.getValueType();
2139 DebugLoc DL = LD->getDebugLoc();
2140 SDVTList VTList = DAG.getVTList(VT, MVT::Other);
2143 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2144 DAG.getConstant(Offset, BasePtrVT));
2146 SDValue Ops[] = { Chain, Ptr, Src };
2147 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2148 LD->getMemOperand());
2151 // Expand an unaligned 32 or 64-bit integer load node.
2152 SDValue MipsTargetLowering::LowerLOAD(SDValue Op, SelectionDAG &DAG) const {
2153 LoadSDNode *LD = cast<LoadSDNode>(Op);
2154 EVT MemVT = LD->getMemoryVT();
2156 // Return if load is aligned or if MemVT is neither i32 nor i64.
2157 if ((LD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2158 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2161 bool IsLittle = Subtarget->isLittle();
2162 EVT VT = Op.getValueType();
2163 ISD::LoadExtType ExtType = LD->getExtensionType();
2164 SDValue Chain = LD->getChain(), Undef = DAG.getUNDEF(VT);
2166 assert((VT == MVT::i32) || (VT == MVT::i64));
2169 // (set dst, (i64 (load baseptr)))
2171 // (set tmp, (ldl (add baseptr, 7), undef))
2172 // (set dst, (ldr baseptr, tmp))
2173 if ((VT == MVT::i64) && (ExtType == ISD::NON_EXTLOAD)) {
2174 SDValue LDL = CreateLoadLR(MipsISD::LDL, DAG, LD, Chain, Undef,
2176 return CreateLoadLR(MipsISD::LDR, DAG, LD, LDL.getValue(1), LDL,
2180 SDValue LWL = CreateLoadLR(MipsISD::LWL, DAG, LD, Chain, Undef,
2182 SDValue LWR = CreateLoadLR(MipsISD::LWR, DAG, LD, LWL.getValue(1), LWL,
2186 // (set dst, (i32 (load baseptr))) or
2187 // (set dst, (i64 (sextload baseptr))) or
2188 // (set dst, (i64 (extload baseptr)))
2190 // (set tmp, (lwl (add baseptr, 3), undef))
2191 // (set dst, (lwr baseptr, tmp))
2192 if ((VT == MVT::i32) || (ExtType == ISD::SEXTLOAD) ||
2193 (ExtType == ISD::EXTLOAD))
2196 assert((VT == MVT::i64) && (ExtType == ISD::ZEXTLOAD));
2199 // (set dst, (i64 (zextload baseptr)))
2201 // (set tmp0, (lwl (add baseptr, 3), undef))
2202 // (set tmp1, (lwr baseptr, tmp0))
2203 // (set tmp2, (shl tmp1, 32))
2204 // (set dst, (srl tmp2, 32))
2205 DebugLoc DL = LD->getDebugLoc();
2206 SDValue Const32 = DAG.getConstant(32, MVT::i32);
2207 SDValue SLL = DAG.getNode(ISD::SHL, DL, MVT::i64, LWR, Const32);
2208 SDValue SRL = DAG.getNode(ISD::SRL, DL, MVT::i64, SLL, Const32);
2209 SDValue Ops[] = { SRL, LWR.getValue(1) };
2210 return DAG.getMergeValues(Ops, 2, DL);
2213 static SDValue CreateStoreLR(unsigned Opc, SelectionDAG &DAG, StoreSDNode *SD,
2214 SDValue Chain, unsigned Offset) {
2215 SDValue Ptr = SD->getBasePtr(), Value = SD->getValue();
2216 EVT MemVT = SD->getMemoryVT(), BasePtrVT = Ptr.getValueType();
2217 DebugLoc DL = SD->getDebugLoc();
2218 SDVTList VTList = DAG.getVTList(MVT::Other);
2221 Ptr = DAG.getNode(ISD::ADD, DL, BasePtrVT, Ptr,
2222 DAG.getConstant(Offset, BasePtrVT));
2224 SDValue Ops[] = { Chain, Value, Ptr };
2225 return DAG.getMemIntrinsicNode(Opc, DL, VTList, Ops, 3, MemVT,
2226 SD->getMemOperand());
2229 // Expand an unaligned 32 or 64-bit integer store node.
2230 SDValue MipsTargetLowering::LowerSTORE(SDValue Op, SelectionDAG &DAG) const {
2231 StoreSDNode *SD = cast<StoreSDNode>(Op);
2232 EVT MemVT = SD->getMemoryVT();
2234 // Return if store is aligned or if MemVT is neither i32 nor i64.
2235 if ((SD->getAlignment() >= MemVT.getSizeInBits() / 8) ||
2236 ((MemVT != MVT::i32) && (MemVT != MVT::i64)))
2239 bool IsLittle = Subtarget->isLittle();
2240 SDValue Value = SD->getValue(), Chain = SD->getChain();
2241 EVT VT = Value.getValueType();
2244 // (store val, baseptr) or
2245 // (truncstore val, baseptr)
2247 // (swl val, (add baseptr, 3))
2248 // (swr val, baseptr)
2249 if ((VT == MVT::i32) || SD->isTruncatingStore()) {
2250 SDValue SWL = CreateStoreLR(MipsISD::SWL, DAG, SD, Chain,
2252 return CreateStoreLR(MipsISD::SWR, DAG, SD, SWL, IsLittle ? 0 : 3);
2255 assert(VT == MVT::i64);
2258 // (store val, baseptr)
2260 // (sdl val, (add baseptr, 7))
2261 // (sdr val, baseptr)
2262 SDValue SDL = CreateStoreLR(MipsISD::SDL, DAG, SD, Chain, IsLittle ? 7 : 0);
2263 return CreateStoreLR(MipsISD::SDR, DAG, SD, SDL, IsLittle ? 0 : 7);
2266 //===----------------------------------------------------------------------===//
2267 // Calling Convention Implementation
2268 //===----------------------------------------------------------------------===//
2270 //===----------------------------------------------------------------------===//
2271 // TODO: Implement a generic logic using tblgen that can support this.
2272 // Mips O32 ABI rules:
2274 // i32 - Passed in A0, A1, A2, A3 and stack
2275 // f32 - Only passed in f32 registers if no int reg has been used yet to hold
2276 // an argument. Otherwise, passed in A1, A2, A3 and stack.
2277 // f64 - Only passed in two aliased f32 registers if no int reg has been used
2278 // yet to hold an argument. Otherwise, use A2, A3 and stack. If A1 is
2279 // not used, it must be shadowed. If only A3 is avaiable, shadow it and
2282 // For vararg functions, all arguments are passed in A0, A1, A2, A3 and stack.
2283 //===----------------------------------------------------------------------===//
2285 static bool CC_MipsO32(unsigned ValNo, MVT ValVT,
2286 MVT LocVT, CCValAssign::LocInfo LocInfo,
2287 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2289 static const unsigned IntRegsSize=4, FloatRegsSize=2;
2291 static const uint16_t IntRegs[] = {
2292 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2294 static const uint16_t F32Regs[] = {
2295 Mips::F12, Mips::F14
2297 static const uint16_t F64Regs[] = {
2302 if (ArgFlags.isByVal()) {
2303 State.HandleByVal(ValNo, ValVT, LocVT, LocInfo,
2304 1 /*MinSize*/, 4 /*MinAlign*/, ArgFlags);
2305 unsigned NextReg = (State.getNextStackOffset() + 3) / 4;
2306 for (unsigned r = State.getFirstUnallocated(IntRegs, IntRegsSize);
2307 r < std::min(IntRegsSize, NextReg); ++r)
2308 State.AllocateReg(IntRegs[r]);
2312 // Promote i8 and i16
2313 if (LocVT == MVT::i8 || LocVT == MVT::i16) {
2315 if (ArgFlags.isSExt())
2316 LocInfo = CCValAssign::SExt;
2317 else if (ArgFlags.isZExt())
2318 LocInfo = CCValAssign::ZExt;
2320 LocInfo = CCValAssign::AExt;
2325 // f32 and f64 are allocated in A0, A1, A2, A3 when either of the following
2326 // is true: function is vararg, argument is 3rd or higher, there is previous
2327 // argument which is not f32 or f64.
2328 bool AllocateFloatsInIntReg = State.isVarArg() || ValNo > 1
2329 || State.getFirstUnallocated(F32Regs, FloatRegsSize) != ValNo;
2330 unsigned OrigAlign = ArgFlags.getOrigAlign();
2331 bool isI64 = (ValVT == MVT::i32 && OrigAlign == 8);
2333 if (ValVT == MVT::i32 || (ValVT == MVT::f32 && AllocateFloatsInIntReg)) {
2334 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2335 // If this is the first part of an i64 arg,
2336 // the allocated register must be either A0 or A2.
2337 if (isI64 && (Reg == Mips::A1 || Reg == Mips::A3))
2338 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2340 } else if (ValVT == MVT::f64 && AllocateFloatsInIntReg) {
2341 // Allocate int register and shadow next int register. If first
2342 // available register is Mips::A1 or Mips::A3, shadow it too.
2343 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2344 if (Reg == Mips::A1 || Reg == Mips::A3)
2345 Reg = State.AllocateReg(IntRegs, IntRegsSize);
2346 State.AllocateReg(IntRegs, IntRegsSize);
2348 } else if (ValVT.isFloatingPoint() && !AllocateFloatsInIntReg) {
2349 // we are guaranteed to find an available float register
2350 if (ValVT == MVT::f32) {
2351 Reg = State.AllocateReg(F32Regs, FloatRegsSize);
2352 // Shadow int register
2353 State.AllocateReg(IntRegs, IntRegsSize);
2355 Reg = State.AllocateReg(F64Regs, FloatRegsSize);
2356 // Shadow int registers
2357 unsigned Reg2 = State.AllocateReg(IntRegs, IntRegsSize);
2358 if (Reg2 == Mips::A1 || Reg2 == Mips::A3)
2359 State.AllocateReg(IntRegs, IntRegsSize);
2360 State.AllocateReg(IntRegs, IntRegsSize);
2363 llvm_unreachable("Cannot handle this ValVT.");
2365 unsigned SizeInBytes = ValVT.getSizeInBits() >> 3;
2366 unsigned Offset = State.AllocateStack(SizeInBytes, OrigAlign);
2369 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2371 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
2373 return false; // CC must always match
2376 static const uint16_t Mips64IntRegs[8] =
2377 {Mips::A0_64, Mips::A1_64, Mips::A2_64, Mips::A3_64,
2378 Mips::T0_64, Mips::T1_64, Mips::T2_64, Mips::T3_64};
2379 static const uint16_t Mips64DPRegs[8] =
2380 {Mips::D12_64, Mips::D13_64, Mips::D14_64, Mips::D15_64,
2381 Mips::D16_64, Mips::D17_64, Mips::D18_64, Mips::D19_64};
2383 static bool CC_Mips64Byval(unsigned ValNo, MVT ValVT, MVT LocVT,
2384 CCValAssign::LocInfo LocInfo,
2385 ISD::ArgFlagsTy ArgFlags, CCState &State) {
2386 unsigned Align = std::max(ArgFlags.getByValAlign(), (unsigned)8);
2387 unsigned Size = (ArgFlags.getByValSize() + 7) / 8 * 8;
2388 unsigned FirstIdx = State.getFirstUnallocated(Mips64IntRegs, 8);
2390 assert(Align <= 16 && "Cannot handle alignments larger than 16.");
2392 // If byval is 16-byte aligned, the first arg register must be even.
2393 if ((Align == 16) && (FirstIdx % 2)) {
2394 State.AllocateReg(Mips64IntRegs[FirstIdx], Mips64DPRegs[FirstIdx]);
2398 // Mark the registers allocated.
2399 for (unsigned I = FirstIdx; Size && (I < 8); Size -= 8, ++I)
2400 State.AllocateReg(Mips64IntRegs[I], Mips64DPRegs[I]);
2402 // Allocate space on caller's stack.
2403 unsigned Offset = State.AllocateStack(Size, Align);
2406 State.addLoc(CCValAssign::getReg(ValNo, ValVT, Mips64IntRegs[FirstIdx],
2409 State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset, LocVT, LocInfo));
2414 #include "MipsGenCallingConv.inc"
2417 AnalyzeMips64CallOperands(CCState &CCInfo,
2418 const SmallVectorImpl<ISD::OutputArg> &Outs) {
2419 unsigned NumOps = Outs.size();
2420 for (unsigned i = 0; i != NumOps; ++i) {
2421 MVT ArgVT = Outs[i].VT;
2422 ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
2425 if (Outs[i].IsFixed)
2426 R = CC_MipsN(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2428 R = CC_MipsN_VarArg(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
2432 dbgs() << "Call operand #" << i << " has unhandled type "
2433 << EVT(ArgVT).getEVTString();
2435 llvm_unreachable(0);
2440 //===----------------------------------------------------------------------===//
2441 // Call Calling Convention Implementation
2442 //===----------------------------------------------------------------------===//
2444 static const unsigned O32IntRegsSize = 4;
2446 static const uint16_t O32IntRegs[] = {
2447 Mips::A0, Mips::A1, Mips::A2, Mips::A3
2450 // Return next O32 integer argument register.
2451 static unsigned getNextIntArgReg(unsigned Reg) {
2452 assert((Reg == Mips::A0) || (Reg == Mips::A2));
2453 return (Reg == Mips::A0) ? Mips::A1 : Mips::A3;
2456 // Write ByVal Arg to arg registers and stack.
2458 WriteByValArg(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2459 SmallVector<std::pair<unsigned, SDValue>, 16> &RegsToPass,
2460 SmallVector<SDValue, 8> &MemOpChains, int &LastFI,
2461 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2462 const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
2463 MVT PtrType, bool isLittle) {
2464 unsigned LocMemOffset = VA.getLocMemOffset();
2465 unsigned Offset = 0;
2466 uint32_t RemainingSize = Flags.getByValSize();
2467 unsigned ByValAlign = Flags.getByValAlign();
2469 // Copy the first 4 words of byval arg to registers A0 - A3.
2470 // FIXME: Use a stricter alignment if it enables better optimization in passes
2472 for (; RemainingSize >= 4 && LocMemOffset < 4 * 4;
2473 Offset += 4, RemainingSize -= 4, LocMemOffset += 4) {
2474 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2475 DAG.getConstant(Offset, MVT::i32));
2476 SDValue LoadVal = DAG.getLoad(MVT::i32, dl, Chain, LoadPtr,
2477 MachinePointerInfo(), false, false, false,
2478 std::min(ByValAlign, (unsigned )4));
2479 MemOpChains.push_back(LoadVal.getValue(1));
2480 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2481 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2484 if (RemainingSize == 0)
2487 // If there still is a register available for argument passing, write the
2488 // remaining part of the structure to it using subword loads and shifts.
2489 if (LocMemOffset < 4 * 4) {
2490 assert(RemainingSize <= 3 && RemainingSize >= 1 &&
2491 "There must be one to three bytes remaining.");
2492 unsigned LoadSize = (RemainingSize == 3 ? 2 : RemainingSize);
2493 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2494 DAG.getConstant(Offset, MVT::i32));
2495 unsigned Alignment = std::min(ByValAlign, (unsigned )4);
2496 SDValue LoadVal = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2497 LoadPtr, MachinePointerInfo(),
2498 MVT::getIntegerVT(LoadSize * 8), false,
2500 MemOpChains.push_back(LoadVal.getValue(1));
2502 // If target is big endian, shift it to the most significant half-word or
2505 LoadVal = DAG.getNode(ISD::SHL, dl, MVT::i32, LoadVal,
2506 DAG.getConstant(32 - LoadSize * 8, MVT::i32));
2509 RemainingSize -= LoadSize;
2511 // Read second subword if necessary.
2512 if (RemainingSize != 0) {
2513 assert(RemainingSize == 1 && "There must be one byte remaining.");
2514 LoadPtr = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2515 DAG.getConstant(Offset, MVT::i32));
2516 unsigned Alignment = std::min(ByValAlign, (unsigned )2);
2517 SDValue Subword = DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i32, Chain,
2518 LoadPtr, MachinePointerInfo(),
2519 MVT::i8, false, false, Alignment);
2520 MemOpChains.push_back(Subword.getValue(1));
2521 // Insert the loaded byte to LoadVal.
2522 // FIXME: Use INS if supported by target.
2523 unsigned ShiftAmt = isLittle ? 16 : 8;
2524 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i32, Subword,
2525 DAG.getConstant(ShiftAmt, MVT::i32));
2526 LoadVal = DAG.getNode(ISD::OR, dl, MVT::i32, LoadVal, Shift);
2529 unsigned DstReg = O32IntRegs[LocMemOffset / 4];
2530 RegsToPass.push_back(std::make_pair(DstReg, LoadVal));
2534 // Create a fixed object on stack at offset LocMemOffset and copy
2535 // remaining part of byval arg to it using memcpy.
2536 SDValue Src = DAG.getNode(ISD::ADD, dl, MVT::i32, Arg,
2537 DAG.getConstant(Offset, MVT::i32));
2538 LastFI = MFI->CreateFixedObject(RemainingSize, LocMemOffset, true);
2539 SDValue Dst = DAG.getFrameIndex(LastFI, PtrType);
2540 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2541 DAG.getConstant(RemainingSize, MVT::i32),
2542 std::min(ByValAlign, (unsigned)4),
2543 /*isVolatile=*/false, /*AlwaysInline=*/false,
2544 MachinePointerInfo(0), MachinePointerInfo(0));
2547 // Copy Mips64 byVal arg to registers and stack.
2549 PassByValArg64(SDValue& ByValChain, SDValue Chain, DebugLoc dl,
2550 SmallVector<std::pair<unsigned, SDValue>, 16> &RegsToPass,
2551 SmallVector<SDValue, 8> &MemOpChains, int &LastFI,
2552 MachineFrameInfo *MFI, SelectionDAG &DAG, SDValue Arg,
2553 const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
2554 EVT PtrTy, bool isLittle) {
2555 unsigned ByValSize = Flags.getByValSize();
2556 unsigned Alignment = std::min(Flags.getByValAlign(), (unsigned)8);
2557 bool IsRegLoc = VA.isRegLoc();
2558 unsigned Offset = 0; // Offset in # of bytes from the beginning of struct.
2559 unsigned LocMemOffset = 0;
2560 unsigned MemCpySize = ByValSize;
2563 LocMemOffset = VA.getLocMemOffset();
2565 const uint16_t *Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8,
2567 const uint16_t *RegEnd = Mips64IntRegs + 8;
2569 // Copy double words to registers.
2570 for (; (Reg != RegEnd) && (ByValSize >= Offset + 8); ++Reg, Offset += 8) {
2571 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2572 DAG.getConstant(Offset, PtrTy));
2573 SDValue LoadVal = DAG.getLoad(MVT::i64, dl, Chain, LoadPtr,
2574 MachinePointerInfo(), false, false, false,
2576 MemOpChains.push_back(LoadVal.getValue(1));
2577 RegsToPass.push_back(std::make_pair(*Reg, LoadVal));
2580 // Return if the struct has been fully copied.
2581 if (!(MemCpySize = ByValSize - Offset))
2584 // If there is an argument register available, copy the remainder of the
2585 // byval argument with sub-doubleword loads and shifts.
2586 if (Reg != RegEnd) {
2587 assert((ByValSize < Offset + 8) &&
2588 "Size of the remainder should be smaller than 8-byte.");
2590 for (unsigned LoadSize = 4; Offset < ByValSize; LoadSize /= 2) {
2591 unsigned RemSize = ByValSize - Offset;
2593 if (RemSize < LoadSize)
2596 SDValue LoadPtr = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2597 DAG.getConstant(Offset, PtrTy));
2599 DAG.getExtLoad(ISD::ZEXTLOAD, dl, MVT::i64, Chain, LoadPtr,
2600 MachinePointerInfo(), MVT::getIntegerVT(LoadSize * 8),
2601 false, false, Alignment);
2602 MemOpChains.push_back(LoadVal.getValue(1));
2604 // Offset in number of bits from double word boundary.
2605 unsigned OffsetDW = (Offset % 8) * 8;
2606 unsigned Shamt = isLittle ? OffsetDW : 64 - (OffsetDW + LoadSize * 8);
2607 SDValue Shift = DAG.getNode(ISD::SHL, dl, MVT::i64, LoadVal,
2608 DAG.getConstant(Shamt, MVT::i32));
2610 Val = Val.getNode() ? DAG.getNode(ISD::OR, dl, MVT::i64, Val, Shift) :
2613 Alignment = std::min(Alignment, LoadSize);
2616 RegsToPass.push_back(std::make_pair(*Reg, Val));
2621 assert(MemCpySize && "MemCpySize must not be zero.");
2623 // Create a fixed object on stack at offset LocMemOffset and copy
2624 // remainder of byval arg to it with memcpy.
2625 SDValue Src = DAG.getNode(ISD::ADD, dl, PtrTy, Arg,
2626 DAG.getConstant(Offset, PtrTy));
2627 LastFI = MFI->CreateFixedObject(MemCpySize, LocMemOffset, true);
2628 SDValue Dst = DAG.getFrameIndex(LastFI, PtrTy);
2629 ByValChain = DAG.getMemcpy(ByValChain, dl, Dst, Src,
2630 DAG.getConstant(MemCpySize, PtrTy), Alignment,
2631 /*isVolatile=*/false, /*AlwaysInline=*/false,
2632 MachinePointerInfo(0), MachinePointerInfo(0));
2635 /// LowerCall - functions arguments are copied from virtual regs to
2636 /// (physical regs)/(stack frame), CALLSEQ_START and CALLSEQ_END are emitted.
2637 /// TODO: isTailCall.
2639 MipsTargetLowering::LowerCall(TargetLowering::CallLoweringInfo &CLI,
2640 SmallVectorImpl<SDValue> &InVals) const {
2641 SelectionDAG &DAG = CLI.DAG;
2642 DebugLoc &dl = CLI.DL;
2643 SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
2644 SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
2645 SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
2646 SDValue InChain = CLI.Chain;
2647 SDValue Callee = CLI.Callee;
2648 SDValue CalleeSave = CLI.Callee;
2649 bool &isTailCall = CLI.IsTailCall;
2650 CallingConv::ID CallConv = CLI.CallConv;
2651 bool isVarArg = CLI.IsVarArg;
2653 // MIPs target does not yet support tail call optimization.
2656 MachineFunction &MF = DAG.getMachineFunction();
2657 MachineFrameInfo *MFI = MF.getFrameInfo();
2658 const TargetFrameLowering *TFL = MF.getTarget().getFrameLowering();
2659 bool IsPIC = getTargetMachine().getRelocationModel() == Reloc::PIC_;
2660 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
2662 // Analyze operands of the call, assigning locations to each operand.
2663 SmallVector<CCValAssign, 16> ArgLocs;
2664 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2665 getTargetMachine(), ArgLocs, *DAG.getContext());
2667 if (CallConv == CallingConv::Fast)
2668 CCInfo.AnalyzeCallOperands(Outs, CC_Mips_FastCC);
2670 CCInfo.AnalyzeCallOperands(Outs, CC_MipsO32);
2672 AnalyzeMips64CallOperands(CCInfo, Outs);
2674 CCInfo.AnalyzeCallOperands(Outs, CC_Mips);
2676 // Get a count of how many bytes are to be pushed on the stack.
2677 unsigned NextStackOffset = CCInfo.getNextStackOffset();
2679 // Chain is the output chain of the last Load/Store or CopyToReg node.
2680 // ByValChain is the output chain of the last Memcpy node created for copying
2681 // byval arguments to the stack.
2682 SDValue Chain, CallSeqStart, ByValChain;
2683 SDValue NextStackOffsetVal = DAG.getIntPtrConstant(NextStackOffset, true);
2684 Chain = CallSeqStart = DAG.getCALLSEQ_START(InChain, NextStackOffsetVal);
2685 ByValChain = InChain;
2687 // Get the frame index of the stack frame object that points to the location
2688 // of dynamically allocated area on the stack.
2689 int DynAllocFI = MipsFI->getDynAllocFI();
2691 // Update size of the maximum argument space.
2692 // For O32, a minimum of four words (16 bytes) of argument space is
2694 if (IsO32 && (CallConv != CallingConv::Fast))
2695 NextStackOffset = std::max(NextStackOffset, (unsigned)16);
2697 unsigned MaxCallFrameSize = MipsFI->getMaxCallFrameSize();
2699 if (MaxCallFrameSize < NextStackOffset) {
2700 MipsFI->setMaxCallFrameSize(NextStackOffset);
2702 // Set the offsets relative to $sp of the $gp restore slot and dynamically
2703 // allocated stack space. These offsets must be aligned to a boundary
2704 // determined by the stack alignment of the ABI.
2705 unsigned StackAlignment = TFL->getStackAlignment();
2706 NextStackOffset = (NextStackOffset + StackAlignment - 1) /
2707 StackAlignment * StackAlignment;
2709 MFI->setObjectOffset(DynAllocFI, NextStackOffset);
2712 // With EABI is it possible to have 16 args on registers.
2713 SmallVector<std::pair<unsigned, SDValue>, 16> RegsToPass;
2714 SmallVector<SDValue, 8> MemOpChains;
2716 int FirstFI = -MFI->getNumFixedObjects() - 1, LastFI = 0;
2718 // Walk the register/memloc assignments, inserting copies/loads.
2719 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
2720 SDValue Arg = OutVals[i];
2721 CCValAssign &VA = ArgLocs[i];
2722 MVT ValVT = VA.getValVT(), LocVT = VA.getLocVT();
2723 ISD::ArgFlagsTy Flags = Outs[i].Flags;
2726 if (Flags.isByVal()) {
2727 assert(Flags.getByValSize() &&
2728 "ByVal args of size 0 should have been ignored by front-end.");
2730 WriteByValArg(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2731 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2732 Subtarget->isLittle());
2734 PassByValArg64(ByValChain, Chain, dl, RegsToPass, MemOpChains, LastFI,
2735 MFI, DAG, Arg, VA, Flags, getPointerTy(),
2736 Subtarget->isLittle());
2740 // Promote the value if needed.
2741 switch (VA.getLocInfo()) {
2742 default: llvm_unreachable("Unknown loc info!");
2743 case CCValAssign::Full:
2744 if (VA.isRegLoc()) {
2745 if ((ValVT == MVT::f32 && LocVT == MVT::i32) ||
2746 (ValVT == MVT::f64 && LocVT == MVT::i64))
2747 Arg = DAG.getNode(ISD::BITCAST, dl, LocVT, Arg);
2748 else if (ValVT == MVT::f64 && LocVT == MVT::i32) {
2749 SDValue Lo = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2750 Arg, DAG.getConstant(0, MVT::i32));
2751 SDValue Hi = DAG.getNode(MipsISD::ExtractElementF64, dl, MVT::i32,
2752 Arg, DAG.getConstant(1, MVT::i32));
2753 if (!Subtarget->isLittle())
2755 unsigned LocRegLo = VA.getLocReg();
2756 unsigned LocRegHigh = getNextIntArgReg(LocRegLo);
2757 RegsToPass.push_back(std::make_pair(LocRegLo, Lo));
2758 RegsToPass.push_back(std::make_pair(LocRegHigh, Hi));
2763 case CCValAssign::SExt:
2764 Arg = DAG.getNode(ISD::SIGN_EXTEND, dl, LocVT, Arg);
2766 case CCValAssign::ZExt:
2767 Arg = DAG.getNode(ISD::ZERO_EXTEND, dl, LocVT, Arg);
2769 case CCValAssign::AExt:
2770 Arg = DAG.getNode(ISD::ANY_EXTEND, dl, LocVT, Arg);
2774 // Arguments that can be passed on register must be kept at
2775 // RegsToPass vector
2776 if (VA.isRegLoc()) {
2777 RegsToPass.push_back(std::make_pair(VA.getLocReg(), Arg));
2781 // Register can't get to this point...
2782 assert(VA.isMemLoc());
2784 // Create the frame index object for this incoming parameter
2785 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
2786 VA.getLocMemOffset(), true);
2787 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
2789 // emit ISD::STORE whichs stores the
2790 // parameter value to a stack Location
2791 MemOpChains.push_back(DAG.getStore(Chain, dl, Arg, PtrOff,
2792 MachinePointerInfo(), false, false, 0));
2795 // Extend range of indices of frame objects for outgoing arguments that were
2796 // created during this function call. Skip this step if no such objects were
2799 MipsFI->extendOutArgFIRange(FirstFI, LastFI);
2801 // If a memcpy has been created to copy a byval arg to a stack, replace the
2802 // chain input of CallSeqStart with ByValChain.
2803 if (InChain != ByValChain)
2804 DAG.UpdateNodeOperands(CallSeqStart.getNode(), ByValChain,
2805 NextStackOffsetVal);
2807 // Transform all store nodes into one single node because all store
2808 // nodes are independent of each other.
2809 if (!MemOpChains.empty())
2810 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
2811 &MemOpChains[0], MemOpChains.size());
2813 // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
2814 // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
2815 // node so that legalize doesn't hack it.
2816 unsigned char OpFlag;
2817 bool IsPICCall = (IsN64 || IsPIC); // true if calls are translated to jalr $25
2818 bool GlobalOrExternal = false;
2821 if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
2822 if (IsPICCall && G->getGlobal()->hasInternalLinkage()) {
2823 OpFlag = IsO32 ? MipsII::MO_GOT : MipsII::MO_GOT_PAGE;
2824 unsigned char LoFlag = IsO32 ? MipsII::MO_ABS_LO : MipsII::MO_GOT_OFST;
2825 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(), 0,
2827 CalleeLo = DAG.getTargetGlobalAddress(G->getGlobal(), dl, getPointerTy(),
2830 OpFlag = IsPICCall ? MipsII::MO_GOT_CALL : MipsII::MO_NO_FLAG;
2831 Callee = DAG.getTargetGlobalAddress(G->getGlobal(), dl,
2832 getPointerTy(), 0, OpFlag);
2835 GlobalOrExternal = true;
2837 else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
2838 if (IsN64 || (!IsO32 && IsPIC))
2839 OpFlag = MipsII::MO_GOT_DISP;
2840 else if (!IsPIC) // !N64 && static
2841 OpFlag = MipsII::MO_NO_FLAG;
2843 OpFlag = MipsII::MO_GOT_CALL;
2844 Callee = DAG.getTargetExternalSymbol(S->getSymbol(), getPointerTy(),
2846 GlobalOrExternal = true;
2851 // Create nodes that load address of callee and copy it to T9
2853 if (GlobalOrExternal) {
2854 // Load callee address
2855 Callee = DAG.getNode(MipsISD::Wrapper, dl, getPointerTy(),
2856 GetGlobalReg(DAG, getPointerTy()), Callee);
2857 SDValue LoadValue = DAG.getLoad(getPointerTy(), dl, DAG.getEntryNode(),
2858 Callee, MachinePointerInfo::getGOT(),
2859 false, false, false, 0);
2861 // Use GOT+LO if callee has internal linkage.
2862 if (CalleeLo.getNode()) {
2863 SDValue Lo = DAG.getNode(MipsISD::Lo, dl, getPointerTy(), CalleeLo);
2864 Callee = DAG.getNode(ISD::ADD, dl, getPointerTy(), LoadValue, Lo);
2870 // T9 should contain the address of the callee function if
2871 // -reloction-model=pic or it is an indirect call.
2872 if (IsPICCall || !GlobalOrExternal) {
2874 unsigned T9Reg = IsN64 ? Mips::T9_64 : Mips::T9;
2875 Chain = DAG.getCopyToReg(Chain, dl, T9Reg, Callee, SDValue(0, 0));
2876 InFlag = Chain.getValue(1);
2877 Callee = DAG.getRegister(T9Reg, getPointerTy());
2880 // Insert node "GP copy globalreg" before call to function.
2881 // Lazy-binding stubs require GP to point to the GOT.
2883 unsigned GPReg = IsN64 ? Mips::GP_64 : Mips::GP;
2884 EVT Ty = IsN64 ? MVT::i64 : MVT::i32;
2885 RegsToPass.push_back(std::make_pair(GPReg, GetGlobalReg(DAG, Ty)));
2888 // Build a sequence of copy-to-reg nodes chained together with token
2889 // chain and flag operands which copy the outgoing args into registers.
2890 // The InFlag in necessary since all emitted instructions must be
2892 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i) {
2893 Chain = DAG.getCopyToReg(Chain, dl, RegsToPass[i].first,
2894 RegsToPass[i].second, InFlag);
2895 InFlag = Chain.getValue(1);
2898 // MipsJmpLink = #chain, #target_address, #opt_in_flags...
2899 // = Chain, Callee, Reg#1, Reg#2, ...
2901 // Returns a chain & a flag for retval copy to use.
2902 SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
2903 SmallVector<SDValue, 8> Ops;
2904 Ops.push_back(Chain);
2905 Ops.push_back(Subtarget->inMips16Mode()? CalleeSave: Callee);
2907 // Add argument registers to the end of the list so that they are
2908 // known live into the call.
2909 for (unsigned i = 0, e = RegsToPass.size(); i != e; ++i)
2910 Ops.push_back(DAG.getRegister(RegsToPass[i].first,
2911 RegsToPass[i].second.getValueType()));
2913 if (Subtarget->inMips16Mode())
2914 Ops.push_back(Callee);
2915 // Add a register mask operand representing the call-preserved registers.
2916 const TargetRegisterInfo *TRI = getTargetMachine().getRegisterInfo();
2917 const uint32_t *Mask = TRI->getCallPreservedMask(CallConv);
2918 assert(Mask && "Missing call preserved mask for calling convention");
2919 Ops.push_back(DAG.getRegisterMask(Mask));
2921 if (InFlag.getNode())
2922 Ops.push_back(InFlag);
2924 Chain = DAG.getNode(MipsISD::JmpLink, dl, NodeTys, &Ops[0], Ops.size());
2925 InFlag = Chain.getValue(1);
2927 // Create the CALLSEQ_END node.
2928 Chain = DAG.getCALLSEQ_END(Chain,
2929 DAG.getIntPtrConstant(NextStackOffset, true),
2930 DAG.getIntPtrConstant(0, true), InFlag);
2931 InFlag = Chain.getValue(1);
2933 // Handle result values, copying them out of physregs into vregs that we
2935 return LowerCallResult(Chain, InFlag, CallConv, isVarArg,
2936 Ins, dl, DAG, InVals);
2939 /// LowerCallResult - Lower the result values of a call into the
2940 /// appropriate copies out of appropriate physical registers.
2942 MipsTargetLowering::LowerCallResult(SDValue Chain, SDValue InFlag,
2943 CallingConv::ID CallConv, bool isVarArg,
2944 const SmallVectorImpl<ISD::InputArg> &Ins,
2945 DebugLoc dl, SelectionDAG &DAG,
2946 SmallVectorImpl<SDValue> &InVals) const {
2947 // Assign locations to each value returned by this call.
2948 SmallVector<CCValAssign, 16> RVLocs;
2949 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
2950 getTargetMachine(), RVLocs, *DAG.getContext());
2952 CCInfo.AnalyzeCallResult(Ins, RetCC_Mips);
2954 // Copy all of the result registers out of their specified physreg.
2955 for (unsigned i = 0; i != RVLocs.size(); ++i) {
2956 Chain = DAG.getCopyFromReg(Chain, dl, RVLocs[i].getLocReg(),
2957 RVLocs[i].getValVT(), InFlag).getValue(1);
2958 InFlag = Chain.getValue(2);
2959 InVals.push_back(Chain.getValue(0));
2965 //===----------------------------------------------------------------------===//
2966 // Formal Arguments Calling Convention Implementation
2967 //===----------------------------------------------------------------------===//
2968 static void ReadByValArg(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2969 std::vector<SDValue> &OutChains,
2970 SelectionDAG &DAG, unsigned NumWords, SDValue FIN,
2971 const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
2972 const Argument *FuncArg) {
2973 unsigned LocMem = VA.getLocMemOffset();
2974 unsigned FirstWord = LocMem / 4;
2976 // copy register A0 - A3 to frame object
2977 for (unsigned i = 0; i < NumWords; ++i) {
2978 unsigned CurWord = FirstWord + i;
2979 if (CurWord >= O32IntRegsSize)
2982 unsigned SrcReg = O32IntRegs[CurWord];
2983 unsigned Reg = AddLiveIn(MF, SrcReg, &Mips::CPURegsRegClass);
2984 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, MVT::i32, FIN,
2985 DAG.getConstant(i * 4, MVT::i32));
2986 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(Reg, MVT::i32),
2987 StorePtr, MachinePointerInfo(FuncArg, i * 4),
2989 OutChains.push_back(Store);
2993 // Create frame object on stack and copy registers used for byval passing to it.
2995 CopyMips64ByValRegs(MachineFunction &MF, SDValue Chain, DebugLoc dl,
2996 std::vector<SDValue> &OutChains, SelectionDAG &DAG,
2997 const CCValAssign &VA, const ISD::ArgFlagsTy &Flags,
2998 MachineFrameInfo *MFI, bool IsRegLoc,
2999 SmallVectorImpl<SDValue> &InVals, MipsFunctionInfo *MipsFI,
3000 EVT PtrTy, const Argument *FuncArg) {
3001 const uint16_t *Reg = Mips64IntRegs + 8;
3002 int FOOffset; // Frame object offset from virtual frame pointer.
3005 Reg = std::find(Mips64IntRegs, Mips64IntRegs + 8, VA.getLocReg());
3006 FOOffset = (Reg - Mips64IntRegs) * 8 - 8 * 8;
3009 FOOffset = VA.getLocMemOffset();
3011 // Create frame object.
3012 unsigned NumRegs = (Flags.getByValSize() + 7) / 8;
3013 unsigned LastFI = MFI->CreateFixedObject(NumRegs * 8, FOOffset, true);
3014 SDValue FIN = DAG.getFrameIndex(LastFI, PtrTy);
3015 InVals.push_back(FIN);
3017 // Copy arg registers.
3018 for (unsigned I = 0; (Reg != Mips64IntRegs + 8) && (I < NumRegs);
3020 unsigned VReg = AddLiveIn(MF, *Reg, &Mips::CPU64RegsRegClass);
3021 SDValue StorePtr = DAG.getNode(ISD::ADD, dl, PtrTy, FIN,
3022 DAG.getConstant(I * 8, PtrTy));
3023 SDValue Store = DAG.getStore(Chain, dl, DAG.getRegister(VReg, MVT::i64),
3024 StorePtr, MachinePointerInfo(FuncArg, I * 8),
3026 OutChains.push_back(Store);
3032 /// LowerFormalArguments - transform physical registers into virtual registers
3033 /// and generate load operations for arguments places on the stack.
3035 MipsTargetLowering::LowerFormalArguments(SDValue Chain,
3036 CallingConv::ID CallConv,
3038 const SmallVectorImpl<ISD::InputArg> &Ins,
3039 DebugLoc dl, SelectionDAG &DAG,
3040 SmallVectorImpl<SDValue> &InVals)
3042 MachineFunction &MF = DAG.getMachineFunction();
3043 MachineFrameInfo *MFI = MF.getFrameInfo();
3044 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3046 MipsFI->setVarArgsFrameIndex(0);
3048 // Used with vargs to acumulate store chains.
3049 std::vector<SDValue> OutChains;
3051 // Assign locations to all of the incoming arguments.
3052 SmallVector<CCValAssign, 16> ArgLocs;
3053 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3054 getTargetMachine(), ArgLocs, *DAG.getContext());
3056 if (CallConv == CallingConv::Fast)
3057 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips_FastCC);
3059 CCInfo.AnalyzeFormalArguments(Ins, CC_MipsO32);
3061 CCInfo.AnalyzeFormalArguments(Ins, CC_Mips);
3063 Function::const_arg_iterator FuncArg =
3064 DAG.getMachineFunction().getFunction()->arg_begin();
3065 int LastFI = 0;// MipsFI->LastInArgFI is 0 at the entry of this function.
3067 for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i, ++FuncArg) {
3068 CCValAssign &VA = ArgLocs[i];
3069 EVT ValVT = VA.getValVT();
3070 ISD::ArgFlagsTy Flags = Ins[i].Flags;
3071 bool IsRegLoc = VA.isRegLoc();
3073 if (Flags.isByVal()) {
3074 assert(Flags.getByValSize() &&
3075 "ByVal args of size 0 should have been ignored by front-end.");
3077 unsigned NumWords = (Flags.getByValSize() + 3) / 4;
3078 LastFI = MFI->CreateFixedObject(NumWords * 4, VA.getLocMemOffset(),
3080 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3081 InVals.push_back(FIN);
3082 ReadByValArg(MF, Chain, dl, OutChains, DAG, NumWords, FIN, VA, Flags,
3085 LastFI = CopyMips64ByValRegs(MF, Chain, dl, OutChains, DAG, VA, Flags,
3086 MFI, IsRegLoc, InVals, MipsFI,
3087 getPointerTy(), &*FuncArg);
3091 // Arguments stored on registers
3093 EVT RegVT = VA.getLocVT();
3094 unsigned ArgReg = VA.getLocReg();
3095 const TargetRegisterClass *RC;
3097 if (RegVT == MVT::i32)
3098 RC = &Mips::CPURegsRegClass;
3099 else if (RegVT == MVT::i64)
3100 RC = &Mips::CPU64RegsRegClass;
3101 else if (RegVT == MVT::f32)
3102 RC = &Mips::FGR32RegClass;
3103 else if (RegVT == MVT::f64)
3104 RC = HasMips64 ? &Mips::FGR64RegClass : &Mips::AFGR64RegClass;
3106 llvm_unreachable("RegVT not supported by FormalArguments Lowering");
3108 // Transform the arguments stored on
3109 // physical registers into virtual ones
3110 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgReg, RC);
3111 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg, RegVT);
3113 // If this is an 8 or 16-bit value, it has been passed promoted
3114 // to 32 bits. Insert an assert[sz]ext to capture this, then
3115 // truncate to the right size.
3116 if (VA.getLocInfo() != CCValAssign::Full) {
3117 unsigned Opcode = 0;
3118 if (VA.getLocInfo() == CCValAssign::SExt)
3119 Opcode = ISD::AssertSext;
3120 else if (VA.getLocInfo() == CCValAssign::ZExt)
3121 Opcode = ISD::AssertZext;
3123 ArgValue = DAG.getNode(Opcode, dl, RegVT, ArgValue,
3124 DAG.getValueType(ValVT));
3125 ArgValue = DAG.getNode(ISD::TRUNCATE, dl, ValVT, ArgValue);
3128 // Handle floating point arguments passed in integer registers.
3129 if ((RegVT == MVT::i32 && ValVT == MVT::f32) ||
3130 (RegVT == MVT::i64 && ValVT == MVT::f64))
3131 ArgValue = DAG.getNode(ISD::BITCAST, dl, ValVT, ArgValue);
3132 else if (IsO32 && RegVT == MVT::i32 && ValVT == MVT::f64) {
3133 unsigned Reg2 = AddLiveIn(DAG.getMachineFunction(),
3134 getNextIntArgReg(ArgReg), RC);
3135 SDValue ArgValue2 = DAG.getCopyFromReg(Chain, dl, Reg2, RegVT);
3136 if (!Subtarget->isLittle())
3137 std::swap(ArgValue, ArgValue2);
3138 ArgValue = DAG.getNode(MipsISD::BuildPairF64, dl, MVT::f64,
3139 ArgValue, ArgValue2);
3142 InVals.push_back(ArgValue);
3143 } else { // VA.isRegLoc()
3146 assert(VA.isMemLoc());
3148 // The stack pointer offset is relative to the caller stack frame.
3149 LastFI = MFI->CreateFixedObject(ValVT.getSizeInBits()/8,
3150 VA.getLocMemOffset(), true);
3152 // Create load nodes to retrieve arguments from the stack
3153 SDValue FIN = DAG.getFrameIndex(LastFI, getPointerTy());
3154 InVals.push_back(DAG.getLoad(ValVT, dl, Chain, FIN,
3155 MachinePointerInfo::getFixedStack(LastFI),
3156 false, false, false, 0));
3160 // The mips ABIs for returning structs by value requires that we copy
3161 // the sret argument into $v0 for the return. Save the argument into
3162 // a virtual register so that we can access it from the return points.
3163 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3164 unsigned Reg = MipsFI->getSRetReturnReg();
3166 Reg = MF.getRegInfo().createVirtualRegister(getRegClassFor(MVT::i32));
3167 MipsFI->setSRetReturnReg(Reg);
3169 SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), dl, Reg, InVals[0]);
3170 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other, Copy, Chain);
3174 unsigned NumOfRegs = IsO32 ? 4 : 8;
3175 const uint16_t *ArgRegs = IsO32 ? O32IntRegs : Mips64IntRegs;
3176 unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs, NumOfRegs);
3177 int FirstRegSlotOffset = IsO32 ? 0 : -64 ; // offset of $a0's slot.
3178 const TargetRegisterClass *RC = IsO32 ?
3179 (const TargetRegisterClass*)&Mips::CPURegsRegClass :
3180 (const TargetRegisterClass*)&Mips::CPU64RegsRegClass;
3181 unsigned RegSize = RC->getSize();
3182 int RegSlotOffset = FirstRegSlotOffset + Idx * RegSize;
3184 // Offset of the first variable argument from stack pointer.
3185 int FirstVaArgOffset;
3187 if (IsO32 || (Idx == NumOfRegs)) {
3189 (CCInfo.getNextStackOffset() + RegSize - 1) / RegSize * RegSize;
3191 FirstVaArgOffset = RegSlotOffset;
3193 // Record the frame index of the first variable argument
3194 // which is a value necessary to VASTART.
3195 LastFI = MFI->CreateFixedObject(RegSize, FirstVaArgOffset, true);
3196 MipsFI->setVarArgsFrameIndex(LastFI);
3198 // Copy the integer registers that have not been used for argument passing
3199 // to the argument register save area. For O32, the save area is allocated
3200 // in the caller's stack frame, while for N32/64, it is allocated in the
3201 // callee's stack frame.
3202 for (int StackOffset = RegSlotOffset;
3203 Idx < NumOfRegs; ++Idx, StackOffset += RegSize) {
3204 unsigned Reg = AddLiveIn(DAG.getMachineFunction(), ArgRegs[Idx], RC);
3205 SDValue ArgValue = DAG.getCopyFromReg(Chain, dl, Reg,
3206 MVT::getIntegerVT(RegSize * 8));
3207 LastFI = MFI->CreateFixedObject(RegSize, StackOffset, true);
3208 SDValue PtrOff = DAG.getFrameIndex(LastFI, getPointerTy());
3209 OutChains.push_back(DAG.getStore(Chain, dl, ArgValue, PtrOff,
3210 MachinePointerInfo(), false, false, 0));
3214 MipsFI->setLastInArgFI(LastFI);
3216 // All stores are grouped in one node to allow the matching between
3217 // the size of Ins and InVals. This only happens when on varg functions
3218 if (!OutChains.empty()) {
3219 OutChains.push_back(Chain);
3220 Chain = DAG.getNode(ISD::TokenFactor, dl, MVT::Other,
3221 &OutChains[0], OutChains.size());
3227 //===----------------------------------------------------------------------===//
3228 // Return Value Calling Convention Implementation
3229 //===----------------------------------------------------------------------===//
3232 MipsTargetLowering::LowerReturn(SDValue Chain,
3233 CallingConv::ID CallConv, bool isVarArg,
3234 const SmallVectorImpl<ISD::OutputArg> &Outs,
3235 const SmallVectorImpl<SDValue> &OutVals,
3236 DebugLoc dl, SelectionDAG &DAG) const {
3238 // CCValAssign - represent the assignment of
3239 // the return value to a location
3240 SmallVector<CCValAssign, 16> RVLocs;
3242 // CCState - Info about the registers and stack slot.
3243 CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(),
3244 getTargetMachine(), RVLocs, *DAG.getContext());
3246 // Analize return values.
3247 CCInfo.AnalyzeReturn(Outs, RetCC_Mips);
3249 // If this is the first return lowered for this function, add
3250 // the regs to the liveout set for the function.
3251 if (DAG.getMachineFunction().getRegInfo().liveout_empty()) {
3252 for (unsigned i = 0; i != RVLocs.size(); ++i)
3253 if (RVLocs[i].isRegLoc())
3254 DAG.getMachineFunction().getRegInfo().addLiveOut(RVLocs[i].getLocReg());
3259 // Copy the result values into the output registers.
3260 for (unsigned i = 0; i != RVLocs.size(); ++i) {
3261 CCValAssign &VA = RVLocs[i];
3262 assert(VA.isRegLoc() && "Can only return in registers!");
3264 Chain = DAG.getCopyToReg(Chain, dl, VA.getLocReg(), OutVals[i], Flag);
3266 // guarantee that all emitted copies are
3267 // stuck together, avoiding something bad
3268 Flag = Chain.getValue(1);
3271 // The mips ABIs for returning structs by value requires that we copy
3272 // the sret argument into $v0 for the return. We saved the argument into
3273 // a virtual register in the entry block, so now we copy the value out
3275 if (DAG.getMachineFunction().getFunction()->hasStructRetAttr()) {
3276 MachineFunction &MF = DAG.getMachineFunction();
3277 MipsFunctionInfo *MipsFI = MF.getInfo<MipsFunctionInfo>();
3278 unsigned Reg = MipsFI->getSRetReturnReg();
3281 llvm_unreachable("sret virtual register not created in the entry block");
3282 SDValue Val = DAG.getCopyFromReg(Chain, dl, Reg, getPointerTy());
3284 Chain = DAG.getCopyToReg(Chain, dl, Mips::V0, Val, Flag);
3285 Flag = Chain.getValue(1);
3288 // Return on Mips is always a "jr $ra"
3290 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain, Flag);
3293 return DAG.getNode(MipsISD::Ret, dl, MVT::Other, Chain);
3296 //===----------------------------------------------------------------------===//
3297 // Mips Inline Assembly Support
3298 //===----------------------------------------------------------------------===//
3300 /// getConstraintType - Given a constraint letter, return the type of
3301 /// constraint it is for this target.
3302 MipsTargetLowering::ConstraintType MipsTargetLowering::
3303 getConstraintType(const std::string &Constraint) const
3305 // Mips specific constrainy
3306 // GCC config/mips/constraints.md
3308 // 'd' : An address register. Equivalent to r
3309 // unless generating MIPS16 code.
3310 // 'y' : Equivalent to r; retained for
3311 // backwards compatibility.
3312 // 'c' : A register suitable for use in an indirect
3313 // jump. This will always be $25 for -mabicalls.
3314 // 'l' : The lo register. 1 word storage.
3315 // 'x' : The hilo register pair. Double word storage.
3316 if (Constraint.size() == 1) {
3317 switch (Constraint[0]) {
3325 return C_RegisterClass;
3328 return TargetLowering::getConstraintType(Constraint);
3331 /// Examine constraint type and operand type and determine a weight value.
3332 /// This object must already have been set up with the operand type
3333 /// and the current alternative constraint selected.
3334 TargetLowering::ConstraintWeight
3335 MipsTargetLowering::getSingleConstraintMatchWeight(
3336 AsmOperandInfo &info, const char *constraint) const {
3337 ConstraintWeight weight = CW_Invalid;
3338 Value *CallOperandVal = info.CallOperandVal;
3339 // If we don't have a value, we can't do a match,
3340 // but allow it at the lowest weight.
3341 if (CallOperandVal == NULL)
3343 Type *type = CallOperandVal->getType();
3344 // Look at the constraint type.
3345 switch (*constraint) {
3347 weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
3351 if (type->isIntegerTy())
3352 weight = CW_Register;
3355 if (type->isFloatTy())
3356 weight = CW_Register;
3358 case 'c': // $25 for indirect jumps
3359 case 'l': // lo register
3360 case 'x': // hilo register pair
3361 if (type->isIntegerTy())
3362 weight = CW_SpecificReg;
3364 case 'I': // signed 16 bit immediate
3365 case 'J': // integer zero
3366 case 'K': // unsigned 16 bit immediate
3367 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3368 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3369 case 'O': // signed 15 bit immediate (+- 16383)
3370 case 'P': // immediate in the range of 65535 to 1 (inclusive)
3371 if (isa<ConstantInt>(CallOperandVal))
3372 weight = CW_Constant;
3378 /// Given a register class constraint, like 'r', if this corresponds directly
3379 /// to an LLVM register class, return a register of 0 and the register class
3381 std::pair<unsigned, const TargetRegisterClass*> MipsTargetLowering::
3382 getRegForInlineAsmConstraint(const std::string &Constraint, EVT VT) const
3384 if (Constraint.size() == 1) {
3385 switch (Constraint[0]) {
3386 case 'd': // Address register. Same as 'r' unless generating MIPS16 code.
3387 case 'y': // Same as 'r'. Exists for compatibility.
3389 if (VT == MVT::i32 || VT == MVT::i16 || VT == MVT::i8)
3390 return std::make_pair(0U, &Mips::CPURegsRegClass);
3391 if (VT == MVT::i64 && !HasMips64)
3392 return std::make_pair(0U, &Mips::CPURegsRegClass);
3393 if (VT == MVT::i64 && HasMips64)
3394 return std::make_pair(0U, &Mips::CPU64RegsRegClass);
3395 // This will generate an error message
3396 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3399 return std::make_pair(0U, &Mips::FGR32RegClass);
3400 if ((VT == MVT::f64) && (!Subtarget->isSingleFloat())) {
3401 if (Subtarget->isFP64bit())
3402 return std::make_pair(0U, &Mips::FGR64RegClass);
3403 return std::make_pair(0U, &Mips::AFGR64RegClass);
3406 case 'c': // register suitable for indirect jump
3408 return std::make_pair((unsigned)Mips::T9, &Mips::CPURegsRegClass);
3409 assert(VT == MVT::i64 && "Unexpected type.");
3410 return std::make_pair((unsigned)Mips::T9_64, &Mips::CPU64RegsRegClass);
3411 case 'l': // register suitable for indirect jump
3413 return std::make_pair((unsigned)Mips::LO, &Mips::HILORegClass);
3414 return std::make_pair((unsigned)Mips::LO64, &Mips::HILO64RegClass);
3415 case 'x': // register suitable for indirect jump
3416 // Fixme: Not triggering the use of both hi and low
3417 // This will generate an error message
3418 return std::make_pair(0u, static_cast<const TargetRegisterClass*>(0));
3421 return TargetLowering::getRegForInlineAsmConstraint(Constraint, VT);
3424 /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
3425 /// vector. If it is invalid, don't add anything to Ops.
3426 void MipsTargetLowering::LowerAsmOperandForConstraint(SDValue Op,
3427 std::string &Constraint,
3428 std::vector<SDValue>&Ops,
3429 SelectionDAG &DAG) const {
3430 SDValue Result(0, 0);
3432 // Only support length 1 constraints for now.
3433 if (Constraint.length() > 1) return;
3435 char ConstraintLetter = Constraint[0];
3436 switch (ConstraintLetter) {
3437 default: break; // This will fall through to the generic implementation
3438 case 'I': // Signed 16 bit constant
3439 // If this fails, the parent routine will give an error
3440 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3441 EVT Type = Op.getValueType();
3442 int64_t Val = C->getSExtValue();
3443 if (isInt<16>(Val)) {
3444 Result = DAG.getTargetConstant(Val, Type);
3449 case 'J': // integer zero
3450 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3451 EVT Type = Op.getValueType();
3452 int64_t Val = C->getZExtValue();
3454 Result = DAG.getTargetConstant(0, Type);
3459 case 'K': // unsigned 16 bit immediate
3460 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3461 EVT Type = Op.getValueType();
3462 uint64_t Val = (uint64_t)C->getZExtValue();
3463 if (isUInt<16>(Val)) {
3464 Result = DAG.getTargetConstant(Val, Type);
3469 case 'L': // signed 32 bit immediate where lower 16 bits are 0
3470 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3471 EVT Type = Op.getValueType();
3472 int64_t Val = C->getSExtValue();
3473 if ((isInt<32>(Val)) && ((Val & 0xffff) == 0)){
3474 Result = DAG.getTargetConstant(Val, Type);
3479 case 'N': // immediate in the range of -65535 to -1 (inclusive)
3480 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3481 EVT Type = Op.getValueType();
3482 int64_t Val = C->getSExtValue();
3483 if ((Val >= -65535) && (Val <= -1)) {
3484 Result = DAG.getTargetConstant(Val, Type);
3489 case 'O': // signed 15 bit immediate
3490 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3491 EVT Type = Op.getValueType();
3492 int64_t Val = C->getSExtValue();
3493 if ((isInt<15>(Val))) {
3494 Result = DAG.getTargetConstant(Val, Type);
3499 case 'P': // immediate in the range of 1 to 65535 (inclusive)
3500 if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op)) {
3501 EVT Type = Op.getValueType();
3502 int64_t Val = C->getSExtValue();
3503 if ((Val <= 65535) && (Val >= 1)) {
3504 Result = DAG.getTargetConstant(Val, Type);
3511 if (Result.getNode()) {
3512 Ops.push_back(Result);
3516 TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
3520 MipsTargetLowering::isOffsetFoldingLegal(const GlobalAddressSDNode *GA) const {
3521 // The Mips target isn't yet aware of offsets.
3525 EVT MipsTargetLowering::getOptimalMemOpType(uint64_t Size, unsigned DstAlign,
3526 unsigned SrcAlign, bool IsZeroVal,
3528 MachineFunction &MF) const {
3529 if (Subtarget->hasMips64())
3535 bool MipsTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT) const {
3536 if (VT != MVT::f32 && VT != MVT::f64)
3538 if (Imm.isNegZero())
3540 return Imm.isZero();
3543 unsigned MipsTargetLowering::getJumpTableEncoding() const {
3545 return MachineJumpTableInfo::EK_GPRel64BlockAddress;
3547 return TargetLowering::getJumpTableEncoding();